title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Determinant of a Matrix in C++ Program
|
In this tutorial, we are going to learn how to find the determinant of a matrix.
Let's see the steps to find the determinant of a matrix.
Initialize the matrix.
Initialize the matrix.
Write a function to find the determinant of the matrix.If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.Initialize variables for determinant, submatrix, sign.Iterate from 1 to the size of the matrix N.Find the submatrix for the current matrix element.All the elements that are not in the current element row and columnAdd the product of the current element and its cofactor to the determinant.Alter the sign.
Write a function to find the determinant of the matrix.
If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.
If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.
Initialize variables for determinant, submatrix, sign.
Initialize variables for determinant, submatrix, sign.
Iterate from 1 to the size of the matrix N.
Iterate from 1 to the size of the matrix N.
Find the submatrix for the current matrix element.All the elements that are not in the current element row and column
Find the submatrix for the current matrix element.
All the elements that are not in the current element row and column
All the elements that are not in the current element row and column
Add the product of the current element and its cofactor to the determinant.
Add the product of the current element and its cofactor to the determinant.
Alter the sign.
Alter the sign.
Print the determinant of the matrix.
Print the determinant of the matrix.
Let's see the code.
Live Demo
#include <bits/stdc++.h>
using namespace std;
#define N 3
void subMatrix(int mat[N][N], int temp[N][N], int p, int q, int n) {
int i = 0, j = 0;
// filling the sub matrix
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
// skipping if the current row or column is not equal to the current
// element row and column
if (row != p && col != q) {
temp[i][j++] = mat[row][col];
if (j == n - 1) {
j = 0;
i++;
}
}
}
}
}
int determinantOfMatrix(int matrix[N][N], int n) {
int determinant = 0;
if (n == 1) {
return matrix[0][0];
}
if (n == 2) {
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
}
int temp[N][N], sign = 1;
for (int i = 0; i < n; i++) {
subMatrix(matrix, temp, 0, i, n);
determinant += sign * matrix[0][i] * determinantOfMatrix(temp, n - 1);
sign = -sign;
}
return determinant;
}
int main() {
int mat[N][N] = {{2, 1, 3}, {6, 5, 7}, {4, 9, 8}};
cout << "Determinant: " << determinantOfMatrix(mat, N) << endl;
return 0;
}
If you execute the above program, then you will get the following result.
Determinant: 36
If you have any queries in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1143,
"s": 1062,
"text": "In this tutorial, we are going to learn how to find the determinant of a matrix."
},
{
"code": null,
"e": 1200,
"s": 1143,
"text": "Let's see the steps to find the determinant of a matrix."
},
{
"code": null,
"e": 1223,
"s": 1200,
"text": "Initialize the matrix."
},
{
"code": null,
"e": 1246,
"s": 1223,
"text": "Initialize the matrix."
},
{
"code": null,
"e": 1713,
"s": 1246,
"text": "Write a function to find the determinant of the matrix.If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing.Initialize variables for determinant, submatrix, sign.Iterate from 1 to the size of the matrix N.Find the submatrix for the current matrix element.All the elements that are not in the current element row and columnAdd the product of the current element and its cofactor to the determinant.Alter the sign."
},
{
"code": null,
"e": 1769,
"s": 1713,
"text": "Write a function to find the determinant of the matrix."
},
{
"code": null,
"e": 1877,
"s": 1769,
"text": "If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing."
},
{
"code": null,
"e": 1985,
"s": 1877,
"text": "If the size of the matrix is 1 or 2, then find the determinant of the matrix. It's a straightforward thing."
},
{
"code": null,
"e": 2040,
"s": 1985,
"text": "Initialize variables for determinant, submatrix, sign."
},
{
"code": null,
"e": 2095,
"s": 2040,
"text": "Initialize variables for determinant, submatrix, sign."
},
{
"code": null,
"e": 2139,
"s": 2095,
"text": "Iterate from 1 to the size of the matrix N."
},
{
"code": null,
"e": 2183,
"s": 2139,
"text": "Iterate from 1 to the size of the matrix N."
},
{
"code": null,
"e": 2301,
"s": 2183,
"text": "Find the submatrix for the current matrix element.All the elements that are not in the current element row and column"
},
{
"code": null,
"e": 2352,
"s": 2301,
"text": "Find the submatrix for the current matrix element."
},
{
"code": null,
"e": 2420,
"s": 2352,
"text": "All the elements that are not in the current element row and column"
},
{
"code": null,
"e": 2488,
"s": 2420,
"text": "All the elements that are not in the current element row and column"
},
{
"code": null,
"e": 2564,
"s": 2488,
"text": "Add the product of the current element and its cofactor to the determinant."
},
{
"code": null,
"e": 2640,
"s": 2564,
"text": "Add the product of the current element and its cofactor to the determinant."
},
{
"code": null,
"e": 2656,
"s": 2640,
"text": "Alter the sign."
},
{
"code": null,
"e": 2672,
"s": 2656,
"text": "Alter the sign."
},
{
"code": null,
"e": 2709,
"s": 2672,
"text": "Print the determinant of the matrix."
},
{
"code": null,
"e": 2746,
"s": 2709,
"text": "Print the determinant of the matrix."
},
{
"code": null,
"e": 2766,
"s": 2746,
"text": "Let's see the code."
},
{
"code": null,
"e": 2777,
"s": 2766,
"text": " Live Demo"
},
{
"code": null,
"e": 3939,
"s": 2777,
"text": "#include <bits/stdc++.h>\nusing namespace std;\n#define N 3\nvoid subMatrix(int mat[N][N], int temp[N][N], int p, int q, int n) {\n int i = 0, j = 0;\n // filling the sub matrix\n for (int row = 0; row < n; row++) {\n for (int col = 0; col < n; col++) {\n // skipping if the current row or column is not equal to the current\n // element row and column\n if (row != p && col != q) {\n temp[i][j++] = mat[row][col];\n if (j == n - 1) {\n j = 0;\n i++;\n }\n }\n }\n }\n}\nint determinantOfMatrix(int matrix[N][N], int n) {\n int determinant = 0;\n if (n == 1) {\n return matrix[0][0];\n }\n if (n == 2) {\n return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);\n }\n int temp[N][N], sign = 1;\n for (int i = 0; i < n; i++) {\n subMatrix(matrix, temp, 0, i, n);\n determinant += sign * matrix[0][i] * determinantOfMatrix(temp, n - 1);\n sign = -sign;\n }\n return determinant;\n}\nint main() {\n int mat[N][N] = {{2, 1, 3}, {6, 5, 7}, {4, 9, 8}};\n cout << \"Determinant: \" << determinantOfMatrix(mat, N) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 4013,
"s": 3939,
"text": "If you execute the above program, then you will get the following result."
},
{
"code": null,
"e": 4029,
"s": 4013,
"text": "Determinant: 36"
},
{
"code": null,
"e": 4107,
"s": 4029,
"text": "If you have any queries in the tutorial, mention them in the comment section."
}
] |
How to use Transformer Networks to build a Forecasting model | by Youness Mansar | Towards Data Science
|
I recently read a really interesting paper called Deep Transformer Models for Time Series Forecasting: The Influenza Prevalence Case. I thought it might be an interesting project to implement something similar from scratch to learn more about time series forecasting.
In time series forecasting, the objective is to predict future values of a time series given its historical values. Some examples of time series forecasting tasks are:
Predicting influenza prevalence case: Deep Transformer Models for Time Series Forecasting: The Influenza Prevalence Case
Energy production prediction: Energy consumption forecasting using a stacked non-parametric Bayesian approach
Weather forecasting: MetNet: A Neural Weather Model for Precipitation Forecasting
We can, for example, store the energy consumption measures of a city for a few months and then train a model that will be able to predict the energy consumption of the city in the future. This can be used to estimate energy demand and thus energy companies can use this model to estimate the optimal value of the energy that needs to be produced at any given time.
The model we will use is an encoder-decoder Transformer where the encoder part takes as input the history of the time series while the decoder part predicts the future values in an auto-regressive fashion.
The decoder is linked with the encoder using an attention mechanism. This way, the decoder can learn to “attend” to the most useful part of the time series historical values before making a prediction.
The decoder uses masked self-attention so that the network can’t cheat during train by looking ahead and using future values to predict past values.
The encoder Sub-Network:
The decoder Sub-Network:
The full model:
This architecture can be constructed using PyTorch using the following:
encoder_layer = nn.TransformerEncoderLayer( d_model=channels, nhead=8, dropout=self.dropout, dim_feedforward=4 * channels,)decoder_layer = nn.TransformerDecoderLayer( d_model=channels, nhead=8, dropout=self.dropout, dim_feedforward=4 * channels,)self.encoder = torch.nn.TransformerEncoder(encoder_layer, num_layers=8)self.decoder = torch.nn.TransformerDecoder(decoder_layer, num_layers=8)
Every time I implement a new approach I like to try it first on synthetic data so that it's easier to understand and debug. This reduces the complexity of the data and focuses more on the implementation/Algorithm.
I wrote a small script that can generate non-trivial time series with different periodicity, offsets, and patterns.
def generate_time_series(dataframe): clip_val = random.uniform(0.3, 1) period = random.choice(periods) phase = random.randint(-1000, 1000) dataframe["views"] = dataframe.apply( lambda x: np.clip( np.cos(x["index"] * 2 * np.pi / period + phase), -clip_val, clip_val ) * x["amplitude"] + x["offset"], axis=1, ) + np.random.normal( 0, dataframe["amplitude"].abs().max() / 10, size=(dataframe.shape[0],) ) return dataframe
The model is then trained on all those time series at once:
We now use the model to make predictions on future values of those time series. The results are somewhat mixed:
The Bad:
The Good:
The results are not as good as I expected, especially given it can generally be easy to make good predictions on synthetic data, but they are still encouraging.
The model’s predictions are somewhat out of phase with a slight over-estimation of the amplitude on some of the bad examples. On the good examples, the prediction fit the ground truth really well, excluding the noise.
I probably need to debug my code a little more and work on optimizing the hyper-parameters before I can expect to achieve better results.
Transformers are currently very popular models in multitudes of Machine Learning applications so it is only natural that they will be used for time series forecasting.
Transformers should probably not be your first go-to approach when dealing with time series since they can be heavy and data-hungry but they are nice to have in your Machine Learning toolkit given their versatility and wide range of applications, starting from their first introduction in NLP to audio processing, computer vision and time series.
Feel free to comment if you have any questions or suggestions.
|
[
{
"code": null,
"e": 440,
"s": 172,
"text": "I recently read a really interesting paper called Deep Transformer Models for Time Series Forecasting: The Influenza Prevalence Case. I thought it might be an interesting project to implement something similar from scratch to learn more about time series forecasting."
},
{
"code": null,
"e": 608,
"s": 440,
"text": "In time series forecasting, the objective is to predict future values of a time series given its historical values. Some examples of time series forecasting tasks are:"
},
{
"code": null,
"e": 729,
"s": 608,
"text": "Predicting influenza prevalence case: Deep Transformer Models for Time Series Forecasting: The Influenza Prevalence Case"
},
{
"code": null,
"e": 839,
"s": 729,
"text": "Energy production prediction: Energy consumption forecasting using a stacked non-parametric Bayesian approach"
},
{
"code": null,
"e": 921,
"s": 839,
"text": "Weather forecasting: MetNet: A Neural Weather Model for Precipitation Forecasting"
},
{
"code": null,
"e": 1286,
"s": 921,
"text": "We can, for example, store the energy consumption measures of a city for a few months and then train a model that will be able to predict the energy consumption of the city in the future. This can be used to estimate energy demand and thus energy companies can use this model to estimate the optimal value of the energy that needs to be produced at any given time."
},
{
"code": null,
"e": 1492,
"s": 1286,
"text": "The model we will use is an encoder-decoder Transformer where the encoder part takes as input the history of the time series while the decoder part predicts the future values in an auto-regressive fashion."
},
{
"code": null,
"e": 1694,
"s": 1492,
"text": "The decoder is linked with the encoder using an attention mechanism. This way, the decoder can learn to “attend” to the most useful part of the time series historical values before making a prediction."
},
{
"code": null,
"e": 1843,
"s": 1694,
"text": "The decoder uses masked self-attention so that the network can’t cheat during train by looking ahead and using future values to predict past values."
},
{
"code": null,
"e": 1868,
"s": 1843,
"text": "The encoder Sub-Network:"
},
{
"code": null,
"e": 1893,
"s": 1868,
"text": "The decoder Sub-Network:"
},
{
"code": null,
"e": 1909,
"s": 1893,
"text": "The full model:"
},
{
"code": null,
"e": 1981,
"s": 1909,
"text": "This architecture can be constructed using PyTorch using the following:"
},
{
"code": null,
"e": 2394,
"s": 1981,
"text": "encoder_layer = nn.TransformerEncoderLayer( d_model=channels, nhead=8, dropout=self.dropout, dim_feedforward=4 * channels,)decoder_layer = nn.TransformerDecoderLayer( d_model=channels, nhead=8, dropout=self.dropout, dim_feedforward=4 * channels,)self.encoder = torch.nn.TransformerEncoder(encoder_layer, num_layers=8)self.decoder = torch.nn.TransformerDecoder(decoder_layer, num_layers=8)"
},
{
"code": null,
"e": 2608,
"s": 2394,
"text": "Every time I implement a new approach I like to try it first on synthetic data so that it's easier to understand and debug. This reduces the complexity of the data and focuses more on the implementation/Algorithm."
},
{
"code": null,
"e": 2724,
"s": 2608,
"text": "I wrote a small script that can generate non-trivial time series with different periodicity, offsets, and patterns."
},
{
"code": null,
"e": 3217,
"s": 2724,
"text": "def generate_time_series(dataframe): clip_val = random.uniform(0.3, 1) period = random.choice(periods) phase = random.randint(-1000, 1000) dataframe[\"views\"] = dataframe.apply( lambda x: np.clip( np.cos(x[\"index\"] * 2 * np.pi / period + phase), -clip_val, clip_val ) * x[\"amplitude\"] + x[\"offset\"], axis=1, ) + np.random.normal( 0, dataframe[\"amplitude\"].abs().max() / 10, size=(dataframe.shape[0],) ) return dataframe"
},
{
"code": null,
"e": 3277,
"s": 3217,
"text": "The model is then trained on all those time series at once:"
},
{
"code": null,
"e": 3389,
"s": 3277,
"text": "We now use the model to make predictions on future values of those time series. The results are somewhat mixed:"
},
{
"code": null,
"e": 3398,
"s": 3389,
"text": "The Bad:"
},
{
"code": null,
"e": 3408,
"s": 3398,
"text": "The Good:"
},
{
"code": null,
"e": 3569,
"s": 3408,
"text": "The results are not as good as I expected, especially given it can generally be easy to make good predictions on synthetic data, but they are still encouraging."
},
{
"code": null,
"e": 3787,
"s": 3569,
"text": "The model’s predictions are somewhat out of phase with a slight over-estimation of the amplitude on some of the bad examples. On the good examples, the prediction fit the ground truth really well, excluding the noise."
},
{
"code": null,
"e": 3925,
"s": 3787,
"text": "I probably need to debug my code a little more and work on optimizing the hyper-parameters before I can expect to achieve better results."
},
{
"code": null,
"e": 4093,
"s": 3925,
"text": "Transformers are currently very popular models in multitudes of Machine Learning applications so it is only natural that they will be used for time series forecasting."
},
{
"code": null,
"e": 4440,
"s": 4093,
"text": "Transformers should probably not be your first go-to approach when dealing with time series since they can be heavy and data-hungry but they are nice to have in your Machine Learning toolkit given their versatility and wide range of applications, starting from their first introduction in NLP to audio processing, computer vision and time series."
}
] |
EJB - Dependency Injection
|
EJB 3.0 specification provides annotations, which can be applied on fields or setter methods to inject dependencies. EJB Container uses the global JNDI registry to locate the dependency. Following annotations are used in EJB 3.0 for dependency injection.
@EJB − used to inject other EJB reference.
@EJB − used to inject other EJB reference.
@Resource − used to inject datasource or singleton services like sessionContext, timerService etc.
@Resource − used to inject datasource or singleton services like sessionContext, timerService etc.
@EJB can be used on fields or on methods in the following manner −
public class LibraryMessageBean implements MessageListener {
//dependency injection on field.
@EJB
LibraryPersistentBeanRemote libraryBean;
...
}
public class LibraryMessageBean implements MessageListener {
LibraryPersistentBeanRemote libraryBean;
//dependency injection on method.
@EJB(beanName="com.tutorialspoint.stateless.LibraryPersistentBean")
public void setLibraryPersistentBean(
LibraryPersistentBeanRemote libraryBean)
{
this.libraryBean = libraryBean;
}
...
}
@Resource is normally used to inject EJB Container provided singletons.
public class LibraryMessageBean implements MessageListener {
@Resource
private MessageDrivenContext mdctx;
...
}
Let us create a test EJB application to test Dependency Injection Service in EJB.
Create a project with a name EjbComponent under a package com.tutorialspoint.timer as explained in the EJB - Create Application chapter.
Use Beans created in the EJB - Message Driven Bean chapter. Keep rest of the files unchanged.
Clean and Build the application to make sure business logic is working as per the requirements.
Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB.
package com.tuturialspoint.messagebean;
import com.tutorialspoint.entity.Book;
import com.tutorialspoint.stateless.LibraryPersistentBeanRemote;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
@MessageDriven(
name = "BookMessageHandler",
activationConfig = {
@ActivationConfigProperty( propertyName = "destinationType",
propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty( propertyName = "destination",
propertyValue ="/queue/BookQueue")
}
)
public class LibraryMessageBean implements MessageListener {
@Resource
private MessageDrivenContext mdctx;
@EJB
LibraryPersistentBeanRemote libraryBean;
public LibraryMessageBean() {
}
public void onMessage(Message message) {
ObjectMessage objectMessage = null;
try {
objectMessage = (ObjectMessage) message;
Book book = (Book) objectMessage.getObject();
libraryBean.addBook(book);
}catch (JMSException ex) {
mdctx.setRollbackOnly();
}
}
}
package com.tutorialspoint.test;
import com.tutorialspoint.entity.Book;
import com.tutorialspoint.stateless.LibraryPersistentBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class EJBTester {
BufferedReader brConsoleReader = null;
Properties props;
InitialContext ctx;
{
props = new Properties();
try {
props.load(new FileInputStream("jndi.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
try {
ctx = new InitialContext(props);
} catch (NamingException ex) {
ex.printStackTrace();
}
brConsoleReader =
new BufferedReader(new InputStreamReader(System.in));
}
public static void main(String[] args) {
EJBTester ejbTester = new EJBTester();
ejbTester.testMessageBeanEjb();
}
private void showGUI() {
System.out.println("**********************");
System.out.println("Welcome to Book Store");
System.out.println("**********************");
System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
}
private void testMessageBeanEjb() {
try {
int choice = 1;
Queue queue = (Queue) ctx.lookup("/queue/BookQueue");
QueueConnectionFactory factory =
(QueueConnectionFactory) ctx.lookup("ConnectionFactory");
QueueConnection connection = factory.createQueueConnection();
QueueSession session = connection.createQueueSession(
false, QueueSession.AUTO_ACKNOWLEDGE);
QueueSender sender = session.createSender(queue);
while (choice != 2) {
String bookName;
showGUI();
String strChoice = brConsoleReader.readLine();
choice = Integer.parseInt(strChoice);
if (choice == 1) {
System.out.print("Enter book name: ");
bookName = brConsoleReader.readLine();
Book book = new Book();
book.setName(bookName);
ObjectMessage objectMessage =
session.createObjectMessage(book);
sender.send(objectMessage);
} else if (choice == 2) {
break;
}
}
LibraryPersistentBeanRemote libraryBean =
(LibraryPersistentBeanRemote)
ctx.lookup("LibraryPersistentBean/remote");
List<Book> booksList = libraryBean.getBooks();
System.out.println("Book(s) entered so far: "
+ booksList.size());
int i = 0;
for (Book book:booksList) {
System.out.println((i+1)+". " + book.getName());
i++;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}finally {
try {
if(brConsoleReader !=null) {
brConsoleReader.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
}
EJBTester performs the following tasks −
Load properties from jndi.properties and initialize the InitialContext object.
Load properties from jndi.properties and initialize the InitialContext object.
In testStatefulEjb() method, jndi lookup is done with the name - "/queue/BookQueue" to obtain reference of queue available in Jboss. Then sender is created using queue session.
In testStatefulEjb() method, jndi lookup is done with the name - "/queue/BookQueue" to obtain reference of queue available in Jboss. Then sender is created using queue session.
Then the user is shown a library store User Interface and he/she is asked to enter a choice.
Then the user is shown a library store User Interface and he/she is asked to enter a choice.
If the user enters 1, the system asks for book name and sender sends the book name to queue. When JBoss container receives this message in queue, it calls our message driven bean's onMessage method. Our message driven bean then saves book using stateful session bean addBook() method. Session Bean is persisting the book in database via EntityManager call.
If the user enters 1, the system asks for book name and sender sends the book name to queue. When JBoss container receives this message in queue, it calls our message driven bean's onMessage method. Our message driven bean then saves book using stateful session bean addBook() method. Session Bean is persisting the book in database via EntityManager call.
If the user enters 2, then another jndi lookup is done with the name - "LibraryStatefulSessionBean/remote" to obtain the remote business object (stateful EJB) again and listing of books is done.
If the user enters 2, then another jndi lookup is done with the name - "LibraryStatefulSessionBean/remote" to obtain the remote business object (stateful EJB) again and listing of books is done.
Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file.
Verify the following output in Netbeans console.
run:
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 1
Enter book name: Learn EJB
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 2
Book(s) entered so far: 2
1. learn java
1. learn EJB
BUILD SUCCESSFUL (total time: 15 seconds)
The output shown above states that our Message driven bean is receiving the message and storing book in persistent storage and books are retrieved from database.
Our message driven bean is using LibraryPersistentBean injected into it using @EJB annotation and in case of exception, MessageDrivenContext, object is used to rollback the transaction.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2302,
"s": 2047,
"text": "EJB 3.0 specification provides annotations, which can be applied on fields or setter methods to inject dependencies. EJB Container uses the global JNDI registry to locate the dependency. Following annotations are used in EJB 3.0 for dependency injection."
},
{
"code": null,
"e": 2345,
"s": 2302,
"text": "@EJB − used to inject other EJB reference."
},
{
"code": null,
"e": 2388,
"s": 2345,
"text": "@EJB − used to inject other EJB reference."
},
{
"code": null,
"e": 2487,
"s": 2388,
"text": "@Resource − used to inject datasource or singleton services like sessionContext, timerService etc."
},
{
"code": null,
"e": 2586,
"s": 2487,
"text": "@Resource − used to inject datasource or singleton services like sessionContext, timerService etc."
},
{
"code": null,
"e": 2653,
"s": 2586,
"text": "@EJB can be used on fields or on methods in the following manner −"
},
{
"code": null,
"e": 3175,
"s": 2653,
"text": "public class LibraryMessageBean implements MessageListener {\n //dependency injection on field. \n @EJB\n LibraryPersistentBeanRemote libraryBean;\n ...\n}\npublic class LibraryMessageBean implements MessageListener {\n \n LibraryPersistentBeanRemote libraryBean;\n \n //dependency injection on method. \n @EJB(beanName=\"com.tutorialspoint.stateless.LibraryPersistentBean\")\n public void setLibraryPersistentBean(\n LibraryPersistentBeanRemote libraryBean)\n {\n this.libraryBean = libraryBean;\n }\n ...\n}"
},
{
"code": null,
"e": 3247,
"s": 3175,
"text": "@Resource is normally used to inject EJB Container provided singletons."
},
{
"code": null,
"e": 3371,
"s": 3247,
"text": "public class LibraryMessageBean implements MessageListener {\n @Resource\n private MessageDrivenContext mdctx; \n ...\n}"
},
{
"code": null,
"e": 3453,
"s": 3371,
"text": "Let us create a test EJB application to test Dependency Injection Service in EJB."
},
{
"code": null,
"e": 3590,
"s": 3453,
"text": "Create a project with a name EjbComponent under a package com.tutorialspoint.timer as explained in the EJB - Create Application chapter."
},
{
"code": null,
"e": 3684,
"s": 3590,
"text": "Use Beans created in the EJB - Message Driven Bean chapter. Keep rest of the files unchanged."
},
{
"code": null,
"e": 3780,
"s": 3684,
"text": "Clean and Build the application to make sure business logic is working as per the requirements."
},
{
"code": null,
"e": 3947,
"s": 3780,
"text": "Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet."
},
{
"code": null,
"e": 4112,
"s": 3947,
"text": "Now create the EJB client, a console based application in the same way as explained in the EJB - Create Application chapter under topic Create Client to access EJB."
},
{
"code": null,
"e": 5456,
"s": 4112,
"text": "package com.tuturialspoint.messagebean;\n \nimport com.tutorialspoint.entity.Book;\nimport com.tutorialspoint.stateless.LibraryPersistentBeanRemote;\nimport javax.annotation.Resource;\nimport javax.ejb.ActivationConfigProperty;\nimport javax.ejb.EJB;\nimport javax.ejb.MessageDriven;\nimport javax.ejb.MessageDrivenContext;\nimport javax.jms.JMSException;\nimport javax.jms.Message;\nimport javax.jms.MessageListener;\nimport javax.jms.ObjectMessage;\n \n@MessageDriven(\n name = \"BookMessageHandler\",\n activationConfig = {\n @ActivationConfigProperty( propertyName = \"destinationType\", \n propertyValue = \"javax.jms.Queue\"),\n @ActivationConfigProperty( propertyName = \"destination\", \n propertyValue =\"/queue/BookQueue\")\n }\n)\npublic class LibraryMessageBean implements MessageListener {\n \n @Resource\n private MessageDrivenContext mdctx; \n \n @EJB\n LibraryPersistentBeanRemote libraryBean;\n \n public LibraryMessageBean() { \n }\n \n public void onMessage(Message message) {\n ObjectMessage objectMessage = null;\n try {\n objectMessage = (ObjectMessage) message;\n Book book = (Book) objectMessage.getObject(); \n libraryBean.addBook(book);\n \n }catch (JMSException ex) {\n mdctx.setRollbackOnly();\n } \n } \n}"
},
{
"code": null,
"e": 8899,
"s": 5456,
"text": "package com.tutorialspoint.test;\n \nimport com.tutorialspoint.entity.Book;\nimport com.tutorialspoint.stateless.LibraryPersistentBeanRemote;\nimport java.io.BufferedReader;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.List;\nimport java.util.Properties;\nimport javax.jms.ObjectMessage;\nimport javax.jms.Queue;\nimport javax.jms.QueueConnection;\nimport javax.jms.QueueConnectionFactory;\nimport javax.jms.QueueSender;\nimport javax.jms.QueueSession;\nimport javax.naming.InitialContext;\nimport javax.naming.NamingException;\n \npublic class EJBTester {\n \n BufferedReader brConsoleReader = null; \n Properties props;\n InitialContext ctx;\n {\n props = new Properties();\n try {\n props.load(new FileInputStream(\"jndi.properties\"));\n } catch (IOException ex) {\n ex.printStackTrace();\n }\n try {\n ctx = new InitialContext(props); \n } catch (NamingException ex) {\n ex.printStackTrace();\n }\n brConsoleReader = \n new BufferedReader(new InputStreamReader(System.in));\n }\n \n public static void main(String[] args) {\n \n EJBTester ejbTester = new EJBTester();\n \n ejbTester.testMessageBeanEjb();\n }\n \n private void showGUI() {\n System.out.println(\"**********************\");\n System.out.println(\"Welcome to Book Store\");\n System.out.println(\"**********************\");\n System.out.print(\"Options \\n1. Add Book\\n2. Exit \\nEnter Choice: \");\n }\n \n private void testMessageBeanEjb() {\n \n try {\n int choice = 1; \n Queue queue = (Queue) ctx.lookup(\"/queue/BookQueue\");\n QueueConnectionFactory factory =\n (QueueConnectionFactory) ctx.lookup(\"ConnectionFactory\");\n QueueConnection connection = factory.createQueueConnection();\n QueueSession session = connection.createQueueSession( \n false, QueueSession.AUTO_ACKNOWLEDGE);\n QueueSender sender = session.createSender(queue);\n \n while (choice != 2) {\n String bookName;\n showGUI();\n String strChoice = brConsoleReader.readLine();\n choice = Integer.parseInt(strChoice);\n if (choice == 1) {\n System.out.print(\"Enter book name: \");\n bookName = brConsoleReader.readLine();\n Book book = new Book();\n book.setName(bookName);\n ObjectMessage objectMessage = \n session.createObjectMessage(book);\n sender.send(objectMessage); \n } else if (choice == 2) {\n break;\n }\n }\n \n LibraryPersistentBeanRemote libraryBean = \n (LibraryPersistentBeanRemote)\n\t\t ctx.lookup(\"LibraryPersistentBean/remote\");\n \n List<Book> booksList = libraryBean.getBooks();\n \n System.out.println(\"Book(s) entered so far: \" \n + booksList.size());\n int i = 0;\n for (Book book:booksList) {\n System.out.println((i+1)+\". \" + book.getName());\n i++;\n } \n } catch (Exception e) {\n System.out.println(e.getMessage());\n e.printStackTrace();\n }finally {\n try {\n if(brConsoleReader !=null) {\n brConsoleReader.close();\n }\n } catch (IOException ex) {\n System.out.println(ex.getMessage());\n }\n }\n } \n}"
},
{
"code": null,
"e": 8940,
"s": 8899,
"text": "EJBTester performs the following tasks −"
},
{
"code": null,
"e": 9019,
"s": 8940,
"text": "Load properties from jndi.properties and initialize the InitialContext object."
},
{
"code": null,
"e": 9098,
"s": 9019,
"text": "Load properties from jndi.properties and initialize the InitialContext object."
},
{
"code": null,
"e": 9275,
"s": 9098,
"text": "In testStatefulEjb() method, jndi lookup is done with the name - \"/queue/BookQueue\" to obtain reference of queue available in Jboss. Then sender is created using queue session."
},
{
"code": null,
"e": 9452,
"s": 9275,
"text": "In testStatefulEjb() method, jndi lookup is done with the name - \"/queue/BookQueue\" to obtain reference of queue available in Jboss. Then sender is created using queue session."
},
{
"code": null,
"e": 9545,
"s": 9452,
"text": "Then the user is shown a library store User Interface and he/she is asked to enter a choice."
},
{
"code": null,
"e": 9638,
"s": 9545,
"text": "Then the user is shown a library store User Interface and he/she is asked to enter a choice."
},
{
"code": null,
"e": 9995,
"s": 9638,
"text": "If the user enters 1, the system asks for book name and sender sends the book name to queue. When JBoss container receives this message in queue, it calls our message driven bean's onMessage method. Our message driven bean then saves book using stateful session bean addBook() method. Session Bean is persisting the book in database via EntityManager call."
},
{
"code": null,
"e": 10352,
"s": 9995,
"text": "If the user enters 1, the system asks for book name and sender sends the book name to queue. When JBoss container receives this message in queue, it calls our message driven bean's onMessage method. Our message driven bean then saves book using stateful session bean addBook() method. Session Bean is persisting the book in database via EntityManager call."
},
{
"code": null,
"e": 10547,
"s": 10352,
"text": "If the user enters 2, then another jndi lookup is done with the name - \"LibraryStatefulSessionBean/remote\" to obtain the remote business object (stateful EJB) again and listing of books is done."
},
{
"code": null,
"e": 10742,
"s": 10547,
"text": "If the user enters 2, then another jndi lookup is done with the name - \"LibraryStatefulSessionBean/remote\" to obtain the remote business object (stateful EJB) again and listing of books is done."
},
{
"code": null,
"e": 10837,
"s": 10742,
"text": "Locate EJBTester.java in project explorer. Right click on EJBTester class and select run file."
},
{
"code": null,
"e": 10886,
"s": 10837,
"text": "Verify the following output in Netbeans console."
},
{
"code": null,
"e": 11242,
"s": 10886,
"text": "run:\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 1\nEnter book name: Learn EJB\n**********************\nWelcome to Book Store\n**********************\nOptions \n1. Add Book\n2. Exit \nEnter Choice: 2\nBook(s) entered so far: 2\n1. learn java\n1. learn EJB\nBUILD SUCCESSFUL (total time: 15 seconds)\n"
},
{
"code": null,
"e": 11404,
"s": 11242,
"text": "The output shown above states that our Message driven bean is receiving the message and storing book in persistent storage and books are retrieved from database."
},
{
"code": null,
"e": 11590,
"s": 11404,
"text": "Our message driven bean is using LibraryPersistentBean injected into it using @EJB annotation and in case of exception, MessageDrivenContext, object is used to rollback the transaction."
},
{
"code": null,
"e": 11597,
"s": 11590,
"text": " Print"
},
{
"code": null,
"e": 11608,
"s": 11597,
"text": " Add Notes"
}
] |
Print all strings of maximum length from an array of strings
|
22 Jun, 2021
Given an array of strings arr[], the task is to print all the strings of maximum length from the given array.
Example:
Input: arr[] = {“aba”, “aa”, “ad”, “vcd”, “aba”}Output: aba vcd abaExplanation:Maximum length among all the strings from the given array is 3.The strings having length equal to 3 from the array are “aba”, “vcd”, “aba”.
Input: arr[] = {“abb”, “abcd”, “guw”, “v”}Output: abcdExplanation:Maximum length among all the strings from the given array is 4.The string having length equal to 4 from the array is “abcd”.
Approach: Follow the steps below to solve the problem:
Traverse the given array of strings. Calculate the maximum length among all the strings from the array and store it in a variable, say len.Now, traverse the array of string again and print those strings from the array having a length equal to len.
Traverse the given array of strings. Calculate the maximum length among all the strings from the array and store it in a variable, say len.
Now, traverse the array of string again and print those strings from the array having a length equal to len.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length// of the longest string from// the given array of stringsint maxLength(vector<string> arr){ int len = INT_MIN; int N = arr.size(); // Traverse the array for (int i = 0; i < N; i++) { // Stores the length // of current string int l = arr[i].size(); // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest strings from the arrayvoid maxStrings(vector<string> arr, int len){ int N = arr.size(); vector<string> ans; // Find the strings having length // equals to len for (int i = 0; i < N; i++) { if (len == arr[i].size()) { ans.push_back(arr[i]); } } // Print the resultant // vector of strings for (int i = 0; i < ans.size(); i++) { cout << ans[i] << " "; }} // Function to print all the// longest strings from the arrayvoid printStrings(vector<string>& arr){ // Find the length of longest string int max = maxLength(arr); // Find and print all the strings // having length equals to max maxStrings(arr, max);} // Driver Codeint main(){ vector<string> arr = { "aba", "aa", "ad", "vcd", "aba" }; printStrings(arr); return 0;}
// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the length// of the longest String from// the given array of Stringsstatic int maxLength(String []arr){ int len = Integer.MIN_VALUE; int N = arr.length; // Traverse the array for(int i = 0; i < N; i++) { // Stores the length // of current String int l = arr[i].length(); // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest Strings from the arraystatic void maxStrings(String []arr, int len){ int N = arr.length; Vector<String> ans = new Vector<String>(); // Find the Strings having length // equals to len for(int i = 0; i < N; i++) { if (len == arr[i].length()) { ans.add(arr[i]); } } // Print the resultant // vector of Strings for(int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i) + " "); }} // Function to print all the// longest Strings from the arraystatic void printStrings(String [] arr){ // Find the length of longest String int max = maxLength(arr); // Find and print all the Strings // having length equals to max maxStrings(arr, max);} // Driver Codepublic static void main(String[] args){ String []arr = { "aba", "aa", "ad", "vcd", "aba" }; printStrings(arr);}} // This code is contributed by Amit Katiyar
# Python3 program to implement# the above approachimport sys # Function to find the length# of the longest string from# the given array of stringsdef maxLength(arr): lenn = -sys.maxsize - 1 N = len(arr) # Traverse the array for i in range(N): # Stores the length # of current string l = len(arr[i]) # Update maximum length if (lenn < l): lenn = l # Return the maximum length return lenn # Function to print the# longest strings from the arraydef maxStrings(arr, lenn): N = len(arr) ans = [] # Find the strings having length # equals to lenn for i in range(N): if (lenn == len(arr[i])): ans.append(arr[i]) # Print the resultant # vector of strings for i in range(len(ans)): print(ans[i], end = " ") # Function to print all the# longest strings from the arraydef printStrings(arr): # Find the length of longest string max = maxLength(arr) # Find and print all the strings # having length equals to max maxStrings(arr, max) # Driver Codeif __name__ == '__main__': arr = [ "aba", "aa", "ad", "vcd", "aba" ] printStrings(arr) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the length// of the longest String from// the given array of Stringsstatic int maxLength(String []arr){ int len = int.MinValue; int N = arr.Length; // Traverse the array for(int i = 0; i < N; i++) { // Stores the length // of current String int l = arr[i].Length; // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest Strings from the arraystatic void maxStrings(String []arr, int len){ int N = arr.Length; List<String> ans = new List<String>(); // Find the Strings having length // equals to len for(int i = 0; i < N; i++) { if (len == arr[i].Length) { ans.Add(arr[i]); } } // Print the resultant // vector of Strings for(int i = 0; i < ans.Count; i++) { Console.Write(ans[i] + " "); }} // Function to print all the// longest Strings from the arraystatic void printStrings(String [] arr){ // Find the length of longest String int max = maxLength(arr); // Find and print all the Strings // having length equals to max maxStrings(arr, max);} // Driver Codepublic static void Main(String[] args){ String []arr = {"aba", "aa", "ad", "vcd", "aba"}; printStrings(arr);}} // This code is contributed by Rajput-Ji
<script>// Javascript program to implement// the above approach // Function to find the length// of the longest String from// the given array of Stringsfunction maxLength(arr){ let len = Number.MIN_VALUE; let N = arr.length; // Traverse the array for(let i = 0; i < N; i++) { // Stores the length // of current String let l = arr[i].length; // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest Strings from the arrayfunction maxStrings(arr,len){ let N = arr.length; let ans = []; // Find the Strings having length // equals to len for(let i = 0; i < N; i++) { if (len == arr[i].length) { ans.push(arr[i]); } } // Print the resultant // vector of Strings for(let i = 0; i < ans.length; i++) { document.write(ans[i] + " "); }} // Function to print all the// longest Strings from the arrayfunction printStrings(arr){ // Find the length of longest String let max = maxLength(arr); // Find and print all the Strings // having length equals to max maxStrings(arr, max);} // Driver Codelet arr=["aba", "aa", "ad", "vcd", "aba" ];printStrings(arr); // This code is contributed by unknown2108</script>
aba vcd aba
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
amit143katiyar
Rajput-Ji
simmytarika5
unknown2108
Arrays
School Programming
Searching
Strings
Arrays
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 162,
"s": 52,
"text": "Given an array of strings arr[], the task is to print all the strings of maximum length from the given array."
},
{
"code": null,
"e": 171,
"s": 162,
"text": "Example:"
},
{
"code": null,
"e": 390,
"s": 171,
"text": "Input: arr[] = {“aba”, “aa”, “ad”, “vcd”, “aba”}Output: aba vcd abaExplanation:Maximum length among all the strings from the given array is 3.The strings having length equal to 3 from the array are “aba”, “vcd”, “aba”."
},
{
"code": null,
"e": 581,
"s": 390,
"text": "Input: arr[] = {“abb”, “abcd”, “guw”, “v”}Output: abcdExplanation:Maximum length among all the strings from the given array is 4.The string having length equal to 4 from the array is “abcd”."
},
{
"code": null,
"e": 636,
"s": 581,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 884,
"s": 636,
"text": "Traverse the given array of strings. Calculate the maximum length among all the strings from the array and store it in a variable, say len.Now, traverse the array of string again and print those strings from the array having a length equal to len."
},
{
"code": null,
"e": 1024,
"s": 884,
"text": "Traverse the given array of strings. Calculate the maximum length among all the strings from the array and store it in a variable, say len."
},
{
"code": null,
"e": 1133,
"s": 1024,
"text": "Now, traverse the array of string again and print those strings from the array having a length equal to len."
},
{
"code": null,
"e": 1184,
"s": 1133,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1188,
"s": 1184,
"text": "C++"
},
{
"code": null,
"e": 1193,
"s": 1188,
"text": "Java"
},
{
"code": null,
"e": 1201,
"s": 1193,
"text": "Python3"
},
{
"code": null,
"e": 1204,
"s": 1201,
"text": "C#"
},
{
"code": null,
"e": 1215,
"s": 1204,
"text": "Javascript"
},
{
"code": "// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to find the length// of the longest string from// the given array of stringsint maxLength(vector<string> arr){ int len = INT_MIN; int N = arr.size(); // Traverse the array for (int i = 0; i < N; i++) { // Stores the length // of current string int l = arr[i].size(); // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest strings from the arrayvoid maxStrings(vector<string> arr, int len){ int N = arr.size(); vector<string> ans; // Find the strings having length // equals to len for (int i = 0; i < N; i++) { if (len == arr[i].size()) { ans.push_back(arr[i]); } } // Print the resultant // vector of strings for (int i = 0; i < ans.size(); i++) { cout << ans[i] << \" \"; }} // Function to print all the// longest strings from the arrayvoid printStrings(vector<string>& arr){ // Find the length of longest string int max = maxLength(arr); // Find and print all the strings // having length equals to max maxStrings(arr, max);} // Driver Codeint main(){ vector<string> arr = { \"aba\", \"aa\", \"ad\", \"vcd\", \"aba\" }; printStrings(arr); return 0;}",
"e": 2613,
"s": 1215,
"text": null
},
{
"code": "// Java program to implement// the above approachimport java.util.*; class GFG{ // Function to find the length// of the longest String from// the given array of Stringsstatic int maxLength(String []arr){ int len = Integer.MIN_VALUE; int N = arr.length; // Traverse the array for(int i = 0; i < N; i++) { // Stores the length // of current String int l = arr[i].length(); // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest Strings from the arraystatic void maxStrings(String []arr, int len){ int N = arr.length; Vector<String> ans = new Vector<String>(); // Find the Strings having length // equals to len for(int i = 0; i < N; i++) { if (len == arr[i].length()) { ans.add(arr[i]); } } // Print the resultant // vector of Strings for(int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i) + \" \"); }} // Function to print all the// longest Strings from the arraystatic void printStrings(String [] arr){ // Find the length of longest String int max = maxLength(arr); // Find and print all the Strings // having length equals to max maxStrings(arr, max);} // Driver Codepublic static void main(String[] args){ String []arr = { \"aba\", \"aa\", \"ad\", \"vcd\", \"aba\" }; printStrings(arr);}} // This code is contributed by Amit Katiyar",
"e": 4164,
"s": 2613,
"text": null
},
{
"code": "# Python3 program to implement# the above approachimport sys # Function to find the length# of the longest string from# the given array of stringsdef maxLength(arr): lenn = -sys.maxsize - 1 N = len(arr) # Traverse the array for i in range(N): # Stores the length # of current string l = len(arr[i]) # Update maximum length if (lenn < l): lenn = l # Return the maximum length return lenn # Function to print the# longest strings from the arraydef maxStrings(arr, lenn): N = len(arr) ans = [] # Find the strings having length # equals to lenn for i in range(N): if (lenn == len(arr[i])): ans.append(arr[i]) # Print the resultant # vector of strings for i in range(len(ans)): print(ans[i], end = \" \") # Function to print all the# longest strings from the arraydef printStrings(arr): # Find the length of longest string max = maxLength(arr) # Find and print all the strings # having length equals to max maxStrings(arr, max) # Driver Codeif __name__ == '__main__': arr = [ \"aba\", \"aa\", \"ad\", \"vcd\", \"aba\" ] printStrings(arr) # This code is contributed by mohit kumar 29",
"e": 5399,
"s": 4164,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the length// of the longest String from// the given array of Stringsstatic int maxLength(String []arr){ int len = int.MinValue; int N = arr.Length; // Traverse the array for(int i = 0; i < N; i++) { // Stores the length // of current String int l = arr[i].Length; // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest Strings from the arraystatic void maxStrings(String []arr, int len){ int N = arr.Length; List<String> ans = new List<String>(); // Find the Strings having length // equals to len for(int i = 0; i < N; i++) { if (len == arr[i].Length) { ans.Add(arr[i]); } } // Print the resultant // vector of Strings for(int i = 0; i < ans.Count; i++) { Console.Write(ans[i] + \" \"); }} // Function to print all the// longest Strings from the arraystatic void printStrings(String [] arr){ // Find the length of longest String int max = maxLength(arr); // Find and print all the Strings // having length equals to max maxStrings(arr, max);} // Driver Codepublic static void Main(String[] args){ String []arr = {\"aba\", \"aa\", \"ad\", \"vcd\", \"aba\"}; printStrings(arr);}} // This code is contributed by Rajput-Ji",
"e": 6963,
"s": 5399,
"text": null
},
{
"code": "<script>// Javascript program to implement// the above approach // Function to find the length// of the longest String from// the given array of Stringsfunction maxLength(arr){ let len = Number.MIN_VALUE; let N = arr.length; // Traverse the array for(let i = 0; i < N; i++) { // Stores the length // of current String let l = arr[i].length; // Update maximum length if (len < l) { len = l; } } // Return the maximum length return len;} // Function to print the// longest Strings from the arrayfunction maxStrings(arr,len){ let N = arr.length; let ans = []; // Find the Strings having length // equals to len for(let i = 0; i < N; i++) { if (len == arr[i].length) { ans.push(arr[i]); } } // Print the resultant // vector of Strings for(let i = 0; i < ans.length; i++) { document.write(ans[i] + \" \"); }} // Function to print all the// longest Strings from the arrayfunction printStrings(arr){ // Find the length of longest String let max = maxLength(arr); // Find and print all the Strings // having length equals to max maxStrings(arr, max);} // Driver Codelet arr=[\"aba\", \"aa\", \"ad\", \"vcd\", \"aba\" ];printStrings(arr); // This code is contributed by unknown2108</script>",
"e": 8352,
"s": 6963,
"text": null
},
{
"code": null,
"e": 8364,
"s": 8352,
"text": "aba vcd aba"
},
{
"code": null,
"e": 8407,
"s": 8364,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 8422,
"s": 8407,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8437,
"s": 8422,
"text": "amit143katiyar"
},
{
"code": null,
"e": 8447,
"s": 8437,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 8460,
"s": 8447,
"text": "simmytarika5"
},
{
"code": null,
"e": 8472,
"s": 8460,
"text": "unknown2108"
},
{
"code": null,
"e": 8479,
"s": 8472,
"text": "Arrays"
},
{
"code": null,
"e": 8498,
"s": 8479,
"text": "School Programming"
},
{
"code": null,
"e": 8508,
"s": 8498,
"text": "Searching"
},
{
"code": null,
"e": 8516,
"s": 8508,
"text": "Strings"
},
{
"code": null,
"e": 8523,
"s": 8516,
"text": "Arrays"
},
{
"code": null,
"e": 8533,
"s": 8523,
"text": "Searching"
},
{
"code": null,
"e": 8541,
"s": 8533,
"text": "Strings"
}
] |
K’th Least Element in a Min-Heap
|
29 Nov, 2018
Given a min-heap of size n, find the kth least element in the min-heap.
Examples:
Input : {10, 50, 40, 75, 60, 65, 45}k = 4Output : 50
Input : {10, 50, 40, 75, 60, 65, 45}k = 2Output : 40
Naive approach:We can extract the minimum element from the min-heap k times and the last element extracted will be the kth least element. Each deletion operations takes O(log n) time, so the total time complexity of this approach comes out to be O(k * log n).
// C++ program to find k-th smallest// element in Min Heap.#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] > h.v[l]) m = l; if (r < h.n && h.v[m] > h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the minimum elementint extractMin(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int findKthSmalles(Heap &h, int k){ for (int i = 1; i < k; ++i) extractMin(h); return extractMin(h);} int main(){ Heap h(7); h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 }; int k = 2; cout << findKthSmalles(h, k); return 0;}
40
Time Complexity: O(k * log n)
Efficient approach:We can note an interesting observation about min-heap. An element x at ith level has i – 1 ancestors. By the property of min-heaps, these i – 1 ancestors are guaranteed to be less than x. This implies that x cannot be among the least i – 1 elements of the heap. Using this property, we can conclude that the kth least element can have a level of at most k.
We can reduce the size of the min-heap such that it has only k levels. We can then obtain the kth least element by our previous strategy of extracting the minimum element k times. Note that the size of the heap is reduced to a maximum of 2k – 1, therefore each heapify operation will take O(log 2k) = O(k) time. The total time complexity will be O(k2). If n >> k, then this approach performs better than the previous one.
// C++ program to find k-th smallest// element in Min Heap using k levels#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] > h.v[l]) m = l; if (r < h.n && h.v[m] > h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the minimum elementint extractMin(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int findKthSmalles(Heap &h, int k){ h.n = min(h.n, int(pow(2, k) - 1)); for (int i = 1; i < k; ++i) extractMin(h); return extractMin(h);} int main(){ Heap h(7); h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 }; int k = 2; cout << findKthSmalles(h, k); return 0;}
40
Time Complexity: O(k2)
More efficient approach:We can further improve the time complexity of this problem by the following algorithm:
Create a priority queue P (or Min Heap) and insert the root node of the min-heap into P. The comparator function of the priority queue should be such that the least element is popped.Repeat these steps k – 1 times:Pop the least element from P.Insert left and right child elements of the popped element. (if they exist).The least element in P is the kth least element of the min-heap.
Create a priority queue P (or Min Heap) and insert the root node of the min-heap into P. The comparator function of the priority queue should be such that the least element is popped.
Repeat these steps k – 1 times:Pop the least element from P.Insert left and right child elements of the popped element. (if they exist).
Pop the least element from P.Insert left and right child elements of the popped element. (if they exist).
Pop the least element from P.
Insert left and right child elements of the popped element. (if they exist).
The least element in P is the kth least element of the min-heap.
The initial size of the priority queue is one, and it increases by at most one at each of the k – 1 steps. Therefore, there are maximum k elements in the priority queue and the time complexity of the pop and insert operations is O(log k). Thus the total time complexity is O(k * log k).
// C++ program to find k-th smallest// element in Min Heap using another// Min Heap (Or Priority Queue)#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} int findKthSmalles(Heap &h, int k){ // Create a Priority Queue priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > p; // Insert root into the priority queue p.push(make_pair(h.v[0], 0)); for (int i = 0; i < k - 1; ++i) { int j = p.top().second; p.pop(); int l = left(j), r = right(j); if (l < h.n) p.push(make_pair(h.v[l], l)); if (r < h.n) p.push(make_pair(h.v[r], r)); } return p.top().first;} int main(){ Heap h(7); h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 }; int k = 4; cout << findKthSmalles(h, k); return 0;}
50
Time Complexity: O(k * log k)
vaibhav29498
cpp-priority-queue
priority-queue
Technical Scripter 2018
Heap
Technical Scripter
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 124,
"s": 52,
"text": "Given a min-heap of size n, find the kth least element in the min-heap."
},
{
"code": null,
"e": 134,
"s": 124,
"text": "Examples:"
},
{
"code": null,
"e": 187,
"s": 134,
"text": "Input : {10, 50, 40, 75, 60, 65, 45}k = 4Output : 50"
},
{
"code": null,
"e": 240,
"s": 187,
"text": "Input : {10, 50, 40, 75, 60, 65, 45}k = 2Output : 40"
},
{
"code": null,
"e": 500,
"s": 240,
"text": "Naive approach:We can extract the minimum element from the min-heap k times and the last element extracted will be the kth least element. Each deletion operations takes O(log n) time, so the total time complexity of this approach comes out to be O(k * log n)."
},
{
"code": "// C++ program to find k-th smallest// element in Min Heap.#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] > h.v[l]) m = l; if (r < h.n && h.v[m] > h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the minimum elementint extractMin(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int findKthSmalles(Heap &h, int k){ for (int i = 1; i < k; ++i) extractMin(h); return extractMin(h);} int main(){ Heap h(7); h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 }; int k = 2; cout << findKthSmalles(h, k); return 0;}",
"e": 1852,
"s": 500,
"text": null
},
{
"code": null,
"e": 1856,
"s": 1852,
"text": "40\n"
},
{
"code": null,
"e": 1886,
"s": 1856,
"text": "Time Complexity: O(k * log n)"
},
{
"code": null,
"e": 2262,
"s": 1886,
"text": "Efficient approach:We can note an interesting observation about min-heap. An element x at ith level has i – 1 ancestors. By the property of min-heaps, these i – 1 ancestors are guaranteed to be less than x. This implies that x cannot be among the least i – 1 elements of the heap. Using this property, we can conclude that the kth least element can have a level of at most k."
},
{
"code": null,
"e": 2684,
"s": 2262,
"text": "We can reduce the size of the min-heap such that it has only k levels. We can then obtain the kth least element by our previous strategy of extracting the minimum element k times. Note that the size of the heap is reduced to a maximum of 2k – 1, therefore each heapify operation will take O(log 2k) = O(k) time. The total time complexity will be O(k2). If n >> k, then this approach performs better than the previous one."
},
{
"code": "// C++ program to find k-th smallest// element in Min Heap using k levels#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Generic function to// swap two integersvoid swap(int& a, int& b){ int temp = a; a = b; b = temp;} // Returns the index of// the parent nodeinline int parent(int i){ return (i - 1) / 2;} // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} // Maintains the heap propertyvoid heapify(Heap& h, int i){ int l = left(i), r = right(i), m = i; if (l < h.n && h.v[i] > h.v[l]) m = l; if (r < h.n && h.v[m] > h.v[r]) m = r; if (m != i) { swap(h.v[m], h.v[i]); heapify(h, m); }} // Extracts the minimum elementint extractMin(Heap& h){ if (!h.n) return -1; int m = h.v[0]; h.v[0] = h.v[h.n-- - 1]; heapify(h, 0); return m;} int findKthSmalles(Heap &h, int k){ h.n = min(h.n, int(pow(2, k) - 1)); for (int i = 1; i < k; ++i) extractMin(h); return extractMin(h);} int main(){ Heap h(7); h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 }; int k = 2; cout << findKthSmalles(h, k); return 0;}",
"e": 4089,
"s": 2684,
"text": null
},
{
"code": null,
"e": 4093,
"s": 4089,
"text": "40\n"
},
{
"code": null,
"e": 4116,
"s": 4093,
"text": "Time Complexity: O(k2)"
},
{
"code": null,
"e": 4227,
"s": 4116,
"text": "More efficient approach:We can further improve the time complexity of this problem by the following algorithm:"
},
{
"code": null,
"e": 4611,
"s": 4227,
"text": "Create a priority queue P (or Min Heap) and insert the root node of the min-heap into P. The comparator function of the priority queue should be such that the least element is popped.Repeat these steps k – 1 times:Pop the least element from P.Insert left and right child elements of the popped element. (if they exist).The least element in P is the kth least element of the min-heap."
},
{
"code": null,
"e": 4795,
"s": 4611,
"text": "Create a priority queue P (or Min Heap) and insert the root node of the min-heap into P. The comparator function of the priority queue should be such that the least element is popped."
},
{
"code": null,
"e": 4932,
"s": 4795,
"text": "Repeat these steps k – 1 times:Pop the least element from P.Insert left and right child elements of the popped element. (if they exist)."
},
{
"code": null,
"e": 5038,
"s": 4932,
"text": "Pop the least element from P.Insert left and right child elements of the popped element. (if they exist)."
},
{
"code": null,
"e": 5068,
"s": 5038,
"text": "Pop the least element from P."
},
{
"code": null,
"e": 5145,
"s": 5068,
"text": "Insert left and right child elements of the popped element. (if they exist)."
},
{
"code": null,
"e": 5210,
"s": 5145,
"text": "The least element in P is the kth least element of the min-heap."
},
{
"code": null,
"e": 5497,
"s": 5210,
"text": "The initial size of the priority queue is one, and it increases by at most one at each of the k – 1 steps. Therefore, there are maximum k elements in the priority queue and the time complexity of the pop and insert operations is O(log k). Thus the total time complexity is O(k * log k)."
},
{
"code": "// C++ program to find k-th smallest// element in Min Heap using another// Min Heap (Or Priority Queue)#include <bits/stdc++.h>using namespace std; // Structure for the heapstruct Heap { vector<int> v; int n; // Size of the heap Heap(int i = 0) : n(i) { v = vector<int>(n); }}; // Returns the index of// the left child nodeinline int left(int i){ return 2 * i + 1;} // Returns the index of// the right child nodeinline int right(int i){ return 2 * i + 2;} int findKthSmalles(Heap &h, int k){ // Create a Priority Queue priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > p; // Insert root into the priority queue p.push(make_pair(h.v[0], 0)); for (int i = 0; i < k - 1; ++i) { int j = p.top().second; p.pop(); int l = left(j), r = right(j); if (l < h.n) p.push(make_pair(h.v[l], l)); if (r < h.n) p.push(make_pair(h.v[r], r)); } return p.top().first;} int main(){ Heap h(7); h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 }; int k = 4; cout << findKthSmalles(h, k); return 0;}",
"e": 6688,
"s": 5497,
"text": null
},
{
"code": null,
"e": 6692,
"s": 6688,
"text": "50\n"
},
{
"code": null,
"e": 6722,
"s": 6692,
"text": "Time Complexity: O(k * log k)"
},
{
"code": null,
"e": 6735,
"s": 6722,
"text": "vaibhav29498"
},
{
"code": null,
"e": 6754,
"s": 6735,
"text": "cpp-priority-queue"
},
{
"code": null,
"e": 6769,
"s": 6754,
"text": "priority-queue"
},
{
"code": null,
"e": 6793,
"s": 6769,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 6798,
"s": 6793,
"text": "Heap"
},
{
"code": null,
"e": 6817,
"s": 6798,
"text": "Technical Scripter"
},
{
"code": null,
"e": 6822,
"s": 6817,
"text": "Heap"
},
{
"code": null,
"e": 6837,
"s": 6822,
"text": "priority-queue"
}
] |
Program to print Even Odd Number Pyramid
|
06 Jun, 2022
Given the total number of rows as n, the task is to print the given pattern.
* 1* *2* 1*3* *2*4* 1*3*5* *2*4*6* 1*3*5*7* *2*4*6*8* 1*3*5*7*9* . .
Examples:
Input: n = 5
Output:
*
1*
*2*
1*3*
*2*4*
Input: n = 10
Output:
*
1*
*2*
1*3*
*2*4*
1*3*5*
*2*4*6*
1*3*5*7*
*2*4*6*8*
1*3*5*7*9*
Below is the solution to the above problem:
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to print Even Odd Number Pyramid #include <iostream>using namespace std; // function for creating patternvoid Pattern(int n){ // Initialization int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers cout << j; } else { // displaying the stars cout << "*"; } } cout << "\n"; }} // driver codeint main(){ // Get n int n = 5; // Print the pattern Pattern(n); return 0;}
// C program to print Even Odd Number Pyramid #include <stdio.h> // function for creating patternvoid Pattern(int n){ // Initialization int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers printf("%d", j); } else { // displaying the stars printf("*"); } } printf("\n"); }} // driver codeint main(){ // Get n int n = 5; // Print the pattern Pattern(n); return 0;}
// Java program to print above pattern import java.util.Scanner; class Pattern { static void display(int n) { int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers System.out.print(j); } else { // displaying the stars System.out.print("*"); } } System.out.print("\n"); } } // Driver Code public static void main(String[] args) { // Get n int n = 5; // Print the pattern display(n); }}
# Python3 program to print above patterndef display(n): for i in range(1, n + 1): k = i for j in range(1, i + 1): if k % 2 == 0: # Displaying the numbers print(j, end = '') else: # Displaying the stars print('*', end = '') k -= 1 print() # Driver Code # Get nn = 5 # Print the patterndisplay(n) # This code is contributed by SamyuktaSHegde
// C# program to print above patternusing System; class GFG{static void display(int n){ int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers Console.Write(j); } else { // displaying the stars Console.Write("*"); } } Console.Write("\n"); }} // Driver Codepublic static void Main(){ // Get n int n = 5; // Print the pattern display(n);}} // This code is contributed by anuj_67
<?php// php program to print// above pattern function display($n){ // Initialization $i; $j; $k; for($i=1; $i<=$n; $i++) { for($j=1, $k=$i; $j<=$i; $j++, $k--) { if($k%2==0){ // displaying the numbers echo $j;} else{ // displaying the stars echo "*";} } echo "\n"; }} // Driver Code // Get n$n = 5; // Print the patterndisplay($n); ?>
<script> // Javascript program to print Even Odd Number Pyramid // function for creating patternfunction Pattern(n){ // Initialization var i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers document.write( j); } else { // displaying the stars document.write("*"); } } document.write("<br>"); }} // driver code// Get nvar n = 5; // Print the patternPattern(n); // This code is contributed by noob2000.</script>
*
1*
*2*
1*3*
*2*4*
Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant.
inderDuMCA
SamyuktaSHegde
srinam
noob2000
tamanna17122007
pattern-printing
Strings
Strings
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2022"
},
{
"code": null,
"e": 106,
"s": 28,
"text": "Given the total number of rows as n, the task is to print the given pattern. "
},
{
"code": null,
"e": 177,
"s": 106,
"text": "* 1* *2* 1*3* *2*4* 1*3*5* *2*4*6* 1*3*5*7* *2*4*6*8* 1*3*5*7*9* . . "
},
{
"code": null,
"e": 189,
"s": 177,
"text": "Examples: "
},
{
"code": null,
"e": 318,
"s": 189,
"text": "Input: n = 5\nOutput:\n*\n1*\n*2*\n1*3*\n*2*4*\n\nInput: n = 10\nOutput:\n*\n1*\n*2*\n1*3*\n*2*4*\n1*3*5*\n*2*4*6*\n1*3*5*7*\n*2*4*6*8*\n1*3*5*7*9*"
},
{
"code": null,
"e": 364,
"s": 318,
"text": "Below is the solution to the above problem: "
},
{
"code": null,
"e": 368,
"s": 364,
"text": "C++"
},
{
"code": null,
"e": 370,
"s": 368,
"text": "C"
},
{
"code": null,
"e": 375,
"s": 370,
"text": "Java"
},
{
"code": null,
"e": 383,
"s": 375,
"text": "Python3"
},
{
"code": null,
"e": 386,
"s": 383,
"text": "C#"
},
{
"code": null,
"e": 390,
"s": 386,
"text": "PHP"
},
{
"code": null,
"e": 401,
"s": 390,
"text": "Javascript"
},
{
"code": "// CPP program to print Even Odd Number Pyramid #include <iostream>using namespace std; // function for creating patternvoid Pattern(int n){ // Initialization int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers cout << j; } else { // displaying the stars cout << \"*\"; } } cout << \"\\n\"; }} // driver codeint main(){ // Get n int n = 5; // Print the pattern Pattern(n); return 0;}",
"e": 1010,
"s": 401,
"text": null
},
{
"code": "// C program to print Even Odd Number Pyramid #include <stdio.h> // function for creating patternvoid Pattern(int n){ // Initialization int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers printf(\"%d\", j); } else { // displaying the stars printf(\"*\"); } } printf(\"\\n\"); }} // driver codeint main(){ // Get n int n = 5; // Print the pattern Pattern(n); return 0;}",
"e": 1600,
"s": 1010,
"text": null
},
{
"code": "// Java program to print above pattern import java.util.Scanner; class Pattern { static void display(int n) { int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers System.out.print(j); } else { // displaying the stars System.out.print(\"*\"); } } System.out.print(\"\\n\"); } } // Driver Code public static void main(String[] args) { // Get n int n = 5; // Print the pattern display(n); }}",
"e": 2298,
"s": 1600,
"text": null
},
{
"code": "# Python3 program to print above patterndef display(n): for i in range(1, n + 1): k = i for j in range(1, i + 1): if k % 2 == 0: # Displaying the numbers print(j, end = '') else: # Displaying the stars print('*', end = '') k -= 1 print() # Driver Code # Get nn = 5 # Print the patterndisplay(n) # This code is contributed by SamyuktaSHegde",
"e": 2789,
"s": 2298,
"text": null
},
{
"code": "// C# program to print above patternusing System; class GFG{static void display(int n){ int i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers Console.Write(j); } else { // displaying the stars Console.Write(\"*\"); } } Console.Write(\"\\n\"); }} // Driver Codepublic static void Main(){ // Get n int n = 5; // Print the pattern display(n);}} // This code is contributed by anuj_67",
"e": 3417,
"s": 2789,
"text": null
},
{
"code": "<?php// php program to print// above pattern function display($n){ // Initialization $i; $j; $k; for($i=1; $i<=$n; $i++) { for($j=1, $k=$i; $j<=$i; $j++, $k--) { if($k%2==0){ // displaying the numbers echo $j;} else{ // displaying the stars echo \"*\";} } echo \"\\n\"; }} // Driver Code // Get n$n = 5; // Print the patterndisplay($n); ?>",
"e": 3881,
"s": 3417,
"text": null
},
{
"code": "<script> // Javascript program to print Even Odd Number Pyramid // function for creating patternfunction Pattern(n){ // Initialization var i, j, k; for (i = 1; i <= n; i++) { for (j = 1, k = i; j <= i; j++, k--) { if (k % 2 == 0) { // displaying the numbers document.write( j); } else { // displaying the stars document.write(\"*\"); } } document.write(\"<br>\"); }} // driver code// Get nvar n = 5; // Print the patternPattern(n); // This code is contributed by noob2000.</script>",
"e": 4499,
"s": 3881,
"text": null
},
{
"code": null,
"e": 4519,
"s": 4499,
"text": "*\n1*\n*2*\n1*3*\n*2*4*"
},
{
"code": null,
"e": 4652,
"s": 4521,
"text": "Time Complexity: O(n2), where n represents the given input.Auxiliary Space: O(1), no extra space is required, so it is a constant."
},
{
"code": null,
"e": 4663,
"s": 4652,
"text": "inderDuMCA"
},
{
"code": null,
"e": 4678,
"s": 4663,
"text": "SamyuktaSHegde"
},
{
"code": null,
"e": 4685,
"s": 4678,
"text": "srinam"
},
{
"code": null,
"e": 4694,
"s": 4685,
"text": "noob2000"
},
{
"code": null,
"e": 4710,
"s": 4694,
"text": "tamanna17122007"
},
{
"code": null,
"e": 4727,
"s": 4710,
"text": "pattern-printing"
},
{
"code": null,
"e": 4735,
"s": 4727,
"text": "Strings"
},
{
"code": null,
"e": 4743,
"s": 4735,
"text": "Strings"
},
{
"code": null,
"e": 4760,
"s": 4743,
"text": "pattern-printing"
}
] |
Lex Program to print the total characters, white spaces, tabs in the given input file
|
30 Apr, 2019
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the lex program are:
lex abc.l (abc is the file name)
cc lex.yy.c -lfl
./a.out
Let’s see Lex program to print the total characters, white spaces, tabs in the given input file.
Below is the implementation:
/* Lex program to print the total characters, white spaces, tabs in the given input file.*/ %{ int n, w, c; %}% %\n { n++; }[^ \n\t] +{ w++; c = c + yyleng;}.c++;% % int yywrap(void){ return 1;} main(){ extern FILE* yyin; yyin = fopen("input.txt", "r"); yylex(); printf("Line= %d word=%d total char=%d \n", n, w, c);}
Input:
Output:
Lex program
C Programs
Compiler Design
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 248,
"s": 52,
"text": "Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language."
},
{
"code": null,
"e": 296,
"s": 248,
"text": "The commands for executing the lex program are:"
},
{
"code": null,
"e": 355,
"s": 296,
"text": "lex abc.l (abc is the file name)\ncc lex.yy.c -lfl\n./a.out\n"
},
{
"code": null,
"e": 452,
"s": 355,
"text": "Let’s see Lex program to print the total characters, white spaces, tabs in the given input file."
},
{
"code": null,
"e": 481,
"s": 452,
"text": "Below is the implementation:"
},
{
"code": "/* Lex program to print the total characters, white spaces, tabs in the given input file.*/ %{ int n, w, c; %}% %\\n { n++; }[^ \\n\\t] +{ w++; c = c + yyleng;}.c++;% % int yywrap(void){ return 1;} main(){ extern FILE* yyin; yyin = fopen(\"input.txt\", \"r\"); yylex(); printf(\"Line= %d word=%d total char=%d \\n\", n, w, c);}",
"e": 830,
"s": 481,
"text": null
},
{
"code": null,
"e": 837,
"s": 830,
"text": "Input:"
},
{
"code": null,
"e": 845,
"s": 837,
"text": "Output:"
},
{
"code": null,
"e": 857,
"s": 845,
"text": "Lex program"
},
{
"code": null,
"e": 868,
"s": 857,
"text": "C Programs"
},
{
"code": null,
"e": 884,
"s": 868,
"text": "Compiler Design"
},
{
"code": null,
"e": 890,
"s": 884,
"text": "GBlog"
}
] |
How to Replace a Element in Java ArrayList?
|
27 Jul, 2021
To replace an element in Java ArrayList, set() method of java.util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of an ArrayList is zero-based. So, to replace the first element, 0 should be the index passed as a parameter.
Declaration:
public Object set(int index, Object element)
Return Value: The element which is at the specified index
Exception Throws: IndexOutOfBoundsException This occurs when the index is out of range.
index < 0 or index >= size()
Implementation:
Here we will be proposing out 2 examples wherein one of them we will be setting the index within bound and in the other, we will be setting the index out of bounds.
Example 1: Where Index is Within Bound
Java
// Java program to demonstrate set() Method of ArrayList// Where Index is Within Bound // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of Arraylist class ArrayList<String> list = new ArrayList<>(); // Adding elements to the List // using add() method // Custom input elements list.add("A"); list.add("B"); list.add("C"); list.add("D"); // Print all the elements added in the above object System.out.println(list); // 2 is the index of the element "C". //"C" will be replaced by "E" list.set(2, "E"); // Printing the newly updated List System.out.println(list); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console System.out.println(e); } }}
[A, B, C, D]
[A, B, E, D]
Example 2: Where Index is Out of Bound
Java
// Java program to demonstrate set() Method of ArrayList// Where Index is Out of Bound // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of Arraylist class ArrayList<String> list = new ArrayList<>(); // Adding elements to the List // using add() method // Custom input elements list.add("A"); list.add("B");å list.add("C"); list.add("D"); // Print all the elements added in the above object System.out.println(list); // Settijg the element at the 6 th index which // does not exist in our input list object list.set(6); // Printing the newly updated List System.out.println(list); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console System.out.println(e); } }}
Output:
comrade
Java-ArrayList
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 Jul, 2021"
},
{
"code": null,
"e": 384,
"s": 53,
"text": "To replace an element in Java ArrayList, set() method of java.util. An ArrayList class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of an ArrayList is zero-based. So, to replace the first element, 0 should be the index passed as a parameter."
},
{
"code": null,
"e": 397,
"s": 384,
"text": "Declaration:"
},
{
"code": null,
"e": 442,
"s": 397,
"text": "public Object set(int index, Object element)"
},
{
"code": null,
"e": 500,
"s": 442,
"text": "Return Value: The element which is at the specified index"
},
{
"code": null,
"e": 588,
"s": 500,
"text": "Exception Throws: IndexOutOfBoundsException This occurs when the index is out of range."
},
{
"code": null,
"e": 617,
"s": 588,
"text": "index < 0 or index >= size()"
},
{
"code": null,
"e": 633,
"s": 617,
"text": "Implementation:"
},
{
"code": null,
"e": 799,
"s": 633,
"text": "Here we will be proposing out 2 examples wherein one of them we will be setting the index within bound and in the other, we will be setting the index out of bounds. "
},
{
"code": null,
"e": 839,
"s": 799,
"text": "Example 1: Where Index is Within Bound "
},
{
"code": null,
"e": 844,
"s": 839,
"text": "Java"
},
{
"code": "// Java program to demonstrate set() Method of ArrayList// Where Index is Within Bound // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of Arraylist class ArrayList<String> list = new ArrayList<>(); // Adding elements to the List // using add() method // Custom input elements list.add(\"A\"); list.add(\"B\"); list.add(\"C\"); list.add(\"D\"); // Print all the elements added in the above object System.out.println(list); // 2 is the index of the element \"C\". //\"C\" will be replaced by \"E\" list.set(2, \"E\"); // Printing the newly updated List System.out.println(list); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console System.out.println(e); } }}",
"e": 1831,
"s": 844,
"text": null
},
{
"code": null,
"e": 1858,
"s": 1831,
"text": "[A, B, C, D]\n[A, B, E, D]\n"
},
{
"code": null,
"e": 1898,
"s": 1858,
"text": " Example 2: Where Index is Out of Bound"
},
{
"code": null,
"e": 1903,
"s": 1898,
"text": "Java"
},
{
"code": "// Java program to demonstrate set() Method of ArrayList// Where Index is Out of Bound // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of Arraylist class ArrayList<String> list = new ArrayList<>(); // Adding elements to the List // using add() method // Custom input elements list.add(\"A\"); list.add(\"B\");å list.add(\"C\"); list.add(\"D\"); // Print all the elements added in the above object System.out.println(list); // Settijg the element at the 6 th index which // does not exist in our input list object list.set(6); // Printing the newly updated List System.out.println(list); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console System.out.println(e); } }}",
"e": 2917,
"s": 1903,
"text": null
},
{
"code": null,
"e": 2925,
"s": 2917,
"text": "Output:"
},
{
"code": null,
"e": 2933,
"s": 2925,
"text": "comrade"
},
{
"code": null,
"e": 2948,
"s": 2933,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 2965,
"s": 2948,
"text": "Java-Collections"
},
{
"code": null,
"e": 2972,
"s": 2965,
"text": "Picked"
},
{
"code": null,
"e": 2977,
"s": 2972,
"text": "Java"
},
{
"code": null,
"e": 2991,
"s": 2977,
"text": "Java Programs"
},
{
"code": null,
"e": 2996,
"s": 2991,
"text": "Java"
},
{
"code": null,
"e": 3013,
"s": 2996,
"text": "Java-Collections"
}
] |
Different ways to Initialize all members of an array to the same value in C
|
09 Oct, 2018
An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it.
int num[100];
How to declare an array in C?
Data_type array_name[size_of_array];
For example,
float num[10];
Below are some of the different ways in which all elements of an array can be initialized to the same value:
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays.int num[5] = {1, 1, 1, 1, 1};
This will initialize the num array with value 1 at all index.We may also ignore the size of the array:int num[ ] = {1, 1, 1, 1, 1}
The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list.int num[5] = { }; // num = [0, 0, 0, 0, 0]
int num[5] = { 0 }; // num = [0, 0, 0, 0, 0]
Designated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers.[ first . . . last ] = value;int num[5]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}
We may also ignore the size of array:int num[ ]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}
Macros: For initializing a huge array with the same value we can use macros.#include<stdio.h> #define x1 1#define x2 x1, x1#define x4 x2, x2#define x8 x4, x4#define x16 x8, x8#define x32 x16, x16 int main(void){// array declarationint num[] = { x32, x8, x4, x1};int size = sizeof(num)/ sizeof(int); // 32+8+4+1= 45 printf("The size of the array is %d\n", size);printf("The value of element in the array at index 5 is %d ", num[4]); return 0; }Output:The size of the array is 45
The value of element in the array at index 5 is 1
Using For Loop: We can also use for loop to initialize an array with the same value.#include<stdio.h> int main(void){ int size = 6; int val = 1; // array declaration int arr[size]; int i; // initializing array elements for (i = 0; i < size ; i++){ arr[i] = val; } // print array printf("The array is:"); for (i = 0; i < size ; i++){ printf("%d ", arr[i]); } return 0;}Output:The array is:1 1 1 1 1 1
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays.int num[5] = {1, 1, 1, 1, 1};
This will initialize the num array with value 1 at all index.We may also ignore the size of the array:int num[ ] = {1, 1, 1, 1, 1}
The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list.int num[5] = { }; // num = [0, 0, 0, 0, 0]
int num[5] = { 0 }; // num = [0, 0, 0, 0, 0]
int num[5] = {1, 1, 1, 1, 1};
This will initialize the num array with value 1 at all index.We may also ignore the size of the array:
int num[ ] = {1, 1, 1, 1, 1}
The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list.
int num[5] = { }; // num = [0, 0, 0, 0, 0]
int num[5] = { 0 }; // num = [0, 0, 0, 0, 0]
Designated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers.[ first . . . last ] = value;int num[5]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}
We may also ignore the size of array:int num[ ]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}
int num[5]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}
We may also ignore the size of array:
int num[ ]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}
Macros: For initializing a huge array with the same value we can use macros.#include<stdio.h> #define x1 1#define x2 x1, x1#define x4 x2, x2#define x8 x4, x4#define x16 x8, x8#define x32 x16, x16 int main(void){// array declarationint num[] = { x32, x8, x4, x1};int size = sizeof(num)/ sizeof(int); // 32+8+4+1= 45 printf("The size of the array is %d\n", size);printf("The value of element in the array at index 5 is %d ", num[4]); return 0; }Output:The size of the array is 45
The value of element in the array at index 5 is 1
#include<stdio.h> #define x1 1#define x2 x1, x1#define x4 x2, x2#define x8 x4, x4#define x16 x8, x8#define x32 x16, x16 int main(void){// array declarationint num[] = { x32, x8, x4, x1};int size = sizeof(num)/ sizeof(int); // 32+8+4+1= 45 printf("The size of the array is %d\n", size);printf("The value of element in the array at index 5 is %d ", num[4]); return 0; }
The size of the array is 45
The value of element in the array at index 5 is 1
Using For Loop: We can also use for loop to initialize an array with the same value.#include<stdio.h> int main(void){ int size = 6; int val = 1; // array declaration int arr[size]; int i; // initializing array elements for (i = 0; i < size ; i++){ arr[i] = val; } // print array printf("The array is:"); for (i = 0; i < size ; i++){ printf("%d ", arr[i]); } return 0;}Output:The array is:1 1 1 1 1 1
#include<stdio.h> int main(void){ int size = 6; int val = 1; // array declaration int arr[size]; int i; // initializing array elements for (i = 0; i < size ; i++){ arr[i] = val; } // print array printf("The array is:"); for (i = 0; i < size ; i++){ printf("%d ", arr[i]); } return 0;}
The array is:1 1 1 1 1 1
c-array
Picked
Technical Scripter 2018
C Language
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Oct, 2018"
},
{
"code": null,
"e": 224,
"s": 54,
"text": "An array is a collection of data that holds fixed number of values of same type. For example: if you want to store marks of 100 students, you can create an array for it."
},
{
"code": null,
"e": 239,
"s": 224,
"text": "int num[100];\n"
},
{
"code": null,
"e": 269,
"s": 239,
"text": "How to declare an array in C?"
},
{
"code": null,
"e": 308,
"s": 269,
"text": "Data_type array_name[size_of_array];\n"
},
{
"code": null,
"e": 321,
"s": 308,
"text": "For example,"
},
{
"code": null,
"e": 337,
"s": 321,
"text": "float num[10];\n"
},
{
"code": null,
"e": 446,
"s": 337,
"text": "Below are some of the different ways in which all elements of an array can be initialized to the same value:"
},
{
"code": null,
"e": 2383,
"s": 446,
"text": "Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays.int num[5] = {1, 1, 1, 1, 1};\nThis will initialize the num array with value 1 at all index.We may also ignore the size of the array:int num[ ] = {1, 1, 1, 1, 1}\nThe array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list.int num[5] = { }; // num = [0, 0, 0, 0, 0]\nint num[5] = { 0 }; // num = [0, 0, 0, 0, 0]\nDesignated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers.[ first . . . last ] = value;int num[5]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}\nWe may also ignore the size of array:int num[ ]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}\nMacros: For initializing a huge array with the same value we can use macros.#include<stdio.h> #define x1 1#define x2 x1, x1#define x4 x2, x2#define x8 x4, x4#define x16 x8, x8#define x32 x16, x16 int main(void){// array declarationint num[] = { x32, x8, x4, x1};int size = sizeof(num)/ sizeof(int); // 32+8+4+1= 45 printf(\"The size of the array is %d\\n\", size);printf(\"The value of element in the array at index 5 is %d \", num[4]); return 0; }Output:The size of the array is 45\nThe value of element in the array at index 5 is 1\nUsing For Loop: We can also use for loop to initialize an array with the same value.#include<stdio.h> int main(void){ int size = 6; int val = 1; // array declaration int arr[size]; int i; // initializing array elements for (i = 0; i < size ; i++){ arr[i] = val; } // print array printf(\"The array is:\"); for (i = 0; i < size ; i++){ printf(\"%d \", arr[i]); } return 0;}Output:The array is:1 1 1 1 1 1\n"
},
{
"code": null,
"e": 2927,
"s": 2383,
"text": "Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays.int num[5] = {1, 1, 1, 1, 1};\nThis will initialize the num array with value 1 at all index.We may also ignore the size of the array:int num[ ] = {1, 1, 1, 1, 1}\nThe array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list.int num[5] = { }; // num = [0, 0, 0, 0, 0]\nint num[5] = { 0 }; // num = [0, 0, 0, 0, 0]\n"
},
{
"code": null,
"e": 2958,
"s": 2927,
"text": "int num[5] = {1, 1, 1, 1, 1};\n"
},
{
"code": null,
"e": 3061,
"s": 2958,
"text": "This will initialize the num array with value 1 at all index.We may also ignore the size of the array:"
},
{
"code": null,
"e": 3091,
"s": 3061,
"text": "int num[ ] = {1, 1, 1, 1, 1}\n"
},
{
"code": null,
"e": 3211,
"s": 3091,
"text": "The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list."
},
{
"code": null,
"e": 3329,
"s": 3211,
"text": "int num[5] = { }; // num = [0, 0, 0, 0, 0]\nint num[5] = { 0 }; // num = [0, 0, 0, 0, 0]\n"
},
{
"code": null,
"e": 3685,
"s": 3329,
"text": "Designated Initializer: This initializer is used when we want to initialize a range with the same value. This is used only with GCC compilers.[ first . . . last ] = value;int num[5]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}\nWe may also ignore the size of array:int num[ ]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}\n"
},
{
"code": null,
"e": 3759,
"s": 3685,
"text": "int num[5]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}\n"
},
{
"code": null,
"e": 3797,
"s": 3759,
"text": "We may also ignore the size of array:"
},
{
"code": null,
"e": 3872,
"s": 3797,
"text": "int num[ ]={ [0 . . . 4 ] = 3 }; // num = { 3, 3, 3, 3, 3}\n"
},
{
"code": null,
"e": 4445,
"s": 3872,
"text": "Macros: For initializing a huge array with the same value we can use macros.#include<stdio.h> #define x1 1#define x2 x1, x1#define x4 x2, x2#define x8 x4, x4#define x16 x8, x8#define x32 x16, x16 int main(void){// array declarationint num[] = { x32, x8, x4, x1};int size = sizeof(num)/ sizeof(int); // 32+8+4+1= 45 printf(\"The size of the array is %d\\n\", size);printf(\"The value of element in the array at index 5 is %d \", num[4]); return 0; }Output:The size of the array is 45\nThe value of element in the array at index 5 is 1\n"
},
{
"code": "#include<stdio.h> #define x1 1#define x2 x1, x1#define x4 x2, x2#define x8 x4, x4#define x16 x8, x8#define x32 x16, x16 int main(void){// array declarationint num[] = { x32, x8, x4, x1};int size = sizeof(num)/ sizeof(int); // 32+8+4+1= 45 printf(\"The size of the array is %d\\n\", size);printf(\"The value of element in the array at index 5 is %d \", num[4]); return 0; }",
"e": 4857,
"s": 4445,
"text": null
},
{
"code": null,
"e": 4936,
"s": 4857,
"text": "The size of the array is 45\nThe value of element in the array at index 5 is 1\n"
},
{
"code": null,
"e": 5403,
"s": 4936,
"text": "Using For Loop: We can also use for loop to initialize an array with the same value.#include<stdio.h> int main(void){ int size = 6; int val = 1; // array declaration int arr[size]; int i; // initializing array elements for (i = 0; i < size ; i++){ arr[i] = val; } // print array printf(\"The array is:\"); for (i = 0; i < size ; i++){ printf(\"%d \", arr[i]); } return 0;}Output:The array is:1 1 1 1 1 1\n"
},
{
"code": "#include<stdio.h> int main(void){ int size = 6; int val = 1; // array declaration int arr[size]; int i; // initializing array elements for (i = 0; i < size ; i++){ arr[i] = val; } // print array printf(\"The array is:\"); for (i = 0; i < size ; i++){ printf(\"%d \", arr[i]); } return 0;}",
"e": 5754,
"s": 5403,
"text": null
},
{
"code": null,
"e": 5780,
"s": 5754,
"text": "The array is:1 1 1 1 1 1\n"
},
{
"code": null,
"e": 5788,
"s": 5780,
"text": "c-array"
},
{
"code": null,
"e": 5795,
"s": 5788,
"text": "Picked"
},
{
"code": null,
"e": 5819,
"s": 5795,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 5830,
"s": 5819,
"text": "C Language"
},
{
"code": null,
"e": 5849,
"s": 5830,
"text": "Technical Scripter"
}
] |
Greedy Algorithm for Egyptian Fraction
|
21 Feb, 2022
Every positive fraction can be represented as sum of unique unit fractions. A fraction is unit fraction if numerator is 1 and denominator is a positive integer, for example 1/3 is a unit fraction. Such a representation is called Egyptian Fraction as it was used by ancient Egyptians. Following are few examples:
Egyptian Fraction Representation of 2/3 is 1/2 + 1/6
Egyptian Fraction Representation of 6/14 is 1/3 + 1/11 + 1/231
Egyptian Fraction Representation of 12/13 is 1/2 + 1/3 + 1/12 + 1/156
We can generate Egyptian Fractions using Greedy Algorithm. For a given number of the form ‘nr/dr’ where dr > nr, first find the greatest possible unit fraction, then recur for the remaining part. For example, consider 6/14, we first find ceiling of 14/6, i.e., 3. So the first unit fraction becomes 1/3, then recur for (6/14 – 1/3) i.e., 4/42. Below is implementation of above idea.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print a fraction in Egyptian Form using Greedy// Algorithm#include <iostream>using namespace std; void printEgyptian(int nr, int dr){ // If either numerator or denominator is 0 if (dr == 0 || nr == 0) return; // If numerator divides denominator, then simple division // makes the fraction in 1/n form if (dr%nr == 0) { cout << "1/" << dr/nr; return; } // If denominator divides numerator, then the given number // is not fraction if (nr%dr == 0) { cout << nr/dr; return; } // If numerator is more than denominator if (nr > dr) { cout << nr/dr << " + "; printEgyptian(nr%dr, dr); return; } // We reach here dr > nr and dr%nr is non-zero // Find ceiling of dr/nr and print it as first // fraction int n = dr/nr + 1; cout << "1/" << n << " + "; // Recur for remaining part printEgyptian(nr*n-dr, dr*n); } // Driver Programint main(){ int nr = 6, dr = 14; cout << "Egyptian Fraction Representation of " << nr << "/" << dr << " is\n "; printEgyptian(nr, dr); return 0;}
//Java program to print a fraction// in Egyptian Form using Greedy// Algorithm class GFG { static void printEgyptian(int nr, int dr) { // If either numerator or // denominator is 0 if (dr == 0 || nr == 0) { return; } // If numerator divides denominator, // then simple division makes // the fraction in 1/n form if (dr % nr == 0) { System.out.print("1/" + dr / nr); return; } // If denominator divides numerator, // then the given number is not fraction if (nr % dr == 0) { System.out.print(nr / dr); return; } // If numerator is more than denominator if (nr > dr) { System.out.print(nr / dr + " + "); printEgyptian(nr % dr, dr); return; } // We reach here dr > nr and dr%nr // is non-zero. Find ceiling of // dr/nr and print it as first // fraction int n = dr / nr + 1; System.out.print("1/" + n + " + "); // Recur for remaining part printEgyptian(nr * n - dr, dr * n); } // Driver Code public static void main(String[] args) { int nr = 6, dr = 14; System.out.print("Egyptian Fraction Representation of " + nr + "/" + dr + " is\n "); printEgyptian(nr, dr); }} /*This code is contributed by Rajput-Ji*/
# Python3 program to print a fraction# in Egyptian Form using Greedy# Algorithm # import math package to use# ceiling functionimport math # define a function egyptianFraction# which receive parameter nr as# numerator and dr as denominatordef egyptianFraction(nr, dr): print("The Egyptian Fraction " + "Representation of {0}/{1} is". format(nr, dr), end="\n") # empty list ef to store # denominator ef = [] # while loop runs until # fraction becomes 0 i.e, # numerator becomes 0 while nr != 0: # taking ceiling x = math.ceil(dr / nr) # storing value in ef list ef.append(x) # updating new nr and dr nr = x * nr - dr dr = dr * x # printing the values for i in range(len(ef)): if i != len(ef) - 1: print(" 1/{0} +" . format(ef[i]), end = " ") else: print(" 1/{0}" . format(ef[i]), end = " ") # calling the functionegyptianFraction(6, 14) # This code is contributed# by Anubhav Raj Singh
// C# program to print a fraction// in Egyptian Form using Greedy// Algorithmusing System; class GFG{static void printEgyptian(int nr, int dr){ // If either numerator or // denominator is 0 if (dr == 0 || nr == 0) return; // If numerator divides denominator, // then simple division makes // the fraction in 1/n form if (dr % nr == 0) { Console.Write("1/" + dr / nr); return; } // If denominator divides numerator, // then the given number is not fraction if (nr % dr == 0) { Console.Write(nr / dr); return; } // If numerator is more than denominator if (nr > dr) { Console.Write(nr / dr + " + "); printEgyptian(nr % dr, dr); return; } // We reach here dr > nr and dr%nr // is non-zero. Find ceiling of // dr/nr and print it as first // fraction int n = dr / nr + 1; Console.Write("1/" + n + " + "); // Recur for remaining part printEgyptian(nr * n - dr, dr * n);} // Driver Codepublic static void Main(){ int nr = 6, dr = 14; Console.Write( "Egyptian Fraction Representation of " + nr + "/" + dr + " is\n "); printEgyptian(nr, dr);}} // This code is contributed// by Akanksha Rai(Abby_akku)
<?php// PHP program to print a fraction// in Egyptian Form using Greedy// Algorithm function printEgyptian($nr, $dr){ // If either numerator or // denominator is 0 if ($dr == 0 || $nr == 0) return; // If numerator divides denominator, // then simple division makes the // fraction in 1/n form if ($dr % $nr == 0) { echo "1/", (int)$dr / $nr; return; } // If denominator divides numerator, // then the given number is not fraction if ($nr%$dr == 0) { echo (int)($nr / $dr); return; } // If numerator is more than denominator if ($nr > $dr) { echo (int)($nr/$dr), " + "; printEgyptian($nr % $dr, $dr); return; } // We reach here dr > nr and dr%nr is // non-zero. Find ceiling of dr/nr and // print it as first fraction $n = (int)($dr / $nr ) + 1; echo "1/" , $n , " + "; // Recur for remaining part printEgyptian($nr * $n - $dr, $dr * $n);} // Driver Code$nr = 6;$dr = 14;echo "Egyptian Fraction Representation of ", $nr, "/", $dr, " is\n ";printEgyptian($nr, $dr); // This code is contributed by ajit.?>
<script> // Javascript program to print a fraction // in Egyptian Form using Greedy // Algorithm function printEgyptian(nr, dr) { // If either numerator or // denominator is 0 if (dr == 0 || nr == 0) return; // If numerator divides denominator, // then simple division makes // the fraction in 1/n form if (dr % nr == 0) { document.write("1/" + parseInt(dr / nr, 10)); return; } // If denominator divides numerator, // then the given number is not fraction if (nr % dr == 0) { document.write(parseInt(nr / dr, 10)); return; } // If numerator is more than denominator if (nr > dr) { document.write(parseInt(nr / dr, 10) + " + "); printEgyptian(nr % dr, dr); return; } // We reach here dr > nr and dr%nr // is non-zero. Find ceiling of // dr/nr and print it as first // fraction let n = parseInt(dr / nr, 10) + 1; document.write("1/" + n + " + "); // Recur for remaining part printEgyptian(nr * n - dr, dr * n); } let nr = 6, dr = 14; document.write( "Egyptian Fraction Representation of " + nr + "/" + dr + " is\n "); printEgyptian(nr, dr); // This code is contributed by divyeshrabadiya07.</script>
Output:
Egyptian Fraction Representation of 6/14 is
1/3 + 1/11 + 1/231
The recursive solution in Python is as follows:
Python3
import math def getEgyptianFraction(numerator,denominator): str = "" output = getEgyptianFractionUtil(numerator,denominator,[]) for denom in output: str += "1/{0} + ".format(denom); strCopy = str[:-3] #removing the last + sign return strCopy def getEgyptianFractionUtil(numerator,denominator,listOfDenoms): if numerator == 0: return listOfDenoms newDenom = math.ceil(denominator/numerator); #append in output list listOfDenoms.append(newDenom); listOfDenoms = getEgyptianFractionUtil(numerator*newDenom - denominator, newDenom*denominator,listOfDenoms); return listOfDenoms print(getEgyptianFraction(6,14)) # Code contributed by # Mayur Sonowal
The Greedy algorithm works because a fraction is always reduced to a form where denominator is greater than numerator and numerator doesn’t divide denominator. For such reduced forms, the highlighted recursive call is made for reduced numerator. So the recursive calls keep on reducing the numerator till it reaches 1.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Greedy Algorithm for Egyptian Fraction | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersGreedy Algorithm for Egyptian Fraction | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:58•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=8icU9XMEwjs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
References: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/egyptian.htmlThis article is contributed by Shubham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
DhruvitJakasaniya
anubhavraj_08
Akanksha_Rai
Rajput-Ji
jit_t
divyeshrabadiya07
mayursonowal1997
Fraction
Greedy
Mathematical
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 368,
"s": 54,
"text": "Every positive fraction can be represented as sum of unique unit fractions. A fraction is unit fraction if numerator is 1 and denominator is a positive integer, for example 1/3 is a unit fraction. Such a representation is called Egyptian Fraction as it was used by ancient Egyptians. Following are few examples: "
},
{
"code": null,
"e": 554,
"s": 368,
"text": "Egyptian Fraction Representation of 2/3 is 1/2 + 1/6\nEgyptian Fraction Representation of 6/14 is 1/3 + 1/11 + 1/231\nEgyptian Fraction Representation of 12/13 is 1/2 + 1/3 + 1/12 + 1/156"
},
{
"code": null,
"e": 938,
"s": 554,
"text": "We can generate Egyptian Fractions using Greedy Algorithm. For a given number of the form ‘nr/dr’ where dr > nr, first find the greatest possible unit fraction, then recur for the remaining part. For example, consider 6/14, we first find ceiling of 14/6, i.e., 3. So the first unit fraction becomes 1/3, then recur for (6/14 – 1/3) i.e., 4/42. Below is implementation of above idea. "
},
{
"code": null,
"e": 942,
"s": 938,
"text": "C++"
},
{
"code": null,
"e": 947,
"s": 942,
"text": "Java"
},
{
"code": null,
"e": 955,
"s": 947,
"text": "Python3"
},
{
"code": null,
"e": 958,
"s": 955,
"text": "C#"
},
{
"code": null,
"e": 962,
"s": 958,
"text": "PHP"
},
{
"code": null,
"e": 973,
"s": 962,
"text": "Javascript"
},
{
"code": "// C++ program to print a fraction in Egyptian Form using Greedy// Algorithm#include <iostream>using namespace std; void printEgyptian(int nr, int dr){ // If either numerator or denominator is 0 if (dr == 0 || nr == 0) return; // If numerator divides denominator, then simple division // makes the fraction in 1/n form if (dr%nr == 0) { cout << \"1/\" << dr/nr; return; } // If denominator divides numerator, then the given number // is not fraction if (nr%dr == 0) { cout << nr/dr; return; } // If numerator is more than denominator if (nr > dr) { cout << nr/dr << \" + \"; printEgyptian(nr%dr, dr); return; } // We reach here dr > nr and dr%nr is non-zero // Find ceiling of dr/nr and print it as first // fraction int n = dr/nr + 1; cout << \"1/\" << n << \" + \"; // Recur for remaining part printEgyptian(nr*n-dr, dr*n); } // Driver Programint main(){ int nr = 6, dr = 14; cout << \"Egyptian Fraction Representation of \" << nr << \"/\" << dr << \" is\\n \"; printEgyptian(nr, dr); return 0;}",
"e": 2106,
"s": 973,
"text": null
},
{
"code": "//Java program to print a fraction// in Egyptian Form using Greedy// Algorithm class GFG { static void printEgyptian(int nr, int dr) { // If either numerator or // denominator is 0 if (dr == 0 || nr == 0) { return; } // If numerator divides denominator, // then simple division makes // the fraction in 1/n form if (dr % nr == 0) { System.out.print(\"1/\" + dr / nr); return; } // If denominator divides numerator, // then the given number is not fraction if (nr % dr == 0) { System.out.print(nr / dr); return; } // If numerator is more than denominator if (nr > dr) { System.out.print(nr / dr + \" + \"); printEgyptian(nr % dr, dr); return; } // We reach here dr > nr and dr%nr // is non-zero. Find ceiling of // dr/nr and print it as first // fraction int n = dr / nr + 1; System.out.print(\"1/\" + n + \" + \"); // Recur for remaining part printEgyptian(nr * n - dr, dr * n); } // Driver Code public static void main(String[] args) { int nr = 6, dr = 14; System.out.print(\"Egyptian Fraction Representation of \" + nr + \"/\" + dr + \" is\\n \"); printEgyptian(nr, dr); }} /*This code is contributed by Rajput-Ji*/",
"e": 3519,
"s": 2106,
"text": null
},
{
"code": "# Python3 program to print a fraction# in Egyptian Form using Greedy# Algorithm # import math package to use# ceiling functionimport math # define a function egyptianFraction# which receive parameter nr as# numerator and dr as denominatordef egyptianFraction(nr, dr): print(\"The Egyptian Fraction \" + \"Representation of {0}/{1} is\". format(nr, dr), end=\"\\n\") # empty list ef to store # denominator ef = [] # while loop runs until # fraction becomes 0 i.e, # numerator becomes 0 while nr != 0: # taking ceiling x = math.ceil(dr / nr) # storing value in ef list ef.append(x) # updating new nr and dr nr = x * nr - dr dr = dr * x # printing the values for i in range(len(ef)): if i != len(ef) - 1: print(\" 1/{0} +\" . format(ef[i]), end = \" \") else: print(\" 1/{0}\" . format(ef[i]), end = \" \") # calling the functionegyptianFraction(6, 14) # This code is contributed# by Anubhav Raj Singh",
"e": 4587,
"s": 3519,
"text": null
},
{
"code": "// C# program to print a fraction// in Egyptian Form using Greedy// Algorithmusing System; class GFG{static void printEgyptian(int nr, int dr){ // If either numerator or // denominator is 0 if (dr == 0 || nr == 0) return; // If numerator divides denominator, // then simple division makes // the fraction in 1/n form if (dr % nr == 0) { Console.Write(\"1/\" + dr / nr); return; } // If denominator divides numerator, // then the given number is not fraction if (nr % dr == 0) { Console.Write(nr / dr); return; } // If numerator is more than denominator if (nr > dr) { Console.Write(nr / dr + \" + \"); printEgyptian(nr % dr, dr); return; } // We reach here dr > nr and dr%nr // is non-zero. Find ceiling of // dr/nr and print it as first // fraction int n = dr / nr + 1; Console.Write(\"1/\" + n + \" + \"); // Recur for remaining part printEgyptian(nr * n - dr, dr * n);} // Driver Codepublic static void Main(){ int nr = 6, dr = 14; Console.Write( \"Egyptian Fraction Representation of \" + nr + \"/\" + dr + \" is\\n \"); printEgyptian(nr, dr);}} // This code is contributed// by Akanksha Rai(Abby_akku)",
"e": 5860,
"s": 4587,
"text": null
},
{
"code": "<?php// PHP program to print a fraction// in Egyptian Form using Greedy// Algorithm function printEgyptian($nr, $dr){ // If either numerator or // denominator is 0 if ($dr == 0 || $nr == 0) return; // If numerator divides denominator, // then simple division makes the // fraction in 1/n form if ($dr % $nr == 0) { echo \"1/\", (int)$dr / $nr; return; } // If denominator divides numerator, // then the given number is not fraction if ($nr%$dr == 0) { echo (int)($nr / $dr); return; } // If numerator is more than denominator if ($nr > $dr) { echo (int)($nr/$dr), \" + \"; printEgyptian($nr % $dr, $dr); return; } // We reach here dr > nr and dr%nr is // non-zero. Find ceiling of dr/nr and // print it as first fraction $n = (int)($dr / $nr ) + 1; echo \"1/\" , $n , \" + \"; // Recur for remaining part printEgyptian($nr * $n - $dr, $dr * $n);} // Driver Code$nr = 6;$dr = 14;echo \"Egyptian Fraction Representation of \", $nr, \"/\", $dr, \" is\\n \";printEgyptian($nr, $dr); // This code is contributed by ajit.?>",
"e": 7022,
"s": 5860,
"text": null
},
{
"code": "<script> // Javascript program to print a fraction // in Egyptian Form using Greedy // Algorithm function printEgyptian(nr, dr) { // If either numerator or // denominator is 0 if (dr == 0 || nr == 0) return; // If numerator divides denominator, // then simple division makes // the fraction in 1/n form if (dr % nr == 0) { document.write(\"1/\" + parseInt(dr / nr, 10)); return; } // If denominator divides numerator, // then the given number is not fraction if (nr % dr == 0) { document.write(parseInt(nr / dr, 10)); return; } // If numerator is more than denominator if (nr > dr) { document.write(parseInt(nr / dr, 10) + \" + \"); printEgyptian(nr % dr, dr); return; } // We reach here dr > nr and dr%nr // is non-zero. Find ceiling of // dr/nr and print it as first // fraction let n = parseInt(dr / nr, 10) + 1; document.write(\"1/\" + n + \" + \"); // Recur for remaining part printEgyptian(nr * n - dr, dr * n); } let nr = 6, dr = 14; document.write( \"Egyptian Fraction Representation of \" + nr + \"/\" + dr + \" is\\n \"); printEgyptian(nr, dr); // This code is contributed by divyeshrabadiya07.</script>",
"e": 8436,
"s": 7022,
"text": null
},
{
"code": null,
"e": 8445,
"s": 8436,
"text": "Output: "
},
{
"code": null,
"e": 8510,
"s": 8445,
"text": "Egyptian Fraction Representation of 6/14 is\n 1/3 + 1/11 + 1/231 "
},
{
"code": null,
"e": 8558,
"s": 8510,
"text": "The recursive solution in Python is as follows:"
},
{
"code": null,
"e": 8566,
"s": 8558,
"text": "Python3"
},
{
"code": "import math def getEgyptianFraction(numerator,denominator): str = \"\" output = getEgyptianFractionUtil(numerator,denominator,[]) for denom in output: str += \"1/{0} + \".format(denom); strCopy = str[:-3] #removing the last + sign return strCopy def getEgyptianFractionUtil(numerator,denominator,listOfDenoms): if numerator == 0: return listOfDenoms newDenom = math.ceil(denominator/numerator); #append in output list listOfDenoms.append(newDenom); listOfDenoms = getEgyptianFractionUtil(numerator*newDenom - denominator, newDenom*denominator,listOfDenoms); return listOfDenoms print(getEgyptianFraction(6,14)) # Code contributed by # Mayur Sonowal",
"e": 9301,
"s": 8566,
"text": null
},
{
"code": null,
"e": 9622,
"s": 9301,
"text": "The Greedy algorithm works because a fraction is always reduced to a form where denominator is greater than numerator and numerator doesn’t divide denominator. For such reduced forms, the highlighted recursive call is made for reduced numerator. So the recursive calls keep on reducing the numerator till it reaches 1. "
},
{
"code": null,
"e": 9631,
"s": 9622,
"text": "Chapters"
},
{
"code": null,
"e": 9658,
"s": 9631,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 9708,
"s": 9658,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 9731,
"s": 9708,
"text": "captions off, selected"
},
{
"code": null,
"e": 9739,
"s": 9731,
"text": "English"
},
{
"code": null,
"e": 9763,
"s": 9739,
"text": "This is a modal window."
},
{
"code": null,
"e": 9832,
"s": 9763,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 9854,
"s": 9832,
"text": "End of dialog window."
},
{
"code": null,
"e": 10748,
"s": 9854,
"text": "Greedy Algorithm for Egyptian Fraction | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersGreedy Algorithm for Egyptian Fraction | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:58•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=8icU9XMEwjs\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 10999,
"s": 10748,
"text": "References: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fractions/egyptian.htmlThis article is contributed by Shubham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 11019,
"s": 11001,
"text": "DhruvitJakasaniya"
},
{
"code": null,
"e": 11033,
"s": 11019,
"text": "anubhavraj_08"
},
{
"code": null,
"e": 11046,
"s": 11033,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 11056,
"s": 11046,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11062,
"s": 11056,
"text": "jit_t"
},
{
"code": null,
"e": 11080,
"s": 11062,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 11097,
"s": 11080,
"text": "mayursonowal1997"
},
{
"code": null,
"e": 11106,
"s": 11097,
"text": "Fraction"
},
{
"code": null,
"e": 11113,
"s": 11106,
"text": "Greedy"
},
{
"code": null,
"e": 11126,
"s": 11113,
"text": "Mathematical"
},
{
"code": null,
"e": 11133,
"s": 11126,
"text": "Greedy"
},
{
"code": null,
"e": 11146,
"s": 11133,
"text": "Mathematical"
}
] |
Check whether two Strings are Anagram of each other using HashMap in Java - GeeksforGeeks
|
01 Aug, 2019
Write a function to check whether two given strings are an Anagram of each other or not.
An anagram of a string is another string that contains the same characters, only the order of characters can be different.
For example, “abcd” and “dabc” are an Anagram of each other.
Approach: Hashmaps can also be used to find if any two given strings are anagrams or not, by mapping the characters of each string to individual hashmaps and comparing them together.
Implementation:
// Java code to check whether two strings// are Anagram or not using HashMap import java.io.*;import java.util.*; class GFG { // Function to check whether two strings // are an anagram of each other static boolean areAnagram(String str1, String str2) { HashMap<Character, Integer> hmap1 = new HashMap<Character, Integer>(); HashMap<Character, Integer> hmap2 = new HashMap<Character, Integer>(); char arr1[] = str1.toCharArray(); char arr2[] = str2.toCharArray(); // Mapping first string for (int i = 0; i < arr1.length; i++) { if (hmap1.get(arr1[i]) == null) { hmap1.put(arr1[i], 1); } else { Integer c = (int)hmap1.get(arr1[i]); hmap1.put(arr1[i], ++c); } } // Mapping second String for (int j = 0; j < arr2.length; j++) { if (hmap2.get(arr2[j]) == null) hmap2.put(arr2[j], 1); else { Integer d = (int)hmap2.get(arr2[j]); hmap2.put(arr2[j], ++d); } } if (hmap1.equals(hmap2)) return true; else return false; } // Test function public static void test(String str1, String str2) { System.out.println("Strings to be checked are:\n" + str1 + "\n" + str2 + "\n"); // Find the result if (areAnagram(str1, str2)) System.out.println("The two strings are " + "anagrams of each other\n"); else System.out.println("The two strings are not" + " anagrams of each other\n"); } // Driver program public static void main(String args[]) { // Get the Strings String str1 = "geeksforgeeks"; String str2 = "forgeeksgeeks"; // Test the Strings test(str1, str2); // Get the Strings str1 = "geeksforgeeks"; str2 = "geeks"; // Test the Strings test(str1, str2); }}
Strings to be checked are:
geeksforgeeks
forgeeksgeeks
The two strings are anagrams of each other
Strings to be checked are:
geeksforgeeks
geeks
The two strings are not anagram of each other
Related Article: Check whether two strings are anagram of each other
anagram
Java-HashMap
Java-Strings
Java
Java-Strings
Java
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Collections in Java
Overriding in Java
|
[
{
"code": null,
"e": 24222,
"s": 24194,
"text": "\n01 Aug, 2019"
},
{
"code": null,
"e": 24311,
"s": 24222,
"text": "Write a function to check whether two given strings are an Anagram of each other or not."
},
{
"code": null,
"e": 24434,
"s": 24311,
"text": "An anagram of a string is another string that contains the same characters, only the order of characters can be different."
},
{
"code": null,
"e": 24495,
"s": 24434,
"text": "For example, “abcd” and “dabc” are an Anagram of each other."
},
{
"code": null,
"e": 24678,
"s": 24495,
"text": "Approach: Hashmaps can also be used to find if any two given strings are anagrams or not, by mapping the characters of each string to individual hashmaps and comparing them together."
},
{
"code": null,
"e": 24694,
"s": 24678,
"text": "Implementation:"
},
{
"code": "// Java code to check whether two strings// are Anagram or not using HashMap import java.io.*;import java.util.*; class GFG { // Function to check whether two strings // are an anagram of each other static boolean areAnagram(String str1, String str2) { HashMap<Character, Integer> hmap1 = new HashMap<Character, Integer>(); HashMap<Character, Integer> hmap2 = new HashMap<Character, Integer>(); char arr1[] = str1.toCharArray(); char arr2[] = str2.toCharArray(); // Mapping first string for (int i = 0; i < arr1.length; i++) { if (hmap1.get(arr1[i]) == null) { hmap1.put(arr1[i], 1); } else { Integer c = (int)hmap1.get(arr1[i]); hmap1.put(arr1[i], ++c); } } // Mapping second String for (int j = 0; j < arr2.length; j++) { if (hmap2.get(arr2[j]) == null) hmap2.put(arr2[j], 1); else { Integer d = (int)hmap2.get(arr2[j]); hmap2.put(arr2[j], ++d); } } if (hmap1.equals(hmap2)) return true; else return false; } // Test function public static void test(String str1, String str2) { System.out.println(\"Strings to be checked are:\\n\" + str1 + \"\\n\" + str2 + \"\\n\"); // Find the result if (areAnagram(str1, str2)) System.out.println(\"The two strings are \" + \"anagrams of each other\\n\"); else System.out.println(\"The two strings are not\" + \" anagrams of each other\\n\"); } // Driver program public static void main(String args[]) { // Get the Strings String str1 = \"geeksforgeeks\"; String str2 = \"forgeeksgeeks\"; // Test the Strings test(str1, str2); // Get the Strings str1 = \"geeksforgeeks\"; str2 = \"geeks\"; // Test the Strings test(str1, str2); }}",
"e": 26814,
"s": 24694,
"text": null
},
{
"code": null,
"e": 27009,
"s": 26814,
"text": "Strings to be checked are:\ngeeksforgeeks\nforgeeksgeeks\n\nThe two strings are anagrams of each other\n\nStrings to be checked are:\ngeeksforgeeks\ngeeks\n\nThe two strings are not anagram of each other\n"
},
{
"code": null,
"e": 27078,
"s": 27009,
"text": "Related Article: Check whether two strings are anagram of each other"
},
{
"code": null,
"e": 27086,
"s": 27078,
"text": "anagram"
},
{
"code": null,
"e": 27099,
"s": 27086,
"text": "Java-HashMap"
},
{
"code": null,
"e": 27112,
"s": 27099,
"text": "Java-Strings"
},
{
"code": null,
"e": 27117,
"s": 27112,
"text": "Java"
},
{
"code": null,
"e": 27130,
"s": 27117,
"text": "Java-Strings"
},
{
"code": null,
"e": 27135,
"s": 27130,
"text": "Java"
},
{
"code": null,
"e": 27143,
"s": 27135,
"text": "anagram"
},
{
"code": null,
"e": 27241,
"s": 27143,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27250,
"s": 27241,
"text": "Comments"
},
{
"code": null,
"e": 27263,
"s": 27250,
"text": "Old Comments"
},
{
"code": null,
"e": 27314,
"s": 27263,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27333,
"s": 27314,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27365,
"s": 27333,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27383,
"s": 27365,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27403,
"s": 27383,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27435,
"s": 27403,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27459,
"s": 27435,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27478,
"s": 27459,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 27498,
"s": 27478,
"text": "Collections in Java"
}
] |
GATE | GATE-CS-2009 | Question 60 - GeeksforGeeks
|
28 Jun, 2021
Let R and S be relational schemes such that R={a,b,c} and S={c}. Now consider the following queries on the database:
IV) SELECT R.a, R.b
FROM R,S
WHERE R.c=S.c
Which of the above queries are equivalent?(A) I and II(B) I and III(C) II and IV(D) III and IVAnswer: (A)Explanation: I and II describe the division operator in Relational Algebra and Tuple Relational Calculus respectively. See Page 3 of this and slide numbers 9,10 of this for more details.Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2006 | Question 49
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2019 | Question 27
GATE | GATE-CS-2016 (Set 1) | Question 65
Compaction in Operating System
|
[
{
"code": null,
"e": 24492,
"s": 24464,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24609,
"s": 24492,
"text": "Let R and S be relational schemes such that R={a,b,c} and S={c}. Now consider the following queries on the database:"
},
{
"code": null,
"e": 24671,
"s": 24609,
"text": "IV) SELECT R.a, R.b\n FROM R,S\n WHERE R.c=S.c"
},
{
"code": null,
"e": 24984,
"s": 24671,
"text": "Which of the above queries are equivalent?(A) I and II(B) I and III(C) II and IV(D) III and IVAnswer: (A)Explanation: I and II describe the division operator in Relational Algebra and Tuple Relational Calculus respectively. See Page 3 of this and slide numbers 9,10 of this for more details.Quiz of this Question"
},
{
"code": null,
"e": 24997,
"s": 24984,
"text": "GATE-CS-2009"
},
{
"code": null,
"e": 25015,
"s": 24997,
"text": "GATE-GATE-CS-2009"
},
{
"code": null,
"e": 25020,
"s": 25015,
"text": "GATE"
},
{
"code": null,
"e": 25118,
"s": 25020,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25152,
"s": 25118,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25194,
"s": 25152,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25228,
"s": 25194,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 25261,
"s": 25228,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25295,
"s": 25261,
"text": "GATE | GATE-CS-2006 | Question 49"
},
{
"code": null,
"e": 25328,
"s": 25295,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25362,
"s": 25328,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25396,
"s": 25362,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 25438,
"s": 25396,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
}
] |
Hibernate - ORM Overview
|
JDBC stands for Java Database Connectivity. It provides a set of Java API for accessing the relational databases from Java program. These Java APIs enables Java programs to execute SQL statements and interact with any SQL compliant database.
JDBC provides a flexible architecture to write a database independent application that can run on different platforms and interact with different DBMS without any modification.
Clean and simple SQL processing
Good performance with large data
Very good for small applications
Simple syntax so easy to learn
Complex if it is used in large projects
Large programming overhead
No encapsulation
Hard to implement MVC concept
Query is DBMS specific
When we work with an object-oriented system, there is a mismatch between the object model and the relational database. RDBMSs represent data in a tabular format whereas object-oriented languages, such as Java or C# represent it as an interconnected graph of objects.
Consider the following Java Class with proper constructors and associated public function −
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;
public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {
return last_name;
}
public int getSalary() {
return salary;
}
}
Consider the above objects are to be stored and retrieved into the following RDBMS table −
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
First problem, what if we need to modify the design of our database after having developed a few pages or our application? Second, loading and storing objects in a relational database exposes us to the following five mismatch problems −
Granularity
Sometimes you will have an object model, which has more classes than the number of corresponding tables in the database.
Inheritance
RDBMSs do not define anything similar to Inheritance, which is a natural paradigm in object-oriented programming languages.
Identity
An RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b)).
Associations
Object-oriented languages represent associations using object references whereas an RDBMS represents an association as a foreign key column.
Navigation
The ways you access objects in Java and in RDBMS are fundamentally different.
The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.
ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C#, etc.
An ORM system has the following advantages over plain JDBC −
An ORM solution consists of the following four entities −
There are several persistent frameworks and ORM options in Java. A persistent framework is an ORM service that stores and retrieves objects into a relational database.
Enterprise JavaBeans Entity Beans
Java Data Objects
Castor
TopLink
Spring DAO
Hibernate
And many more
108 Lectures
11 hours
Chaand Sheikh
65 Lectures
5 hours
Karthikeya T
39 Lectures
4.5 hours
TELCOMA Global
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2305,
"s": 2063,
"text": "JDBC stands for Java Database Connectivity. It provides a set of Java API for accessing the relational databases from Java program. These Java APIs enables Java programs to execute SQL statements and interact with any SQL compliant database."
},
{
"code": null,
"e": 2482,
"s": 2305,
"text": "JDBC provides a flexible architecture to write a database independent application that can run on different platforms and interact with different DBMS without any modification."
},
{
"code": null,
"e": 2514,
"s": 2482,
"text": "Clean and simple SQL processing"
},
{
"code": null,
"e": 2547,
"s": 2514,
"text": "Good performance with large data"
},
{
"code": null,
"e": 2580,
"s": 2547,
"text": "Very good for small applications"
},
{
"code": null,
"e": 2611,
"s": 2580,
"text": "Simple syntax so easy to learn"
},
{
"code": null,
"e": 2651,
"s": 2611,
"text": "Complex if it is used in large projects"
},
{
"code": null,
"e": 2678,
"s": 2651,
"text": "Large programming overhead"
},
{
"code": null,
"e": 2695,
"s": 2678,
"text": "No encapsulation"
},
{
"code": null,
"e": 2725,
"s": 2695,
"text": "Hard to implement MVC concept"
},
{
"code": null,
"e": 2748,
"s": 2725,
"text": "Query is DBMS specific"
},
{
"code": null,
"e": 3015,
"s": 2748,
"text": "When we work with an object-oriented system, there is a mismatch between the object model and the relational database. RDBMSs represent data in a tabular format whereas object-oriented languages, such as Java or C# represent it as an interconnected graph of objects."
},
{
"code": null,
"e": 3107,
"s": 3015,
"text": "Consider the following Java Class with proper constructors and associated public function −"
},
{
"code": null,
"e": 3662,
"s": 3107,
"text": "public class Employee {\n private int id;\n private String first_name; \n private String last_name; \n private int salary; \n\n public Employee() {}\n public Employee(String fname, String lname, int salary) {\n this.first_name = fname;\n this.last_name = lname;\n this.salary = salary;\n }\n \n public int getId() {\n return id;\n }\n \n public String getFirstName() {\n return first_name;\n }\n \n public String getLastName() {\n return last_name;\n }\n \n public int getSalary() {\n return salary;\n }\n}"
},
{
"code": null,
"e": 3753,
"s": 3662,
"text": "Consider the above objects are to be stored and retrieved into the following RDBMS table −"
},
{
"code": null,
"e": 3948,
"s": 3753,
"text": "create table EMPLOYEE (\n id INT NOT NULL auto_increment,\n first_name VARCHAR(20) default NULL,\n last_name VARCHAR(20) default NULL,\n salary INT default NULL,\n PRIMARY KEY (id)\n);"
},
{
"code": null,
"e": 4185,
"s": 3948,
"text": "First problem, what if we need to modify the design of our database after having developed a few pages or our application? Second, loading and storing objects in a relational database exposes us to the following five mismatch problems −"
},
{
"code": null,
"e": 4197,
"s": 4185,
"text": "Granularity"
},
{
"code": null,
"e": 4318,
"s": 4197,
"text": "Sometimes you will have an object model, which has more classes than the number of corresponding tables in the database."
},
{
"code": null,
"e": 4330,
"s": 4318,
"text": "Inheritance"
},
{
"code": null,
"e": 4454,
"s": 4330,
"text": "RDBMSs do not define anything similar to Inheritance, which is a natural paradigm in object-oriented programming languages."
},
{
"code": null,
"e": 4463,
"s": 4454,
"text": "Identity"
},
{
"code": null,
"e": 4617,
"s": 4463,
"text": "An RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b))."
},
{
"code": null,
"e": 4630,
"s": 4617,
"text": "Associations"
},
{
"code": null,
"e": 4771,
"s": 4630,
"text": "Object-oriented languages represent associations using object references whereas an RDBMS represents an association as a foreign key column."
},
{
"code": null,
"e": 4782,
"s": 4771,
"text": "Navigation"
},
{
"code": null,
"e": 4860,
"s": 4782,
"text": "The ways you access objects in Java and in RDBMS are fundamentally different."
},
{
"code": null,
"e": 4958,
"s": 4860,
"text": "The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches."
},
{
"code": null,
"e": 5146,
"s": 4958,
"text": "ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C#, etc."
},
{
"code": null,
"e": 5207,
"s": 5146,
"text": "An ORM system has the following advantages over plain JDBC −"
},
{
"code": null,
"e": 5265,
"s": 5207,
"text": "An ORM solution consists of the following four entities −"
},
{
"code": null,
"e": 5433,
"s": 5265,
"text": "There are several persistent frameworks and ORM options in Java. A persistent framework is an ORM service that stores and retrieves objects into a relational database."
},
{
"code": null,
"e": 5467,
"s": 5433,
"text": "Enterprise JavaBeans Entity Beans"
},
{
"code": null,
"e": 5485,
"s": 5467,
"text": "Java Data Objects"
},
{
"code": null,
"e": 5492,
"s": 5485,
"text": "Castor"
},
{
"code": null,
"e": 5500,
"s": 5492,
"text": "TopLink"
},
{
"code": null,
"e": 5511,
"s": 5500,
"text": "Spring DAO"
},
{
"code": null,
"e": 5521,
"s": 5511,
"text": "Hibernate"
},
{
"code": null,
"e": 5535,
"s": 5521,
"text": "And many more"
},
{
"code": null,
"e": 5570,
"s": 5535,
"text": "\n 108 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 5585,
"s": 5570,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5618,
"s": 5585,
"text": "\n 65 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5632,
"s": 5618,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5667,
"s": 5632,
"text": "\n 39 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5683,
"s": 5667,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5690,
"s": 5683,
"text": " Print"
},
{
"code": null,
"e": 5701,
"s": 5690,
"text": " Add Notes"
}
] |
H2 Database - Select
|
Select command is used to fetch record data from a table or multiple tables. If we design a select query, then it returns data in the form of result table called result sets.
The basic syntax of SELECT statement is as follows −
SELECT [ TOP term ] [ DISTINCT | ALL ] selectExpression [,...]
FROM tableExpression [,...] [ WHERE expression ]
[ GROUP BY expression [,...] ] [ HAVING expression ]
[ { UNION [ ALL ] | MINUS | EXCEPT | INTERSECT } select ] [ ORDER BY order [,...] ]
[ [ LIMIT expression ] [ OFFSET expression ] [ SAMPLE_SIZE rowCountInt ] ]
[ FOR UPDATE ]
To fetch all the available fields, use the following syntax.
SELECT * FROM table_name;
Consider the CUSTOMER table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
To get the customer table along with the given data, execute the following queries.
CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address varchar(20),
salary number);
INSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000);
INSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500);
INSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000);
INSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500);
INSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500);
INSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500);
INSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000);
The following command is an example, which would fetch ID, Name and Salary fields of the customers available in the CUSTOMER table.
SELECT ID, NAME, SALARY FROM CUSTOMERS;
The above command produces the following result.
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
Use the following query to fetch all the fields of CUSTOMERS table.
SQL> SELECT * FROM CUSTOMERS;
The above query produces the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
14 Lectures
1 hours
Mahesh Kumar
100 Lectures
9.5 hours
Hari Om Singh
108 Lectures
8 hours
Pavan Lalwani
10 Lectures
1 hours
Deepti Trivedi
20 Lectures
2 hours
Deepti Trivedi
14 Lectures
1 hours
Deepti Trivedi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2282,
"s": 2107,
"text": "Select command is used to fetch record data from a table or multiple tables. If we design a select query, then it returns data in the form of result table called result sets."
},
{
"code": null,
"e": 2335,
"s": 2282,
"text": "The basic syntax of SELECT statement is as follows −"
},
{
"code": null,
"e": 2680,
"s": 2335,
"text": "SELECT [ TOP term ] [ DISTINCT | ALL ] selectExpression [,...] \nFROM tableExpression [,...] [ WHERE expression ] \n[ GROUP BY expression [,...] ] [ HAVING expression ] \n[ { UNION [ ALL ] | MINUS | EXCEPT | INTERSECT } select ] [ ORDER BY order [,...] ] \n[ [ LIMIT expression ] [ OFFSET expression ] [ SAMPLE_SIZE rowCountInt ] ] \n[ FOR UPDATE ]\n"
},
{
"code": null,
"e": 2741,
"s": 2680,
"text": "To fetch all the available fields, use the following syntax."
},
{
"code": null,
"e": 2768,
"s": 2741,
"text": "SELECT * FROM table_name;\n"
},
{
"code": null,
"e": 2827,
"s": 2768,
"text": "Consider the CUSTOMER table having the following records −"
},
{
"code": null,
"e": 3356,
"s": 2827,
"text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n"
},
{
"code": null,
"e": 3440,
"s": 3356,
"text": "To get the customer table along with the given data, execute the following queries."
},
{
"code": null,
"e": 3990,
"s": 3440,
"text": "CREATE TABLE CUSTOMER (id number, name varchar(20), age number, address varchar(20), \nsalary number); \n\nINSERT into CUSTOMER values (1, 'Ramesh', 32, 'Ahmedabad', 2000); \nINSERT into CUSTOMER values (2, 'Khilan', 25, 'Delhi', 1500); \nINSERT into CUSTOMER values (3, 'kaushik', 23, 'Kota', 2000); \nINSERT into CUSTOMER values (4, 'Chaitali', 25, 'Mumbai', 6500); \nINSERT into CUSTOMER values (5, 'Hardik', 27, 'Bhopal', 8500); \nINSERT into CUSTOMER values (6, 'Komal', 22, 'MP', 4500); \nINSERT into CUSTOMER values (7, 'Muffy', 24, 'Indore', 10000);"
},
{
"code": null,
"e": 4122,
"s": 3990,
"text": "The following command is an example, which would fetch ID, Name and Salary fields of the customers available in the CUSTOMER table."
},
{
"code": null,
"e": 4162,
"s": 4122,
"text": "SELECT ID, NAME, SALARY FROM CUSTOMERS;"
},
{
"code": null,
"e": 4211,
"s": 4162,
"text": "The above command produces the following result."
},
{
"code": null,
"e": 4542,
"s": 4211,
"text": "+----+----------+----------+ \n| ID | NAME | SALARY | \n+----+----------+----------+ \n| 1 | Ramesh | 2000.00 | \n| 2 | Khilan | 1500.00 | \n| 3 | kaushik | 2000.00 | \n| 4 | Chaitali | 6500.00 | \n| 5 | Hardik | 8500.00 | \n| 6 | Komal | 4500.00 | \n| 7 | Muffy | 10000.00 | \n+----+----------+----------+ \n"
},
{
"code": null,
"e": 4610,
"s": 4542,
"text": "Use the following query to fetch all the fields of CUSTOMERS table."
},
{
"code": null,
"e": 4640,
"s": 4610,
"text": "SQL> SELECT * FROM CUSTOMERS;"
},
{
"code": null,
"e": 4688,
"s": 4640,
"text": "The above query produces the following result −"
},
{
"code": null,
"e": 5217,
"s": 4688,
"text": "+----+----------+-----+-----------+----------+ \n| ID | NAME | AGE | ADDRESS | SALARY | \n+----+----------+-----+-----------+----------+ \n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | \n| 2 | Khilan | 25 | Delhi | 1500.00 | \n| 3 | kaushik | 23 | Kota | 2000.00 | \n| 4 | Chaitali | 25 | Mumbai | 6500.00 | \n| 5 | Hardik | 27 | Bhopal | 8500.00 | \n| 6 | Komal | 22 | MP | 4500.00 | \n| 7 | Muffy | 24 | Indore | 10000.00 | \n+----+----------+-----+-----------+----------+ \n"
},
{
"code": null,
"e": 5250,
"s": 5217,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5264,
"s": 5250,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 5300,
"s": 5264,
"text": "\n 100 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 5315,
"s": 5300,
"text": " Hari Om Singh"
},
{
"code": null,
"e": 5349,
"s": 5315,
"text": "\n 108 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5364,
"s": 5349,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 5397,
"s": 5364,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5413,
"s": 5397,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 5446,
"s": 5413,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5462,
"s": 5446,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 5495,
"s": 5462,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5511,
"s": 5495,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 5518,
"s": 5511,
"text": " Print"
},
{
"code": null,
"e": 5529,
"s": 5518,
"text": " Add Notes"
}
] |
Absolute, Relative and Percentage errors in Numerical Analysis - GeeksforGeeks
|
05 Jan, 2021
Let’s first know some basics about numbers used in floating-point arithmetic or in other words Numerical analysis and how they are calculated.
Basically, all the numbers that we use in Numerical Analysis are of two types as follows.
Exact Numbers –Numbers that have their exact quantity, means their value isn’t going to change. For example- 3, 2, 5, 7, 1/3, 4/5, or √2 etc.
Approximate Numbers –These numbers are represented in decimal numbers. They have some certain degrees of accuracy. Like the value of π is 3.1416 if we want more precise value, we can write 3.14159265, but we can’t write the exact value of π.These digits that we use in any approximate value, or in other way digits which represent the numbers are called Significant Digits.
These digits that we use in any approximate value, or in other way digits which represent the numbers are called Significant Digits.
How to count significant digits in a given number :For example –In the normal value of π (3.1416), there are 5 significant digits and when we write more precise value of it (3.14159265) we get 9 significant digits.Let’s say we have numbers: 0.0123, 1.2300, and 0.10234. Now we have 4, 3, and 5 significant digits respectively.In the Scientific Representation of numbers –2.345×107, 8.7456 ×104, 5.4×106 have 4, 5 and 2 significant digits respectively.
Absolute Error :Let the true value of a quantity be X and the approximate value of that quantity be X1. Hence absolute error has defined the difference between X and X1. Absolute Error is denoted by EA.
Hence EA= X-X1=δX
Relative Error :It is defined as follow.
ER = EA/X = (Absolute Error)/X
Percentage Error :It is defined as follow.
EP= 100×EP= 100×EA/X
Let’s say we have a number δX = |X1-X|, It is an upper limit on the magnitude of Absolute Error and known as Absolute Accuracy.
Similarly the quantity δX/ |X| or δX/ |X1| called Relative Accuracy.
Now let’s solve some examples as follows.
Ex-1 :We are given an approximate value of π is 22/7 = 3.1428571 and true value is 3.1415926. Calculate absolute, relative and percentage errors?Solution –We have True value X= 3.1415926, And Approx. value X1= 3.1428571.
So now we calculate Absolute error, we know that EA= X - X1=δX
Hence EA= 3.1415926- 3.1428571 = -0.0012645
Answer is -0.0012645
Now for Relative error we’ve (absolute error)/(true value of quantity)
Hence ER = EA/X = (Absolute Error)/X, EA=(-0.0012645)/3.1415926 = -0.000402ans.
Percentage Error,
EP= 100 × EA/X = 100 × (-0.000402) = - 0.0402ans.
We have True value X= 3.1415926, And Approx. value X1= 3.1428571.
So now we calculate Absolute error, we know that EA= X - X1=δX
Hence EA= 3.1415926- 3.1428571 = -0.0012645
Answer is -0.0012645
Now for Relative error we’ve (absolute error)/(true value of quantity)
Hence ER = EA/X = (Absolute Error)/X, EA=(-0.0012645)/3.1415926 = -0.000402ans.
Percentage Error,
EP= 100 × EA/X = 100 × (-0.000402) = - 0.0402ans.
Ex-2 :Let the approximate values of a number 1/3 be 0.30, 0.33, 0.34. Find out the best approximation.Solution –Our approach is that we first find the value of Absolute Error, and any value having the least absolute will be best. So, we first calculate the absolute errors in all approx values are given.<pre|X-X1| = |1/3 – 0.30| = 1/30|1/3 – 0.33| = 1/300|1/3 – 0.34| = 0.02/3 = 1/500Hence, we can say that 0.33 is the most precise value of 1/3;
Hence, we can say that 0.33 is the most precise value of 1/3;
Ex-3 :Finding the difference—√5.35 - √4.35
Solution –
√5.35 = 2.31300
√4.35 = 2.08566
Hence, √5.35 - √4.35 = 2.31300 – 2.08566 = 0.22734
Here our answer has 5 significant digits we can modify them as per our requirements.
Finding the difference—
√5.35 - √4.35
Solution –
√5.35 = 2.31300
√4.35 = 2.08566
Hence, √5.35 - √4.35 = 2.31300 – 2.08566 = 0.22734
Here our answer has 5 significant digits we can modify them as per our requirements.
Technical Scripter 2020
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Activation Functions
Proof that vertex cover is NP complete
Univariate, Bivariate and Multivariate data and its analysis
Logic Notations in LaTeX
Difference between Propositional Logic and Predicate Logic
Z-test
Brackets in Latex
Betweenness Centrality (Centrality Measure)
Difference between Descriptive and Inferential statistics
Boolean Algebraic Theorems
|
[
{
"code": null,
"e": 24916,
"s": 24888,
"text": "\n05 Jan, 2021"
},
{
"code": null,
"e": 25060,
"s": 24916,
"text": "Let’s first know some basics about numbers used in floating-point arithmetic or in other words Numerical analysis and how they are calculated."
},
{
"code": null,
"e": 25150,
"s": 25060,
"text": "Basically, all the numbers that we use in Numerical Analysis are of two types as follows."
},
{
"code": null,
"e": 25292,
"s": 25150,
"text": "Exact Numbers –Numbers that have their exact quantity, means their value isn’t going to change. For example- 3, 2, 5, 7, 1/3, 4/5, or √2 etc."
},
{
"code": null,
"e": 25666,
"s": 25292,
"text": "Approximate Numbers –These numbers are represented in decimal numbers. They have some certain degrees of accuracy. Like the value of π is 3.1416 if we want more precise value, we can write 3.14159265, but we can’t write the exact value of π.These digits that we use in any approximate value, or in other way digits which represent the numbers are called Significant Digits."
},
{
"code": null,
"e": 25799,
"s": 25666,
"text": "These digits that we use in any approximate value, or in other way digits which represent the numbers are called Significant Digits."
},
{
"code": null,
"e": 26251,
"s": 25799,
"text": "How to count significant digits in a given number :For example –In the normal value of π (3.1416), there are 5 significant digits and when we write more precise value of it (3.14159265) we get 9 significant digits.Let’s say we have numbers: 0.0123, 1.2300, and 0.10234. Now we have 4, 3, and 5 significant digits respectively.In the Scientific Representation of numbers –2.345×107, 8.7456 ×104, 5.4×106 have 4, 5 and 2 significant digits respectively."
},
{
"code": null,
"e": 26454,
"s": 26251,
"text": "Absolute Error :Let the true value of a quantity be X and the approximate value of that quantity be X1. Hence absolute error has defined the difference between X and X1. Absolute Error is denoted by EA."
},
{
"code": null,
"e": 26473,
"s": 26454,
"text": "Hence EA= X-X1=δX "
},
{
"code": null,
"e": 26514,
"s": 26473,
"text": "Relative Error :It is defined as follow."
},
{
"code": null,
"e": 26546,
"s": 26514,
"text": "ER = EA/X = (Absolute Error)/X\n"
},
{
"code": null,
"e": 26589,
"s": 26546,
"text": "Percentage Error :It is defined as follow."
},
{
"code": null,
"e": 26610,
"s": 26589,
"text": "EP= 100×EP= 100×EA/X"
},
{
"code": null,
"e": 26740,
"s": 26610,
"text": "Let’s say we have a number δX = |X1-X|, It is an upper limit on the magnitude of Absolute Error and known as Absolute Accuracy."
},
{
"code": null,
"e": 26809,
"s": 26740,
"text": "Similarly the quantity δX/ |X| or δX/ |X1| called Relative Accuracy."
},
{
"code": null,
"e": 26851,
"s": 26809,
"text": "Now let’s solve some examples as follows."
},
{
"code": null,
"e": 27427,
"s": 26851,
"text": "Ex-1 :We are given an approximate value of π is 22/7 = 3.1428571 and true value is 3.1415926. Calculate absolute, relative and percentage errors?Solution –We have True value X= 3.1415926, And Approx. value X1= 3.1428571.\nSo now we calculate Absolute error, we know that EA= X - X1=δX\nHence EA= 3.1415926- 3.1428571 = -0.0012645\n\nAnswer is -0.0012645\nNow for Relative error we’ve (absolute error)/(true value of quantity) \nHence ER = EA/X = (Absolute Error)/X, EA=(-0.0012645)/3.1415926 = -0.000402ans.\n\nPercentage Error, \nEP= 100 × EA/X = 100 × (-0.000402) = - 0.0402ans."
},
{
"code": null,
"e": 27848,
"s": 27427,
"text": "We have True value X= 3.1415926, And Approx. value X1= 3.1428571.\nSo now we calculate Absolute error, we know that EA= X - X1=δX\nHence EA= 3.1415926- 3.1428571 = -0.0012645\n\nAnswer is -0.0012645\nNow for Relative error we’ve (absolute error)/(true value of quantity) \nHence ER = EA/X = (Absolute Error)/X, EA=(-0.0012645)/3.1415926 = -0.000402ans.\n\nPercentage Error, \nEP= 100 × EA/X = 100 × (-0.000402) = - 0.0402ans."
},
{
"code": null,
"e": 28295,
"s": 27848,
"text": "Ex-2 :Let the approximate values of a number 1/3 be 0.30, 0.33, 0.34. Find out the best approximation.Solution –Our approach is that we first find the value of Absolute Error, and any value having the least absolute will be best. So, we first calculate the absolute errors in all approx values are given.<pre|X-X1| = |1/3 – 0.30| = 1/30|1/3 – 0.33| = 1/300|1/3 – 0.34| = 0.02/3 = 1/500Hence, we can say that 0.33 is the most precise value of 1/3;"
},
{
"code": null,
"e": 28357,
"s": 28295,
"text": "Hence, we can say that 0.33 is the most precise value of 1/3;"
},
{
"code": null,
"e": 28580,
"s": 28357,
"text": "Ex-3 :Finding the difference—√5.35 - √4.35\nSolution – \n√5.35 = 2.31300\n√4.35 = 2.08566\nHence, √5.35 - √4.35 = 2.31300 – 2.08566 = 0.22734\nHere our answer has 5 significant digits we can modify them as per our requirements."
},
{
"code": null,
"e": 28604,
"s": 28580,
"text": "Finding the difference—"
},
{
"code": null,
"e": 28619,
"s": 28604,
"text": "√5.35 - √4.35\n"
},
{
"code": null,
"e": 28630,
"s": 28619,
"text": "Solution –"
},
{
"code": null,
"e": 28716,
"s": 28630,
"text": " \n√5.35 = 2.31300\n√4.35 = 2.08566\nHence, √5.35 - √4.35 = 2.31300 – 2.08566 = 0.22734\n"
},
{
"code": null,
"e": 28801,
"s": 28716,
"text": "Here our answer has 5 significant digits we can modify them as per our requirements."
},
{
"code": null,
"e": 28825,
"s": 28801,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28849,
"s": 28825,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 28947,
"s": 28849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28956,
"s": 28947,
"text": "Comments"
},
{
"code": null,
"e": 28969,
"s": 28956,
"text": "Old Comments"
},
{
"code": null,
"e": 28990,
"s": 28969,
"text": "Activation Functions"
},
{
"code": null,
"e": 29029,
"s": 28990,
"text": "Proof that vertex cover is NP complete"
},
{
"code": null,
"e": 29090,
"s": 29029,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 29115,
"s": 29090,
"text": "Logic Notations in LaTeX"
},
{
"code": null,
"e": 29174,
"s": 29115,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 29181,
"s": 29174,
"text": "Z-test"
},
{
"code": null,
"e": 29199,
"s": 29181,
"text": "Brackets in Latex"
},
{
"code": null,
"e": 29243,
"s": 29199,
"text": "Betweenness Centrality (Centrality Measure)"
},
{
"code": null,
"e": 29301,
"s": 29243,
"text": "Difference between Descriptive and Inferential statistics"
}
] |
Euphoria - Flow Control
|
Program execution flow refers to the order in which program statements get executed. By default the statements get executed one after another.
However; many times the order of execution needs to be altered from the default order, to get the task done.
Euphoria has a number of flow control statements that you can use to arrange the execution order of statements.
Exiting a loop is done with the keyword exit. This causes flow to immediately leave the current loop and recommence with the first statement after the end of the loop.
The syntax of an exit statement is as follows −
exit [ "Label Name" ] [Number]
The exit statement terminates the latest and innermost loop until an optional label name or number is specified.
A special form of exit N is exit 0. This leaves all levels of loop, regardless of the depth. Control continues after the outermost loop block. Likewise, exit -1 exits the second outermost loop, and so on.
#!/home/euphoria-4.0b2/bin/eui
integer b
for a = 1 to 16 do
printf(1, "value of a %d\n", a)
if a = 10 then
b = a
exit
end if
end for
printf(1, "value of b %d\n", b)
This produces the following result −
value of a 1
value of a 2
value of a 3
value of a 4
value of a 5
value of a 6
value of a 7
value of a 8
value of a 9
value of a 10
value of b 10
The break statement works exactly like the exit statement, but applies to if statements or switch statements rather than to loop statements of any kind.
The syntax of break statement is as follows −
break [ "Label Name" ] [Number]
The break statement terminates the latest and innermost if or switch block until an optional label name or number is specified.
A special form of break N is break 0. This leaves the outer most if or switch block, regardless of the depth. Control continues after the outermost block. Likewise, break -1 breaks the second outermost if or switch block, and so on.
#!/home/euphoria-4.0b2/bin/eui
integer a, b
sequence s = {'E','u', 'p'}
if s[1] = 'E' then
a = 3
if s[2] = 'u' then
b = 1
if s[3] = 'p' then
break 0 -- leave topmost if block
end if
a = 2
else
b = 4
end if
else
a = 0
b = 0
end if
printf(1, "value of a %d\n", a)
printf(1, "value of b %d\n", b)
This produces the following result −
value of a 3
value of b 1
The continue statement continues execution of the loop it applies to by going to the next iteration and skipping the rest of an iteration.
Going to the next iteration means testing a condition variable index and checking whether it is still within bounds.
The syntax of continue statement is as follows −
continue [ "Label Name" ] [Number]
The continue statement would re-iterate the latest and inner most loop until an optional label name or number is specified.
A special form of continue N is continue 0. This re-iterate the outer most loop, regardless of the depth. Likewise, continue -1 starts from the second outermost loop, and so on.
#!/home/euphoria-4.0b2/bin/eui
for a = 3 to 6 do
printf(1, "value of a %d\n", a)
if a = 4 then
puts(1,"(2)\n")
continue
end if
printf(1, "value of a %d\n", a*a)
end for
This would produce following result:
value of a 3
value of a 9
value of a 4
(2)
value of a 5
value of a 25
value of a 6
value of a 36
The retry statement continues execution of the loop it applies to by going to the next iteration and skipping the rest of an iteration.
The syntax of retry statement is as follows −
retry [ "Label Name" ] [Number]
The retry statement retries executing the current iteration of the loop it applies to. The statement branches to the first statement of the designated loop neither testing anything nor incrementing the for loop index.
A special form of retry N is retry 0. This retries executing the outer most loop, regardless of the depth. Likewise, retry -1 retries the second outermost loop, and so on.
Normally, a sub-block which contains a retry statement also contains another flow control keyword like exit, continue, or break. Otherwise, the iteration would be endlessly executed.
#!/home/euphoria-4.0b2/bin/eui
integer errors = 0
integer files_to_open = 10
for i = 1 to length(files_to_open) do
fh = open(files_to_open[i], "rb")
if fh = -1 then
if errors > 5 then
exit
else
errors += 1
retry
end if
end if
file_handles[i] = fh
end for
Since retry does not change the value of i and tries again opening the same file, there has to be a way to break from the loop, which the exit statement provides.
The goto statement instructs the computer to resume code execution at a labeled place.
The place to resume execution is called the target of the statement. It is restricted to lie in the current routine, or the current file if outside any routine.
The syntax of goto statement is as follows −
goto "Label Name"
The target of a goto statement can be any accessible label statement −
label "Label Name"
Label names must be double quoted constant strings. Characters that are illegal in Euphoria identifiers may appear in a label name, since it is a regular string.
#!/home/euphoria-4.0b2/bin/eui
integer a = 0
label "FIRST"
printf(1, "value of a %d\n", a)
a += 10
if a < 50 then
goto "FIRST"
end if
printf(1, "Final value of a %d\n", a)
This produces the following result −
value of a 0
value of a 10
value of a 20
value of a 30
value of a 40
Final value of a 50
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2110,
"s": 1967,
"text": "Program execution flow refers to the order in which program statements get executed. By default the statements get executed one after another."
},
{
"code": null,
"e": 2219,
"s": 2110,
"text": "However; many times the order of execution needs to be altered from the default order, to get the task done."
},
{
"code": null,
"e": 2331,
"s": 2219,
"text": "Euphoria has a number of flow control statements that you can use to arrange the execution order of statements."
},
{
"code": null,
"e": 2499,
"s": 2331,
"text": "Exiting a loop is done with the keyword exit. This causes flow to immediately leave the current loop and recommence with the first statement after the end of the loop."
},
{
"code": null,
"e": 2547,
"s": 2499,
"text": "The syntax of an exit statement is as follows −"
},
{
"code": null,
"e": 2579,
"s": 2547,
"text": "exit [ \"Label Name\" ] [Number]\n"
},
{
"code": null,
"e": 2692,
"s": 2579,
"text": "The exit statement terminates the latest and innermost loop until an optional label name or number is specified."
},
{
"code": null,
"e": 2897,
"s": 2692,
"text": "A special form of exit N is exit 0. This leaves all levels of loop, regardless of the depth. Control continues after the outermost loop block. Likewise, exit -1 exits the second outermost loop, and so on."
},
{
"code": null,
"e": 3090,
"s": 2897,
"text": "#!/home/euphoria-4.0b2/bin/eui\n\ninteger b\n\nfor a = 1 to 16 do\n printf(1, \"value of a %d\\n\", a)\n \n if a = 10 then\n b = a\n exit\n end if\nend for\n\nprintf(1, \"value of b %d\\n\", b)"
},
{
"code": null,
"e": 3127,
"s": 3090,
"text": "This produces the following result −"
},
{
"code": null,
"e": 3273,
"s": 3127,
"text": "value of a 1\nvalue of a 2\nvalue of a 3\nvalue of a 4\nvalue of a 5\nvalue of a 6\nvalue of a 7\nvalue of a 8\nvalue of a 9\nvalue of a 10\nvalue of b 10\n"
},
{
"code": null,
"e": 3426,
"s": 3273,
"text": "The break statement works exactly like the exit statement, but applies to if statements or switch statements rather than to loop statements of any kind."
},
{
"code": null,
"e": 3472,
"s": 3426,
"text": "The syntax of break statement is as follows −"
},
{
"code": null,
"e": 3505,
"s": 3472,
"text": "break [ \"Label Name\" ] [Number]\n"
},
{
"code": null,
"e": 3633,
"s": 3505,
"text": "The break statement terminates the latest and innermost if or switch block until an optional label name or number is specified."
},
{
"code": null,
"e": 3866,
"s": 3633,
"text": "A special form of break N is break 0. This leaves the outer most if or switch block, regardless of the depth. Control continues after the outermost block. Likewise, break -1 breaks the second outermost if or switch block, and so on."
},
{
"code": null,
"e": 4224,
"s": 3866,
"text": "#!/home/euphoria-4.0b2/bin/eui\n\ninteger a, b\nsequence s = {'E','u', 'p'}\n\nif s[1] = 'E' then\n a = 3\n \n if s[2] = 'u' then\n b = 1\n if s[3] = 'p' then\n break 0 -- leave topmost if block\n end if\n a = 2\n else\n b = 4\n end if\nelse\n a = 0\n b = 0\nend if\n\nprintf(1, \"value of a %d\\n\", a)\nprintf(1, \"value of b %d\\n\", b)"
},
{
"code": null,
"e": 4261,
"s": 4224,
"text": "This produces the following result −"
},
{
"code": null,
"e": 4288,
"s": 4261,
"text": "value of a 3\nvalue of b 1\n"
},
{
"code": null,
"e": 4427,
"s": 4288,
"text": "The continue statement continues execution of the loop it applies to by going to the next iteration and skipping the rest of an iteration."
},
{
"code": null,
"e": 4544,
"s": 4427,
"text": "Going to the next iteration means testing a condition variable index and checking whether it is still within bounds."
},
{
"code": null,
"e": 4593,
"s": 4544,
"text": "The syntax of continue statement is as follows −"
},
{
"code": null,
"e": 4629,
"s": 4593,
"text": "continue [ \"Label Name\" ] [Number]\n"
},
{
"code": null,
"e": 4753,
"s": 4629,
"text": "The continue statement would re-iterate the latest and inner most loop until an optional label name or number is specified."
},
{
"code": null,
"e": 4931,
"s": 4753,
"text": "A special form of continue N is continue 0. This re-iterate the outer most loop, regardless of the depth. Likewise, continue -1 starts from the second outermost loop, and so on."
},
{
"code": null,
"e": 5262,
"s": 4931,
"text": "#!/home/euphoria-4.0b2/bin/eui\n\nfor a = 3 to 6 do\n printf(1, \"value of a %d\\n\", a)\n\n if a = 4 then\n puts(1,\"(2)\\n\")\n continue\n end if\n\n printf(1, \"value of a %d\\n\", a*a)\nend for\nThis would produce following result:\n\nvalue of a 3\nvalue of a 9\nvalue of a 4\n(2)\nvalue of a 5\nvalue of a 25\nvalue of a 6\nvalue of a 36"
},
{
"code": null,
"e": 5398,
"s": 5262,
"text": "The retry statement continues execution of the loop it applies to by going to the next iteration and skipping the rest of an iteration."
},
{
"code": null,
"e": 5444,
"s": 5398,
"text": "The syntax of retry statement is as follows −"
},
{
"code": null,
"e": 5477,
"s": 5444,
"text": "retry [ \"Label Name\" ] [Number]\n"
},
{
"code": null,
"e": 5695,
"s": 5477,
"text": "The retry statement retries executing the current iteration of the loop it applies to. The statement branches to the first statement of the designated loop neither testing anything nor incrementing the for loop index."
},
{
"code": null,
"e": 5867,
"s": 5695,
"text": "A special form of retry N is retry 0. This retries executing the outer most loop, regardless of the depth. Likewise, retry -1 retries the second outermost loop, and so on."
},
{
"code": null,
"e": 6050,
"s": 5867,
"text": "Normally, a sub-block which contains a retry statement also contains another flow control keyword like exit, continue, or break. Otherwise, the iteration would be endlessly executed."
},
{
"code": null,
"e": 6368,
"s": 6050,
"text": "#!/home/euphoria-4.0b2/bin/eui\n\ninteger errors = 0\ninteger files_to_open = 10\n\nfor i = 1 to length(files_to_open) do\n fh = open(files_to_open[i], \"rb\")\n \n if fh = -1 then\n if errors > 5 then\n exit\n else\n errors += 1\n retry\n end if\n end if\n file_handles[i] = fh\nend for"
},
{
"code": null,
"e": 6531,
"s": 6368,
"text": "Since retry does not change the value of i and tries again opening the same file, there has to be a way to break from the loop, which the exit statement provides."
},
{
"code": null,
"e": 6618,
"s": 6531,
"text": "The goto statement instructs the computer to resume code execution at a labeled place."
},
{
"code": null,
"e": 6779,
"s": 6618,
"text": "The place to resume execution is called the target of the statement. It is restricted to lie in the current routine, or the current file if outside any routine."
},
{
"code": null,
"e": 6824,
"s": 6779,
"text": "The syntax of goto statement is as follows −"
},
{
"code": null,
"e": 6843,
"s": 6824,
"text": "goto \"Label Name\"\n"
},
{
"code": null,
"e": 6914,
"s": 6843,
"text": "The target of a goto statement can be any accessible label statement −"
},
{
"code": null,
"e": 6933,
"s": 6914,
"text": "label \"Label Name\""
},
{
"code": null,
"e": 7095,
"s": 6933,
"text": "Label names must be double quoted constant strings. Characters that are illegal in Euphoria identifiers may appear in a label name, since it is a regular string."
},
{
"code": null,
"e": 7274,
"s": 7095,
"text": "#!/home/euphoria-4.0b2/bin/eui\n\ninteger a = 0\n\nlabel \"FIRST\"\nprintf(1, \"value of a %d\\n\", a)\na += 10\n\nif a < 50 then\n goto \"FIRST\"\nend if \nprintf(1, \"Final value of a %d\\n\", a)"
},
{
"code": null,
"e": 7311,
"s": 7274,
"text": "This produces the following result −"
},
{
"code": null,
"e": 7401,
"s": 7311,
"text": "value of a 0\nvalue of a 10\nvalue of a 20\nvalue of a 30\nvalue of a 40\nFinal value of a 50\n"
},
{
"code": null,
"e": 7408,
"s": 7401,
"text": " Print"
},
{
"code": null,
"e": 7419,
"s": 7408,
"text": " Add Notes"
}
] |
C# | Math.Sign() Method - GeeksforGeeks
|
31 Jan, 2019
In C#, Sign() is a math class method which returns an integer that specify the sign of the number. This method can be overloaded by changing the data type of the passed arguments as follows:
Math.Sign(Decimal): Returns the integer that specifies the sign of a decimal number.
Math.Sign(Double): Returns the integer that specifies the sign of a double-precision floating-point number.
Math.Sign(Int16): Returns the integer that specifies the sign of a 16-bit signed integer. Here Int16 is short data type
Math.Sign(Int32): Returns the integer that specifies the sign of a 32-bit signed integer. Here Int32 is int data type.
Math.Sign(Int64): Returns the integer that specifies the sign of a 64-bit signed integer. Here Int64 is long data type.
Math.Sign(SByte): Returns the integer that specifies the sign of an 8-bit signed integer.
Math.Sign(Single): Returns the integer that specifies the sign of a single-precision floating-point number. Here single is float data type.
Common Syntax for all above methods:
public static int Sign(data_type value)
Parameter: This method takes a single parameter in the form of either bytes, int, double, sbyte, etc.
Return type : This method returns the value of type System.Int32 as per following mentioned conditions:
Example:
// C# program to demonstrate the // Math.Sign() methodusing System; class GFG { // Main Method static void Main(string[] args) { // Decimal data type Decimal de = 150M; // Double data type Double d = 34.5432d; // Int16 data type short sh = 0; // Int32 data type int i = -5678; // Int64 data type long l = 598964564; // SByte data type sbyte sb = -34; // float data type float f = 56.89f; // displaying result Console.WriteLine("Decimal: " + de + " " + check(Math.Sign(de))); Console.WriteLine("Double: " + d + " " + check(Math.Sign(d))); Console.WriteLine("Int16: " + sh + " " + check(Math.Sign(sh))); Console.WriteLine("Int32: " + i + " " + check(Math.Sign(i))); Console.WriteLine("Int64: " + l + " " + check(Math.Sign(l))); Console.WriteLine("SByte: " + sb + " " + check(Math.Sign(sb))); Console.WriteLine("Single: " + f + " " + check(Math.Sign(f))); } // function to check whether the input // number is greater than zero or not public static String check(int compare) { if (compare == 0) return "equal to zero"; else if (compare < 0) return "less than zero"; else return "greater than zero"; }}
Decimal: 150 greater than zero
Double: 34.5432 greater than zero
Int16: 0 equal to zero
Int32: -5678 less than zero
Int64: 598964564 greater than zero
SByte: -34 less than zero
Single: 56.89 greater than zero
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
C# | Replace() Method
Extension Method in C#
C# | Class and Object
C# | Constructors
Introduction to .NET Framework
|
[
{
"code": null,
"e": 25611,
"s": 25583,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 25802,
"s": 25611,
"text": "In C#, Sign() is a math class method which returns an integer that specify the sign of the number. This method can be overloaded by changing the data type of the passed arguments as follows:"
},
{
"code": null,
"e": 25887,
"s": 25802,
"text": "Math.Sign(Decimal): Returns the integer that specifies the sign of a decimal number."
},
{
"code": null,
"e": 25995,
"s": 25887,
"text": "Math.Sign(Double): Returns the integer that specifies the sign of a double-precision floating-point number."
},
{
"code": null,
"e": 26115,
"s": 25995,
"text": "Math.Sign(Int16): Returns the integer that specifies the sign of a 16-bit signed integer. Here Int16 is short data type"
},
{
"code": null,
"e": 26234,
"s": 26115,
"text": "Math.Sign(Int32): Returns the integer that specifies the sign of a 32-bit signed integer. Here Int32 is int data type."
},
{
"code": null,
"e": 26354,
"s": 26234,
"text": "Math.Sign(Int64): Returns the integer that specifies the sign of a 64-bit signed integer. Here Int64 is long data type."
},
{
"code": null,
"e": 26444,
"s": 26354,
"text": "Math.Sign(SByte): Returns the integer that specifies the sign of an 8-bit signed integer."
},
{
"code": null,
"e": 26584,
"s": 26444,
"text": "Math.Sign(Single): Returns the integer that specifies the sign of a single-precision floating-point number. Here single is float data type."
},
{
"code": null,
"e": 26621,
"s": 26584,
"text": "Common Syntax for all above methods:"
},
{
"code": null,
"e": 26662,
"s": 26621,
"text": "public static int Sign(data_type value)\n"
},
{
"code": null,
"e": 26764,
"s": 26662,
"text": "Parameter: This method takes a single parameter in the form of either bytes, int, double, sbyte, etc."
},
{
"code": null,
"e": 26868,
"s": 26764,
"text": "Return type : This method returns the value of type System.Int32 as per following mentioned conditions:"
},
{
"code": null,
"e": 26877,
"s": 26868,
"text": "Example:"
},
{
"code": "// C# program to demonstrate the // Math.Sign() methodusing System; class GFG { // Main Method static void Main(string[] args) { // Decimal data type Decimal de = 150M; // Double data type Double d = 34.5432d; // Int16 data type short sh = 0; // Int32 data type int i = -5678; // Int64 data type long l = 598964564; // SByte data type sbyte sb = -34; // float data type float f = 56.89f; // displaying result Console.WriteLine(\"Decimal: \" + de + \" \" + check(Math.Sign(de))); Console.WriteLine(\"Double: \" + d + \" \" + check(Math.Sign(d))); Console.WriteLine(\"Int16: \" + sh + \" \" + check(Math.Sign(sh))); Console.WriteLine(\"Int32: \" + i + \" \" + check(Math.Sign(i))); Console.WriteLine(\"Int64: \" + l + \" \" + check(Math.Sign(l))); Console.WriteLine(\"SByte: \" + sb + \" \" + check(Math.Sign(sb))); Console.WriteLine(\"Single: \" + f + \" \" + check(Math.Sign(f))); } // function to check whether the input // number is greater than zero or not public static String check(int compare) { if (compare == 0) return \"equal to zero\"; else if (compare < 0) return \"less than zero\"; else return \"greater than zero\"; }}",
"e": 28333,
"s": 26877,
"text": null
},
{
"code": null,
"e": 28543,
"s": 28333,
"text": "Decimal: 150 greater than zero\nDouble: 34.5432 greater than zero\nInt16: 0 equal to zero\nInt32: -5678 less than zero\nInt64: 598964564 greater than zero\nSByte: -34 less than zero\nSingle: 56.89 greater than zero\n"
},
{
"code": null,
"e": 28555,
"s": 28543,
"text": "CSharp-Math"
},
{
"code": null,
"e": 28569,
"s": 28555,
"text": "CSharp-method"
},
{
"code": null,
"e": 28572,
"s": 28569,
"text": "C#"
},
{
"code": null,
"e": 28670,
"s": 28572,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28698,
"s": 28670,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28713,
"s": 28698,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28736,
"s": 28713,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28758,
"s": 28736,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28804,
"s": 28758,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28826,
"s": 28804,
"text": "C# | Replace() Method"
},
{
"code": null,
"e": 28849,
"s": 28826,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28871,
"s": 28849,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28889,
"s": 28871,
"text": "C# | Constructors"
}
] |
C Program for Cutting a Rod | DP-13 - GeeksforGeeks
|
25 Jun, 2021
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 1 5 8 9 10 17 17 20
And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1)
length | 1 2 3 4 5 6 7 8
--------------------------------------------
price | 3 5 8 9 10 17 17 20
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
Following is simple recursive implementation of the Rod Cutting problem. The implementation simply follows the recursive structure mentioned above.
C++
// A Naive recursive solution for Rod cutting problem#include <limits.h>#include <stdio.h> // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ if (n <= 0) return 0; int max_val = INT_MIN; // Recursively cut the rod in different pieces and compare different // configurations for (int i = 0; i < n; i++) max_val = max(max_val, price[i] + cutRod(price, n - i - 1)); return max_val;} /* Driver program to test above functions */int main(){ int arr[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Maximum Obtainable Value is %d", cutRod(arr, size)); getchar(); return 0;}
Maximum Obtainable Value is 22
Considering the above implementation, following is recursion tree for a Rod of length 4.
cR() ---> cutRod()
cR(4)
/ /
/ /
cR(3) cR(2) cR(1) cR(0)
/ | / |
/ | / |
cR(2) cR(1) cR(0) cR(1) cR(0) cR(0)
/ | |
/ | |
cR(1) cR(0) cR(0) cR(0)
/
/
CR(0)
In the above partial recursion tree, cR(2) is being solved twice. We can see that there are many subproblems which are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom-up manner.
C++
// A Dynamic Programming solution for Rod cutting problem#include <limits.h>#include <stdio.h> // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ int val[n + 1]; val[0] = 0; int i, j; // Build the table val[] in bottom up manner and return the last entry // from the table for (i = 1; i <= n; i++) { int max_val = INT_MIN; for (j = 0; j < i; j++) max_val = max(max_val, price[j] + val[i - j - 1]); val[i] = max_val; } return val[n];} /* Driver program to test above functions */int main(){ int arr[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int size = sizeof(arr) / sizeof(arr[0]); printf("Maximum Obtainable Value is %d", cutRod(arr, size)); getchar(); return 0;}
Maximum Obtainable Value is 22
Please refer complete article on Cutting a Rod | DP-13 for more details!
anikakapoor
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Create n-child process from same parent process using fork() in C
Conditional wait and signal in multi-threading
Lamport's logical clock
|
[
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n25 Jun, 2021"
},
{
"code": null,
"e": 26558,
"s": 26175,
"text": "Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) "
},
{
"code": null,
"e": 26687,
"s": 26558,
"text": "length | 1 2 3 4 5 6 7 8 \n--------------------------------------------\nprice | 1 5 8 9 10 17 17 20"
},
{
"code": null,
"e": 26804,
"s": 26687,
"text": "And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1)"
},
{
"code": null,
"e": 26933,
"s": 26804,
"text": "length | 1 2 3 4 5 6 7 8 \n--------------------------------------------\nprice | 3 5 8 9 10 17 17 20"
},
{
"code": null,
"e": 27018,
"s": 26933,
"text": "Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution."
},
{
"code": null,
"e": 27168,
"s": 27020,
"text": "Following is simple recursive implementation of the Rod Cutting problem. The implementation simply follows the recursive structure mentioned above."
},
{
"code": null,
"e": 27172,
"s": 27168,
"text": "C++"
},
{
"code": "// A Naive recursive solution for Rod cutting problem#include <limits.h>#include <stdio.h> // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ if (n <= 0) return 0; int max_val = INT_MIN; // Recursively cut the rod in different pieces and compare different // configurations for (int i = 0; i < n; i++) max_val = max(max_val, price[i] + cutRod(price, n - i - 1)); return max_val;} /* Driver program to test above functions */int main(){ int arr[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Maximum Obtainable Value is %d\", cutRod(arr, size)); getchar(); return 0;}",
"e": 28017,
"s": 27172,
"text": null
},
{
"code": null,
"e": 28048,
"s": 28017,
"text": "Maximum Obtainable Value is 22"
},
{
"code": null,
"e": 28139,
"s": 28050,
"text": "Considering the above implementation, following is recursion tree for a Rod of length 4."
},
{
"code": null,
"e": 28546,
"s": 28139,
"text": "cR() ---> cutRod() \n\n cR(4)\n / / \n / / \n cR(3) cR(2) cR(1) cR(0)\n / | / |\n / | / | \n cR(2) cR(1) cR(0) cR(1) cR(0) cR(0)\n / | |\n / | | \n cR(1) cR(0) cR(0) cR(0)\n /\n /\nCR(0)"
},
{
"code": null,
"e": 29046,
"s": 28546,
"text": "In the above partial recursion tree, cR(2) is being solved twice. We can see that there are many subproblems which are solved again and again. Since same subproblems are called again, this problem has Overlapping Subproblems property. So the Rod Cutting problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array val[] in bottom-up manner."
},
{
"code": null,
"e": 29050,
"s": 29046,
"text": "C++"
},
{
"code": "// A Dynamic Programming solution for Rod cutting problem#include <limits.h>#include <stdio.h> // A utility function to get the maximum of two integersint max(int a, int b) { return (a > b) ? a : b; } /* Returns the best obtainable price for a rod of length n and price[] as prices of different pieces */int cutRod(int price[], int n){ int val[n + 1]; val[0] = 0; int i, j; // Build the table val[] in bottom up manner and return the last entry // from the table for (i = 1; i <= n; i++) { int max_val = INT_MIN; for (j = 0; j < i; j++) max_val = max(max_val, price[j] + val[i - j - 1]); val[i] = max_val; } return val[n];} /* Driver program to test above functions */int main(){ int arr[] = { 1, 5, 8, 9, 10, 17, 17, 20 }; int size = sizeof(arr) / sizeof(arr[0]); printf(\"Maximum Obtainable Value is %d\", cutRod(arr, size)); getchar(); return 0;}",
"e": 29973,
"s": 29050,
"text": null
},
{
"code": null,
"e": 30004,
"s": 29973,
"text": "Maximum Obtainable Value is 22"
},
{
"code": null,
"e": 30080,
"s": 30006,
"text": "Please refer complete article on Cutting a Rod | DP-13 for more details! "
},
{
"code": null,
"e": 30092,
"s": 30080,
"text": "anikakapoor"
},
{
"code": null,
"e": 30103,
"s": 30092,
"text": "C Programs"
},
{
"code": null,
"e": 30201,
"s": 30103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30242,
"s": 30201,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 30273,
"s": 30242,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 30314,
"s": 30273,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 30348,
"s": 30314,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 30438,
"s": 30348,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 30463,
"s": 30438,
"text": "Regular expressions in C"
},
{
"code": null,
"e": 30534,
"s": 30463,
"text": "C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 30600,
"s": 30534,
"text": "Create n-child process from same parent process using fork() in C"
},
{
"code": null,
"e": 30647,
"s": 30600,
"text": "Conditional wait and signal in multi-threading"
}
] |
Just Start with the Dask LocalCluster | by Hugo Shi | Towards Data Science
|
This article is the first article of an ongoing series on using Dask in practice. Each article in this series will be simple enough for beginners, but provide useful tips for real work. The next article in the series is about parallelizing for loops, and other embarssingly parallel operations with dask.delayed.
At Saturn Cloud, we manage a data science platform that provides Jupyter notebooks, Dask clusters and ways to deploy models, dashboards and jobs. We’ve seen a few customers start with multi-node clusters when that’s completely unecessary. When you first use Dask, LocalCluster is the way to go.
There are many ways to run Dask clusters. This article urges users to start as simplistically as possible, and runs through easy ways of doing just that.
We host and manage multi-node Dask clusters. These clusters can even use GPUs. With Saturn users can access a cluster with hundreds of GPUs with a few clicks.
But wait.
Just because you have a Ferarri, doesn’t mean you should drive it to the grocery store.
Simpler is usually better.
Your order of scaling should be:
Start with Pandas. That’s usually enough.Running out of memory? Use Pandas with a bigger machine. Saturn now has Jupyter instances with 4 terabytes of RAMTry a Dask Local ClusterTry a multi-node (and possibly multi-GPU) Dask Cluster
Start with Pandas. That’s usually enough.
Running out of memory? Use Pandas with a bigger machine. Saturn now has Jupyter instances with 4 terabytes of RAM
Try a Dask Local Cluster
Try a multi-node (and possibly multi-GPU) Dask Cluster
In general, the simpler your stack, the less time you’ll spend tinkering, and the more time you’ll spend being productive. I’m writing this article because I’ve spent time talking to users who use multi-node clusters when they don’t need to. It’s kind of our fault — we make them really easy to spin up.
Your computer has multiple cores (mine has 4). If you’re writing regular Python code, you’re probably only leveraging 1 of those cores. Some of your code (specifically code that calls NumPy, for things like matrix multiplication) is leveraging multiple cores because NumPy knows how to do so. Python doesn’t know how to execute the code you’re writing automatically on multiple cores.
Using a Dask cluster (along with a library that understands how to parallelize over dask) allows you to take advantage of all the cores on your system. Dask comes with some parallelized modules such as dask.dataframe and dask.array. Other libraries like Xarray and dask-ml` also integrate with Dask.
Dask can help you scale to enormous data sets with multi-node clusters. Dask can also help you take advantage of all the cores on your computer with LocalCluster
It’s just easier working with a single machine. On a single machine, htop can help you understand how your system is doing. On a single machine, you don’t have to worry about copying your code, or data files to your cluster of computers. On a single machine, you can see all the logs for your entire Dask cluster in the terminal.
Multiprocessing is great for embarrassingly parallel problems. For non-embarrassingly parallel problems, you’ll need a tool like Dask that knows how to parallelize complex operations over multiple cores. Since Dask can handle both types of parallel problems, you only have to learn one syntax. Plus, you get the fabulous Dask dashboard to monitor your work.
For non-embarassingly parallel problems, you’ll need a tool like Dask that knows how to paraellelize complex operations over multiple cores.
There are many ways to use LocalCluster. I’ll show you the best one.
Dask makes it really really easy to get started. Create a Dask client, and you’ve automatically got a LocalCluster
>>> from dask.distributed import Client >>> c = Client() >>> c.cluster LocalCluster(16ff34f9, 'tcp://127.0.0.1:35257', workers=4, threads=8, memory=41.92 GB) >>>
You can also use LocalCluster explicitly in Python
>>> from dask.distributed import Client >>> from dask.distributed import LocalCluster >>> cluster = LocalCluster() >>> client = Client(cluster)
I use this approach when I deploy production data pipelines, but I don’t like doing this for research. If you have multiple Python sessions or notebooks, this approach makes it easy for you to accidentally end up with multiple clusters on your computer. It also makes it harder to view the logs, and find the address of the Dask dashboard.
Open a terminal.
$ dask-scheduler
Open a second terminal.
$ dask-worker tcp://127.0.0.1:8786
In your Python session (possibly a Jupyter notebook), execute the following:
from dask.distributed import Client client = Client('tcp://127.0.0.1:8786')
There you go. The default address for the dask-scheduler is tcp://127.0.0.1:8786 and that second command was enough to set up Dask workers connected to the scheduler. The best part of this approach is that all the logs for all of your work will be in the second terminal. To shut it down, just hit ctrl-c in both terminals.
Python has this annoying thing called the global interpreter lock. You don’t need to understand too much about it, except that it means that Python can’t really leverage multiple threads very well. The general exceptions to this rule are code that is mostly doing I/O (downloading data), or code that is leveraging mostly C++ and other non-python libraries (NumPy, for example).
Most users that we’ve worked with are best served using processes over threads (you can mix them as well). This is how I do this on my machine.
I have 40 GB of RAM (Thank you System76!!)I have 4 cores. So I want 4 workers.This means each worker can consume 10 GB of RAM.
I have 40 GB of RAM (Thank you System76!!)
I have 4 cores. So I want 4 workers.
This means each worker can consume 10 GB of RAM.
$ dask-worker tcp://127.0.0.1:8786 --nprocs 4 --memory-limit 10GB
Start simple, and scale up gradually. At Saturn, we can give you 4 terabyte instances for all your local cluster needs. And if that’s not enough, you can then run the same code on a multi-node (and multi-GPU) cluster, with a few clicks. Happy Dask-ing!
Disclaimer: I’m the CTO of Saturn Cloud. We make it easy to connect your team with cloud resources. Want to use Jupyter and Dask? Deploy models, dashboards or jobs? Work from your laptop, or a 4 TB Jupyter instance? Get complete transparency into who is consuming what cloud resources? We do all of that, and more.
Originally published at https://saturncloud.io on August 8, 2021.
|
[
{
"code": null,
"e": 485,
"s": 172,
"text": "This article is the first article of an ongoing series on using Dask in practice. Each article in this series will be simple enough for beginners, but provide useful tips for real work. The next article in the series is about parallelizing for loops, and other embarssingly parallel operations with dask.delayed."
},
{
"code": null,
"e": 780,
"s": 485,
"text": "At Saturn Cloud, we manage a data science platform that provides Jupyter notebooks, Dask clusters and ways to deploy models, dashboards and jobs. We’ve seen a few customers start with multi-node clusters when that’s completely unecessary. When you first use Dask, LocalCluster is the way to go."
},
{
"code": null,
"e": 934,
"s": 780,
"text": "There are many ways to run Dask clusters. This article urges users to start as simplistically as possible, and runs through easy ways of doing just that."
},
{
"code": null,
"e": 1093,
"s": 934,
"text": "We host and manage multi-node Dask clusters. These clusters can even use GPUs. With Saturn users can access a cluster with hundreds of GPUs with a few clicks."
},
{
"code": null,
"e": 1103,
"s": 1093,
"text": "But wait."
},
{
"code": null,
"e": 1191,
"s": 1103,
"text": "Just because you have a Ferarri, doesn’t mean you should drive it to the grocery store."
},
{
"code": null,
"e": 1218,
"s": 1191,
"text": "Simpler is usually better."
},
{
"code": null,
"e": 1251,
"s": 1218,
"text": "Your order of scaling should be:"
},
{
"code": null,
"e": 1484,
"s": 1251,
"text": "Start with Pandas. That’s usually enough.Running out of memory? Use Pandas with a bigger machine. Saturn now has Jupyter instances with 4 terabytes of RAMTry a Dask Local ClusterTry a multi-node (and possibly multi-GPU) Dask Cluster"
},
{
"code": null,
"e": 1526,
"s": 1484,
"text": "Start with Pandas. That’s usually enough."
},
{
"code": null,
"e": 1640,
"s": 1526,
"text": "Running out of memory? Use Pandas with a bigger machine. Saturn now has Jupyter instances with 4 terabytes of RAM"
},
{
"code": null,
"e": 1665,
"s": 1640,
"text": "Try a Dask Local Cluster"
},
{
"code": null,
"e": 1720,
"s": 1665,
"text": "Try a multi-node (and possibly multi-GPU) Dask Cluster"
},
{
"code": null,
"e": 2024,
"s": 1720,
"text": "In general, the simpler your stack, the less time you’ll spend tinkering, and the more time you’ll spend being productive. I’m writing this article because I’ve spent time talking to users who use multi-node clusters when they don’t need to. It’s kind of our fault — we make them really easy to spin up."
},
{
"code": null,
"e": 2409,
"s": 2024,
"text": "Your computer has multiple cores (mine has 4). If you’re writing regular Python code, you’re probably only leveraging 1 of those cores. Some of your code (specifically code that calls NumPy, for things like matrix multiplication) is leveraging multiple cores because NumPy knows how to do so. Python doesn’t know how to execute the code you’re writing automatically on multiple cores."
},
{
"code": null,
"e": 2709,
"s": 2409,
"text": "Using a Dask cluster (along with a library that understands how to parallelize over dask) allows you to take advantage of all the cores on your system. Dask comes with some parallelized modules such as dask.dataframe and dask.array. Other libraries like Xarray and dask-ml` also integrate with Dask."
},
{
"code": null,
"e": 2871,
"s": 2709,
"text": "Dask can help you scale to enormous data sets with multi-node clusters. Dask can also help you take advantage of all the cores on your computer with LocalCluster"
},
{
"code": null,
"e": 3201,
"s": 2871,
"text": "It’s just easier working with a single machine. On a single machine, htop can help you understand how your system is doing. On a single machine, you don’t have to worry about copying your code, or data files to your cluster of computers. On a single machine, you can see all the logs for your entire Dask cluster in the terminal."
},
{
"code": null,
"e": 3559,
"s": 3201,
"text": "Multiprocessing is great for embarrassingly parallel problems. For non-embarrassingly parallel problems, you’ll need a tool like Dask that knows how to parallelize complex operations over multiple cores. Since Dask can handle both types of parallel problems, you only have to learn one syntax. Plus, you get the fabulous Dask dashboard to monitor your work."
},
{
"code": null,
"e": 3700,
"s": 3559,
"text": "For non-embarassingly parallel problems, you’ll need a tool like Dask that knows how to paraellelize complex operations over multiple cores."
},
{
"code": null,
"e": 3769,
"s": 3700,
"text": "There are many ways to use LocalCluster. I’ll show you the best one."
},
{
"code": null,
"e": 3884,
"s": 3769,
"text": "Dask makes it really really easy to get started. Create a Dask client, and you’ve automatically got a LocalCluster"
},
{
"code": null,
"e": 4046,
"s": 3884,
"text": ">>> from dask.distributed import Client >>> c = Client() >>> c.cluster LocalCluster(16ff34f9, 'tcp://127.0.0.1:35257', workers=4, threads=8, memory=41.92 GB) >>>"
},
{
"code": null,
"e": 4097,
"s": 4046,
"text": "You can also use LocalCluster explicitly in Python"
},
{
"code": null,
"e": 4241,
"s": 4097,
"text": ">>> from dask.distributed import Client >>> from dask.distributed import LocalCluster >>> cluster = LocalCluster() >>> client = Client(cluster)"
},
{
"code": null,
"e": 4581,
"s": 4241,
"text": "I use this approach when I deploy production data pipelines, but I don’t like doing this for research. If you have multiple Python sessions or notebooks, this approach makes it easy for you to accidentally end up with multiple clusters on your computer. It also makes it harder to view the logs, and find the address of the Dask dashboard."
},
{
"code": null,
"e": 4598,
"s": 4581,
"text": "Open a terminal."
},
{
"code": null,
"e": 4615,
"s": 4598,
"text": "$ dask-scheduler"
},
{
"code": null,
"e": 4639,
"s": 4615,
"text": "Open a second terminal."
},
{
"code": null,
"e": 4674,
"s": 4639,
"text": "$ dask-worker tcp://127.0.0.1:8786"
},
{
"code": null,
"e": 4751,
"s": 4674,
"text": "In your Python session (possibly a Jupyter notebook), execute the following:"
},
{
"code": null,
"e": 4827,
"s": 4751,
"text": "from dask.distributed import Client client = Client('tcp://127.0.0.1:8786')"
},
{
"code": null,
"e": 5151,
"s": 4827,
"text": "There you go. The default address for the dask-scheduler is tcp://127.0.0.1:8786 and that second command was enough to set up Dask workers connected to the scheduler. The best part of this approach is that all the logs for all of your work will be in the second terminal. To shut it down, just hit ctrl-c in both terminals."
},
{
"code": null,
"e": 5530,
"s": 5151,
"text": "Python has this annoying thing called the global interpreter lock. You don’t need to understand too much about it, except that it means that Python can’t really leverage multiple threads very well. The general exceptions to this rule are code that is mostly doing I/O (downloading data), or code that is leveraging mostly C++ and other non-python libraries (NumPy, for example)."
},
{
"code": null,
"e": 5674,
"s": 5530,
"text": "Most users that we’ve worked with are best served using processes over threads (you can mix them as well). This is how I do this on my machine."
},
{
"code": null,
"e": 5801,
"s": 5674,
"text": "I have 40 GB of RAM (Thank you System76!!)I have 4 cores. So I want 4 workers.This means each worker can consume 10 GB of RAM."
},
{
"code": null,
"e": 5844,
"s": 5801,
"text": "I have 40 GB of RAM (Thank you System76!!)"
},
{
"code": null,
"e": 5881,
"s": 5844,
"text": "I have 4 cores. So I want 4 workers."
},
{
"code": null,
"e": 5930,
"s": 5881,
"text": "This means each worker can consume 10 GB of RAM."
},
{
"code": null,
"e": 5996,
"s": 5930,
"text": "$ dask-worker tcp://127.0.0.1:8786 --nprocs 4 --memory-limit 10GB"
},
{
"code": null,
"e": 6249,
"s": 5996,
"text": "Start simple, and scale up gradually. At Saturn, we can give you 4 terabyte instances for all your local cluster needs. And if that’s not enough, you can then run the same code on a multi-node (and multi-GPU) cluster, with a few clicks. Happy Dask-ing!"
},
{
"code": null,
"e": 6564,
"s": 6249,
"text": "Disclaimer: I’m the CTO of Saturn Cloud. We make it easy to connect your team with cloud resources. Want to use Jupyter and Dask? Deploy models, dashboards or jobs? Work from your laptop, or a 4 TB Jupyter instance? Get complete transparency into who is consuming what cloud resources? We do all of that, and more."
}
] |
ReactJS Blueprint Dialog Component - GeeksforGeeks
|
08 Apr, 2022
BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications.
Dialog Component allows the user to show content on top of an overlay that requires user interaction. We can use the following approach in ReactJS to use the Blueprint Dialog Component.
Dialog Props:
autoFocus: It is used to indicate whether the overlay should acquire application focus when it first opens.
backdropClassName: It is used to denote the CSS class names to apply to the backdrop element.
backdropProps: It is used to denote the HTML props for the backdrop element.
canEscapeKeyClose: It is used to indicate whether pressing the ESC key should invoke onClose.
canOutsideClickClose: It is used to indicate whether clicking outside overlay element should invoke onClose.
className: It is used to denote a space-delimited list of class names to pass along to a child element.
enforceFocus: It is used to indicate whether the overlay should prevent focus from leaving itself.
icon: It is used to denote the name of an icon or an icon element to render in the dialog’s header.
isCloseButtonShow: It is used to indicate whether to show the close button in the dialog’s header or not.
isOpen: It is used to toggle the visibility of the overlay and its children.
lazy: The Portal containing the children is created and attached to the DOM when the overlay is opened for the first time when this is set to true and usePortal is true.
onClose: It is a callback that is triggered when user interaction causes the overlay to close.
onClosed: It is used to denote a lifecycle method invoked just after the CSS close transition ends but before the child has been removed from the DOM.
onClosing: It is used to denote a lifecycle method invoked just before CSS close transition begins on a child.
onOpened: It is used to denote a lifecycle method invoked just after the CSS open transition ends.
onOpening: It is used to denote a lifecycle method invoked just after mounting the child in the DOM but just before the CSS open transition begins.
portalClassName: It is used to denote a space-delimited string of class names applied to the Portal element if usePortal is true.
portalContainer: It is used to denote the container element into which the overlay renders its contents when usePortal is true.
style: It is used to denote the CSS styles to apply to the dialog.
title: It is used to denote the title of the dialog.
transitionDuration: It is used to indicate how long the overlay appears/disappears transition takes in milliseconds.
transitionName: It is used to denote the name of the transition for internal CSSTransition.
usePortal: It is used to indicate whether the overlay should be rendered inside a Portal attached to portalContainer prop.
MultistepDialog Props:
autoFocus: It is used to indicate whether the overlay should acquire application focus when it first opens.
backButtonProps: It is used to denote the props for the back button.
backdropClassName: It is used to denote the CSS class names to apply to the backdrop element.
backdropProps: It is used to denote the HTML props for the backdrop element.
canEscapeKeyClose: It is used to indicate whether pressing the ESC key should invoke onClose.
canOutsideClickClose: It is used to indicate whether clicking outside overlay element should invoke onClose.
className: It is used to denote a space-delimited list of class names to pass along to a child element.
enforceFocus: It is used to indicate whether the overlay should prevent focus from leaving itself.
finalButtonProps: It is used to denote the props for the button to display on the final step.
icon: It is used to denote the name of an icon or an icon element to render in the dialog’s header.
initialStepIndex: It is used to denote the initial step-index.
isCloseButtonShow: It is used to indicate whether to show the close button in the dialog’s header or not.
isOpen: It is used to toggle the visibility of the overlay and its children.
lazy: The Portal containing the children is created and attached to the DOM when the overlay is opened for the first time when this is set to true and usePortal is true.
nextButtonProps: It is used to denote the props for the next button.
onChange: It is a callback function that is triggered when the user selects a different step by clicking on back, next, or a step itself.
onClose: It is a callback that is triggered when user interaction causes the overlay to close.
onClosed: It is used to denote a lifecycle method invoked just after the CSS close transition ends but before the child has been removed from the DOM.
onClosing: It is used to denote a lifecycle method invoked just before CSS close transition begins on a child.
onOpened: It is used to denote a lifecycle method invoked just after the CSS open transition ends.
onOpening: It is used to denote a lifecycle method invoked just after mounting the child in the DOM but just before the CSS open transition begins.
portalClassName: It is used to denote a space-delimited string of class names applied to the Portal element if usePortal is true.
portalContainer: It is used to denote the container element into which the overlay renders its contents when usePortal is true.
resetOnClose: It is used to indicate whether to reset the dialog state to its initial state on close or not.
style: It is used to denote the CSS styles to apply to the dialog.
title: It is used to denote the title of the dialog.
transitionDuration: It is used to indicate how long the overlay appears/disappears transition takes in milliseconds.
transitionName: It is used to denote the name of the transition for internal CSSTransition.
usePortal: It is used to indicate whether the overlay should be rendered inside a Portal attached to portalContainer prop.
DialogStep Props:
backButtonProps: It is used to denote the props for the back button.
className: It is used to denote a space-delimited list of class names to pass along to a child element.
id: It is used to denote the unique identifier used to identify which step is selected.
nextButtonProps: It is used to denote the props for the next button.
panel: It is used to denote the panel content.
panelClassName: It is used to denote the space-delimited string of class names that are applied to multistep dialog panel container.
title: It is used to denote the content of step title element, rendered in a list left of the active panel.
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 @blueprintjs/core
npm install @blueprintjs/core
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 '@blueprintjs/core/lib/css/blueprint.css';import { Dialog, Classes } from "@blueprintjs/core"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint Dialog Component</h4> <Dialog title="Dialog Title" icon="info-sign" isOpen={true} > <div className={Classes.DIALOG_BODY}> <p> Sample Dialog Content to display! </p> </div> </Dialog> </div> );} export default App;
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://blueprintjs.com/docs/#core/components/dialog
Blueprint-Core
Blueprint-Overlays
React-Blueprint
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to filter object array based on attributes?
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": 26667,
"s": 26639,
"text": "\n08 Apr, 2022"
},
{
"code": null,
"e": 26841,
"s": 26667,
"text": "BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications."
},
{
"code": null,
"e": 27027,
"s": 26841,
"text": "Dialog Component allows the user to show content on top of an overlay that requires user interaction. We can use the following approach in ReactJS to use the Blueprint Dialog Component."
},
{
"code": null,
"e": 27041,
"s": 27027,
"text": "Dialog Props:"
},
{
"code": null,
"e": 27149,
"s": 27041,
"text": "autoFocus: It is used to indicate whether the overlay should acquire application focus when it first opens."
},
{
"code": null,
"e": 27243,
"s": 27149,
"text": "backdropClassName: It is used to denote the CSS class names to apply to the backdrop element."
},
{
"code": null,
"e": 27320,
"s": 27243,
"text": "backdropProps: It is used to denote the HTML props for the backdrop element."
},
{
"code": null,
"e": 27414,
"s": 27320,
"text": "canEscapeKeyClose: It is used to indicate whether pressing the ESC key should invoke onClose."
},
{
"code": null,
"e": 27523,
"s": 27414,
"text": "canOutsideClickClose: It is used to indicate whether clicking outside overlay element should invoke onClose."
},
{
"code": null,
"e": 27627,
"s": 27523,
"text": "className: It is used to denote a space-delimited list of class names to pass along to a child element."
},
{
"code": null,
"e": 27726,
"s": 27627,
"text": "enforceFocus: It is used to indicate whether the overlay should prevent focus from leaving itself."
},
{
"code": null,
"e": 27826,
"s": 27726,
"text": "icon: It is used to denote the name of an icon or an icon element to render in the dialog’s header."
},
{
"code": null,
"e": 27932,
"s": 27826,
"text": "isCloseButtonShow: It is used to indicate whether to show the close button in the dialog’s header or not."
},
{
"code": null,
"e": 28009,
"s": 27932,
"text": "isOpen: It is used to toggle the visibility of the overlay and its children."
},
{
"code": null,
"e": 28179,
"s": 28009,
"text": "lazy: The Portal containing the children is created and attached to the DOM when the overlay is opened for the first time when this is set to true and usePortal is true."
},
{
"code": null,
"e": 28274,
"s": 28179,
"text": "onClose: It is a callback that is triggered when user interaction causes the overlay to close."
},
{
"code": null,
"e": 28425,
"s": 28274,
"text": "onClosed: It is used to denote a lifecycle method invoked just after the CSS close transition ends but before the child has been removed from the DOM."
},
{
"code": null,
"e": 28536,
"s": 28425,
"text": "onClosing: It is used to denote a lifecycle method invoked just before CSS close transition begins on a child."
},
{
"code": null,
"e": 28635,
"s": 28536,
"text": "onOpened: It is used to denote a lifecycle method invoked just after the CSS open transition ends."
},
{
"code": null,
"e": 28783,
"s": 28635,
"text": "onOpening: It is used to denote a lifecycle method invoked just after mounting the child in the DOM but just before the CSS open transition begins."
},
{
"code": null,
"e": 28913,
"s": 28783,
"text": "portalClassName: It is used to denote a space-delimited string of class names applied to the Portal element if usePortal is true."
},
{
"code": null,
"e": 29041,
"s": 28913,
"text": "portalContainer: It is used to denote the container element into which the overlay renders its contents when usePortal is true."
},
{
"code": null,
"e": 29108,
"s": 29041,
"text": "style: It is used to denote the CSS styles to apply to the dialog."
},
{
"code": null,
"e": 29161,
"s": 29108,
"text": "title: It is used to denote the title of the dialog."
},
{
"code": null,
"e": 29278,
"s": 29161,
"text": "transitionDuration: It is used to indicate how long the overlay appears/disappears transition takes in milliseconds."
},
{
"code": null,
"e": 29370,
"s": 29278,
"text": "transitionName: It is used to denote the name of the transition for internal CSSTransition."
},
{
"code": null,
"e": 29493,
"s": 29370,
"text": "usePortal: It is used to indicate whether the overlay should be rendered inside a Portal attached to portalContainer prop."
},
{
"code": null,
"e": 29516,
"s": 29493,
"text": "MultistepDialog Props:"
},
{
"code": null,
"e": 29624,
"s": 29516,
"text": "autoFocus: It is used to indicate whether the overlay should acquire application focus when it first opens."
},
{
"code": null,
"e": 29693,
"s": 29624,
"text": "backButtonProps: It is used to denote the props for the back button."
},
{
"code": null,
"e": 29787,
"s": 29693,
"text": "backdropClassName: It is used to denote the CSS class names to apply to the backdrop element."
},
{
"code": null,
"e": 29864,
"s": 29787,
"text": "backdropProps: It is used to denote the HTML props for the backdrop element."
},
{
"code": null,
"e": 29958,
"s": 29864,
"text": "canEscapeKeyClose: It is used to indicate whether pressing the ESC key should invoke onClose."
},
{
"code": null,
"e": 30067,
"s": 29958,
"text": "canOutsideClickClose: It is used to indicate whether clicking outside overlay element should invoke onClose."
},
{
"code": null,
"e": 30171,
"s": 30067,
"text": "className: It is used to denote a space-delimited list of class names to pass along to a child element."
},
{
"code": null,
"e": 30270,
"s": 30171,
"text": "enforceFocus: It is used to indicate whether the overlay should prevent focus from leaving itself."
},
{
"code": null,
"e": 30364,
"s": 30270,
"text": "finalButtonProps: It is used to denote the props for the button to display on the final step."
},
{
"code": null,
"e": 30464,
"s": 30364,
"text": "icon: It is used to denote the name of an icon or an icon element to render in the dialog’s header."
},
{
"code": null,
"e": 30527,
"s": 30464,
"text": "initialStepIndex: It is used to denote the initial step-index."
},
{
"code": null,
"e": 30633,
"s": 30527,
"text": "isCloseButtonShow: It is used to indicate whether to show the close button in the dialog’s header or not."
},
{
"code": null,
"e": 30710,
"s": 30633,
"text": "isOpen: It is used to toggle the visibility of the overlay and its children."
},
{
"code": null,
"e": 30880,
"s": 30710,
"text": "lazy: The Portal containing the children is created and attached to the DOM when the overlay is opened for the first time when this is set to true and usePortal is true."
},
{
"code": null,
"e": 30949,
"s": 30880,
"text": "nextButtonProps: It is used to denote the props for the next button."
},
{
"code": null,
"e": 31087,
"s": 30949,
"text": "onChange: It is a callback function that is triggered when the user selects a different step by clicking on back, next, or a step itself."
},
{
"code": null,
"e": 31182,
"s": 31087,
"text": "onClose: It is a callback that is triggered when user interaction causes the overlay to close."
},
{
"code": null,
"e": 31333,
"s": 31182,
"text": "onClosed: It is used to denote a lifecycle method invoked just after the CSS close transition ends but before the child has been removed from the DOM."
},
{
"code": null,
"e": 31444,
"s": 31333,
"text": "onClosing: It is used to denote a lifecycle method invoked just before CSS close transition begins on a child."
},
{
"code": null,
"e": 31543,
"s": 31444,
"text": "onOpened: It is used to denote a lifecycle method invoked just after the CSS open transition ends."
},
{
"code": null,
"e": 31691,
"s": 31543,
"text": "onOpening: It is used to denote a lifecycle method invoked just after mounting the child in the DOM but just before the CSS open transition begins."
},
{
"code": null,
"e": 31821,
"s": 31691,
"text": "portalClassName: It is used to denote a space-delimited string of class names applied to the Portal element if usePortal is true."
},
{
"code": null,
"e": 31949,
"s": 31821,
"text": "portalContainer: It is used to denote the container element into which the overlay renders its contents when usePortal is true."
},
{
"code": null,
"e": 32058,
"s": 31949,
"text": "resetOnClose: It is used to indicate whether to reset the dialog state to its initial state on close or not."
},
{
"code": null,
"e": 32125,
"s": 32058,
"text": "style: It is used to denote the CSS styles to apply to the dialog."
},
{
"code": null,
"e": 32178,
"s": 32125,
"text": "title: It is used to denote the title of the dialog."
},
{
"code": null,
"e": 32295,
"s": 32178,
"text": "transitionDuration: It is used to indicate how long the overlay appears/disappears transition takes in milliseconds."
},
{
"code": null,
"e": 32387,
"s": 32295,
"text": "transitionName: It is used to denote the name of the transition for internal CSSTransition."
},
{
"code": null,
"e": 32510,
"s": 32387,
"text": "usePortal: It is used to indicate whether the overlay should be rendered inside a Portal attached to portalContainer prop."
},
{
"code": null,
"e": 32530,
"s": 32512,
"text": "DialogStep Props:"
},
{
"code": null,
"e": 32599,
"s": 32530,
"text": "backButtonProps: It is used to denote the props for the back button."
},
{
"code": null,
"e": 32703,
"s": 32599,
"text": "className: It is used to denote a space-delimited list of class names to pass along to a child element."
},
{
"code": null,
"e": 32791,
"s": 32703,
"text": "id: It is used to denote the unique identifier used to identify which step is selected."
},
{
"code": null,
"e": 32860,
"s": 32791,
"text": "nextButtonProps: It is used to denote the props for the next button."
},
{
"code": null,
"e": 32907,
"s": 32860,
"text": "panel: It is used to denote the panel content."
},
{
"code": null,
"e": 33040,
"s": 32907,
"text": "panelClassName: It is used to denote the space-delimited string of class names that are applied to multistep dialog panel container."
},
{
"code": null,
"e": 33148,
"s": 33040,
"text": "title: It is used to denote the content of step title element, rendered in a list left of the active panel."
},
{
"code": null,
"e": 33198,
"s": 33148,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 33293,
"s": 33198,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 33357,
"s": 33293,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 33389,
"s": 33357,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 33502,
"s": 33389,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 33602,
"s": 33502,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 33616,
"s": 33602,
"text": "cd foldername"
},
{
"code": null,
"e": 33750,
"s": 33616,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install @blueprintjs/core"
},
{
"code": null,
"e": 33780,
"s": 33750,
"text": "npm install @blueprintjs/core"
},
{
"code": null,
"e": 33832,
"s": 33780,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 33850,
"s": 33832,
"text": "Project Structure"
},
{
"code": null,
"e": 33980,
"s": 33850,
"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": 33987,
"s": 33980,
"text": "App.js"
},
{
"code": "import React from 'react'import '@blueprintjs/core/lib/css/blueprint.css';import { Dialog, Classes } from \"@blueprintjs/core\"; function App() { return ( <div style={{ display: 'block', width: 400, padding: 30 }}> <h4>ReactJS Blueprint Dialog Component</h4> <Dialog title=\"Dialog Title\" icon=\"info-sign\" isOpen={true} > <div className={Classes.DIALOG_BODY}> <p> Sample Dialog Content to display! </p> </div> </Dialog> </div> );} export default App;",
"e": 34659,
"s": 33987,
"text": null
},
{
"code": null,
"e": 34772,
"s": 34659,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 34782,
"s": 34772,
"text": "npm start"
},
{
"code": null,
"e": 34881,
"s": 34782,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 34945,
"s": 34881,
"text": "Reference: https://blueprintjs.com/docs/#core/components/dialog"
},
{
"code": null,
"e": 34960,
"s": 34945,
"text": "Blueprint-Core"
},
{
"code": null,
"e": 34979,
"s": 34960,
"text": "Blueprint-Overlays"
},
{
"code": null,
"e": 34995,
"s": 34979,
"text": "React-Blueprint"
},
{
"code": null,
"e": 35006,
"s": 34995,
"text": "JavaScript"
},
{
"code": null,
"e": 35014,
"s": 35006,
"text": "ReactJS"
},
{
"code": null,
"e": 35031,
"s": 35014,
"text": "Web Technologies"
},
{
"code": null,
"e": 35129,
"s": 35031,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35169,
"s": 35129,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35230,
"s": 35169,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35271,
"s": 35230,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 35293,
"s": 35271,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 35341,
"s": 35293,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 35384,
"s": 35341,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 35429,
"s": 35384,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 35494,
"s": 35429,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 35562,
"s": 35494,
"text": "How to pass data from one component to other component in ReactJS ?"
}
] |
Convert CSV to list in R - GeeksforGeeks
|
16 May, 2021
In this article, we will discuss how to convert the content of the CSV file to list in R Programming Language.
CSV Used:
In this method, the file is first read into the R program and then one by one using for loop the columns are extracted and converted to list explicitly using list() function.
Example :
R
df=read.csv("item.csv") lst1=list() for(i in 1:ncol(df)) { lst1[[i]] <- df[ , i] } names(lst1)=colnames(df) print(lst1)
Output :
In this method, the file is first read and then each column is extracted one by one explicitly with the name of the column. Then using the list method, all the extracted columns are converted to a list using list() in one go. Here names of the extracted columns is given as comma-separated values to list() to get the required functionality.
Example :
R
df=read.csv('item.csv') a=df$idb=df$itemc=df$quantityd=df$pricee=df$boughtf=df$forenoong=df$afternoonh=df$X lst=list(a,b,c,d,e,f,g,h) names(lst)=colnames(df) print(lst)
Output :
R List-Programs
R-CSV
R-List
R Language
R Programs
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
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 26598,
"s": 26487,
"text": "In this article, we will discuss how to convert the content of the CSV file to list in R Programming Language."
},
{
"code": null,
"e": 26608,
"s": 26598,
"text": "CSV Used:"
},
{
"code": null,
"e": 26783,
"s": 26608,
"text": "In this method, the file is first read into the R program and then one by one using for loop the columns are extracted and converted to list explicitly using list() function."
},
{
"code": null,
"e": 26793,
"s": 26783,
"text": "Example :"
},
{
"code": null,
"e": 26795,
"s": 26793,
"text": "R"
},
{
"code": "df=read.csv(\"item.csv\") lst1=list() for(i in 1:ncol(df)) { lst1[[i]] <- df[ , i] } names(lst1)=colnames(df) print(lst1) ",
"e": 26933,
"s": 26795,
"text": null
},
{
"code": null,
"e": 26942,
"s": 26933,
"text": "Output :"
},
{
"code": null,
"e": 27284,
"s": 26942,
"text": "In this method, the file is first read and then each column is extracted one by one explicitly with the name of the column. Then using the list method, all the extracted columns are converted to a list using list() in one go. Here names of the extracted columns is given as comma-separated values to list() to get the required functionality."
},
{
"code": null,
"e": 27294,
"s": 27284,
"text": "Example :"
},
{
"code": null,
"e": 27296,
"s": 27294,
"text": "R"
},
{
"code": "df=read.csv('item.csv') a=df$idb=df$itemc=df$quantityd=df$pricee=df$boughtf=df$forenoong=df$afternoonh=df$X lst=list(a,b,c,d,e,f,g,h) names(lst)=colnames(df) print(lst)",
"e": 27469,
"s": 27296,
"text": null
},
{
"code": null,
"e": 27478,
"s": 27469,
"text": "Output :"
},
{
"code": null,
"e": 27494,
"s": 27478,
"text": "R List-Programs"
},
{
"code": null,
"e": 27500,
"s": 27494,
"text": "R-CSV"
},
{
"code": null,
"e": 27507,
"s": 27500,
"text": "R-List"
},
{
"code": null,
"e": 27518,
"s": 27507,
"text": "R Language"
},
{
"code": null,
"e": 27529,
"s": 27518,
"text": "R Programs"
},
{
"code": null,
"e": 27627,
"s": 27529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27679,
"s": 27627,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27714,
"s": 27679,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27752,
"s": 27714,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27810,
"s": 27752,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27853,
"s": 27810,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27911,
"s": 27853,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27954,
"s": 27911,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28003,
"s": 27954,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28053,
"s": 28003,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
What is the maximum length of MySQL VARCHAR column?
|
Actually VARCHAR data type stores variable-length character data in single byte and multibyte character Syntax for this data type is VARCHAR(n),where n is the maximum number of characters and it must be specified while creating the table. Before MySQL 5.03 the value of n can be in the range of 0 to 255 but in and after MySQL 5.03 the value can be in the range of 0 to 65,535.
The maximum number of characters stored in VARCHAR depends upon maximum row size and character set used. If we are using ASCII character set then it can store 65,535 characters because ASCII would use 1 byte per character. On the other hand, if we are using utf8 character set then the character limit would be of 21,844 because utf8 will use 3 bytes per characters. Maximum row size limit is 65,535 bytes which means that including all columns it must not be more than 65,535 bytes.
mysql> Create Table var_test(FName Varchar(32765) NOT NULL, LName Varchar(32766)
NOT NULL);
Query OK, 0 rows affected (0.25 sec)
The query above created a table with two columns, FName Varchar(32765) and LName Varchar(32766). Hence the total length would be 32765+2+32766+2=65535(2 bytes are used each column for storing length).
mysql> Create Table var_test1(FName varchar(32766) NOT NULL, LName Varchar(32766)
NOT NULL);
ERROR 1118 (42000): Row size too large. The maximum row size for the used
table
type, not counting BLOBs, is 65535. You have to change some columns to TEXT
or BLOBs
Now, on increasing the length by 1 byte MySQL returns an error as shown in the query above.
|
[
{
"code": null,
"e": 1440,
"s": 1062,
"text": "Actually VARCHAR data type stores variable-length character data in single byte and multibyte character Syntax for this data type is VARCHAR(n),where n is the maximum number of characters and it must be specified while creating the table. Before MySQL 5.03 the value of n can be in the range of 0 to 255 but in and after MySQL 5.03 the value can be in the range of 0 to 65,535."
},
{
"code": null,
"e": 1924,
"s": 1440,
"text": "The maximum number of characters stored in VARCHAR depends upon maximum row size and character set used. If we are using ASCII character set then it can store 65,535 characters because ASCII would use 1 byte per character. On the other hand, if we are using utf8 character set then the character limit would be of 21,844 because utf8 will use 3 bytes per characters. Maximum row size limit is 65,535 bytes which means that including all columns it must not be more than 65,535 bytes."
},
{
"code": null,
"e": 2067,
"s": 1924,
"text": "mysql> Create Table var_test(FName Varchar(32765) NOT NULL, LName Varchar(32766)\n NOT NULL);\n Query OK, 0 rows affected (0.25 sec)"
},
{
"code": null,
"e": 2268,
"s": 2067,
"text": "The query above created a table with two columns, FName Varchar(32765) and LName Varchar(32766). Hence the total length would be 32765+2+32766+2=65535(2 bytes are used each column for storing length)."
},
{
"code": null,
"e": 2561,
"s": 2268,
"text": "mysql> Create Table var_test1(FName varchar(32766) NOT NULL, LName Varchar(32766)\n NOT NULL);\n ERROR 1118 (42000): Row size too large. The maximum row size for the used\n table\n type, not counting BLOBs, is 65535. You have to change some columns to TEXT\n or BLOBs"
},
{
"code": null,
"e": 2653,
"s": 2561,
"text": "Now, on increasing the length by 1 byte MySQL returns an error as shown in the query above."
}
] |
How to get button toggle state within HTML? - GeeksforGeeks
|
21 Apr, 2021
Toggle buttons are basically on/off buttons. A button can be switched from on to off state and vice-versa. This process is called toggling.Examples of toggle button:
The buttons on our switchboards are the best example of toggle buttons.
Some of the buttons on our phones- the torch button, the mobile data button, the wifi button, flight mode, Bluetooth button can be either on or off. These are all toggle buttons.
Approach: Now let’s see how to design these buttons in HTML with the help of Bootstrap.Example 1: The default toggle button Code in HTML (Using Bootstrap):
html
<div class="toggle"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="toggleSwitches"> <label class="custom-control-label" for="toggleSwitches"> TOGGLE</label> </div></div>
Style using CSS:
html
<style> .toggle, { margin-top: 100px; font-size: 20px; } h1{ color: green; font-size: 30px; } </style>
Complete Code:
html
<!DOCTYPE html><html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" /> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" type="text/css" href="style.css" /> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Lato:ital, wght@0, 100;0, 300;0, 400;1, 300&display=swap" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/gijgo@1.8.1/combined/js/gijgo.min.js" type="text/javascript"></script> <link href="https://cdn.jsdelivr.net/npm/gijgo@1.8.1/combined/css/gijgo.min.js" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="css/lightbox.min.css" /> <script type="text/javascript" src="js/lightbox-plus-jquery.min.js"> </script> <title>Buttons</title> <h1>GeeksforGeeks</h1> <style> .toggle { margin-top: 100px; font-size: 20px; } h1 { color: green; font-size: 30px; } </style> </head> <body> <div class="toggle"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="toggleSwitches" /> <label class="custom-control-label" for="toggleSwitches"> TOGGLE </label> </div> </div> </body></html>
Output:
The switches use a custom-switch class to change it into toggle switches. Slight modifications can be done in the code to get desired resultsExample 2: The toggle switches can also be given a checked attribute. If it is done so then the toggle button will always be pre-selected when the page loads. The checked attribute is a boolean attribute.Code snippet:
html
<div class="toggle"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="toggleSwitches" checked /> <label class="custom-control-label" for="toggleSwitches"> CHECKED TOGGLE BUTTON </label> </div></div>
Output:
Example 3: We can also add the disabled attribute to the toggle button . If this is done then the switch can never be used and clicked.Code snippet:
html
<div class="toggle"> <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" id="toggleSwitches" disabled /> <label class="custom-control-label" for="toggleSwitches"> DISABLED TOGGLE BUTTON</label> </div></div>
Output:
arorakashish0911
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 26017,
"s": 25989,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 26185,
"s": 26017,
"text": "Toggle buttons are basically on/off buttons. A button can be switched from on to off state and vice-versa. This process is called toggling.Examples of toggle button: "
},
{
"code": null,
"e": 26257,
"s": 26185,
"text": "The buttons on our switchboards are the best example of toggle buttons."
},
{
"code": null,
"e": 26436,
"s": 26257,
"text": "Some of the buttons on our phones- the torch button, the mobile data button, the wifi button, flight mode, Bluetooth button can be either on or off. These are all toggle buttons."
},
{
"code": null,
"e": 26594,
"s": 26436,
"text": "Approach: Now let’s see how to design these buttons in HTML with the help of Bootstrap.Example 1: The default toggle button Code in HTML (Using Bootstrap): "
},
{
"code": null,
"e": 26599,
"s": 26594,
"text": "html"
},
{
"code": "<div class=\"toggle\"> <div class=\"custom-control custom-switch\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"toggleSwitches\"> <label class=\"custom-control-label\" for=\"toggleSwitches\"> TOGGLE</label> </div></div>",
"e": 26881,
"s": 26599,
"text": null
},
{
"code": null,
"e": 26900,
"s": 26881,
"text": "Style using CSS: "
},
{
"code": null,
"e": 26905,
"s": 26900,
"text": "html"
},
{
"code": "<style> .toggle, { margin-top: 100px; font-size: 20px; } h1{ color: green; font-size: 30px; } </style>",
"e": 27119,
"s": 26905,
"text": null
},
{
"code": null,
"e": 27136,
"s": 27119,
"text": "Complete Code: "
},
{
"code": null,
"e": 27141,
"s": 27136,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- Latest compiled and minified CSS --> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" /> <!-- jQuery library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script> <!-- Popper JS --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> </script> <!-- Latest compiled JavaScript --> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\"> </script> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" /> <link href=\"https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css\" rel=\"stylesheet\" /> <link href=\"https://fonts.googleapis.com/css2?family=Lato:ital, wght@0, 100;0, 300;0, 400;1, 300&display=swap\" rel=\"stylesheet\" /> <script src=\"https://cdn.jsdelivr.net/npm/gijgo@1.8.1/combined/js/gijgo.min.js\" type=\"text/javascript\"></script> <link href=\"https://cdn.jsdelivr.net/npm/gijgo@1.8.1/combined/css/gijgo.min.js\" rel=\"stylesheet\" type=\"text/css\" /> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/lightbox.min.css\" /> <script type=\"text/javascript\" src=\"js/lightbox-plus-jquery.min.js\"> </script> <title>Buttons</title> <h1>GeeksforGeeks</h1> <style> .toggle { margin-top: 100px; font-size: 20px; } h1 { color: green; font-size: 30px; } </style> </head> <body> <div class=\"toggle\"> <div class=\"custom-control custom-switch\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"toggleSwitches\" /> <label class=\"custom-control-label\" for=\"toggleSwitches\"> TOGGLE </label> </div> </div> </body></html>",
"e": 29465,
"s": 27141,
"text": null
},
{
"code": null,
"e": 29475,
"s": 29465,
"text": "Output: "
},
{
"code": null,
"e": 29838,
"s": 29477,
"text": "The switches use a custom-switch class to change it into toggle switches. Slight modifications can be done in the code to get desired resultsExample 2: The toggle switches can also be given a checked attribute. If it is done so then the toggle button will always be pre-selected when the page loads. The checked attribute is a boolean attribute.Code snippet: "
},
{
"code": null,
"e": 29843,
"s": 29838,
"text": "html"
},
{
"code": "<div class=\"toggle\"> <div class=\"custom-control custom-switch\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"toggleSwitches\" checked /> <label class=\"custom-control-label\" for=\"toggleSwitches\"> CHECKED TOGGLE BUTTON </label> </div></div>",
"e": 30182,
"s": 29843,
"text": null
},
{
"code": null,
"e": 30192,
"s": 30182,
"text": "Output: "
},
{
"code": null,
"e": 30343,
"s": 30192,
"text": "Example 3: We can also add the disabled attribute to the toggle button . If this is done then the switch can never be used and clicked.Code snippet: "
},
{
"code": null,
"e": 30348,
"s": 30343,
"text": "html"
},
{
"code": "<div class=\"toggle\"> <div class=\"custom-control custom-switch\"> <input type=\"checkbox\" class=\"custom-control-input\" id=\"toggleSwitches\" disabled /> <label class=\"custom-control-label\" for=\"toggleSwitches\"> DISABLED TOGGLE BUTTON</label> </div></div>",
"e": 30683,
"s": 30348,
"text": null
},
{
"code": null,
"e": 30693,
"s": 30683,
"text": "Output: "
},
{
"code": null,
"e": 30712,
"s": 30695,
"text": "arorakashish0911"
},
{
"code": null,
"e": 30727,
"s": 30712,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 30734,
"s": 30727,
"text": "Picked"
},
{
"code": null,
"e": 30744,
"s": 30734,
"text": "Bootstrap"
},
{
"code": null,
"e": 30761,
"s": 30744,
"text": "Web Technologies"
},
{
"code": null,
"e": 30859,
"s": 30761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30900,
"s": 30859,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 30963,
"s": 30900,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 31004,
"s": 30963,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 31037,
"s": 31004,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 31084,
"s": 31037,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 31124,
"s": 31084,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31157,
"s": 31124,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31202,
"s": 31157,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31245,
"s": 31202,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
I analyzed hundreds of user’s Tinder data — including messages — so you don’t have to. | by Alyssa Beatriz Fernandez | Towards Data Science
|
I read Modern Romance by Aziz Ansari in 2016 and beyond a shadow of a doubt, it is one of the most influential books I’ve ever read. At the time, I was a snot-nosed college student who was still dating someone from high school.
The numbers and figures given by the book about online dating success struck me as being callous. Millennials and their predecessors were blessed and cursed with the advent of the internet. The proliferation of partner-choice desensitizes us and gives us unrealistic expectations when it came to searching for our “soulmate.”
Instead of feeling dissuaded, I felt inspired. Within a few months I broke up with my high school boyfriend and entered the online dating world myself. I quickly learned that dating is awful in it of itself, and it becomes exacerbated when it goes digital.
Tinder. Bumble. Hinge. CoffeeMeetsBagel. If it was on the App Store then I may have used it. Despite having mostly indifferent-to-underwhelming dating experiences, I couldn’t shake this fascination I had with these godforsaken apps. I decided to channel that fascination as part of my final project for the Lede Program for Data Journalism at Columbia University.
Using nothing more than Python, Jupyter Notebook and frantic emails, I went head-first to create a project using dating app data.
Now that I had a project in mind, I needed to find the actual data. This was a huge hurdle.
First, I needed to choose an app to focus on. After browsing on r/dataisbeautiful for a few hours, I decided on Tinder due to its popularity.
I learned from Reddit and by reading other articles that I could request my own data. A few years ago, The Guardian wrote a story about how Tinder was using personal data. Part of the company’s response was to make user data available upon request
www.theguardian.com
Seems easy enough to do, right? Except, I didn’t have any data to download. I had a habit of downloading Tinder to use for a few months before deleting my account out of frustration only to repeat the process.
I knew the data existed out there and despite the obstacles, I was determined to find it. After several rounds of googling “Tinder data” and coming up empty, I went back to Reddit. I noticed on r/dataisbeautiful that some people were visualizing their Tinder data using a website called Swipestats.io.
I decided to shoot my shot and send an email to the site’s owner asking if he could share anonymous Tinder data with me for my project. He agreed (Thank you, Kris).
Next thing you know, I’m sitting on one JSON with 556 Tinder profiles.
This was a complete nightmare.
I’ve lost dozens of hours of my life not only trying to make sense of the data, but to clean it as well. By the end, I was in a very committed relationship with an overstuffed JSON.
The first obstacle I faced was figuring out how to open the file. It is big and whenever I tried to upload it to a notebook, I would get an error. I spoke with my mentor from the Lede Program (Thank you, Jeff) and he advised to run it through a JSON lint. I had no idea what that was.
I felt useless that I could barley open a large JSON. Things were looking bleak but I was hard-bent on creating a project using Tinder data.
Long story short, I converted the JSON into a .txt file then split the large .txt file into smaller ones using this site. By the miracle of some deity, the website split each .txt file perfectly by each person’s file. Next, I converted the newly spit-up .txt files back into JSON format. Now I had a folder with 556 JSONs.
# Loading the dataimport jsonf = open(“user_x.json”, encoding=”utf-8")data = json.load(f)
Finally, I was able to open my data. To my amazement, I noticed that messages were included.
I knew I had to prioritize and decided to focus on only three different objects, conversations, conversationsMeta and user. In the flowchart, I outlined the information in each object.
The possibilities were endless on what I could do, but I still wasn’t done cleaning the data. The next obstacle was organizing it.
My next step was to organize the files by gender and language. A lot of the articles I read liked to compare men and women’s experiences with dating, so I wanted to have those separate datasets. Additionally, I received quite an international set that was sprinkled in languages such as Japanese, Spanish, or German. As much as I appreciate the diversity, I only wanted to work with English profiles.
I had no idea where to start with organizing, so I went to office hours (Thank you, Thanasis). After a lot of head-scratching on Gather, we—mostly Thanasis— found a solution.
import shutilimport osimport globfrom os import pathall_files = '/directory'male = "/directory/MALE"female = "/directory/FEMALE"files = glob.glob(all_files+"/*.json")for file in files: with open(file, encoding="utf-8") as f: data = json.load(f) stat = data["user"] for stats in stat: if stat["gender"] == "M": try: shutil.move(os.path.join(all_files, file), male) except: pass else: try: shutil.move(os.path.join(all_files, file), female) except: pass
This code simply moved a JSON to its respective folder whether it was male or female.
I tried to write a similar code to separate by language using TextBlob and langdetect. It didn’t work. Out of pure spite, I separated the files by hand based on language.
By this point I’m feeling delirious but I’m almost at the end. My last step was to save the data into friendly CSVs, leaving me ~300 English-speaking data.
Note: The Tinder messages came with HTML tags. I included code to remove them below.
all_files = '/GENDER/ENGLISH'files = glob.glob(all_files+"/*.json")# HTML parser codefrom io import StringIOfrom html.parser import HTMLParserclass MLStripper(HTMLParser): def __init__(self): super().__init__() self.reset() self.strict = False self.convert_charrefs= True self.text = StringIO() def handle_data(self, d): self.text.write(d) def get_data(self): return self.text.getvalue()def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data()for file in files: with open(file, encoding="utf-8") as q: data = json.load(q) all_convo = data["conversations"] text = [] for message in all_convo: for messages in message["messages"]: messages["final_messages"] = "" updated = messages["message"] messages["final_messages"] = strip_tags(updated) text.append(messages) with open('GENDER_convos.csv', 'a') as csvfile: field_names = ['to', 'from', 'message', 'sent_date', 'final_messages'] writer = csv.DictWriter(csvfile, fieldnames=field_names, extrasaction='ignore') writer.writeheader() writer.writerows(text)
for file in files: with open(file, encoding="utf-8") as q: data = json.load(q) user_data = [] user_data.append(data["conversationsMeta"]) field_names = ['nrOfConversations', 'longestConversation', 'longestConversationInDays', 'averageConversationLength', 'averageConversationLengthInDays', 'medianConversationLength', 'medianConversationLengthInDays', 'nrOfOneMessageConversations', 'percentOfOneMessageConversations', 'nrOfGhostingsAfterInitialMessage'] with open('GENDER_convometa.csv', 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writeheader() writer.writerows(user_data)
for file in files: with open(file, encoding="utf-8") as q: data = json.load(q) user_data = [] md = data["user"] for job in md['jobs']: if job['title'] == None: pass else: md['jobs'] = job['title'] try: for school in md['schools']: if school['name'] == None: pass else: md['schools'] = school['name'] except: pass user_data.append(md) field_names = ['birthDate', 'ageFilterMin', 'ageFilterMax', 'cityName', 'country', 'createDate', 'education', 'gender', 'interestedIn', 'genderFilter', 'instagram', 'spotify', 'jobs', 'educationLevel', 'schools'] with open('GENDER_md.csv', 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writeheader() writer.writerows(user_data)
Is data ever completely cleaned? No. It’s an endless task.
Before you get too excited, I need to admit that just about everything I found is kind of boring. I spent the vast majority of my time cleaning the data so this part is a little dull, especially considering that I’m writing this at 10:54 PM and am supposed to turn this in at 9:00 AM tomorrow.
You live and you learn.
I made an analysis based on the three CSVs made earlier. As a reminder, they each contain conversations, conversationsMeta and user metadata. The code is available here.
Side note: I was heavily influenced by this article from Data Drive that analyzed Tinder data made from bots. That article goes in much greater depth and uses substantially cleaner code.
This was arguably the most tedious of all the datasets because it contains half a million Tinder messages. The downside is that Tinder only stores messages sent and not received.
The first thing I did with conversations was to create a language model to detect flirtation. The final product is rudimentary at best and can be read about here.
Moving forward, the first analysis I made was to discover what are the most commonly used words and emojis among users. In order to avoid crashing my computer, I used only 200,000 messages with an even mix of men and women.
So what are the top ten words?
Riveting.
To make it more exciting, I borrowed what Data Dive did and made a word cloud in the shape of the iconic Tinder flame after filtering out stop words.
Yeah, yeah, yeah. Words are great— but what about emojis?
Fun fact: My biggest pet peeve is the laugh-cry emoji, otherwise known as : joy : in shortcode. I dislike it so much I won’t even display it in this article outside of the graph. I vote to retire it immediately and indefinitely.
How much do these results vary by gender?
It seems that “like” is still the reining champion among both genders. Although, I think it’s interesting how “hey” appears in the top ten for men but not women. Could it be because men are expected to initiate conversations? Possibly.
What about emoji comparisons?
It seems that female users use flirtier emojis (😍, 😘) more often than male users. Still, I’m upset but not surprised that : joy : transcends gender when it comes to dominating the emoji charts.
This portion was the most straightforward but could have also used the most elbow grease. For now, I used it to find averages.
These are the keys available in this dataframe:
[‘nrOfConversations’, ‘longestConversation’, ‘longestConversationInDays’, ‘averageConversationLength’, ‘averageConversationLengthInDays’, ‘medianConversationLength’, ‘medianConversationLengthInDays’, ‘nrOfOneMessageConversations’, ‘percentOfOneMessageConversations’, ‘nrOfGhostingsAfterInitialMessage’, ‘Sex’]
The ones that stick out to me are nrOfConversations, nrOfOneMessageConversations and nrOfGhostingsAfterInitialMessage.
import pandas as pdimport numpy as npcmd = pd.read_csv('all_eng_convometa.csv')# Average number of conversations between both sexesprint("The average number of total Tinder conversations for both sexes is", cmd.nrOfConversations.mean().round())# Average number of conversations separated by sexprint("The average number of total Tinder conversations for men is", cmd.nrOfConversations[cmd.Sex.str.contains("M")].mean().round())print("The average number of total Tinder conversations for women is", cmd.nrOfConversations[cmd.Sex.str.contains("F")].mean().round())
The average number of total Tinder conversations for both sexes is 278.0.
The average number of total Tinder conversations for men is 218.0.
The average number of total Tinder conversations for women is 464.0.
Wow. The variation between men and women’s Tinder experiences is felt here.
# Average number of one message conversations between both sexesprint("The average number of one message Tinder conversations for both sexes is", cmd.nrOfOneMessageConversations.mean().round())# Average number of one message conversations separated by sexprint("The average number of one message Tinder conversations for men is", cmd.nrOfOneMessageConversations[cmd.Sex.str.contains("M")].mean().round())print("The average number of one message Tinder conversations for women is", cmd.nrOfOneMessageConversations[cmd.Sex.str.contains("F")].mean().round())
The average number of one message Tinder conversations for both sexes is 80.0.
The average number of one message Tinder conversations for men is 74.0.
The average number of one message Tinder conversations for women is 99.0.
Interesting. Especially after seeing that, on average, women receive just over double the messages on Tinder I’m surprised that they have the most one message conversations. However, it isn’t clarified who sent that first message. My guest is that it only reads when the user sends the first message since Tinder doesn’t save received messages. Only Tinder can clarify.
# Average number of ghostings between each sexprint("The average number of ghostings after one message between both sexes is", cmd.nrOfGhostingsAfterInitialMessage.mean().round())# Average number of ghostings separated by sexprint("The average number of ghostings after one message for men is", cmd.nrOfGhostingsAfterInitialMessage[cmd.Sex.str.contains("M")].mean().round())print("The average number of ghostings after one message for women is", cmd.nrOfGhostingsAfterInitialMessage[cmd.Sex.str.contains("F")].mean().round())
The average number of ghostings after one message between both sexes is 50.0.
The average number of ghostings after one message for men is 18.0.
The average number of ghostings after one message for women is 151.0
Similar to what I brought up previously on nrOfOneMessageConversations, it isn’t entirely clear who initiated the ghosting. I would be personally shocked if women were being ghosted more on Tinder.
Here are the objects available in the user metadata.
['birthDate', 'ageFilterMin', 'ageFilterMax', 'cityName', 'country', 'createDate', 'education', 'gender', 'interestedIn', 'genderFilter', 'instagram', 'spotify', 'jobs', 'educationLevel', 'schools']
I wanted to create an age column and decided that I could determine user age as (createDate - birthDate).
# CSV of updated_md has duplicatesmd = md.drop_duplicates(keep=False)from datetime import datetime, datemd['birthDate'] = pd.to_datetime(md.birthDate, format='%Y.%m.%d').dt.datemd['createDate'] = pd.to_datetime(md.createDate, format='%Y.%m.%d').dt.datemd['Age'] = (md['createDate'] - md['birthDate'])/365md['age'] = md['Age'].astype(str)md['age'] = md['age'].str[:3]md['age'] = md['age'].astype(int)# Dropping unnecessary columnsmd = md.drop(columns = 'Age')md = md.drop(columns= 'education')md = md.drop(columns= 'educationLevel')# Rearranging columnsmd = md[['gender', 'age', 'birthDate','createDate', 'jobs', 'schools', 'cityName', 'country', 'interestedIn', 'genderFilter', 'ageFilterMin', 'ageFilterMax','instagram', 'spotify']]# Replaces empty list with NaNmd = md.mask(md.applymap(str).eq('[]'))# Converting age filter to integermd['ageFilterMax'] = md['ageFilterMax'].astype(int)md['ageFilterMin'] = md['ageFilterMin'].astype(int)
Next, I wanted to find the mean of age, ageFilterMax and ageFilterMin. I noticed that the numbers were skewed unusually high so I checked my dataset and noticed some trolling. I removed the following from the dataset.
One person who had their age at 106 and another at 137. Two people aged 16 and one listed as 15. I also removed 17 people who put 1000 as their ageFilterMax and one person who listed 95.
I discovered the following:
# Combined age data print("The average user age for both genders is", all_age.age.mean().round()) print("The average user age filter maximum for both genders is", all_age.ageFilterMin.mean().round()) print("The average user age filter minimum for both genders is", all_age.ageFilterMax.mean().round()) print("--------------------") # By gender print("The average male user age is", all_age.age[all_age.gender.str.contains("M")].mean().round()) print("The average female user age", all_age.age[all_age.gender.str.contains("F")].mean().round()) print("--------------------") print("The average male user age filter maximum is", all_age.ageFilterMax[all_age.gender.str.contains("M")].mean().round()) print("The average female user age filter maximum is", all_age.ageFilterMax[all_age.gender.str.contains("F")].mean().round()) print("--------------------") print("The average male user age filter minumum is", all_age.ageFilterMin[all_age.gender.str.contains("M")].mean().round()) print("The average female user age filter minumum is", all_age.ageFilterMin[all_age.gender.str.contains("F")].mean().round())
The average user age for both genders is 24.0The average user age filter maximum for both genders is 21.0The average user age filter minimum for both genders is 31.0--------------------The average male user age is 24.0The average female user age 23.0--------------------The average male user age filter maximum is 31.0The average female user age filter maximum is 32.0--------------------The average male user age filter minumum is 20.0The average female user age filter minumum is 23.0
For added effect, I used this same data to make histograms.
Last, but certainly not least, I looked at jobs, schools, cities and country.
# Creating df of jobs listedjobs_df = pd.DataFrame(md['jobs'].value_counts(dropna=True))jobs_df.reset_index(level=0, inplace=True)jobs_df = jobs_df.rename(columns={"index": "Jobs", "jobs": "Count"})# Dropped index that said Falsejobs_df = jobs_df.drop(0)jobs_df = jobs_df.drop(1)jobs_df.head(10)
I know what you’re thinking— boring, right? I went through the list myself and selected my favorites.
These are the top ten schools from the Tinder data.
# Creating df of schools listedschool_df = pd.DataFrame(md['schools'].value_counts(dropna=True))school_df.reset_index(level=0, inplace=True)school_df = school_df.rename(columns={"index": "Schools", "schools": "Count"})# Dropped index that was empty listschool_df = school_df.drop(0)school_df.head(10)
Top ten cities based on the Tinder data.
# Creating df of cities listedcity_df = pd.DataFrame(md['cityName'].value_counts(dropna=True))city_df.reset_index(level=0, inplace=True)city_df = city_df.rename(columns={"index": "City", "cityName": "Count"})city_df.head(10)
Finally, the top ten countries. However, Tinder grouped states and country together so its messy to say the least.
# Creating df of countries/states listedcountry_df = pd.DataFrame(md['country'].value_counts(dropna=True))country_df.reset_index(level=0, inplace=True)country_df = country_df.rename(columns={"index": "Country/State", "country": "Count"})country_df.head(10)
All in all, the data is embarrassingly intimate but reveals the most boring parts of ourselves we already knew.
It was no surprise to discover that women on average have more conversations on Tinder than men or that : joy : is the most popular emoji used. Frankly, my findings are underwhelming but it’s a start.
I see a lot of potential for future projects using this data and I hardly touched the surface. Ideas for the future include building a more reliable flirtation analysis tool or creating a Tinder message bot.
In either case, I’m excited for what’s to come.
Thank you to Soma for not only being an excellent instructor but for spearheading the Lede program! Extra shoutouts for Carson, Thanasis, Jeff and Pete for helping me out.
And a special thank you to Swipestats.io for providing me with the data and can be contacted below.
Kristian Elset Bø
|
[
{
"code": null,
"e": 399,
"s": 171,
"text": "I read Modern Romance by Aziz Ansari in 2016 and beyond a shadow of a doubt, it is one of the most influential books I’ve ever read. At the time, I was a snot-nosed college student who was still dating someone from high school."
},
{
"code": null,
"e": 725,
"s": 399,
"text": "The numbers and figures given by the book about online dating success struck me as being callous. Millennials and their predecessors were blessed and cursed with the advent of the internet. The proliferation of partner-choice desensitizes us and gives us unrealistic expectations when it came to searching for our “soulmate.”"
},
{
"code": null,
"e": 982,
"s": 725,
"text": "Instead of feeling dissuaded, I felt inspired. Within a few months I broke up with my high school boyfriend and entered the online dating world myself. I quickly learned that dating is awful in it of itself, and it becomes exacerbated when it goes digital."
},
{
"code": null,
"e": 1346,
"s": 982,
"text": "Tinder. Bumble. Hinge. CoffeeMeetsBagel. If it was on the App Store then I may have used it. Despite having mostly indifferent-to-underwhelming dating experiences, I couldn’t shake this fascination I had with these godforsaken apps. I decided to channel that fascination as part of my final project for the Lede Program for Data Journalism at Columbia University."
},
{
"code": null,
"e": 1476,
"s": 1346,
"text": "Using nothing more than Python, Jupyter Notebook and frantic emails, I went head-first to create a project using dating app data."
},
{
"code": null,
"e": 1568,
"s": 1476,
"text": "Now that I had a project in mind, I needed to find the actual data. This was a huge hurdle."
},
{
"code": null,
"e": 1710,
"s": 1568,
"text": "First, I needed to choose an app to focus on. After browsing on r/dataisbeautiful for a few hours, I decided on Tinder due to its popularity."
},
{
"code": null,
"e": 1958,
"s": 1710,
"text": "I learned from Reddit and by reading other articles that I could request my own data. A few years ago, The Guardian wrote a story about how Tinder was using personal data. Part of the company’s response was to make user data available upon request"
},
{
"code": null,
"e": 1978,
"s": 1958,
"text": "www.theguardian.com"
},
{
"code": null,
"e": 2188,
"s": 1978,
"text": "Seems easy enough to do, right? Except, I didn’t have any data to download. I had a habit of downloading Tinder to use for a few months before deleting my account out of frustration only to repeat the process."
},
{
"code": null,
"e": 2490,
"s": 2188,
"text": "I knew the data existed out there and despite the obstacles, I was determined to find it. After several rounds of googling “Tinder data” and coming up empty, I went back to Reddit. I noticed on r/dataisbeautiful that some people were visualizing their Tinder data using a website called Swipestats.io."
},
{
"code": null,
"e": 2655,
"s": 2490,
"text": "I decided to shoot my shot and send an email to the site’s owner asking if he could share anonymous Tinder data with me for my project. He agreed (Thank you, Kris)."
},
{
"code": null,
"e": 2726,
"s": 2655,
"text": "Next thing you know, I’m sitting on one JSON with 556 Tinder profiles."
},
{
"code": null,
"e": 2757,
"s": 2726,
"text": "This was a complete nightmare."
},
{
"code": null,
"e": 2939,
"s": 2757,
"text": "I’ve lost dozens of hours of my life not only trying to make sense of the data, but to clean it as well. By the end, I was in a very committed relationship with an overstuffed JSON."
},
{
"code": null,
"e": 3224,
"s": 2939,
"text": "The first obstacle I faced was figuring out how to open the file. It is big and whenever I tried to upload it to a notebook, I would get an error. I spoke with my mentor from the Lede Program (Thank you, Jeff) and he advised to run it through a JSON lint. I had no idea what that was."
},
{
"code": null,
"e": 3365,
"s": 3224,
"text": "I felt useless that I could barley open a large JSON. Things were looking bleak but I was hard-bent on creating a project using Tinder data."
},
{
"code": null,
"e": 3688,
"s": 3365,
"text": "Long story short, I converted the JSON into a .txt file then split the large .txt file into smaller ones using this site. By the miracle of some deity, the website split each .txt file perfectly by each person’s file. Next, I converted the newly spit-up .txt files back into JSON format. Now I had a folder with 556 JSONs."
},
{
"code": null,
"e": 3778,
"s": 3688,
"text": "# Loading the dataimport jsonf = open(“user_x.json”, encoding=”utf-8\")data = json.load(f)"
},
{
"code": null,
"e": 3871,
"s": 3778,
"text": "Finally, I was able to open my data. To my amazement, I noticed that messages were included."
},
{
"code": null,
"e": 4056,
"s": 3871,
"text": "I knew I had to prioritize and decided to focus on only three different objects, conversations, conversationsMeta and user. In the flowchart, I outlined the information in each object."
},
{
"code": null,
"e": 4187,
"s": 4056,
"text": "The possibilities were endless on what I could do, but I still wasn’t done cleaning the data. The next obstacle was organizing it."
},
{
"code": null,
"e": 4588,
"s": 4187,
"text": "My next step was to organize the files by gender and language. A lot of the articles I read liked to compare men and women’s experiences with dating, so I wanted to have those separate datasets. Additionally, I received quite an international set that was sprinkled in languages such as Japanese, Spanish, or German. As much as I appreciate the diversity, I only wanted to work with English profiles."
},
{
"code": null,
"e": 4763,
"s": 4588,
"text": "I had no idea where to start with organizing, so I went to office hours (Thank you, Thanasis). After a lot of head-scratching on Gather, we—mostly Thanasis— found a solution."
},
{
"code": null,
"e": 5400,
"s": 4763,
"text": "import shutilimport osimport globfrom os import pathall_files = '/directory'male = \"/directory/MALE\"female = \"/directory/FEMALE\"files = glob.glob(all_files+\"/*.json\")for file in files: with open(file, encoding=\"utf-8\") as f: data = json.load(f) stat = data[\"user\"] for stats in stat: if stat[\"gender\"] == \"M\": try: shutil.move(os.path.join(all_files, file), male) except: pass else: try: shutil.move(os.path.join(all_files, file), female) except: pass"
},
{
"code": null,
"e": 5486,
"s": 5400,
"text": "This code simply moved a JSON to its respective folder whether it was male or female."
},
{
"code": null,
"e": 5657,
"s": 5486,
"text": "I tried to write a similar code to separate by language using TextBlob and langdetect. It didn’t work. Out of pure spite, I separated the files by hand based on language."
},
{
"code": null,
"e": 5813,
"s": 5657,
"text": "By this point I’m feeling delirious but I’m almost at the end. My last step was to save the data into friendly CSVs, leaving me ~300 English-speaking data."
},
{
"code": null,
"e": 5898,
"s": 5813,
"text": "Note: The Tinder messages came with HTML tags. I included code to remove them below."
},
{
"code": null,
"e": 7140,
"s": 5898,
"text": "all_files = '/GENDER/ENGLISH'files = glob.glob(all_files+\"/*.json\")# HTML parser codefrom io import StringIOfrom html.parser import HTMLParserclass MLStripper(HTMLParser): def __init__(self): super().__init__() self.reset() self.strict = False self.convert_charrefs= True self.text = StringIO() def handle_data(self, d): self.text.write(d) def get_data(self): return self.text.getvalue()def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data()for file in files: with open(file, encoding=\"utf-8\") as q: data = json.load(q) all_convo = data[\"conversations\"] text = [] for message in all_convo: for messages in message[\"messages\"]: messages[\"final_messages\"] = \"\" updated = messages[\"message\"] messages[\"final_messages\"] = strip_tags(updated) text.append(messages) with open('GENDER_convos.csv', 'a') as csvfile: field_names = ['to', 'from', 'message', 'sent_date', 'final_messages'] writer = csv.DictWriter(csvfile, fieldnames=field_names, extrasaction='ignore') writer.writeheader() writer.writerows(text)"
},
{
"code": null,
"e": 7915,
"s": 7140,
"text": "for file in files: with open(file, encoding=\"utf-8\") as q: data = json.load(q) user_data = [] user_data.append(data[\"conversationsMeta\"]) field_names = ['nrOfConversations', 'longestConversation', 'longestConversationInDays', 'averageConversationLength', 'averageConversationLengthInDays', 'medianConversationLength', 'medianConversationLengthInDays', 'nrOfOneMessageConversations', 'percentOfOneMessageConversations', 'nrOfGhostingsAfterInitialMessage'] with open('GENDER_convometa.csv', 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writeheader() writer.writerows(user_data)"
},
{
"code": null,
"e": 8914,
"s": 7915,
"text": "for file in files: with open(file, encoding=\"utf-8\") as q: data = json.load(q) user_data = [] md = data[\"user\"] for job in md['jobs']: if job['title'] == None: pass else: md['jobs'] = job['title'] try: for school in md['schools']: if school['name'] == None: pass else: md['schools'] = school['name'] except: pass user_data.append(md) field_names = ['birthDate', 'ageFilterMin', 'ageFilterMax', 'cityName', 'country', 'createDate', 'education', 'gender', 'interestedIn', 'genderFilter', 'instagram', 'spotify', 'jobs', 'educationLevel', 'schools'] with open('GENDER_md.csv', 'a') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=field_names) writer.writeheader() writer.writerows(user_data)"
},
{
"code": null,
"e": 8973,
"s": 8914,
"text": "Is data ever completely cleaned? No. It’s an endless task."
},
{
"code": null,
"e": 9267,
"s": 8973,
"text": "Before you get too excited, I need to admit that just about everything I found is kind of boring. I spent the vast majority of my time cleaning the data so this part is a little dull, especially considering that I’m writing this at 10:54 PM and am supposed to turn this in at 9:00 AM tomorrow."
},
{
"code": null,
"e": 9291,
"s": 9267,
"text": "You live and you learn."
},
{
"code": null,
"e": 9461,
"s": 9291,
"text": "I made an analysis based on the three CSVs made earlier. As a reminder, they each contain conversations, conversationsMeta and user metadata. The code is available here."
},
{
"code": null,
"e": 9648,
"s": 9461,
"text": "Side note: I was heavily influenced by this article from Data Drive that analyzed Tinder data made from bots. That article goes in much greater depth and uses substantially cleaner code."
},
{
"code": null,
"e": 9827,
"s": 9648,
"text": "This was arguably the most tedious of all the datasets because it contains half a million Tinder messages. The downside is that Tinder only stores messages sent and not received."
},
{
"code": null,
"e": 9990,
"s": 9827,
"text": "The first thing I did with conversations was to create a language model to detect flirtation. The final product is rudimentary at best and can be read about here."
},
{
"code": null,
"e": 10214,
"s": 9990,
"text": "Moving forward, the first analysis I made was to discover what are the most commonly used words and emojis among users. In order to avoid crashing my computer, I used only 200,000 messages with an even mix of men and women."
},
{
"code": null,
"e": 10245,
"s": 10214,
"text": "So what are the top ten words?"
},
{
"code": null,
"e": 10255,
"s": 10245,
"text": "Riveting."
},
{
"code": null,
"e": 10405,
"s": 10255,
"text": "To make it more exciting, I borrowed what Data Dive did and made a word cloud in the shape of the iconic Tinder flame after filtering out stop words."
},
{
"code": null,
"e": 10463,
"s": 10405,
"text": "Yeah, yeah, yeah. Words are great— but what about emojis?"
},
{
"code": null,
"e": 10692,
"s": 10463,
"text": "Fun fact: My biggest pet peeve is the laugh-cry emoji, otherwise known as : joy : in shortcode. I dislike it so much I won’t even display it in this article outside of the graph. I vote to retire it immediately and indefinitely."
},
{
"code": null,
"e": 10734,
"s": 10692,
"text": "How much do these results vary by gender?"
},
{
"code": null,
"e": 10970,
"s": 10734,
"text": "It seems that “like” is still the reining champion among both genders. Although, I think it’s interesting how “hey” appears in the top ten for men but not women. Could it be because men are expected to initiate conversations? Possibly."
},
{
"code": null,
"e": 11000,
"s": 10970,
"text": "What about emoji comparisons?"
},
{
"code": null,
"e": 11194,
"s": 11000,
"text": "It seems that female users use flirtier emojis (😍, 😘) more often than male users. Still, I’m upset but not surprised that : joy : transcends gender when it comes to dominating the emoji charts."
},
{
"code": null,
"e": 11321,
"s": 11194,
"text": "This portion was the most straightforward but could have also used the most elbow grease. For now, I used it to find averages."
},
{
"code": null,
"e": 11369,
"s": 11321,
"text": "These are the keys available in this dataframe:"
},
{
"code": null,
"e": 11679,
"s": 11369,
"text": "[‘nrOfConversations’, ‘longestConversation’, ‘longestConversationInDays’, ‘averageConversationLength’, ‘averageConversationLengthInDays’, ‘medianConversationLength’, ‘medianConversationLengthInDays’, ‘nrOfOneMessageConversations’, ‘percentOfOneMessageConversations’, ‘nrOfGhostingsAfterInitialMessage’, ‘Sex’]"
},
{
"code": null,
"e": 11798,
"s": 11679,
"text": "The ones that stick out to me are nrOfConversations, nrOfOneMessageConversations and nrOfGhostingsAfterInitialMessage."
},
{
"code": null,
"e": 12361,
"s": 11798,
"text": "import pandas as pdimport numpy as npcmd = pd.read_csv('all_eng_convometa.csv')# Average number of conversations between both sexesprint(\"The average number of total Tinder conversations for both sexes is\", cmd.nrOfConversations.mean().round())# Average number of conversations separated by sexprint(\"The average number of total Tinder conversations for men is\", cmd.nrOfConversations[cmd.Sex.str.contains(\"M\")].mean().round())print(\"The average number of total Tinder conversations for women is\", cmd.nrOfConversations[cmd.Sex.str.contains(\"F\")].mean().round())"
},
{
"code": null,
"e": 12435,
"s": 12361,
"text": "The average number of total Tinder conversations for both sexes is 278.0."
},
{
"code": null,
"e": 12502,
"s": 12435,
"text": "The average number of total Tinder conversations for men is 218.0."
},
{
"code": null,
"e": 12571,
"s": 12502,
"text": "The average number of total Tinder conversations for women is 464.0."
},
{
"code": null,
"e": 12647,
"s": 12571,
"text": "Wow. The variation between men and women’s Tinder experiences is felt here."
},
{
"code": null,
"e": 13203,
"s": 12647,
"text": "# Average number of one message conversations between both sexesprint(\"The average number of one message Tinder conversations for both sexes is\", cmd.nrOfOneMessageConversations.mean().round())# Average number of one message conversations separated by sexprint(\"The average number of one message Tinder conversations for men is\", cmd.nrOfOneMessageConversations[cmd.Sex.str.contains(\"M\")].mean().round())print(\"The average number of one message Tinder conversations for women is\", cmd.nrOfOneMessageConversations[cmd.Sex.str.contains(\"F\")].mean().round())"
},
{
"code": null,
"e": 13282,
"s": 13203,
"text": "The average number of one message Tinder conversations for both sexes is 80.0."
},
{
"code": null,
"e": 13354,
"s": 13282,
"text": "The average number of one message Tinder conversations for men is 74.0."
},
{
"code": null,
"e": 13428,
"s": 13354,
"text": "The average number of one message Tinder conversations for women is 99.0."
},
{
"code": null,
"e": 13798,
"s": 13428,
"text": "Interesting. Especially after seeing that, on average, women receive just over double the messages on Tinder I’m surprised that they have the most one message conversations. However, it isn’t clarified who sent that first message. My guest is that it only reads when the user sends the first message since Tinder doesn’t save received messages. Only Tinder can clarify."
},
{
"code": null,
"e": 14324,
"s": 13798,
"text": "# Average number of ghostings between each sexprint(\"The average number of ghostings after one message between both sexes is\", cmd.nrOfGhostingsAfterInitialMessage.mean().round())# Average number of ghostings separated by sexprint(\"The average number of ghostings after one message for men is\", cmd.nrOfGhostingsAfterInitialMessage[cmd.Sex.str.contains(\"M\")].mean().round())print(\"The average number of ghostings after one message for women is\", cmd.nrOfGhostingsAfterInitialMessage[cmd.Sex.str.contains(\"F\")].mean().round())"
},
{
"code": null,
"e": 14402,
"s": 14324,
"text": "The average number of ghostings after one message between both sexes is 50.0."
},
{
"code": null,
"e": 14469,
"s": 14402,
"text": "The average number of ghostings after one message for men is 18.0."
},
{
"code": null,
"e": 14538,
"s": 14469,
"text": "The average number of ghostings after one message for women is 151.0"
},
{
"code": null,
"e": 14736,
"s": 14538,
"text": "Similar to what I brought up previously on nrOfOneMessageConversations, it isn’t entirely clear who initiated the ghosting. I would be personally shocked if women were being ghosted more on Tinder."
},
{
"code": null,
"e": 14789,
"s": 14736,
"text": "Here are the objects available in the user metadata."
},
{
"code": null,
"e": 14988,
"s": 14789,
"text": "['birthDate', 'ageFilterMin', 'ageFilterMax', 'cityName', 'country', 'createDate', 'education', 'gender', 'interestedIn', 'genderFilter', 'instagram', 'spotify', 'jobs', 'educationLevel', 'schools']"
},
{
"code": null,
"e": 15094,
"s": 14988,
"text": "I wanted to create an age column and decided that I could determine user age as (createDate - birthDate)."
},
{
"code": null,
"e": 16046,
"s": 15094,
"text": "# CSV of updated_md has duplicatesmd = md.drop_duplicates(keep=False)from datetime import datetime, datemd['birthDate'] = pd.to_datetime(md.birthDate, format='%Y.%m.%d').dt.datemd['createDate'] = pd.to_datetime(md.createDate, format='%Y.%m.%d').dt.datemd['Age'] = (md['createDate'] - md['birthDate'])/365md['age'] = md['Age'].astype(str)md['age'] = md['age'].str[:3]md['age'] = md['age'].astype(int)# Dropping unnecessary columnsmd = md.drop(columns = 'Age')md = md.drop(columns= 'education')md = md.drop(columns= 'educationLevel')# Rearranging columnsmd = md[['gender', 'age', 'birthDate','createDate', 'jobs', 'schools', 'cityName', 'country', 'interestedIn', 'genderFilter', 'ageFilterMin', 'ageFilterMax','instagram', 'spotify']]# Replaces empty list with NaNmd = md.mask(md.applymap(str).eq('[]'))# Converting age filter to integermd['ageFilterMax'] = md['ageFilterMax'].astype(int)md['ageFilterMin'] = md['ageFilterMin'].astype(int)"
},
{
"code": null,
"e": 16264,
"s": 16046,
"text": "Next, I wanted to find the mean of age, ageFilterMax and ageFilterMin. I noticed that the numbers were skewed unusually high so I checked my dataset and noticed some trolling. I removed the following from the dataset."
},
{
"code": null,
"e": 16451,
"s": 16264,
"text": "One person who had their age at 106 and another at 137. Two people aged 16 and one listed as 15. I also removed 17 people who put 1000 as their ageFilterMax and one person who listed 95."
},
{
"code": null,
"e": 16479,
"s": 16451,
"text": "I discovered the following:"
},
{
"code": null,
"e": 17588,
"s": 16479,
"text": "# Combined age data print(\"The average user age for both genders is\", all_age.age.mean().round()) print(\"The average user age filter maximum for both genders is\", all_age.ageFilterMin.mean().round()) print(\"The average user age filter minimum for both genders is\", all_age.ageFilterMax.mean().round()) print(\"--------------------\") # By gender print(\"The average male user age is\", all_age.age[all_age.gender.str.contains(\"M\")].mean().round()) print(\"The average female user age\", all_age.age[all_age.gender.str.contains(\"F\")].mean().round()) print(\"--------------------\") print(\"The average male user age filter maximum is\", all_age.ageFilterMax[all_age.gender.str.contains(\"M\")].mean().round()) print(\"The average female user age filter maximum is\", all_age.ageFilterMax[all_age.gender.str.contains(\"F\")].mean().round()) print(\"--------------------\") print(\"The average male user age filter minumum is\", all_age.ageFilterMin[all_age.gender.str.contains(\"M\")].mean().round()) print(\"The average female user age filter minumum is\", all_age.ageFilterMin[all_age.gender.str.contains(\"F\")].mean().round())"
},
{
"code": null,
"e": 18075,
"s": 17588,
"text": "The average user age for both genders is 24.0The average user age filter maximum for both genders is 21.0The average user age filter minimum for both genders is 31.0--------------------The average male user age is 24.0The average female user age 23.0--------------------The average male user age filter maximum is 31.0The average female user age filter maximum is 32.0--------------------The average male user age filter minumum is 20.0The average female user age filter minumum is 23.0"
},
{
"code": null,
"e": 18135,
"s": 18075,
"text": "For added effect, I used this same data to make histograms."
},
{
"code": null,
"e": 18213,
"s": 18135,
"text": "Last, but certainly not least, I looked at jobs, schools, cities and country."
},
{
"code": null,
"e": 18509,
"s": 18213,
"text": "# Creating df of jobs listedjobs_df = pd.DataFrame(md['jobs'].value_counts(dropna=True))jobs_df.reset_index(level=0, inplace=True)jobs_df = jobs_df.rename(columns={\"index\": \"Jobs\", \"jobs\": \"Count\"})# Dropped index that said Falsejobs_df = jobs_df.drop(0)jobs_df = jobs_df.drop(1)jobs_df.head(10)"
},
{
"code": null,
"e": 18611,
"s": 18509,
"text": "I know what you’re thinking— boring, right? I went through the list myself and selected my favorites."
},
{
"code": null,
"e": 18663,
"s": 18611,
"text": "These are the top ten schools from the Tinder data."
},
{
"code": null,
"e": 18964,
"s": 18663,
"text": "# Creating df of schools listedschool_df = pd.DataFrame(md['schools'].value_counts(dropna=True))school_df.reset_index(level=0, inplace=True)school_df = school_df.rename(columns={\"index\": \"Schools\", \"schools\": \"Count\"})# Dropped index that was empty listschool_df = school_df.drop(0)school_df.head(10)"
},
{
"code": null,
"e": 19005,
"s": 18964,
"text": "Top ten cities based on the Tinder data."
},
{
"code": null,
"e": 19230,
"s": 19005,
"text": "# Creating df of cities listedcity_df = pd.DataFrame(md['cityName'].value_counts(dropna=True))city_df.reset_index(level=0, inplace=True)city_df = city_df.rename(columns={\"index\": \"City\", \"cityName\": \"Count\"})city_df.head(10)"
},
{
"code": null,
"e": 19345,
"s": 19230,
"text": "Finally, the top ten countries. However, Tinder grouped states and country together so its messy to say the least."
},
{
"code": null,
"e": 19602,
"s": 19345,
"text": "# Creating df of countries/states listedcountry_df = pd.DataFrame(md['country'].value_counts(dropna=True))country_df.reset_index(level=0, inplace=True)country_df = country_df.rename(columns={\"index\": \"Country/State\", \"country\": \"Count\"})country_df.head(10)"
},
{
"code": null,
"e": 19714,
"s": 19602,
"text": "All in all, the data is embarrassingly intimate but reveals the most boring parts of ourselves we already knew."
},
{
"code": null,
"e": 19915,
"s": 19714,
"text": "It was no surprise to discover that women on average have more conversations on Tinder than men or that : joy : is the most popular emoji used. Frankly, my findings are underwhelming but it’s a start."
},
{
"code": null,
"e": 20123,
"s": 19915,
"text": "I see a lot of potential for future projects using this data and I hardly touched the surface. Ideas for the future include building a more reliable flirtation analysis tool or creating a Tinder message bot."
},
{
"code": null,
"e": 20171,
"s": 20123,
"text": "In either case, I’m excited for what’s to come."
},
{
"code": null,
"e": 20343,
"s": 20171,
"text": "Thank you to Soma for not only being an excellent instructor but for spearheading the Lede program! Extra shoutouts for Carson, Thanasis, Jeff and Pete for helping me out."
},
{
"code": null,
"e": 20443,
"s": 20343,
"text": "And a special thank you to Swipestats.io for providing me with the data and can be contacted below."
}
] |
asin() and atan() functions in C/C++ with Example - GeeksforGeeks
|
30 Oct, 2020
In C++, asin() and atan() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions. All the functions available in this library take double as an argument and return double as the result.
asin()
asin() function is used to find the arc sine of a number means give a sin value to this function it will return the angle in radian corresponding to that value. In trigonometrics, arc sine is the inverse operation of sine. Note: The argument passed to this function must be in the range of [-1, 1] and asin() function returns the values in the range of [-?/2, ?/2].Syntax:
double asin(double k)
Parameters:
k is the value whose corresponding angle we have to find.
CPP
// CPP code to illustrate// the use of asin function#include <bits/stdc++.h>using namespace std; #define PI 3.14159265 int main(){ double k, ret, val; // Take any value between [-1, 1] k = 0.5; // asin() returns value in the range of [-?/2,?/2] ret = asin(k); val = (ret * 180) / PI; cout << "The arcsine of " << k << " is " << ret << " radians or " << val << " degrees"; return 0;}
Output:
The arcsine of 0.5 is 0.523599 radians or 30 degrees
atan()
atan() function is used to find the arc tangent of a number means gives a tangent value to this function it will return the angle in radians corresponding to that value. arc tangent is the inverse operation of tangent. This function accepts all the real numbers and atan() function returns the values in the range of [-?/2, ?/2].Syntax:
double atan(double k)
Parameters:
k is the value whose corresponding angle we have to find.
CPP
// CPP code to illustrate// the use of atan function#include <bits/stdc++.h>using namespace std; #define PI 3.14159265 int main(){ double k, ret, val; // Take any value k = 1.0; ret = atan(k); val = (ret * 180) / PI; cout << "The arctangent of " << k << " is " << ret << " radians or " << val << " degrees"; return 0;}
Output:
The arctangent of 1 is 0.785398 radians or 45 degrees
badger_666
CPP-Library
cpp-math
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Inheritance in C++
Map in C++ Standard Template Library (STL)
Constructors in C++
C++ Classes and Objects
Socket Programming in C/C++
Bitwise Operators in C/C++
Operator Overloading in C++
Multidimensional Arrays in C / C++
Copy Constructor in C++
Virtual Function in C++
|
[
{
"code": null,
"e": 24219,
"s": 24191,
"text": "\n30 Oct, 2020"
},
{
"code": null,
"e": 24481,
"s": 24219,
"text": "In C++, asin() and atan() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions. All the functions available in this library take double as an argument and return double as the result."
},
{
"code": null,
"e": 24488,
"s": 24481,
"text": "asin()"
},
{
"code": null,
"e": 24863,
"s": 24488,
"text": "asin() function is used to find the arc sine of a number means give a sin value to this function it will return the angle in radian corresponding to that value. In trigonometrics, arc sine is the inverse operation of sine. Note: The argument passed to this function must be in the range of [-1, 1] and asin() function returns the values in the range of [-?/2, ?/2].Syntax: "
},
{
"code": null,
"e": 24957,
"s": 24863,
"text": "double asin(double k)\n\nParameters:\nk is the value whose corresponding angle we have to find. "
},
{
"code": null,
"e": 24961,
"s": 24957,
"text": "CPP"
},
{
"code": "// CPP code to illustrate// the use of asin function#include <bits/stdc++.h>using namespace std; #define PI 3.14159265 int main(){ double k, ret, val; // Take any value between [-1, 1] k = 0.5; // asin() returns value in the range of [-?/2,?/2] ret = asin(k); val = (ret * 180) / PI; cout << \"The arcsine of \" << k << \" is \" << ret << \" radians or \" << val << \" degrees\"; return 0;}",
"e": 25378,
"s": 24961,
"text": null
},
{
"code": null,
"e": 25387,
"s": 25378,
"text": "Output: "
},
{
"code": null,
"e": 25441,
"s": 25387,
"text": "The arcsine of 0.5 is 0.523599 radians or 30 degrees "
},
{
"code": null,
"e": 25448,
"s": 25441,
"text": "atan()"
},
{
"code": null,
"e": 25787,
"s": 25448,
"text": "atan() function is used to find the arc tangent of a number means gives a tangent value to this function it will return the angle in radians corresponding to that value. arc tangent is the inverse operation of tangent. This function accepts all the real numbers and atan() function returns the values in the range of [-?/2, ?/2].Syntax: "
},
{
"code": null,
"e": 25881,
"s": 25787,
"text": "double atan(double k)\n\nParameters:\nk is the value whose corresponding angle we have to find.\n"
},
{
"code": null,
"e": 25885,
"s": 25881,
"text": "CPP"
},
{
"code": "// CPP code to illustrate// the use of atan function#include <bits/stdc++.h>using namespace std; #define PI 3.14159265 int main(){ double k, ret, val; // Take any value k = 1.0; ret = atan(k); val = (ret * 180) / PI; cout << \"The arctangent of \" << k << \" is \" << ret << \" radians or \" << val << \" degrees\"; return 0;}",
"e": 26235,
"s": 25885,
"text": null
},
{
"code": null,
"e": 26244,
"s": 26235,
"text": "Output: "
},
{
"code": null,
"e": 26299,
"s": 26244,
"text": "The arctangent of 1 is 0.785398 radians or 45 degrees "
},
{
"code": null,
"e": 26310,
"s": 26299,
"text": "badger_666"
},
{
"code": null,
"e": 26322,
"s": 26310,
"text": "CPP-Library"
},
{
"code": null,
"e": 26331,
"s": 26322,
"text": "cpp-math"
},
{
"code": null,
"e": 26335,
"s": 26331,
"text": "C++"
},
{
"code": null,
"e": 26339,
"s": 26335,
"text": "CPP"
},
{
"code": null,
"e": 26437,
"s": 26339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26446,
"s": 26437,
"text": "Comments"
},
{
"code": null,
"e": 26459,
"s": 26446,
"text": "Old Comments"
},
{
"code": null,
"e": 26478,
"s": 26459,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 26521,
"s": 26478,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 26541,
"s": 26521,
"text": "Constructors in C++"
},
{
"code": null,
"e": 26565,
"s": 26541,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 26593,
"s": 26565,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 26620,
"s": 26593,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 26648,
"s": 26620,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 26683,
"s": 26648,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 26707,
"s": 26683,
"text": "Copy Constructor in C++"
}
] |
Dekker's algorithm in Operating System
|
Dekker’s algorithm is the first solution of critical section problem. There are many versions of this algorithms, the 5th or final version satisfies the all the conditions below and is the most efficient among all of them.
The solution to critical section problem must ensure the following three conditions:
Mutual Exclusion
Progress
Bounded Waiting
Dekker’s algorithm succeeds to achieve mutual exclusion.
It uses variables to control thread execution.
It constantly checks whether critical section available.
main(){
int thread_no = 1;
startThreads();
}
Thread1(){
do {
// entry section
// wait until threadno is 1
while (threado == 2)
;
// critical section
// exit section
// give access to the other thread
threadno = 2;
// remainder section
} while (completed == false)
}
Thread2(){
do {
// entry section
// wait until threadno is 2
while (threadno == 1)
;
// critical section
// exit section
// give access to the other thread
threadno = 1;
// remainder section
} while (completed == false)
}
The problem of this first version of Dekker’s algorithm is implementation of lockstep synchronization. It means each thread depends on other to complete its execution. If one of the two processes completes its execution, then the second process runs. Then it gives access to the completed one and waits for its run. But the completed one would never run and so it would never return access back to the second process. Thus the second process waits for infinite time.
In Second version of Dekker’s algorithm, lockstep synchronization is removed. It is done by using two flags to indicate its current status and updates them accordingly at the entry and exit section.
main(){
// flags to indicate whether each thread is in
// its critial section or not.
boolean th1 = false;
boolean th2 = false;
startThreads();
}
Thread1(){
do {
// entry section
// wait until th2 is in its critical section
while (th2 == true);
// indicate thread1 entering its critical section
th1 = true;
// critical section
// exit section
// indicate th1 exiting its critical section
th1 = false;
// remainder section
} while (completed == false)
}
Thread2(){
do {
// entry section
// wait until th1 is in its critical section
while (th1 == true);
// indicate th2 entering its critical section
th2 = true;
// critical section
// exit section
// indicate th2 exiting its critical section
th2 = false;
// remainder section
} while (completed == false)
}
Mutual exclusion is violated in this version. During flag update, if threads are preempted then both the threads enter into the critical section. Once the preempted thread is restarted, also the same can be observed at the start itself, when both the flags are false.
In this version, critical section flag is set before entering critical section test to ensure mutual exclusion.
main(){
// flags to indicate whether each thread is in
// queue to enter its critical section
boolean th1wantstoenter = false;
boolean th2wantstoenter = false;
startThreads();
}
Thread1(){
do {
th1wantstoenter = true;
// entry section
// wait until th2 wants to enter
// its critical section
while (th2wantstoenter == true)
;
// critical section
// exit section
// indicate th1 has completed
// its critical section
th1wantstoenter = false;
// remainder section
} while (completed == false)
}
Thread2(){
do {
th2wantstoenter = true;
// entry section
// wait until th1 wants to enter
// its critical section
while (th1wantstoenter == true)
;
// critical section
// exit section
// indicate th2 has completed
// its critical section
th2wantstoenter = false;
// remainder section
} while (completed == false)
}
This version failed to solve the problem of mutual exclusion. It also introduces deadlock possibility, both threads could get flag simultaneously and they will wait for infinite time.
In this version of Dekker’s algorithm, it sets flag to false for small period of time to provide control and solves the problem of mutual exclusion and deadlock.
main(){
// flags to indicate whether each thread is in
// queue to enter its critical section
boolean th1wantstoenter = false;
boolean th2wantstoenter = false;
startThreads();
}
Thread1(){
do {
th1wantstoenter = true;
while (th2wantstoenter == true) {
// gives access to other thread
// wait for random amount of time
th1wantstoenter = false;
th1wantstoenter = true;
}
// entry section
// wait until th2 wants to enter
// its critical section
// critical section
// exit section
// indicate th1 has completed
// its critical section
th1wantstoenter = false;
// remainder section
} while (completed == false)
}
Thread2(){
do {
th2wantstoenter = true;
while (th1wantstoenter == true) {
// gives access to other thread
// wait for random amount of time
th2wantstoenter = false;
th2wantstoenter = true;
}
// entry section
// wait until th1 wants to enter
// its critical section
// critical section
// exit section
// indicate th2 has completed
// its critical section
th2wantstoenter = false;
// remainder section
} while (completed == false)
}
Indefinite postponement is the problem of this version. Random amount of time is unpredictable depending upon the situation in which the algorithm is being implemented, hence it is not acceptable in case of business critical systems.
Fifth Version (Final Solution)
In this version, flavored thread motion is used to determine entry to critical section. It provides mutual exclusion and avoiding deadlock, indefinite postponement or lockstep synchronization by resolving the conflict that which thread should execute first. This version of Dekker’s algorithm provides the complete solution of critical section problems.
main(){
// to denote which thread will enter next
int favouredthread = 1;
// flags to indicate whether each thread is in
// queue to enter its critical section
boolean th1wantstoenter = false;
boolean th2wantstoenter = false;
startThreads();
}
Thread1(){
do {
thread1wantstoenter = true;
// entry section
// wait until th2 wants to enter
// its critical section
while (th2wantstoenter == true) {
// if 2nd thread is more favored
if (favaouredthread == 2) {
// gives access to other thread
th1wantstoenter = false;
// wait until this thread is favored
while (favouredthread == 2);
th1wantstoenter = true;
}
}
// critical section
// favor the 2nd thread
favouredthread = 2;
// exit section
// indicate th1 has completed
// its critical section
th1wantstoenter = false;
// remainder section
} while (completed == false)
}
Thread2(){
do {
th2wantstoenter = true;
// entry section
// wait until th1 wants to enter
// its critical section
while (th1wantstoenter == true) {
// if 1st thread is more favored
if (favaouredthread == 1) {
// gives access to other thread
th2wantstoenter = false;
// wait until this thread is favored
while (favouredthread == 1);
th2wantstoenter = true;
}
}
// critical section
// favour the 1st thread
favouredthread = 1;
// exit section
// indicate th2 has completed
// its critical section
th2wantstoenter = false;
// remainder section
} while (completed == false)
}
|
[
{
"code": null,
"e": 1285,
"s": 1062,
"text": "Dekker’s algorithm is the first solution of critical section problem. There are many versions of this algorithms, the 5th or final version satisfies the all the conditions below and is the most efficient among all of them."
},
{
"code": null,
"e": 1370,
"s": 1285,
"text": "The solution to critical section problem must ensure the following three conditions:"
},
{
"code": null,
"e": 1387,
"s": 1370,
"text": "Mutual Exclusion"
},
{
"code": null,
"e": 1396,
"s": 1387,
"text": "Progress"
},
{
"code": null,
"e": 1412,
"s": 1396,
"text": "Bounded Waiting"
},
{
"code": null,
"e": 1469,
"s": 1412,
"text": "Dekker’s algorithm succeeds to achieve mutual exclusion."
},
{
"code": null,
"e": 1516,
"s": 1469,
"text": "It uses variables to control thread execution."
},
{
"code": null,
"e": 1573,
"s": 1516,
"text": "It constantly checks whether critical section available."
},
{
"code": null,
"e": 2199,
"s": 1573,
"text": "main(){\n int thread_no = 1;\n startThreads();\n}\nThread1(){\n do {\n // entry section\n // wait until threadno is 1\n while (threado == 2)\n ;\n // critical section\n // exit section\n // give access to the other thread\n threadno = 2;\n // remainder section\n } while (completed == false)\n}\nThread2(){\n do {\n // entry section\n // wait until threadno is 2\n while (threadno == 1)\n ;\n // critical section\n // exit section\n // give access to the other thread\n threadno = 1;\n // remainder section\n } while (completed == false)\n}"
},
{
"code": null,
"e": 2666,
"s": 2199,
"text": "The problem of this first version of Dekker’s algorithm is implementation of lockstep synchronization. It means each thread depends on other to complete its execution. If one of the two processes completes its execution, then the second process runs. Then it gives access to the completed one and waits for its run. But the completed one would never run and so it would never return access back to the second process. Thus the second process waits for infinite time."
},
{
"code": null,
"e": 2865,
"s": 2666,
"text": "In Second version of Dekker’s algorithm, lockstep synchronization is removed. It is done by using two flags to indicate its current status and updates them accordingly at the entry and exit section."
},
{
"code": null,
"e": 3768,
"s": 2865,
"text": "main(){\n // flags to indicate whether each thread is in\n // its critial section or not.\n boolean th1 = false;\n boolean th2 = false;\n startThreads();\n}\nThread1(){\n do {\n // entry section\n // wait until th2 is in its critical section\n while (th2 == true);\n // indicate thread1 entering its critical section\n th1 = true;\n // critical section\n // exit section\n // indicate th1 exiting its critical section\n th1 = false;\n // remainder section\n } while (completed == false)\n}\nThread2(){\n do {\n // entry section\n // wait until th1 is in its critical section\n while (th1 == true);\n // indicate th2 entering its critical section\n th2 = true;\n // critical section\n // exit section\n // indicate th2 exiting its critical section\n th2 = false;\n // remainder section\n } while (completed == false)\n}"
},
{
"code": null,
"e": 4036,
"s": 3768,
"text": "Mutual exclusion is violated in this version. During flag update, if threads are preempted then both the threads enter into the critical section. Once the preempted thread is restarted, also the same can be observed at the start itself, when both the flags are false."
},
{
"code": null,
"e": 4148,
"s": 4036,
"text": "In this version, critical section flag is set before entering critical section test to ensure mutual exclusion."
},
{
"code": null,
"e": 5145,
"s": 4148,
"text": "main(){\n // flags to indicate whether each thread is in\n // queue to enter its critical section\n boolean th1wantstoenter = false;\n boolean th2wantstoenter = false;\n startThreads();\n}\nThread1(){\n do {\n th1wantstoenter = true;\n // entry section\n // wait until th2 wants to enter\n // its critical section\n while (th2wantstoenter == true)\n ;\n // critical section\n // exit section\n // indicate th1 has completed\n // its critical section\n th1wantstoenter = false;\n // remainder section\n } while (completed == false)\n}\nThread2(){\n do {\n th2wantstoenter = true;\n // entry section\n // wait until th1 wants to enter\n // its critical section\n while (th1wantstoenter == true)\n ;\n // critical section\n // exit section\n // indicate th2 has completed\n // its critical section\n th2wantstoenter = false;\n // remainder section\n } while (completed == false)\n}"
},
{
"code": null,
"e": 5329,
"s": 5145,
"text": "This version failed to solve the problem of mutual exclusion. It also introduces deadlock possibility, both threads could get flag simultaneously and they will wait for infinite time."
},
{
"code": null,
"e": 5491,
"s": 5329,
"text": "In this version of Dekker’s algorithm, it sets flag to false for small period of time to provide control and solves the problem of mutual exclusion and deadlock."
},
{
"code": null,
"e": 6692,
"s": 5491,
"text": "main(){\n // flags to indicate whether each thread is in\n // queue to enter its critical section\n boolean th1wantstoenter = false;\n boolean th2wantstoenter = false;\n startThreads();\n}\nThread1(){\n do {\n th1wantstoenter = true;\n while (th2wantstoenter == true) {\n // gives access to other thread\n // wait for random amount of time\n th1wantstoenter = false;\n th1wantstoenter = true;\n }\n // entry section\n // wait until th2 wants to enter\n // its critical section\n // critical section\n // exit section\n // indicate th1 has completed\n // its critical section\n th1wantstoenter = false;\n // remainder section\n } while (completed == false)\n}\nThread2(){\n do {\n th2wantstoenter = true;\n while (th1wantstoenter == true) {\n // gives access to other thread\n // wait for random amount of time\n th2wantstoenter = false;\n th2wantstoenter = true;\n }\n // entry section\n // wait until th1 wants to enter\n // its critical section\n // critical section\n // exit section\n // indicate th2 has completed\n // its critical section\n th2wantstoenter = false;\n // remainder section\n } while (completed == false)\n}"
},
{
"code": null,
"e": 6926,
"s": 6692,
"text": "Indefinite postponement is the problem of this version. Random amount of time is unpredictable depending upon the situation in which the algorithm is being implemented, hence it is not acceptable in case of business critical systems."
},
{
"code": null,
"e": 6957,
"s": 6926,
"text": "Fifth Version (Final Solution)"
},
{
"code": null,
"e": 7311,
"s": 6957,
"text": "In this version, flavored thread motion is used to determine entry to critical section. It provides mutual exclusion and avoiding deadlock, indefinite postponement or lockstep synchronization by resolving the conflict that which thread should execute first. This version of Dekker’s algorithm provides the complete solution of critical section problems."
},
{
"code": null,
"e": 9077,
"s": 7311,
"text": "main(){\n // to denote which thread will enter next\n int favouredthread = 1;\n // flags to indicate whether each thread is in\n // queue to enter its critical section\n boolean th1wantstoenter = false;\n boolean th2wantstoenter = false;\n startThreads();\n}\nThread1(){\n do {\n thread1wantstoenter = true;\n // entry section\n // wait until th2 wants to enter\n // its critical section\n while (th2wantstoenter == true) {\n // if 2nd thread is more favored\n if (favaouredthread == 2) {\n // gives access to other thread\n th1wantstoenter = false;\n // wait until this thread is favored\n while (favouredthread == 2);\n th1wantstoenter = true;\n }\n }\n // critical section\n // favor the 2nd thread\n favouredthread = 2;\n // exit section\n // indicate th1 has completed\n // its critical section\n th1wantstoenter = false;\n // remainder section\n } while (completed == false)\n}\nThread2(){\n do {\n th2wantstoenter = true;\n // entry section\n // wait until th1 wants to enter\n // its critical section\n while (th1wantstoenter == true) {\n // if 1st thread is more favored\n if (favaouredthread == 1) {\n // gives access to other thread\n th2wantstoenter = false;\n // wait until this thread is favored\n while (favouredthread == 1);\n th2wantstoenter = true;\n }\n }\n // critical section\n // favour the 1st thread\n favouredthread = 1;\n // exit section\n // indicate th2 has completed\n // its critical section\n th2wantstoenter = false;\n // remainder section\n } while (completed == false)\n}"
}
] |
How to iterate json array – JavaScript?
|
To iterate JSON array, use the JSON.parse().
Following is the code −
var apiValues =
[
'{"name": "John", "scores": [78, 89]}',
'{"name": "David", "scores": [58, 98]}',
'{"name": "Bob", "scores": [56, 79]}',
'{"name": "Mike", "scores": [94, 91]}'
];
var parseJSONObject = apiValues.map(obj => JSON.parse(obj));
console.log("The original String : ", apiValues);
console.log("The JSON Objects : ", parseJSONObject);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo252.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo252.js
The original String : [
'{"name": "John", "scores": [78, 89]}',
'{"name": "David", "scores": [58, 98]}',
'{"name": "Bob", "scores": [56, 79]}',
'{"name": "Mike", "scores": [94, 91]}'
]
The JSON Objects : [
{ name: 'John', scores: [ 78, 89 ] },
{ name: 'David', scores: [ 58, 98 ] },
{ name: 'Bob', scores: [ 56, 79 ] },
{ name: 'Mike', scores: [ 94, 91 ] }
]
|
[
{
"code": null,
"e": 1107,
"s": 1062,
"text": "To iterate JSON array, use the JSON.parse()."
},
{
"code": null,
"e": 1131,
"s": 1107,
"text": "Following is the code −"
},
{
"code": null,
"e": 1505,
"s": 1131,
"text": "var apiValues =\n [\n '{\"name\": \"John\", \"scores\": [78, 89]}',\n '{\"name\": \"David\", \"scores\": [58, 98]}',\n '{\"name\": \"Bob\", \"scores\": [56, 79]}',\n '{\"name\": \"Mike\", \"scores\": [94, 91]}'\n ];\nvar parseJSONObject = apiValues.map(obj => JSON.parse(obj));\nconsole.log(\"The original String : \", apiValues);\nconsole.log(\"The JSON Objects : \", parseJSONObject);"
},
{
"code": null,
"e": 1571,
"s": 1505,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1589,
"s": 1571,
"text": "node fileName.js."
},
{
"code": null,
"e": 1623,
"s": 1589,
"text": "Here, my file name is demo252.js."
},
{
"code": null,
"e": 1675,
"s": 1623,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2110,
"s": 1675,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo252.js\nThe original String : [\n '{\"name\": \"John\", \"scores\": [78, 89]}',\n '{\"name\": \"David\", \"scores\": [58, 98]}',\n '{\"name\": \"Bob\", \"scores\": [56, 79]}',\n '{\"name\": \"Mike\", \"scores\": [94, 91]}'\n]\nThe JSON Objects : [\n { name: 'John', scores: [ 78, 89 ] },\n { name: 'David', scores: [ 58, 98 ] },\n { name: 'Bob', scores: [ 56, 79 ] },\n { name: 'Mike', scores: [ 94, 91 ] }\n]"
}
] |
How to get an attribute value in jQuery?
|
To get an attribute value in jQuery is quite easy. For this, use the jQuery attr() method. You can try to run the following code to learn how to get an attribute value in jQuery −
Live Demo
<html>
<head>
<title>jQuery Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("img").attr("height"));
});
});
</script>
</head>
<body>
<img src="/green/images/logo.png" alt="logo" width="350" height="120"><br>
<button>Get the height</button>
</body>
</html>
|
[
{
"code": null,
"e": 1242,
"s": 1062,
"text": "To get an attribute value in jQuery is quite easy. For this, use the jQuery attr() method. You can try to run the following code to learn how to get an attribute value in jQuery −"
},
{
"code": null,
"e": 1252,
"s": 1242,
"text": "Live Demo"
},
{
"code": null,
"e": 1744,
"s": 1252,
"text": "<html>\n\n <head>\n <title>jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n\n <script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n alert($(\"img\").attr(\"height\"));\n });\n });\n </script>\n </head>\n \n <body>\n <img src=\"/green/images/logo.png\" alt=\"logo\" width=\"350\" height=\"120\"><br>\n <button>Get the height</button>\n </body>\n \n</html>"
}
] |
MySQL regular expression to update a table with column values including string, numbers and special characters
|
For this, use UPDATE command along with REGEXP. Let us first create a table −
mysql> create table DemoTable2023
-> (
-> StreetNumber varchar(100)
-> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2023 values('7');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2023 values('1');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable2023 values('AUS-100');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable2023 values('US-101');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2023;
This will produce the following output −
+--------------+
| StreetNumber |
+--------------+
| 7 |
| 1 |
| AUS-100 |
| US-101 |
+--------------+
4 rows in set (0.00 sec)
Here is the query to update a table using a regular expression −
mysql> update DemoTable2023
-> set StreetNumber=concat('Street',StreetNumber)
-> where StreetNumber regexp'^[0-9]{1,2}$';
Query OK, 2 rows affected (0.19 sec)
Rows matched: 2 Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable2023;
This will produce the following output −
+--------------+
| StreetNumber |
+--------------+
| Street7 |
| Street1 |
| AUS-100 |
| US-101 |
+--------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "For this, use UPDATE command along with REGEXP. Let us first create a table −"
},
{
"code": null,
"e": 1260,
"s": 1140,
"text": "mysql> create table DemoTable2023\n -> (\n -> StreetNumber varchar(100)\n -> );\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1316,
"s": 1260,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1658,
"s": 1316,
"text": "mysql> insert into DemoTable2023 values('7');\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable2023 values('1');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable2023 values('AUS-100');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DemoTable2023 values('US-101');\nQuery OK, 1 row affected (0.11 sec)"
},
{
"code": null,
"e": 1718,
"s": 1658,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1753,
"s": 1718,
"text": "mysql> select *from DemoTable2023;"
},
{
"code": null,
"e": 1794,
"s": 1753,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1955,
"s": 1794,
"text": "+--------------+\n| StreetNumber |\n+--------------+\n| 7 |\n| 1 |\n| AUS-100 |\n| US-101 |\n+--------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2020,
"s": 1955,
"text": "Here is the query to update a table using a regular expression −"
},
{
"code": null,
"e": 2224,
"s": 2020,
"text": "mysql> update DemoTable2023\n -> set StreetNumber=concat('Street',StreetNumber)\n -> where StreetNumber regexp'^[0-9]{1,2}$';\nQuery OK, 2 rows affected (0.19 sec)\nRows matched: 2 Changed: 2 Warnings: 0"
},
{
"code": null,
"e": 2268,
"s": 2224,
"text": "Let us check the table records once again −"
},
{
"code": null,
"e": 2303,
"s": 2268,
"text": "mysql> select *from DemoTable2023;"
},
{
"code": null,
"e": 2344,
"s": 2303,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2505,
"s": 2344,
"text": "+--------------+\n| StreetNumber |\n+--------------+\n| Street7 |\n| Street1 |\n| AUS-100 |\n| US-101 |\n+--------------+\n4 rows in set (0.00 sec)"
}
] |
Guava - Quick Guide
|
Guava is an open source, Java-based library and contains many core libraries of Google, which are being used in many of their projects. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations.
Standardized − The Guava library is managed by Google.
Standardized − The Guava library is managed by Google.
Efficient − It is a reliable, fast, and efficient extension to the Java standard library.
Efficient − It is a reliable, fast, and efficient extension to the Java standard library.
Optimized − The library is highly optimized.
Optimized − The library is highly optimized.
Functional Programming − It adds functional processing capability to Java.
Functional Programming − It adds functional processing capability to Java.
Utilities − It provides many utility classes which are regularly required in programming application development.
Utilities − It provides many utility classes which are regularly required in programming application development.
Validation − It provides a standard failsafe validation mechanism.
Validation − It provides a standard failsafe validation mechanism.
Best Practices − It emphasizes on best practices.
Best Practices − It emphasizes on best practices.
Consider the following code snippet.
public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();
Integer a = null;
Integer b = new Integer(10);
System.out.println(guavaTester.sum(a,b));
}
public Integer sum(Integer a, Integer b) {
return a + b;
}
}
Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at GuavaTester.sum(GuavaTester.java:13)
at GuavaTester.main(GuavaTester.java:9)
Following are the problems with the code.
sum() is not taking care of any of the parameters to be passed as null.
sum() is not taking care of any of the parameters to be passed as null.
caller function is also not worried about passing a null to the sum() method accidently.
caller function is also not worried about passing a null to the sum() method accidently.
When the program runs, NullPointerException occurs.
When the program runs, NullPointerException occurs.
In order to avoid the above problems, null check is to be made in each and every place where such problems are present.
Let's see the use of Optional, a Guava provided Utility class, to solve the above problems in a standardized way.
import com.google.common.base.Optional;
public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();
Integer invalidInput = null;
Optional<Integer> a = Optional.of(invalidInput);
Optional<Integer> b = Optional.of(new Integer(10));
System.out.println(guavaTester.sum(a,b));
}
public Integer sum(Optional<Integer> a, Optional<Integer> b) {
return a.get() + b.get();
}
}
Run the program to get the following result.
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210)
at com.google.common.base.Optional.of(Optional.java:85)
at GuavaTester.main(GuavaTester.java:8)
Let's understand the important concepts of the above program.
Optional − A utility class, to make the code use the null properly.
Optional − A utility class, to make the code use the null properly.
Optional.of − It returns the instance of Optional class to be used as a parameter. It checks the value passed, not to be ‘null’.
Optional.of − It returns the instance of Optional class to be used as a parameter. It checks the value passed, not to be ‘null’.
Optional.get − It gets the value of the input stored in the Optional class.
Optional.get − It gets the value of the input stored in the Optional class.
Using the Optional class, you can check whether the caller method is passing a proper parameter or not.
If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.
Java SE is freely available from the link Download Java. So you download a version based on your operating system.
Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories −
We are assuming that you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
We are assuming that you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'
To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −
Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/.
Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/.
Download the latest version of Guava jar file from guava-18.0.jar. At the time of writing this tutorial, we have downloaded guava-18.0.jar and copied it into C:\>Guava folder.
Set the Guava_HOME environment variable to point to the base directory location where Guava jar is stored on your machine. Assuming, we've extracted guava-18.0.jar in Guava folder on various Operating Systems as follows.
Set the CLASSPATH environment variable to point to the Guava jar location. Assuming, you have stored guava-18.0.jar in Guava folder on various Operating Systems as follows.
Optional is an immutable object used to contain a not-null object. Optional object is used to represent null with absent value. This class has various utility methods to facilitate the code to handle values as available or not available instead of checking null values.
Following is the declaration for com.google.common.base.Optional<T> class −
@GwtCompatible(serializable = true)
public abstract class Optional<T>
extends Object
implements Serializable
static <T> Optional<T> absent()
Returns an Optional instance with no contained reference.
abstract Set<T> asSet()
Returns an immutable singleton Set whose only element is the contained instance if it is present; an empty immutable Set otherwise.
abstract boolean equals(Object object)
Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent.
static <T> Optional<T> fromNullable(T nullableReference)
If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns absent().
abstract T get()
Returns the contained instance, which must be present.
abstract int hashCode()
Returns a hash code for this instance.
abstract boolean isPresent()
Returns true if this holder contains a (non-null) instance.
static <T> Optional<T> of(T reference)
Returns an Optional instance containing the given non-null reference.
abstract Optional<T> or(Optional<? extends T> secondChoice)
Returns this Optional if it has a value present; secondChoice otherwise.
abstract T or(Supplier<? extends T> supplier)
Returns the contained instance if it is present; supplier.get() otherwise.
abstract T or(T defaultValue)
Returns the contained instance if it is present; defaultValue otherwise.
abstract T orNull()
Returns the contained instance if it is present; null otherwise.
static <T> Iterable<T> presentInstances(Iterable<? extends Optional<? extends T>> optionals)
Returns the value of each present instance from the supplied optionals, in order, skipping over occurrences of absent().
abstract String toString()
Returns a string representation for this instance.
abstract <V> Optional<V> transform(Function<? super T,V> function)
If the instance is present, it is transformed with the given Function; otherwise, absent() is returned.
This class inherits methods from the following class −
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import com.google.common.base.Optional;
public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();
Integer value1 = null;
Integer value2 = new Integer(10);
//Optional.fromNullable - allows passed parameter to be null.
Optional<Integer> a = Optional.fromNullable(value1);
//Optional.of - throws NullPointerException if passed parameter is null
Optional<Integer> b = Optional.of(value2);
System.out.println(guavaTester.sum(a,b));
}
public Integer sum(Optional<Integer> a, Optional<Integer> b) {
//Optional.isPresent - checks the value is present or not
System.out.println("First parameter is present: " + a.isPresent());
System.out.println("Second parameter is present: " + b.isPresent());
//Optional.or - returns the value if present otherwise returns
//the default value passed.
Integer value1 = a.or(new Integer(0));
//Optional.get - gets the value, value should be present
Integer value2 = b.get();
return value1 + value2;
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
First parameter is present: false
Second parameter is present: true
10
Preconditions provide static methods to check that a method or a constructor is invoked with proper parameter or not. It checks the pre-conditions. Its methods throw IllegalArgumentException on failure.
Following is the declaration for com.google.common.base.Preconditions class −
@GwtCompatible
public final class Preconditions
extends Object
static void checkArgument(boolean expression)
Ensures the truth of an expression involving one or more parameters to the calling method.
static void checkArgument(boolean expression, Object errorMessage)
Ensures the truth of an expression involving one or more parameters to the calling method.
static void checkArgument(boolean expression, String errorMessageTemplate, Object. errorMessageArgs)
Ensures the truth of an expression involving one or more parameters to the calling method.
static int checkElementIndex(int index, int size)
Ensures that index specifies a valid element in an array, list or a string of size.
static int checkElementIndex(int index, int size, String desc)
Ensures that index specifies a valid element in an array, list, or a string of size.
static <T> T checkNotNull(T reference)
Ensures that an object reference passed as a parameter to the calling method is not null.
static <T> T checkNotNull(T reference, Object errorMessage)
Ensures that an object reference passed as a parameter to the calling method is not null.
static <T> T checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs)
Ensures that an object reference passed as a parameter to the calling method is not null.
static int checkPositionIndex(int index, int size)
Ensures that index specifies a valid position in an array, list or a string of size.
static int checkPositionIndex(int index, int size, String desc)
Ensures that index specifies a valid position in an array, list or a string of size.
static void checkPositionIndexes(int start, int end, int size)
Ensures that start and end specify a valid positions in an array, list or a string of size, and are in order.
static void checkState(boolean expression)
Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
static void checkState(boolean expression, Object errorMessage)
Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
static void checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs)
Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method.
This class inherits methods from the following class −
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import com.google.common.base.Preconditions;
public class GuavaTester {
public static void main(String args[]) {
GuavaTester guavaTester = new GuavaTester();
try {
System.out.println(guavaTester.sqrt(-3.0));
} catch(IllegalArgumentException e) {
System.out.println(e.getMessage());
}
try {
System.out.println(guavaTester.sum(null,3));
} catch(NullPointerException e) {
System.out.println(e.getMessage());
}
try {
System.out.println(guavaTester.getValue(6));
} catch(IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
public double sqrt(double input) throws IllegalArgumentException {
Preconditions.checkArgument(input > 0.0,
"Illegal Argument passed: Negative value %s.", input);
return Math.sqrt(input);
}
public int sum(Integer a, Integer b) {
a = Preconditions.checkNotNull(a, "Illegal Argument passed: First parameter is Null.");
b = Preconditions.checkNotNull(b, "Illegal Argument passed: Second parameter is Null.");
return a+b;
}
public int getValue(int input) {
int[] data = {1,2,3,4,5};
Preconditions.checkElementIndex(input,data.length, "Illegal Argument passed: Invalid index.");
return 0;
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
Illegal Argument passed: Negative value -3.0.
Illegal Argument passed: First parameter is Null.
Illegal Argument passed: Invalid index. (6) must be less than size (5)
Ordering can be seen as an enriched comparator with enhanced chaining functionality, multiple utility methods, multi-type sorting capability, etc.
Following is the declaration for com.google.common.collect.Ordering<T> class −
@GwtCompatible
public abstract class Ordering<T>
extends Object
implements Comparator<T>
static Ordering<Object> allEqual()
Returns an ordering which treats all values as equal, indicating "no ordering." Passing this ordering to any stable sort algorithm results in no change to the order of elements.
static Ordering<Object> arbitrary()
Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality).
int binarySearch(List<? extends T> sortedList, T key)
Searches sortedList for key using the binary search algorithm.
abstract int compare(T left, T right)
Compares its two arguments for order.
<U extends T> Ordering<U> compound(Comparator<? super U> secondaryComparator)
Returns an ordering which first uses the ordering this, but which in the event of a "tie", then delegates to secondaryComparator.
static <T> Ordering<T> compound(Iterable<? extends Comparator<? super T>> comparators)
Returns an ordering which tries each given comparator in order until a non-zero result is found, returning that result, and returning zero only if all comparators return zero.
static <T> Ordering<T> explicit(List<T> valuesInOrder)
Returns an ordering that compares objects according to the order in which they appear in the given list.
static <T> Ordering<T> explicit(T leastValue, T... remainingValuesInOrder)
Returns an ordering that compares objects according to the order in which they are given to this method.
static <T> Ordering<T> from(Comparator<T> comparator)
Returns an ordering based on an existing comparator instance.
<E extends T> List<E> greatestOf(Iterable<E> iterable, int k)
Returns the k greatest elements of the given iterable according to this ordering, in order from greatest to least.
<E extends T> List<E> greatestOf(Iterator<E> iterator, int k)
Returns the k greatest elements from the given iterator according to this ordering, in order from greatest to least.
<E extends T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements)
Returns an immutable list containing elements sorted by this ordering.
boolean isOrdered(Iterable<? extends T> iterable)
Returns true if each element in iterable after the first is greater than or equal to the element that preceded it, according to this ordering.
boolean isStrictlyOrdered(Iterable<? extends T> iterable)
Returns true if each element in iterable after the first is strictly greater than the element that preceded it, according to this ordering
<E extends T> List<E> leastOf(Iterable<E> iterable, int k)
Returns the k least elements of the given iterable according to this ordering, in order from least to greatest.
<E extends T> List<E> leastOf(Iterator<E> elements, int k)
Returns the k least elements from the given iterator according to this ordering, in order from least to greatest.
<S extends T> Ordering<Iterable<S>> lexicographical()
Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until a nonzero result is found; imposes "dictionary order".
<E extends T> E max(E a, E b)
Returns the greater of the two values according to this ordering.
<E extends T> E max(E a, E b, E c, E... rest)
Returns the greatest of the specified values according to this ordering.
<E extends T> E max(Iterable<E> iterable)
Returns the greatest of the specified values according to this ordering.
<E extends T> E max(Iterator<E> iterator)
Returns the greatest of the specified values according to this ordering.
<E extends T> E min(E a, E b)
Returns the lesser of the two values according to this ordering.
<E extends T> E min(E a, E b, E c, E... rest)
Returns the least of the specified values according to this ordering.
<E extends T> E min(Iterable<E> iterable)
Returns the least of the specified values according to this ordering.
<E extends T> E min(Iterator<E> iterator)
Returns the least of the specified values according to this ordering.
static <C extends Comparable> Ordering<C> natural()
Returns a serializable ordering that uses the natural order of the values.
<S extends T> Ordering<S> nullsFirst()
Returns an ordering that treats null as less than all other values and uses this to compare non-null values.
<S extends T> Ordering<S> nullsLast()
Returns an ordering that treats null as greater than all other values and uses this ordering to compare non-null values.
<F> Ordering<F> onResultOf(Function<F,? extends T> function)
Returns a new ordering on F which orders elements by first applying a function to them, then comparing those results using this.
<S extends T> Ordering<S> reverse()
Returns the reverse of this ordering; the Ordering equivalent to Collections.reverseOrder(Comparator).
<E extends T> List<E> sortedCopy(Iterable<E> elements)
Returns a mutable list containing elements sorted by this ordering; use this only when the resulting list may need further modification, or may contain null.
static Ordering<Object> usingToString()
Returns an ordering that compares objects by the natural ordering of their string representations as returned by toString().
This class inherits methods from the following class −
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Ordering;
public class GuavaTester {
public static void main(String args[]) {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(new Integer(5));
numbers.add(new Integer(2));
numbers.add(new Integer(15));
numbers.add(new Integer(51));
numbers.add(new Integer(53));
numbers.add(new Integer(35));
numbers.add(new Integer(45));
numbers.add(new Integer(32));
numbers.add(new Integer(43));
numbers.add(new Integer(16));
Ordering ordering = Ordering.natural();
System.out.println("Input List: ");
System.out.println(numbers);
Collections.sort(numbers,ordering );
System.out.println("Sorted List: ");
System.out.println(numbers);
System.out.println("======================");
System.out.println("List is sorted: " + ordering.isOrdered(numbers));
System.out.println("Minimum: " + ordering.min(numbers));
System.out.println("Maximum: " + ordering.max(numbers));
Collections.sort(numbers,ordering.reverse());
System.out.println("Reverse: " + numbers);
numbers.add(null);
System.out.println("Null added to Sorted List: ");
System.out.println(numbers);
Collections.sort(numbers,ordering.nullsFirst());
System.out.println("Null first Sorted List: ");
System.out.println(numbers);
System.out.println("======================");
List<String> names = new ArrayList<String>();
names.add("Ram");
names.add("Shyam");
names.add("Mohan");
names.add("Sohan");
names.add("Ramesh");
names.add("Suresh");
names.add("Naresh");
names.add("Mahesh");
names.add(null);
names.add("Vikas");
names.add("Deepak");
System.out.println("Another List: ");
System.out.println(names);
Collections.sort(names,ordering.nullsFirst().reverse());
System.out.println("Null first then reverse sorted list: ");
System.out.println(names);
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
Input List:
[5, 2, 15, 51, 53, 35, 45, 32, 43, 16]
Sorted List:
[2, 5, 15, 16, 32, 35, 43, 45, 51, 53]
======================
List is sorted: true
Minimum: 2
Maximum: 53
Reverse: [53, 51, 45, 43, 35, 32, 16, 15, 5, 2]
Null added to Sorted List:
[53, 51, 45, 43, 35, 32, 16, 15, 5, 2, null]
Null first Sorted List:
[null, 2, 5, 15, 16, 32, 35, 43, 45, 51, 53]
======================
Another List:
[Ram, Shyam, Mohan, Sohan, Ramesh, Suresh, Naresh, Mahesh, null, Vikas, Deepak]
Null first then reverse sorted list:
[Vikas, Suresh, Sohan, Shyam, Ramesh, Ram, Naresh, Mohan, Mahesh, Deepak, null]
Objects class provides helper functions applicable to all objects such as equals, hashCode, etc.
Following is the declaration for com.google.common.base.Objects class −
@GwtCompatible
public final class Objects
extends Object
static boolean equal(Object a, Object b)
Determines whether two possibly-null objects are equal.
static <T> T firstNonNull(T first, T second)
Deprecated. Use MoreObjects.firstNonNull(T, T) instead. This method is scheduled for removal in June 2016.
static int hashCode(Object... objects)
Generates a hash code for multiple values.
static Objects.ToStringHelper toStringHelper(Class<?> clazz)
Deprecated. Use MoreObjects.toStringHelper(Class) instead. This method is scheduled for removal in June 2016
static Objects.ToStringHelper toStringHelper(Object self)
Deprecated. Use MoreObjects.toStringHelper(Object) instead. This method is scheduled for removal in June 2016.
static Objects.ToStringHelper toStringHelper(String className)
Deprecated. Use MoreObjects.toStringHelper(String) instead. This method is scheduled for removal in June 2016.
This class inherits methods from the following class −
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import com.google.common.base.Objects;
public class GuavaTester {
public static void main(String args[]) {
Student s1 = new Student("Mahesh", "Parashar", 1, "VI");
Student s2 = new Student("Suresh", null, 3, null);
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(
Objects.toStringHelper(s1)
.add("Name",s1.getFirstName()+" " + s1.getLastName())
.add("Class", s1.getClassName())
.add("Roll No", s1.getRollNo())
.toString());
}
}
class Student {
private String firstName;
private String lastName;
private int rollNo;
private String className;
public Student(String firstName, String lastName, int rollNo, String className) {
this.firstName = firstName;
this.lastName = lastName;
this.rollNo = rollNo;
this.className = className;
}
@Override
public boolean equals(Object object) {
if(!(object instanceof Student) || object == null) {
return false;
}
Student student = (Student)object;
// no need to handle null here
// Objects.equal("test", "test") == true
// Objects.equal("test", null) == false
// Objects.equal(null, "test") == false
// Objects.equal(null, null) == true
return Objects.equal(firstName, student.firstName) // first name can be null
&& Objects.equal(lastName, student.lastName) // last name can be null
&& Objects.equal(rollNo, student.rollNo)
&& Objects.equal(className, student.className); // class name can be null
}
@Override
public int hashCode() {
//no need to compute hashCode by self
return Objects.hashCode(className,rollNo);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
false
85871
Student{Name=Mahesh Parashar, Class=VI, Roll No=1}
Range represents an interval or a sequence. It is used to get a set of numbers/ strings lying in a particular range.
Following is the declaration for com.google.common.collect.Range<C> class −
@GwtCompatible
public final class Range<C extends Comparable>
extends Object
implements Predicate<C>, Serializable
static <C extends Comparable<?>> Range<C> all()
Returns a range that contains every value of type C.
boolean apply(C input)Deprecated.
Provided only to satisfy the Predicate interface; use contains(C) instead.
static <C extends Comparable<?>> Range<C> atLeast(C endpoint)
Returns a range that contains all values greater than or equal to endpoint.
static <C extends Comparable<?>> Range<C> atMost(C endpoint)
Returns a range that contains all values less than or equal to endpoint.
Range<C> canonical(DiscreteDomain<C> domain)
Returns the canonical form of this range in the given domain.
static <C extends Comparable<?>> Range<C> closed(C lower, C upper)
Returns a range that contains all values greater than or equal to lower and less than or equal to upper.
static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper)
Returns a range that contains all values greater than or equal to lower and strictly less than upper.
boolean contains(C value)
Returns true if value is within the bounds of this range.
boolean containsAll(Iterable<? extends C> values)
Returns true if every element in values is contained in this range.
static <C extends Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType)
Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive (open), with no upper bound.
static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values)
Returns the minimal range that contains all of the given values.
boolean encloses(Range<C> other)
Returns true if the bounds of other do not extend outside the bounds of this range.
boolean equals(Object object)
Returns true if object is a range having the same endpoints and bound types as this range.
static <C extends Comparable<?>> Range<C> greaterThan(C endpoint)
Returns a range that contains all values strictly greater than endpoint.
int hashCode()
Returns a hash code for this range.
boolean hasLowerBound()
Returns true if this range has a lower endpoint.
boolean hasUpperBound()
Returns true if this range has an upper endpoint.
Range<C> intersection(Range<C> connectedRange)
Returns the maximal range enclosed by both this range and connectedRange, if such a range exists.
boolean isConnected(Range<C> other)
Returns true if there exists a (possibly empty) range which is enclosed by both this range and other.
boolean isEmpty()
Returns true if this range is of the form [v..v) or (v..v].
static <C extends Comparable<?>> Range<C> lessThan(C endpoint)
Returns a range that contains all values strictly less than endpoint.
BoundType lowerBoundType()
Returns the type of this range's lower bound: BoundType.CLOSED if the range includes its lower endpoint, BoundType.OPEN if it does not.
C lowerEndpoint()
Returns the lower endpoint of this range.
static <C extends Comparable<?>> Range<C> open(C lower, C upper)
Returns a range that contains all values strictly greater than lower and strictly less than upper.
static <C extends Comparable<?>> Range<C> openClosed(C lower, C upper)
Returns a range that contains all values strictly greater than lower and less than or equal to upper.
static <C extends Comparable<?>> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType)
Returns a range that contains any value from lower to upper, where each endpoint may be either inclusive (closed) or exclusive (open).
static <C extends Comparable<?>> Range<C> singleton(C value)
Returns a range that contains only the given value.
Range<C> span(Range<C> other)
Returns the minimal range that encloses both this range and other.
String toString()
Returns a string representation of this range, such as "[3..5)" (other examples are listed in the class documentation).
BoundType upperBoundType()
Returns the type of this range's upper bound: BoundType.CLOSED if the range includes its upper endpoint, BoundType.OPEN if it does not.
C upperEndpoint()
Returns the upper endpoint of this range.
static <C extends Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType)
Returns a range with no lower bound up to the given endpoint, which may be either inclusive (closed) or exclusive (open).
This class inherits methods from the following class −
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;
import com.google.common.primitives.Ints;
public class GuavaTester {
public static void main(String args[]) {
GuavaTester tester = new GuavaTester();
tester.testRange();
}
private void testRange() {
//create a range [a,b] = { x | a <= x <= b}
Range<Integer> range1 = Range.closed(0, 9);
System.out.print("[0,9] : ");
printRange(range1);
System.out.println("5 is present: " + range1.contains(5));
System.out.println("(1,2,3) is present: " + range1.containsAll(Ints.asList(1, 2, 3)));
System.out.println("Lower Bound: " + range1.lowerEndpoint());
System.out.println("Upper Bound: " + range1.upperEndpoint());
//create a range (a,b) = { x | a < x < b}
Range<Integer> range2 = Range.open(0, 9);
System.out.print("(0,9) : ");
printRange(range2);
//create a range (a,b] = { x | a < x <= b}
Range<Integer> range3 = Range.openClosed(0, 9);
System.out.print("(0,9] : ");
printRange(range3);
//create a range [a,b) = { x | a <= x < b}
Range<Integer> range4 = Range.closedOpen(0, 9);
System.out.print("[0,9) : ");
printRange(range4);
//create an open ended range (9, infinity
Range<Integer> range5 = Range.greaterThan(9);
System.out.println("(9,infinity) : ");
System.out.println("Lower Bound: " + range5.lowerEndpoint());
System.out.println("Upper Bound present: " + range5.hasUpperBound());
Range<Integer> range6 = Range.closed(3, 5);
printRange(range6);
//check a subrange [3,5] in [0,9]
System.out.println("[0,9] encloses [3,5]:" + range1.encloses(range6));
Range<Integer> range7 = Range.closed(9, 20);
printRange(range7);
//check ranges to be connected
System.out.println("[0,9] is connected [9,20]:" + range1.isConnected(range7));
Range<Integer> range8 = Range.closed(5, 15);
//intersection
printRange(range1.intersection(range8));
//span
printRange(range1.span(range8));
}
private void printRange(Range<Integer> range) {
System.out.print("[ ");
for(int grade : ContiguousSet.create(range, DiscreteDomain.integers())) {
System.out.print(grade +" ");
}
System.out.println("]");
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
[0,9] : [ 0 1 2 3 4 5 6 7 8 9 ]
5 is present: true
(1,2,3) is present: true
Lower Bound: 0
Upper Bound: 9
(0,9) : [ 1 2 3 4 5 6 7 8 ]
(0,9] : [ 1 2 3 4 5 6 7 8 9 ]
[0,9) : [ 0 1 2 3 4 5 6 7 8 ]
(9,infinity) :
Lower Bound: 9
Upper Bound present: false
[ 3 4 5 ]
[0,9] encloses [3,5]:true
[ 9 10 11 12 13 14 15 16 17 18 19 20 ]
[0,9] is connected [9,20]:true
[ 5 6 7 8 9 ]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ]
Throwables class provides utility methods related to Throwable interface.
Following is the declaration for com.google.common.base.Throwables class −
public final class Throwables
extends Object
static List<Throwable> getCausalChain(Throwable throwable)
Gets a Throwable cause chain as a list.
static Throwable getRootCause(Throwable throwable)
Returns the innermost cause of throwable.
static String getStackTraceAsString(Throwable throwable)
Returns a string containing the result of toString(), followed by the full, recursive stack trace of throwable.
static RuntimeException propagate(Throwable throwable)
Propagates throwable as-is if it is an instance of RuntimeException or Error, or else as a last resort, wraps it in a RuntimeException then propagates.
static <X extends Throwable> void propagateIfInstanceOf(Throwable throwable, Class<X> declaredType)
Propagates throwable exactly as-is, if and only if it is an instance of declaredType.
static void propagateIfPossible(Throwable throwable)
Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException or Error.
static <X extends Throwable> void propagateIfPossible(Throwable throwable, Class<X> declaredType)
Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, or declaredType.
static <X1 extends Throwable,X2 extends Throwable>void propagateIfPossible(Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)
Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, declaredType1, or declaredType2.
This class inherits methods from the following class −
java.lang.Object
Create the following java program using any editor of your choice in say C:/> Guava.
import java.io.IOException;
import com.google.common.base.Objects;
import com.google.common.base.Throwables;
public class GuavaTester {
public static void main(String args[]) {
GuavaTester tester = new GuavaTester();
try {
tester.showcaseThrowables();
} catch (InvalidInputException e) {
//get the root cause
System.out.println(Throwables.getRootCause(e));
} catch (Exception e) {
//get the stack trace in string format
System.out.println(Throwables.getStackTraceAsString(e));
}
try {
tester.showcaseThrowables1();
} catch (Exception e) {
System.out.println(Throwables.getStackTraceAsString(e));
}
}
public void showcaseThrowables() throws InvalidInputException {
try {
sqrt(-3.0);
} catch (Throwable e) {
//check the type of exception and throw it
Throwables.propagateIfInstanceOf(e, InvalidInputException.class);
Throwables.propagate(e);
}
}
public void showcaseThrowables1() {
try {
int[] data = {1,2,3};
getValue(data, 4);
} catch (Throwable e) {
Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class);
Throwables.propagate(e);
}
}
public double sqrt(double input) throws InvalidInputException {
if(input < 0) throw new InvalidInputException();
return Math.sqrt(input);
}
public double getValue(int[] list, int index) throws IndexOutOfBoundsException {
return list[index];
}
public void dummyIO() throws IOException {
throw new IOException();
}
}
class InvalidInputException extends Exception {
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
InvalidInputException
java.lang.ArrayIndexOutOfBoundsException: 4
at GuavaTester.getValue(GuavaTester.java:52)
at GuavaTester.showcaseThrowables1(GuavaTester.java:38)
at GuavaTester.main(GuavaTester.java:19)
Guava introduces many advanced collections based on developers' experience in application development works. Given below is a list of useful collections −
An extension to Set interface to allow duplicate elements.
An extension to Map interface so that its keys can be mapped to multiple values at a time.
An extension to Map interface to support inverse operations.
Table represents a special map where two keys can be specified in combined fashion to refer to a single value.
Guava provides a very powerful memory based caching mechanism by an interface LoadingCache<K,V>. Values are automatically loaded in the cache and it provides many utility methods useful for caching needs.
Following is the declaration for com.google.common.cache.LoadingCache<K,V> interface −
@Beta
@GwtCompatible
public interface LoadingCache<K,V>
extends Cache<K,V>, Function<K,V>
V apply(K key)
Deprecated. Provided to satisfy the Function interface; use get(K) or getUnchecked(K) instead.
ConcurrentMap<K,V> asMap()
Returns a view of the entries stored in this cache as a thread-safe map.
V get(K key)
Returns the value associated with key in this cache, first loading that value if necessary.
ImmutableMap<K,V> getAll(Iterable<? extends K> keys)
Returns a map of the values associated with keys, creating or retrieving those values if necessary.
V getUnchecked(K key)
Returns the value associated with key in this cache, first loading that value if necessary.
void refresh(K key)
Loads a new value for key, possibly asynchronously.
Create the following java program using any editor of your choice in say C:/> Guava.
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.google.common.base.MoreObjects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
public class GuavaTester {
public static void main(String args[]) {
//create a cache for employees based on their employee id
LoadingCache<String, Employee> employeeCache =
CacheBuilder.newBuilder()
.maximumSize(100) // maximum 100 records can be cached
.expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access
.build(new CacheLoader<String, Employee>() { // build the cacheloader
@Override
public Employee load(String empId) throws Exception {
//make the expensive call
return getFromDatabase(empId);
}
});
try {
//on first invocation, cache will be populated with corresponding
//employee record
System.out.println("Invocation #1");
System.out.println(employeeCache.get("100"));
System.out.println(employeeCache.get("103"));
System.out.println(employeeCache.get("110"));
//second invocation, data will be returned from cache
System.out.println("Invocation #2");
System.out.println(employeeCache.get("100"));
System.out.println(employeeCache.get("103"));
System.out.println(employeeCache.get("110"));
} catch (ExecutionException e) {
e.printStackTrace();
}
}
private static Employee getFromDatabase(String empId) {
Employee e1 = new Employee("Mahesh", "Finance", "100");
Employee e2 = new Employee("Rohan", "IT", "103");
Employee e3 = new Employee("Sohan", "Admin", "110");
Map<String, Employee> database = new HashMap<String, Employee>();
database.put("100", e1);
database.put("103", e2);
database.put("110", e3);
System.out.println("Database hit for" + empId);
return database.get(empId);
}
}
class Employee {
String name;
String dept;
String emplD;
public Employee(String name, String dept, String empID) {
this.name = name;
this.dept = dept;
this.emplD = empID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getEmplD() {
return emplD;
}
public void setEmplD(String emplD) {
this.emplD = emplD;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(Employee.class)
.add("Name", name)
.add("Department", dept)
.add("Emp Id", emplD).toString();
}
}
Compile the class using javac compiler as follows −
C:\Guava>javac GuavaTester.java
Now run the GuavaTester to see the result.
C:\Guava>java GuavaTester
See the result.
Invocation #1
Database hit for100
Employee{Name=Mahesh, Department=Finance, Emp Id=100}
Database hit for103
Employee{Name=Rohan, Department=IT, Emp Id=103}
Database hit for110
Employee{Name=Sohan, Department=Admin, Emp Id=110}
Invocation #2
Employee{Name=Mahesh, Department=Finance, Emp Id=100}
Employee{Name=Rohan, Department=IT, Emp Id=103}
Employee{Name=Sohan, Department=Admin, Emp Id=110}
Guava introduces many advanced string utilities based on developers' experience in application development works. Following is the list of useful string based utilities −
Utility to join objects, string etc.
Utility to split string.
Utility for character operations.
Utility for changing string formats.
As primitive types of Java cannot be used to pass in generics or in collections as input, Guava provided a lot of Wrapper Utilities classes to handle primitive types as Objects. Following is the list of useful primitive processing utilities −
Utility for primitive byte.
Utility for primitive short.
Utility for primitive int.
Utility for primitive long.
Utility for primitive float.
Utility for primitive double.
Utility for primitive char.
Utility for primitive boolean.
Guava provides Mathematics related Utilities classes to handle int, long and BigInteger. Following is the list of useful utilities −
Math utility for int.
Math utility for long.
Math utility for BigInteger.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2238,
"s": 1885,
"text": "Guava is an open source, Java-based library and contains many core libraries of Google, which are being used in many of their projects. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations."
},
{
"code": null,
"e": 2293,
"s": 2238,
"text": "Standardized − The Guava library is managed by Google."
},
{
"code": null,
"e": 2348,
"s": 2293,
"text": "Standardized − The Guava library is managed by Google."
},
{
"code": null,
"e": 2439,
"s": 2348,
"text": "Efficient − It is a reliable, fast, and efficient extension to the Java standard library."
},
{
"code": null,
"e": 2530,
"s": 2439,
"text": "Efficient − It is a reliable, fast, and efficient extension to the Java standard library."
},
{
"code": null,
"e": 2575,
"s": 2530,
"text": "Optimized − The library is highly optimized."
},
{
"code": null,
"e": 2620,
"s": 2575,
"text": "Optimized − The library is highly optimized."
},
{
"code": null,
"e": 2695,
"s": 2620,
"text": "Functional Programming − It adds functional processing capability to Java."
},
{
"code": null,
"e": 2770,
"s": 2695,
"text": "Functional Programming − It adds functional processing capability to Java."
},
{
"code": null,
"e": 2884,
"s": 2770,
"text": "Utilities − It provides many utility classes which are regularly required in programming application development."
},
{
"code": null,
"e": 2998,
"s": 2884,
"text": "Utilities − It provides many utility classes which are regularly required in programming application development."
},
{
"code": null,
"e": 3065,
"s": 2998,
"text": "Validation − It provides a standard failsafe validation mechanism."
},
{
"code": null,
"e": 3132,
"s": 3065,
"text": "Validation − It provides a standard failsafe validation mechanism."
},
{
"code": null,
"e": 3182,
"s": 3132,
"text": "Best Practices − It emphasizes on best practices."
},
{
"code": null,
"e": 3232,
"s": 3182,
"text": "Best Practices − It emphasizes on best practices."
},
{
"code": null,
"e": 3269,
"s": 3232,
"text": "Consider the following code snippet."
},
{
"code": null,
"e": 3587,
"s": 3269,
"text": "public class GuavaTester {\n public static void main(String args[]) {\n GuavaTester guavaTester = new GuavaTester();\n \n Integer a = null;\n Integer b = new Integer(10);\n System.out.println(guavaTester.sum(a,b));\n }\n\n public Integer sum(Integer a, Integer b) {\n return a + b;\n }\t\n}"
},
{
"code": null,
"e": 3632,
"s": 3587,
"text": "Run the program to get the following result."
},
{
"code": null,
"e": 3777,
"s": 3632,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n at GuavaTester.sum(GuavaTester.java:13)\n at GuavaTester.main(GuavaTester.java:9)\n"
},
{
"code": null,
"e": 3819,
"s": 3777,
"text": "Following are the problems with the code."
},
{
"code": null,
"e": 3891,
"s": 3819,
"text": "sum() is not taking care of any of the parameters to be passed as null."
},
{
"code": null,
"e": 3963,
"s": 3891,
"text": "sum() is not taking care of any of the parameters to be passed as null."
},
{
"code": null,
"e": 4052,
"s": 3963,
"text": "caller function is also not worried about passing a null to the sum() method accidently."
},
{
"code": null,
"e": 4141,
"s": 4052,
"text": "caller function is also not worried about passing a null to the sum() method accidently."
},
{
"code": null,
"e": 4193,
"s": 4141,
"text": "When the program runs, NullPointerException occurs."
},
{
"code": null,
"e": 4245,
"s": 4193,
"text": "When the program runs, NullPointerException occurs."
},
{
"code": null,
"e": 4365,
"s": 4245,
"text": "In order to avoid the above problems, null check is to be made in each and every place where such problems are present."
},
{
"code": null,
"e": 4479,
"s": 4365,
"text": "Let's see the use of Optional, a Guava provided Utility class, to solve the above problems in a standardized way."
},
{
"code": null,
"e": 4959,
"s": 4479,
"text": "import com.google.common.base.Optional;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n GuavaTester guavaTester = new GuavaTester();\n\n Integer invalidInput = null;\n Optional<Integer> a = Optional.of(invalidInput);\n Optional<Integer> b = Optional.of(new Integer(10));\n System.out.println(guavaTester.sum(a,b)); \n }\n\n public Integer sum(Optional<Integer> a, Optional<Integer> b) {\n return a.get() + b.get();\n }\t\n}"
},
{
"code": null,
"e": 5004,
"s": 4959,
"text": "Run the program to get the following result."
},
{
"code": null,
"e": 5239,
"s": 5004,
"text": "Exception in thread \"main\" java.lang.NullPointerException\n\tat com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210)\n\tat com.google.common.base.Optional.of(Optional.java:85)\n\tat GuavaTester.main(GuavaTester.java:8)\n"
},
{
"code": null,
"e": 5301,
"s": 5239,
"text": "Let's understand the important concepts of the above program."
},
{
"code": null,
"e": 5369,
"s": 5301,
"text": "Optional − A utility class, to make the code use the null properly."
},
{
"code": null,
"e": 5437,
"s": 5369,
"text": "Optional − A utility class, to make the code use the null properly."
},
{
"code": null,
"e": 5566,
"s": 5437,
"text": "Optional.of − It returns the instance of Optional class to be used as a parameter. It checks the value passed, not to be ‘null’."
},
{
"code": null,
"e": 5695,
"s": 5566,
"text": "Optional.of − It returns the instance of Optional class to be used as a parameter. It checks the value passed, not to be ‘null’."
},
{
"code": null,
"e": 5771,
"s": 5695,
"text": "Optional.get − It gets the value of the input stored in the Optional class."
},
{
"code": null,
"e": 5847,
"s": 5771,
"text": "Optional.get − It gets the value of the input stored in the Optional class."
},
{
"code": null,
"e": 5951,
"s": 5847,
"text": "Using the Optional class, you can check whether the caller method is passing a proper parameter or not."
},
{
"code": null,
"e": 6182,
"s": 5951,
"text": "If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment."
},
{
"code": null,
"e": 6297,
"s": 6182,
"text": "Java SE is freely available from the link Download Java. So you download a version based on your operating system."
},
{
"code": null,
"e": 6525,
"s": 6297,
"text": "Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories −"
},
{
"code": null,
"e": 6611,
"s": 6525,
"text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 6665,
"s": 6611,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 6719,
"s": 6665,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 6789,
"s": 6719,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 6859,
"s": 6789,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 7095,
"s": 6859,
"text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 7331,
"s": 7095,
"text": "Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\\WINDOWS\\SYSTEM32', then change your path to read 'C:\\WINDOWS\\SYSTEM32;c:\\Program Files\\java\\jdk\\bin'."
},
{
"code": null,
"e": 7417,
"s": 7331,
"text": "We are assuming that you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 7537,
"s": 7417,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'"
},
{
"code": null,
"e": 7657,
"s": 7537,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin'"
},
{
"code": null,
"e": 7820,
"s": 7657,
"text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this."
},
{
"code": null,
"e": 7960,
"s": 7820,
"text": "Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'"
},
{
"code": null,
"e": 8125,
"s": 7960,
"text": "To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −"
},
{
"code": null,
"e": 8244,
"s": 8125,
"text": "Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 8363,
"s": 8244,
"text": "Notepad − On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad."
},
{
"code": null,
"e": 8486,
"s": 8363,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html."
},
{
"code": null,
"e": 8609,
"s": 8486,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from https://www.netbeans.org/index.html."
},
{
"code": null,
"e": 8741,
"s": 8609,
"text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/."
},
{
"code": null,
"e": 8873,
"s": 8741,
"text": "Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/."
},
{
"code": null,
"e": 9049,
"s": 8873,
"text": "Download the latest version of Guava jar file from guava-18.0.jar. At the time of writing this tutorial, we have downloaded guava-18.0.jar and copied it into C:\\>Guava folder."
},
{
"code": null,
"e": 9270,
"s": 9049,
"text": "Set the Guava_HOME environment variable to point to the base directory location where Guava jar is stored on your machine. Assuming, we've extracted guava-18.0.jar in Guava folder on various Operating Systems as follows."
},
{
"code": null,
"e": 9443,
"s": 9270,
"text": "Set the CLASSPATH environment variable to point to the Guava jar location. Assuming, you have stored guava-18.0.jar in Guava folder on various Operating Systems as follows."
},
{
"code": null,
"e": 9713,
"s": 9443,
"text": "Optional is an immutable object used to contain a not-null object. Optional object is used to represent null with absent value. This class has various utility methods to facilitate the code to handle values as available or not available instead of checking null values."
},
{
"code": null,
"e": 9789,
"s": 9713,
"text": "Following is the declaration for com.google.common.base.Optional<T> class −"
},
{
"code": null,
"e": 9907,
"s": 9789,
"text": "@GwtCompatible(serializable = true)\npublic abstract class Optional<T>\n extends Object\n implements Serializable"
},
{
"code": null,
"e": 9939,
"s": 9907,
"text": "static <T> Optional<T>\tabsent()"
},
{
"code": null,
"e": 9997,
"s": 9939,
"text": "Returns an Optional instance with no contained reference."
},
{
"code": null,
"e": 10021,
"s": 9997,
"text": "abstract Set<T> asSet()"
},
{
"code": null,
"e": 10153,
"s": 10021,
"text": "Returns an immutable singleton Set whose only element is the contained instance if it is present; an empty immutable Set otherwise."
},
{
"code": null,
"e": 10192,
"s": 10153,
"text": "abstract boolean equals(Object object)"
},
{
"code": null,
"e": 10320,
"s": 10192,
"text": "Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent."
},
{
"code": null,
"e": 10377,
"s": 10320,
"text": "static <T> Optional<T>\tfromNullable(T nullableReference)"
},
{
"code": null,
"e": 10495,
"s": 10377,
"text": "If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns absent()."
},
{
"code": null,
"e": 10512,
"s": 10495,
"text": "abstract T\tget()"
},
{
"code": null,
"e": 10567,
"s": 10512,
"text": "Returns the contained instance, which must be present."
},
{
"code": null,
"e": 10591,
"s": 10567,
"text": "abstract int hashCode()"
},
{
"code": null,
"e": 10630,
"s": 10591,
"text": "Returns a hash code for this instance."
},
{
"code": null,
"e": 10659,
"s": 10630,
"text": "abstract boolean isPresent()"
},
{
"code": null,
"e": 10719,
"s": 10659,
"text": "Returns true if this holder contains a (non-null) instance."
},
{
"code": null,
"e": 10758,
"s": 10719,
"text": "static <T> Optional<T>\tof(T reference)"
},
{
"code": null,
"e": 10828,
"s": 10758,
"text": "Returns an Optional instance containing the given non-null reference."
},
{
"code": null,
"e": 10888,
"s": 10828,
"text": "abstract Optional<T> or(Optional<? extends T> secondChoice)"
},
{
"code": null,
"e": 10961,
"s": 10888,
"text": "Returns this Optional if it has a value present; secondChoice otherwise."
},
{
"code": null,
"e": 11007,
"s": 10961,
"text": "abstract T or(Supplier<? extends T> supplier)"
},
{
"code": null,
"e": 11082,
"s": 11007,
"text": "Returns the contained instance if it is present; supplier.get() otherwise."
},
{
"code": null,
"e": 11112,
"s": 11082,
"text": "abstract T or(T defaultValue)"
},
{
"code": null,
"e": 11185,
"s": 11112,
"text": "Returns the contained instance if it is present; defaultValue otherwise."
},
{
"code": null,
"e": 11205,
"s": 11185,
"text": "abstract T orNull()"
},
{
"code": null,
"e": 11270,
"s": 11205,
"text": "Returns the contained instance if it is present; null otherwise."
},
{
"code": null,
"e": 11363,
"s": 11270,
"text": "static <T> Iterable<T> presentInstances(Iterable<? extends Optional<? extends T>> optionals)"
},
{
"code": null,
"e": 11484,
"s": 11363,
"text": "Returns the value of each present instance from the supplied optionals, in order, skipping over occurrences of absent()."
},
{
"code": null,
"e": 11511,
"s": 11484,
"text": "abstract String toString()"
},
{
"code": null,
"e": 11562,
"s": 11511,
"text": "Returns a string representation for this instance."
},
{
"code": null,
"e": 11629,
"s": 11562,
"text": "abstract <V> Optional<V> transform(Function<? super T,V> function)"
},
{
"code": null,
"e": 11733,
"s": 11629,
"text": "If the instance is present, it is transformed with the given Function; otherwise, absent() is returned."
},
{
"code": null,
"e": 11788,
"s": 11733,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 11805,
"s": 11788,
"text": "java.lang.Object"
},
{
"code": null,
"e": 11890,
"s": 11805,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 13015,
"s": 11890,
"text": "import com.google.common.base.Optional;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n GuavaTester guavaTester = new GuavaTester();\n\n Integer value1 = null;\n Integer value2 = new Integer(10);\n \n //Optional.fromNullable - allows passed parameter to be null.\n Optional<Integer> a = Optional.fromNullable(value1);\n \n //Optional.of - throws NullPointerException if passed parameter is null\n Optional<Integer> b = Optional.of(value2);\t\t\n\n System.out.println(guavaTester.sum(a,b));\n }\n\n public Integer sum(Optional<Integer> a, Optional<Integer> b) {\n //Optional.isPresent - checks the value is present or not\n System.out.println(\"First parameter is present: \" + a.isPresent());\n\n System.out.println(\"Second parameter is present: \" + b.isPresent());\n\n //Optional.or - returns the value if present otherwise returns\n //the default value passed.\n Integer value1 = a.or(new Integer(0));\t\n\n //Optional.get - gets the value, value should be present\n Integer value2 = b.get();\n\n return value1 + value2;\n }\t\n}"
},
{
"code": null,
"e": 13067,
"s": 13015,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 13100,
"s": 13067,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 13143,
"s": 13100,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 13170,
"s": 13143,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 13186,
"s": 13170,
"text": "See the result."
},
{
"code": null,
"e": 13258,
"s": 13186,
"text": "First parameter is present: false\nSecond parameter is present: true\n10\n"
},
{
"code": null,
"e": 13461,
"s": 13258,
"text": "Preconditions provide static methods to check that a method or a constructor is invoked with proper parameter or not. It checks the pre-conditions. Its methods throw IllegalArgumentException on failure."
},
{
"code": null,
"e": 13539,
"s": 13461,
"text": "Following is the declaration for com.google.common.base.Preconditions class −"
},
{
"code": null,
"e": 13605,
"s": 13539,
"text": "@GwtCompatible\npublic final class Preconditions\n extends Object"
},
{
"code": null,
"e": 13651,
"s": 13605,
"text": "static void checkArgument(boolean expression)"
},
{
"code": null,
"e": 13742,
"s": 13651,
"text": "Ensures the truth of an expression involving one or more parameters to the calling method."
},
{
"code": null,
"e": 13809,
"s": 13742,
"text": "static void checkArgument(boolean expression, Object errorMessage)"
},
{
"code": null,
"e": 13900,
"s": 13809,
"text": "Ensures the truth of an expression involving one or more parameters to the calling method."
},
{
"code": null,
"e": 14001,
"s": 13900,
"text": "static void checkArgument(boolean expression, String errorMessageTemplate, Object. errorMessageArgs)"
},
{
"code": null,
"e": 14092,
"s": 14001,
"text": "Ensures the truth of an expression involving one or more parameters to the calling method."
},
{
"code": null,
"e": 14142,
"s": 14092,
"text": "static int\tcheckElementIndex(int index, int size)"
},
{
"code": null,
"e": 14226,
"s": 14142,
"text": "Ensures that index specifies a valid element in an array, list or a string of size."
},
{
"code": null,
"e": 14289,
"s": 14226,
"text": "static int checkElementIndex(int index, int size, String desc)"
},
{
"code": null,
"e": 14374,
"s": 14289,
"text": "Ensures that index specifies a valid element in an array, list, or a string of size."
},
{
"code": null,
"e": 14413,
"s": 14374,
"text": "static <T> T checkNotNull(T reference)"
},
{
"code": null,
"e": 14503,
"s": 14413,
"text": "Ensures that an object reference passed as a parameter to the calling method is not null."
},
{
"code": null,
"e": 14563,
"s": 14503,
"text": "static <T> T checkNotNull(T reference, Object errorMessage)"
},
{
"code": null,
"e": 14653,
"s": 14563,
"text": "Ensures that an object reference passed as a parameter to the calling method is not null."
},
{
"code": null,
"e": 14749,
"s": 14653,
"text": "static <T> T checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs)"
},
{
"code": null,
"e": 14839,
"s": 14749,
"text": "Ensures that an object reference passed as a parameter to the calling method is not null."
},
{
"code": null,
"e": 14890,
"s": 14839,
"text": "static int\tcheckPositionIndex(int index, int size)"
},
{
"code": null,
"e": 14975,
"s": 14890,
"text": "Ensures that index specifies a valid position in an array, list or a string of size."
},
{
"code": null,
"e": 15039,
"s": 14975,
"text": "static int checkPositionIndex(int index, int size, String desc)"
},
{
"code": null,
"e": 15124,
"s": 15039,
"text": "Ensures that index specifies a valid position in an array, list or a string of size."
},
{
"code": null,
"e": 15187,
"s": 15124,
"text": "static void checkPositionIndexes(int start, int end, int size)"
},
{
"code": null,
"e": 15297,
"s": 15187,
"text": "Ensures that start and end specify a valid positions in an array, list or a string of size, and are in order."
},
{
"code": null,
"e": 15340,
"s": 15297,
"text": "static void checkState(boolean expression)"
},
{
"code": null,
"e": 15476,
"s": 15340,
"text": "Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method."
},
{
"code": null,
"e": 15540,
"s": 15476,
"text": "static void checkState(boolean expression, Object errorMessage)"
},
{
"code": null,
"e": 15676,
"s": 15540,
"text": "Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method."
},
{
"code": null,
"e": 15776,
"s": 15676,
"text": "static void checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs)"
},
{
"code": null,
"e": 15912,
"s": 15776,
"text": "Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method."
},
{
"code": null,
"e": 15967,
"s": 15912,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 15984,
"s": 15967,
"text": "java.lang.Object"
},
{
"code": null,
"e": 16069,
"s": 15984,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 17398,
"s": 16069,
"text": "import com.google.common.base.Preconditions;\n\npublic class GuavaTester {\n\n public static void main(String args[]) {\n GuavaTester guavaTester = new GuavaTester();\n\n try {\n System.out.println(guavaTester.sqrt(-3.0));\n } catch(IllegalArgumentException e) {\n System.out.println(e.getMessage());\n }\n\n try {\n System.out.println(guavaTester.sum(null,3));\n } catch(NullPointerException e) {\n System.out.println(e.getMessage());\n }\n\n try {\n System.out.println(guavaTester.getValue(6));\n } catch(IndexOutOfBoundsException e) {\n System.out.println(e.getMessage());\n }\n }\n\n public double sqrt(double input) throws IllegalArgumentException {\n Preconditions.checkArgument(input > 0.0,\n \"Illegal Argument passed: Negative value %s.\", input);\n return Math.sqrt(input);\n }\n\n public int sum(Integer a, Integer b) {\n a = Preconditions.checkNotNull(a, \"Illegal Argument passed: First parameter is Null.\");\n b = Preconditions.checkNotNull(b, \"Illegal Argument passed: Second parameter is Null.\");\n\n return a+b;\n }\n\n public int getValue(int input) {\n int[] data = {1,2,3,4,5};\n Preconditions.checkElementIndex(input,data.length, \"Illegal Argument passed: Invalid index.\");\n return 0;\n }\n}"
},
{
"code": null,
"e": 17450,
"s": 17398,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 17483,
"s": 17450,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 17526,
"s": 17483,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 17553,
"s": 17526,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 17569,
"s": 17553,
"text": "See the result."
},
{
"code": null,
"e": 17737,
"s": 17569,
"text": "Illegal Argument passed: Negative value -3.0.\nIllegal Argument passed: First parameter is Null.\nIllegal Argument passed: Invalid index. (6) must be less than size (5)\n"
},
{
"code": null,
"e": 17884,
"s": 17737,
"text": "Ordering can be seen as an enriched comparator with enhanced chaining functionality, multiple utility methods, multi-type sorting capability, etc."
},
{
"code": null,
"e": 17963,
"s": 17884,
"text": "Following is the declaration for com.google.common.collect.Ordering<T> class −"
},
{
"code": null,
"e": 18061,
"s": 17963,
"text": "@GwtCompatible\npublic abstract class Ordering<T>\n extends Object\n implements Comparator<T>"
},
{
"code": null,
"e": 18096,
"s": 18061,
"text": "static Ordering<Object> allEqual()"
},
{
"code": null,
"e": 18274,
"s": 18096,
"text": "Returns an ordering which treats all values as equal, indicating \"no ordering.\" Passing this ordering to any stable sort algorithm results in no change to the order of elements."
},
{
"code": null,
"e": 18310,
"s": 18274,
"text": "static Ordering<Object> arbitrary()"
},
{
"code": null,
"e": 18423,
"s": 18310,
"text": "Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality)."
},
{
"code": null,
"e": 18477,
"s": 18423,
"text": "int binarySearch(List<? extends T> sortedList, T key)"
},
{
"code": null,
"e": 18540,
"s": 18477,
"text": "Searches sortedList for key using the binary search algorithm."
},
{
"code": null,
"e": 18578,
"s": 18540,
"text": "abstract int compare(T left, T right)"
},
{
"code": null,
"e": 18616,
"s": 18578,
"text": "Compares its two arguments for order."
},
{
"code": null,
"e": 18694,
"s": 18616,
"text": "<U extends T> Ordering<U> compound(Comparator<? super U> secondaryComparator)"
},
{
"code": null,
"e": 18824,
"s": 18694,
"text": "Returns an ordering which first uses the ordering this, but which in the event of a \"tie\", then delegates to secondaryComparator."
},
{
"code": null,
"e": 18911,
"s": 18824,
"text": "static <T> Ordering<T>\tcompound(Iterable<? extends Comparator<? super T>> comparators)"
},
{
"code": null,
"e": 19087,
"s": 18911,
"text": "Returns an ordering which tries each given comparator in order until a non-zero result is found, returning that result, and returning zero only if all comparators return zero."
},
{
"code": null,
"e": 19142,
"s": 19087,
"text": "static <T> Ordering<T>\texplicit(List<T> valuesInOrder)"
},
{
"code": null,
"e": 19247,
"s": 19142,
"text": "Returns an ordering that compares objects according to the order in which they appear in the given list."
},
{
"code": null,
"e": 19322,
"s": 19247,
"text": "static <T> Ordering<T>\texplicit(T leastValue, T... remainingValuesInOrder)"
},
{
"code": null,
"e": 19427,
"s": 19322,
"text": "Returns an ordering that compares objects according to the order in which they are given to this method."
},
{
"code": null,
"e": 19481,
"s": 19427,
"text": "static <T> Ordering<T>\tfrom(Comparator<T> comparator)"
},
{
"code": null,
"e": 19543,
"s": 19481,
"text": "Returns an ordering based on an existing comparator instance."
},
{
"code": null,
"e": 19605,
"s": 19543,
"text": "<E extends T> List<E> greatestOf(Iterable<E> iterable, int k)"
},
{
"code": null,
"e": 19720,
"s": 19605,
"text": "Returns the k greatest elements of the given iterable according to this ordering, in order from greatest to least."
},
{
"code": null,
"e": 19782,
"s": 19720,
"text": "<E extends T> List<E> greatestOf(Iterator<E> iterator, int k)"
},
{
"code": null,
"e": 19899,
"s": 19782,
"text": "Returns the k greatest elements from the given iterator according to this ordering, in order from greatest to least."
},
{
"code": null,
"e": 19972,
"s": 19899,
"text": "<E extends T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements)"
},
{
"code": null,
"e": 20043,
"s": 19972,
"text": "Returns an immutable list containing elements sorted by this ordering."
},
{
"code": null,
"e": 20093,
"s": 20043,
"text": "boolean isOrdered(Iterable<? extends T> iterable)"
},
{
"code": null,
"e": 20236,
"s": 20093,
"text": "Returns true if each element in iterable after the first is greater than or equal to the element that preceded it, according to this ordering."
},
{
"code": null,
"e": 20294,
"s": 20236,
"text": "boolean isStrictlyOrdered(Iterable<? extends T> iterable)"
},
{
"code": null,
"e": 20433,
"s": 20294,
"text": "Returns true if each element in iterable after the first is strictly greater than the element that preceded it, according to this ordering"
},
{
"code": null,
"e": 20492,
"s": 20433,
"text": "<E extends T> List<E> leastOf(Iterable<E> iterable, int k)"
},
{
"code": null,
"e": 20604,
"s": 20492,
"text": "Returns the k least elements of the given iterable according to this ordering, in order from least to greatest."
},
{
"code": null,
"e": 20663,
"s": 20604,
"text": "<E extends T> List<E> leastOf(Iterator<E> elements, int k)"
},
{
"code": null,
"e": 20777,
"s": 20663,
"text": "Returns the k least elements from the given iterator according to this ordering, in order from least to greatest."
},
{
"code": null,
"e": 20831,
"s": 20777,
"text": "<S extends T> Ordering<Iterable<S>> lexicographical()"
},
{
"code": null,
"e": 20982,
"s": 20831,
"text": "Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until a nonzero result is found; imposes \"dictionary order\"."
},
{
"code": null,
"e": 21012,
"s": 20982,
"text": "<E extends T> E max(E a, E b)"
},
{
"code": null,
"e": 21078,
"s": 21012,
"text": "Returns the greater of the two values according to this ordering."
},
{
"code": null,
"e": 21124,
"s": 21078,
"text": "<E extends T> E max(E a, E b, E c, E... rest)"
},
{
"code": null,
"e": 21197,
"s": 21124,
"text": "Returns the greatest of the specified values according to this ordering."
},
{
"code": null,
"e": 21239,
"s": 21197,
"text": "<E extends T> E max(Iterable<E> iterable)"
},
{
"code": null,
"e": 21312,
"s": 21239,
"text": "Returns the greatest of the specified values according to this ordering."
},
{
"code": null,
"e": 21354,
"s": 21312,
"text": "<E extends T> E max(Iterator<E> iterator)"
},
{
"code": null,
"e": 21427,
"s": 21354,
"text": "Returns the greatest of the specified values according to this ordering."
},
{
"code": null,
"e": 21457,
"s": 21427,
"text": "<E extends T> E min(E a, E b)"
},
{
"code": null,
"e": 21522,
"s": 21457,
"text": "Returns the lesser of the two values according to this ordering."
},
{
"code": null,
"e": 21568,
"s": 21522,
"text": "<E extends T> E min(E a, E b, E c, E... rest)"
},
{
"code": null,
"e": 21638,
"s": 21568,
"text": "Returns the least of the specified values according to this ordering."
},
{
"code": null,
"e": 21680,
"s": 21638,
"text": "<E extends T> E min(Iterable<E> iterable)"
},
{
"code": null,
"e": 21750,
"s": 21680,
"text": "Returns the least of the specified values according to this ordering."
},
{
"code": null,
"e": 21792,
"s": 21750,
"text": "<E extends T> E min(Iterator<E> iterator)"
},
{
"code": null,
"e": 21862,
"s": 21792,
"text": "Returns the least of the specified values according to this ordering."
},
{
"code": null,
"e": 21914,
"s": 21862,
"text": "static <C extends Comparable> Ordering<C> natural()"
},
{
"code": null,
"e": 21989,
"s": 21914,
"text": "Returns a serializable ordering that uses the natural order of the values."
},
{
"code": null,
"e": 22028,
"s": 21989,
"text": "<S extends T> Ordering<S> nullsFirst()"
},
{
"code": null,
"e": 22137,
"s": 22028,
"text": "Returns an ordering that treats null as less than all other values and uses this to compare non-null values."
},
{
"code": null,
"e": 22175,
"s": 22137,
"text": "<S extends T> Ordering<S> nullsLast()"
},
{
"code": null,
"e": 22296,
"s": 22175,
"text": "Returns an ordering that treats null as greater than all other values and uses this ordering to compare non-null values."
},
{
"code": null,
"e": 22357,
"s": 22296,
"text": "<F> Ordering<F> onResultOf(Function<F,? extends T> function)"
},
{
"code": null,
"e": 22486,
"s": 22357,
"text": "Returns a new ordering on F which orders elements by first applying a function to them, then comparing those results using this."
},
{
"code": null,
"e": 22522,
"s": 22486,
"text": "<S extends T> Ordering<S> reverse()"
},
{
"code": null,
"e": 22625,
"s": 22522,
"text": "Returns the reverse of this ordering; the Ordering equivalent to Collections.reverseOrder(Comparator)."
},
{
"code": null,
"e": 22680,
"s": 22625,
"text": "<E extends T> List<E> sortedCopy(Iterable<E> elements)"
},
{
"code": null,
"e": 22838,
"s": 22680,
"text": "Returns a mutable list containing elements sorted by this ordering; use this only when the resulting list may need further modification, or may contain null."
},
{
"code": null,
"e": 22878,
"s": 22838,
"text": "static Ordering<Object> usingToString()"
},
{
"code": null,
"e": 23003,
"s": 22878,
"text": "Returns an ordering that compares objects by the natural ordering of their string representations as returned by toString()."
},
{
"code": null,
"e": 23058,
"s": 23003,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 23075,
"s": 23058,
"text": "java.lang.Object"
},
{
"code": null,
"e": 23160,
"s": 23075,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 25322,
"s": 23160,
"text": "import java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport com.google.common.collect.Ordering;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n List<Integer> numbers = new ArrayList<Integer>();\n \n numbers.add(new Integer(5));\n numbers.add(new Integer(2));\n numbers.add(new Integer(15));\n numbers.add(new Integer(51));\n numbers.add(new Integer(53));\n numbers.add(new Integer(35));\n numbers.add(new Integer(45));\n numbers.add(new Integer(32));\n numbers.add(new Integer(43));\n numbers.add(new Integer(16));\n\n Ordering ordering = Ordering.natural();\n System.out.println(\"Input List: \");\n System.out.println(numbers);\t\t\n \n Collections.sort(numbers,ordering );\n System.out.println(\"Sorted List: \");\n System.out.println(numbers);\n \n System.out.println(\"======================\");\n System.out.println(\"List is sorted: \" + ordering.isOrdered(numbers));\n System.out.println(\"Minimum: \" + ordering.min(numbers));\n System.out.println(\"Maximum: \" + ordering.max(numbers));\n \n Collections.sort(numbers,ordering.reverse());\n System.out.println(\"Reverse: \" + numbers);\n\n numbers.add(null);\n System.out.println(\"Null added to Sorted List: \");\n System.out.println(numbers);\t\t\n\n Collections.sort(numbers,ordering.nullsFirst());\n System.out.println(\"Null first Sorted List: \");\n System.out.println(numbers);\n System.out.println(\"======================\");\n\n List<String> names = new ArrayList<String>();\n \n names.add(\"Ram\");\n names.add(\"Shyam\");\n names.add(\"Mohan\");\n names.add(\"Sohan\");\n names.add(\"Ramesh\");\n names.add(\"Suresh\");\n names.add(\"Naresh\");\n names.add(\"Mahesh\");\n names.add(null);\n names.add(\"Vikas\");\n names.add(\"Deepak\");\n\n System.out.println(\"Another List: \");\n System.out.println(names);\n\n Collections.sort(names,ordering.nullsFirst().reverse());\n System.out.println(\"Null first then reverse sorted list: \");\n System.out.println(names);\n }\n}"
},
{
"code": null,
"e": 25374,
"s": 25322,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 25407,
"s": 25374,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 25450,
"s": 25407,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 25477,
"s": 25450,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 25493,
"s": 25477,
"text": "See the result."
},
{
"code": null,
"e": 26093,
"s": 25493,
"text": "Input List: \n[5, 2, 15, 51, 53, 35, 45, 32, 43, 16]\nSorted List: \n[2, 5, 15, 16, 32, 35, 43, 45, 51, 53]\n======================\nList is sorted: true\nMinimum: 2\nMaximum: 53\nReverse: [53, 51, 45, 43, 35, 32, 16, 15, 5, 2]\nNull added to Sorted List: \n[53, 51, 45, 43, 35, 32, 16, 15, 5, 2, null]\nNull first Sorted List: \n[null, 2, 5, 15, 16, 32, 35, 43, 45, 51, 53]\n======================\nAnother List: \n[Ram, Shyam, Mohan, Sohan, Ramesh, Suresh, Naresh, Mahesh, null, Vikas, Deepak]\nNull first then reverse sorted list: \n[Vikas, Suresh, Sohan, Shyam, Ramesh, Ram, Naresh, Mohan, Mahesh, Deepak, null]\n"
},
{
"code": null,
"e": 26190,
"s": 26093,
"text": "Objects class provides helper functions applicable to all objects such as equals, hashCode, etc."
},
{
"code": null,
"e": 26262,
"s": 26190,
"text": "Following is the declaration for com.google.common.base.Objects class −"
},
{
"code": null,
"e": 26322,
"s": 26262,
"text": "@GwtCompatible\npublic final class Objects\n extends Object"
},
{
"code": null,
"e": 26363,
"s": 26322,
"text": "static boolean\tequal(Object a, Object b)"
},
{
"code": null,
"e": 26419,
"s": 26363,
"text": "Determines whether two possibly-null objects are equal."
},
{
"code": null,
"e": 26464,
"s": 26419,
"text": "static <T> T\tfirstNonNull(T first, T second)"
},
{
"code": null,
"e": 26571,
"s": 26464,
"text": "Deprecated. Use MoreObjects.firstNonNull(T, T) instead. This method is scheduled for removal in June 2016."
},
{
"code": null,
"e": 26610,
"s": 26571,
"text": "static int hashCode(Object... objects)"
},
{
"code": null,
"e": 26653,
"s": 26610,
"text": "Generates a hash code for multiple values."
},
{
"code": null,
"e": 26714,
"s": 26653,
"text": "static Objects.ToStringHelper\ttoStringHelper(Class<?> clazz)"
},
{
"code": null,
"e": 26823,
"s": 26714,
"text": "Deprecated. Use MoreObjects.toStringHelper(Class) instead. This method is scheduled for removal in June 2016"
},
{
"code": null,
"e": 26881,
"s": 26823,
"text": "static Objects.ToStringHelper\ttoStringHelper(Object self)"
},
{
"code": null,
"e": 26992,
"s": 26881,
"text": "Deprecated. Use MoreObjects.toStringHelper(Object) instead. This method is scheduled for removal in June 2016."
},
{
"code": null,
"e": 27055,
"s": 26992,
"text": "static Objects.ToStringHelper\ttoStringHelper(String className)"
},
{
"code": null,
"e": 27166,
"s": 27055,
"text": "Deprecated. Use MoreObjects.toStringHelper(String) instead. This method is scheduled for removal in June 2016."
},
{
"code": null,
"e": 27221,
"s": 27166,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 27238,
"s": 27221,
"text": "java.lang.Object"
},
{
"code": null,
"e": 27323,
"s": 27238,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 29688,
"s": 27323,
"text": "import com.google.common.base.Objects;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n Student s1 = new Student(\"Mahesh\", \"Parashar\", 1, \"VI\");\t\n Student s2 = new Student(\"Suresh\", null, 3, null);\t\n\t \n System.out.println(s1.equals(s2));\n System.out.println(s1.hashCode());\t\n System.out.println(\n Objects.toStringHelper(s1)\n .add(\"Name\",s1.getFirstName()+\" \" + s1.getLastName())\n .add(\"Class\", s1.getClassName())\n .add(\"Roll No\", s1.getRollNo())\n .toString());\n }\n}\n\nclass Student {\n private String firstName;\n private String lastName;\n private int rollNo;\n private String className;\n\n public Student(String firstName, String lastName, int rollNo, String className) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.rollNo = rollNo;\n this.className = className;\t\t\n }\n\n @Override\n public boolean equals(Object object) {\n if(!(object instanceof Student) || object == null) {\n return false;\n }\n Student student = (Student)object;\n // no need to handle null here\t\t\n // Objects.equal(\"test\", \"test\") == true\n // Objects.equal(\"test\", null) == false\n // Objects.equal(null, \"test\") == false\n // Objects.equal(null, null) == true\t\t\n return Objects.equal(firstName, student.firstName) // first name can be null\n && Objects.equal(lastName, student.lastName) // last name can be null\n && Objects.equal(rollNo, student.rollNo)\t\n && Objects.equal(className, student.className); // class name can be null\n }\n\n @Override\n public int hashCode() {\n //no need to compute hashCode by self\n return Objects.hashCode(className,rollNo);\n }\n \n public String getFirstName() {\n return firstName;\n }\n \n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n \n public String getLastName() {\n return lastName;\n }\n \n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n \n public int getRollNo() {\n return rollNo;\n }\n \n public void setRollNo(int rollNo) {\n this.rollNo = rollNo;\n }\n \n public String getClassName() {\n return className;\n }\n \n public void setClassName(String className) {\n this.className = className;\n }\n}"
},
{
"code": null,
"e": 29740,
"s": 29688,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 29773,
"s": 29740,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 29816,
"s": 29773,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 29843,
"s": 29816,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 29859,
"s": 29843,
"text": "See the result."
},
{
"code": null,
"e": 29923,
"s": 29859,
"text": "false\n85871\nStudent{Name=Mahesh Parashar, Class=VI, Roll No=1}\n"
},
{
"code": null,
"e": 30040,
"s": 29923,
"text": "Range represents an interval or a sequence. It is used to get a set of numbers/ strings lying in a particular range."
},
{
"code": null,
"e": 30116,
"s": 30040,
"text": "Following is the declaration for com.google.common.collect.Range<C> class −"
},
{
"code": null,
"e": 30240,
"s": 30116,
"text": "@GwtCompatible\npublic final class Range<C extends Comparable>\n extends Object\n implements Predicate<C>, Serializable"
},
{
"code": null,
"e": 30288,
"s": 30240,
"text": "static <C extends Comparable<?>> Range<C> all()"
},
{
"code": null,
"e": 30341,
"s": 30288,
"text": "Returns a range that contains every value of type C."
},
{
"code": null,
"e": 30375,
"s": 30341,
"text": "boolean apply(C input)Deprecated."
},
{
"code": null,
"e": 30450,
"s": 30375,
"text": "Provided only to satisfy the Predicate interface; use contains(C) instead."
},
{
"code": null,
"e": 30512,
"s": 30450,
"text": "static <C extends Comparable<?>> Range<C> atLeast(C endpoint)"
},
{
"code": null,
"e": 30588,
"s": 30512,
"text": "Returns a range that contains all values greater than or equal to endpoint."
},
{
"code": null,
"e": 30649,
"s": 30588,
"text": "static <C extends Comparable<?>> Range<C> atMost(C endpoint)"
},
{
"code": null,
"e": 30722,
"s": 30649,
"text": "Returns a range that contains all values less than or equal to endpoint."
},
{
"code": null,
"e": 30767,
"s": 30722,
"text": "Range<C> canonical(DiscreteDomain<C> domain)"
},
{
"code": null,
"e": 30829,
"s": 30767,
"text": "Returns the canonical form of this range in the given domain."
},
{
"code": null,
"e": 30896,
"s": 30829,
"text": "static <C extends Comparable<?>> Range<C> closed(C lower, C upper)"
},
{
"code": null,
"e": 31001,
"s": 30896,
"text": "Returns a range that contains all values greater than or equal to lower and less than or equal to upper."
},
{
"code": null,
"e": 31072,
"s": 31001,
"text": "static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper)"
},
{
"code": null,
"e": 31174,
"s": 31072,
"text": "Returns a range that contains all values greater than or equal to lower and strictly less than upper."
},
{
"code": null,
"e": 31200,
"s": 31174,
"text": "boolean contains(C value)"
},
{
"code": null,
"e": 31258,
"s": 31200,
"text": "Returns true if value is within the bounds of this range."
},
{
"code": null,
"e": 31308,
"s": 31258,
"text": "boolean containsAll(Iterable<? extends C> values)"
},
{
"code": null,
"e": 31376,
"s": 31308,
"text": "Returns true if every element in values is contained in this range."
},
{
"code": null,
"e": 31458,
"s": 31376,
"text": "static <C extends Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType)"
},
{
"code": null,
"e": 31580,
"s": 31458,
"text": "Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive (open), with no upper bound."
},
{
"code": null,
"e": 31653,
"s": 31580,
"text": "static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values)"
},
{
"code": null,
"e": 31718,
"s": 31653,
"text": "Returns the minimal range that contains all of the given values."
},
{
"code": null,
"e": 31751,
"s": 31718,
"text": "boolean encloses(Range<C> other)"
},
{
"code": null,
"e": 31835,
"s": 31751,
"text": "Returns true if the bounds of other do not extend outside the bounds of this range."
},
{
"code": null,
"e": 31865,
"s": 31835,
"text": "boolean equals(Object object)"
},
{
"code": null,
"e": 31956,
"s": 31865,
"text": "Returns true if object is a range having the same endpoints and bound types as this range."
},
{
"code": null,
"e": 32022,
"s": 31956,
"text": "static <C extends Comparable<?>> Range<C> greaterThan(C endpoint)"
},
{
"code": null,
"e": 32095,
"s": 32022,
"text": "Returns a range that contains all values strictly greater than endpoint."
},
{
"code": null,
"e": 32110,
"s": 32095,
"text": "int hashCode()"
},
{
"code": null,
"e": 32146,
"s": 32110,
"text": "Returns a hash code for this range."
},
{
"code": null,
"e": 32170,
"s": 32146,
"text": "boolean hasLowerBound()"
},
{
"code": null,
"e": 32219,
"s": 32170,
"text": "Returns true if this range has a lower endpoint."
},
{
"code": null,
"e": 32243,
"s": 32219,
"text": "boolean hasUpperBound()"
},
{
"code": null,
"e": 32293,
"s": 32243,
"text": "Returns true if this range has an upper endpoint."
},
{
"code": null,
"e": 32340,
"s": 32293,
"text": "Range<C> intersection(Range<C> connectedRange)"
},
{
"code": null,
"e": 32438,
"s": 32340,
"text": "Returns the maximal range enclosed by both this range and connectedRange, if such a range exists."
},
{
"code": null,
"e": 32474,
"s": 32438,
"text": "boolean isConnected(Range<C> other)"
},
{
"code": null,
"e": 32576,
"s": 32474,
"text": "Returns true if there exists a (possibly empty) range which is enclosed by both this range and other."
},
{
"code": null,
"e": 32594,
"s": 32576,
"text": "boolean isEmpty()"
},
{
"code": null,
"e": 32654,
"s": 32594,
"text": "Returns true if this range is of the form [v..v) or (v..v]."
},
{
"code": null,
"e": 32717,
"s": 32654,
"text": "static <C extends Comparable<?>> Range<C> lessThan(C endpoint)"
},
{
"code": null,
"e": 32787,
"s": 32717,
"text": "Returns a range that contains all values strictly less than endpoint."
},
{
"code": null,
"e": 32814,
"s": 32787,
"text": "BoundType lowerBoundType()"
},
{
"code": null,
"e": 32950,
"s": 32814,
"text": "Returns the type of this range's lower bound: BoundType.CLOSED if the range includes its lower endpoint, BoundType.OPEN if it does not."
},
{
"code": null,
"e": 32968,
"s": 32950,
"text": "C lowerEndpoint()"
},
{
"code": null,
"e": 33010,
"s": 32968,
"text": "Returns the lower endpoint of this range."
},
{
"code": null,
"e": 33075,
"s": 33010,
"text": "static <C extends Comparable<?>> Range<C> open(C lower, C upper)"
},
{
"code": null,
"e": 33174,
"s": 33075,
"text": "Returns a range that contains all values strictly greater than lower and strictly less than upper."
},
{
"code": null,
"e": 33245,
"s": 33174,
"text": "static <C extends Comparable<?>> Range<C> openClosed(C lower, C upper)"
},
{
"code": null,
"e": 33347,
"s": 33245,
"text": "Returns a range that contains all values strictly greater than lower and less than or equal to upper."
},
{
"code": null,
"e": 33455,
"s": 33347,
"text": "static <C extends Comparable<?>> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType)"
},
{
"code": null,
"e": 33590,
"s": 33455,
"text": "Returns a range that contains any value from lower to upper, where each endpoint may be either inclusive (closed) or exclusive (open)."
},
{
"code": null,
"e": 33651,
"s": 33590,
"text": "static <C extends Comparable<?>> Range<C> singleton(C value)"
},
{
"code": null,
"e": 33703,
"s": 33651,
"text": "Returns a range that contains only the given value."
},
{
"code": null,
"e": 33733,
"s": 33703,
"text": "Range<C> span(Range<C> other)"
},
{
"code": null,
"e": 33800,
"s": 33733,
"text": "Returns the minimal range that encloses both this range and other."
},
{
"code": null,
"e": 33818,
"s": 33800,
"text": "String toString()"
},
{
"code": null,
"e": 33938,
"s": 33818,
"text": "Returns a string representation of this range, such as \"[3..5)\" (other examples are listed in the class documentation)."
},
{
"code": null,
"e": 33965,
"s": 33938,
"text": "BoundType upperBoundType()"
},
{
"code": null,
"e": 34101,
"s": 33965,
"text": "Returns the type of this range's upper bound: BoundType.CLOSED if the range includes its upper endpoint, BoundType.OPEN if it does not."
},
{
"code": null,
"e": 34119,
"s": 34101,
"text": "C upperEndpoint()"
},
{
"code": null,
"e": 34161,
"s": 34119,
"text": "Returns the upper endpoint of this range."
},
{
"code": null,
"e": 34241,
"s": 34161,
"text": "static <C extends Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType)"
},
{
"code": null,
"e": 34363,
"s": 34241,
"text": "Returns a range with no lower bound up to the given endpoint, which may be either inclusive (closed) or exclusive (open)."
},
{
"code": null,
"e": 34418,
"s": 34363,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 34435,
"s": 34418,
"text": "java.lang.Object"
},
{
"code": null,
"e": 34520,
"s": 34435,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 36973,
"s": 34520,
"text": "import com.google.common.collect.ContiguousSet;\nimport com.google.common.collect.DiscreteDomain;\nimport com.google.common.collect.Range;\nimport com.google.common.primitives.Ints;\n\npublic class GuavaTester {\n\n public static void main(String args[]) {\n GuavaTester tester = new GuavaTester();\n tester.testRange();\n }\n\n private void testRange() {\n\n //create a range [a,b] = { x | a <= x <= b}\n Range<Integer> range1 = Range.closed(0, 9);\t\n System.out.print(\"[0,9] : \");\n printRange(range1);\t\t\n \n System.out.println(\"5 is present: \" + range1.contains(5));\n System.out.println(\"(1,2,3) is present: \" + range1.containsAll(Ints.asList(1, 2, 3)));\n System.out.println(\"Lower Bound: \" + range1.lowerEndpoint());\n System.out.println(\"Upper Bound: \" + range1.upperEndpoint());\n\n //create a range (a,b) = { x | a < x < b}\n Range<Integer> range2 = Range.open(0, 9);\n System.out.print(\"(0,9) : \");\n printRange(range2);\n\n //create a range (a,b] = { x | a < x <= b}\n Range<Integer> range3 = Range.openClosed(0, 9);\n System.out.print(\"(0,9] : \");\n printRange(range3);\n\n //create a range [a,b) = { x | a <= x < b}\n Range<Integer> range4 = Range.closedOpen(0, 9);\n System.out.print(\"[0,9) : \");\n printRange(range4);\n\n //create an open ended range (9, infinity\n Range<Integer> range5 = Range.greaterThan(9);\n System.out.println(\"(9,infinity) : \");\n System.out.println(\"Lower Bound: \" + range5.lowerEndpoint());\n System.out.println(\"Upper Bound present: \" + range5.hasUpperBound());\n\n Range<Integer> range6 = Range.closed(3, 5);\t\n printRange(range6);\n\n //check a subrange [3,5] in [0,9]\n System.out.println(\"[0,9] encloses [3,5]:\" + range1.encloses(range6));\n\n Range<Integer> range7 = Range.closed(9, 20);\t\n printRange(range7);\n \n //check ranges to be connected\t\t\n System.out.println(\"[0,9] is connected [9,20]:\" + range1.isConnected(range7));\n Range<Integer> range8 = Range.closed(5, 15);\t\n\n //intersection\n printRange(range1.intersection(range8));\n\n //span\n printRange(range1.span(range8));\n }\n\n private void printRange(Range<Integer> range) {\t\t\n \n System.out.print(\"[ \");\n \n for(int grade : ContiguousSet.create(range, DiscreteDomain.integers())) {\n System.out.print(grade +\" \");\n }\n System.out.println(\"]\");\n }\n}"
},
{
"code": null,
"e": 37025,
"s": 36973,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 37058,
"s": 37025,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 37101,
"s": 37058,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 37128,
"s": 37101,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 37144,
"s": 37128,
"text": "See the result."
},
{
"code": null,
"e": 37559,
"s": 37144,
"text": "[0,9] : [ 0 1 2 3 4 5 6 7 8 9 ]\n5 is present: true\n(1,2,3) is present: true\nLower Bound: 0\nUpper Bound: 9\n(0,9) : [ 1 2 3 4 5 6 7 8 ]\n(0,9] : [ 1 2 3 4 5 6 7 8 9 ]\n[0,9) : [ 0 1 2 3 4 5 6 7 8 ]\n(9,infinity) : \nLower Bound: 9\nUpper Bound present: false\n[ 3 4 5 ]\n[0,9] encloses [3,5]:true\n[ 9 10 11 12 13 14 15 16 17 18 19 20 ]\n[0,9] is connected [9,20]:true\n[ 5 6 7 8 9 ]\n[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ]\n"
},
{
"code": null,
"e": 37633,
"s": 37559,
"text": "Throwables class provides utility methods related to Throwable interface."
},
{
"code": null,
"e": 37708,
"s": 37633,
"text": "Following is the declaration for com.google.common.base.Throwables class −"
},
{
"code": null,
"e": 37756,
"s": 37708,
"text": "public final class Throwables\n extends Object"
},
{
"code": null,
"e": 37815,
"s": 37756,
"text": "static List<Throwable> getCausalChain(Throwable throwable)"
},
{
"code": null,
"e": 37855,
"s": 37815,
"text": "Gets a Throwable cause chain as a list."
},
{
"code": null,
"e": 37906,
"s": 37855,
"text": "static Throwable getRootCause(Throwable throwable)"
},
{
"code": null,
"e": 37948,
"s": 37906,
"text": "Returns the innermost cause of throwable."
},
{
"code": null,
"e": 38005,
"s": 37948,
"text": "static String getStackTraceAsString(Throwable throwable)"
},
{
"code": null,
"e": 38117,
"s": 38005,
"text": "Returns a string containing the result of toString(), followed by the full, recursive stack trace of throwable."
},
{
"code": null,
"e": 38172,
"s": 38117,
"text": "static RuntimeException propagate(Throwable throwable)"
},
{
"code": null,
"e": 38324,
"s": 38172,
"text": "Propagates throwable as-is if it is an instance of RuntimeException or Error, or else as a last resort, wraps it in a RuntimeException then propagates."
},
{
"code": null,
"e": 38424,
"s": 38324,
"text": "static <X extends Throwable> void propagateIfInstanceOf(Throwable throwable, Class<X> declaredType)"
},
{
"code": null,
"e": 38510,
"s": 38424,
"text": "Propagates throwable exactly as-is, if and only if it is an instance of declaredType."
},
{
"code": null,
"e": 38563,
"s": 38510,
"text": "static void propagateIfPossible(Throwable throwable)"
},
{
"code": null,
"e": 38662,
"s": 38563,
"text": "Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException or Error."
},
{
"code": null,
"e": 38760,
"s": 38662,
"text": "static <X extends Throwable> void propagateIfPossible(Throwable throwable, Class<X> declaredType)"
},
{
"code": null,
"e": 38874,
"s": 38760,
"text": "Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, or declaredType."
},
{
"code": null,
"e": 39020,
"s": 38874,
"text": "static <X1 extends Throwable,X2 extends Throwable>void propagateIfPossible(Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2)"
},
{
"code": null,
"e": 39150,
"s": 39020,
"text": "Propagates throwable exactly as-is, if and only if it is an instance of RuntimeException, Error, declaredType1, or declaredType2."
},
{
"code": null,
"e": 39205,
"s": 39150,
"text": "This class inherits methods from the following class −"
},
{
"code": null,
"e": 39222,
"s": 39205,
"text": "java.lang.Object"
},
{
"code": null,
"e": 39307,
"s": 39222,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 41033,
"s": 39307,
"text": "import java.io.IOException;\n\nimport com.google.common.base.Objects;\nimport com.google.common.base.Throwables;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n \n GuavaTester tester = new GuavaTester();\n\n try {\n tester.showcaseThrowables();\n \n } catch (InvalidInputException e) {\n //get the root cause\n System.out.println(Throwables.getRootCause(e));\n \n } catch (Exception e) {\n //get the stack trace in string format\n System.out.println(Throwables.getStackTraceAsString(e));\n }\n\n try {\n tester.showcaseThrowables1();\n\n } catch (Exception e) {\n System.out.println(Throwables.getStackTraceAsString(e));\n }\n }\n\n public void showcaseThrowables() throws InvalidInputException {\n try {\n sqrt(-3.0);\n } catch (Throwable e) {\n //check the type of exception and throw it\n Throwables.propagateIfInstanceOf(e, InvalidInputException.class);\n Throwables.propagate(e);\n }\n }\n\n public void showcaseThrowables1() {\n try {\n int[] data = {1,2,3};\n getValue(data, 4);\n } catch (Throwable e) {\n Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class);\n Throwables.propagate(e);\n }\n }\n\n public double sqrt(double input) throws InvalidInputException {\n if(input < 0) throw new InvalidInputException();\n return Math.sqrt(input);\n }\n\n public double getValue(int[] list, int index) throws IndexOutOfBoundsException {\n return list[index];\n }\n\n public void dummyIO() throws IOException {\n throw new IOException();\n }\n}\n\nclass InvalidInputException extends Exception {\n}"
},
{
"code": null,
"e": 41085,
"s": 41033,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 41118,
"s": 41085,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 41161,
"s": 41118,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 41188,
"s": 41161,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 41204,
"s": 41188,
"text": "See the result."
},
{
"code": null,
"e": 41422,
"s": 41204,
"text": "InvalidInputException\njava.lang.ArrayIndexOutOfBoundsException: 4\n at GuavaTester.getValue(GuavaTester.java:52)\n at GuavaTester.showcaseThrowables1(GuavaTester.java:38)\n at GuavaTester.main(GuavaTester.java:19)\n"
},
{
"code": null,
"e": 41577,
"s": 41422,
"text": "Guava introduces many advanced collections based on developers' experience in application development works. Given below is a list of useful collections −"
},
{
"code": null,
"e": 41636,
"s": 41577,
"text": "An extension to Set interface to allow duplicate elements."
},
{
"code": null,
"e": 41727,
"s": 41636,
"text": "An extension to Map interface so that its keys can be mapped to multiple values at a time."
},
{
"code": null,
"e": 41788,
"s": 41727,
"text": "An extension to Map interface to support inverse operations."
},
{
"code": null,
"e": 41899,
"s": 41788,
"text": "Table represents a special map where two keys can be specified in combined fashion to refer to a single value."
},
{
"code": null,
"e": 42104,
"s": 41899,
"text": "Guava provides a very powerful memory based caching mechanism by an interface LoadingCache<K,V>. Values are automatically loaded in the cache and it provides many utility methods useful for caching needs."
},
{
"code": null,
"e": 42191,
"s": 42104,
"text": "Following is the declaration for com.google.common.cache.LoadingCache<K,V> interface −"
},
{
"code": null,
"e": 42284,
"s": 42191,
"text": "@Beta\n@GwtCompatible\npublic interface LoadingCache<K,V>\n extends Cache<K,V>, Function<K,V>"
},
{
"code": null,
"e": 42299,
"s": 42284,
"text": "V apply(K key)"
},
{
"code": null,
"e": 42394,
"s": 42299,
"text": "Deprecated. Provided to satisfy the Function interface; use get(K) or getUnchecked(K) instead."
},
{
"code": null,
"e": 42421,
"s": 42394,
"text": "ConcurrentMap<K,V> asMap()"
},
{
"code": null,
"e": 42494,
"s": 42421,
"text": "Returns a view of the entries stored in this cache as a thread-safe map."
},
{
"code": null,
"e": 42507,
"s": 42494,
"text": "V get(K key)"
},
{
"code": null,
"e": 42599,
"s": 42507,
"text": "Returns the value associated with key in this cache, first loading that value if necessary."
},
{
"code": null,
"e": 42652,
"s": 42599,
"text": "ImmutableMap<K,V> getAll(Iterable<? extends K> keys)"
},
{
"code": null,
"e": 42752,
"s": 42652,
"text": "Returns a map of the values associated with keys, creating or retrieving those values if necessary."
},
{
"code": null,
"e": 42774,
"s": 42752,
"text": "V getUnchecked(K key)"
},
{
"code": null,
"e": 42866,
"s": 42774,
"text": "Returns the value associated with key in this cache, first loading that value if necessary."
},
{
"code": null,
"e": 42886,
"s": 42866,
"text": "void refresh(K key)"
},
{
"code": null,
"e": 42938,
"s": 42886,
"text": "Loads a new value for key, possibly asynchronously."
},
{
"code": null,
"e": 43023,
"s": 42938,
"text": "Create the following java program using any editor of your choice in say C:/> Guava."
},
{
"code": null,
"e": 46078,
"s": 43023,
"text": "import java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurrent.TimeUnit;\n\nimport com.google.common.base.MoreObjects;\nimport com.google.common.cache.CacheBuilder;\nimport com.google.common.cache.CacheLoader;\nimport com.google.common.cache.LoadingCache;\n\npublic class GuavaTester {\n public static void main(String args[]) {\n \n //create a cache for employees based on their employee id\n LoadingCache<String, Employee> employeeCache = \n CacheBuilder.newBuilder()\n .maximumSize(100) // maximum 100 records can be cached\n .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access\n .build(new CacheLoader<String, Employee>() { // build the cacheloader\n \n @Override\n public Employee load(String empId) throws Exception {\n //make the expensive call\n return getFromDatabase(empId);\n } \n });\n\n try {\t\t\t\n //on first invocation, cache will be populated with corresponding\n //employee record\n System.out.println(\"Invocation #1\");\n System.out.println(employeeCache.get(\"100\"));\n System.out.println(employeeCache.get(\"103\"));\n System.out.println(employeeCache.get(\"110\"));\n \n //second invocation, data will be returned from cache\n System.out.println(\"Invocation #2\");\n System.out.println(employeeCache.get(\"100\"));\n System.out.println(employeeCache.get(\"103\"));\n System.out.println(employeeCache.get(\"110\"));\n\n } catch (ExecutionException e) {\n e.printStackTrace();\n }\n }\n\n private static Employee getFromDatabase(String empId) {\n \n Employee e1 = new Employee(\"Mahesh\", \"Finance\", \"100\");\n Employee e2 = new Employee(\"Rohan\", \"IT\", \"103\");\n Employee e3 = new Employee(\"Sohan\", \"Admin\", \"110\");\n\n Map<String, Employee> database = new HashMap<String, Employee>();\n \n database.put(\"100\", e1);\n database.put(\"103\", e2);\n database.put(\"110\", e3);\n \n System.out.println(\"Database hit for\" + empId);\n \n return database.get(empId);\t\t\n }\n}\n\nclass Employee {\n String name;\n String dept;\n String emplD;\n\n public Employee(String name, String dept, String empID) {\n this.name = name;\n this.dept = dept;\n this.emplD = empID;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public String getDept() {\n return dept;\n }\n \n public void setDept(String dept) {\n this.dept = dept;\n }\n \n public String getEmplD() {\n return emplD;\n }\n \n public void setEmplD(String emplD) {\n this.emplD = emplD;\n }\n\n @Override\n public String toString() {\n return MoreObjects.toStringHelper(Employee.class)\n .add(\"Name\", name)\n .add(\"Department\", dept)\n .add(\"Emp Id\", emplD).toString();\n }\t\n}"
},
{
"code": null,
"e": 46130,
"s": 46078,
"text": "Compile the class using javac compiler as follows −"
},
{
"code": null,
"e": 46163,
"s": 46130,
"text": "C:\\Guava>javac GuavaTester.java\n"
},
{
"code": null,
"e": 46206,
"s": 46163,
"text": "Now run the GuavaTester to see the result."
},
{
"code": null,
"e": 46233,
"s": 46206,
"text": "C:\\Guava>java GuavaTester\n"
},
{
"code": null,
"e": 46249,
"s": 46233,
"text": "See the result."
},
{
"code": null,
"e": 46644,
"s": 46249,
"text": "Invocation #1\nDatabase hit for100\nEmployee{Name=Mahesh, Department=Finance, Emp Id=100}\nDatabase hit for103\nEmployee{Name=Rohan, Department=IT, Emp Id=103}\nDatabase hit for110\nEmployee{Name=Sohan, Department=Admin, Emp Id=110}\nInvocation #2\nEmployee{Name=Mahesh, Department=Finance, Emp Id=100}\nEmployee{Name=Rohan, Department=IT, Emp Id=103}\nEmployee{Name=Sohan, Department=Admin, Emp Id=110}\n"
},
{
"code": null,
"e": 46815,
"s": 46644,
"text": "Guava introduces many advanced string utilities based on developers' experience in application development works. Following is the list of useful string based utilities −"
},
{
"code": null,
"e": 46852,
"s": 46815,
"text": "Utility to join objects, string etc."
},
{
"code": null,
"e": 46877,
"s": 46852,
"text": "Utility to split string."
},
{
"code": null,
"e": 46911,
"s": 46877,
"text": "Utility for character operations."
},
{
"code": null,
"e": 46948,
"s": 46911,
"text": "Utility for changing string formats."
},
{
"code": null,
"e": 47191,
"s": 46948,
"text": "As primitive types of Java cannot be used to pass in generics or in collections as input, Guava provided a lot of Wrapper Utilities classes to handle primitive types as Objects. Following is the list of useful primitive processing utilities −"
},
{
"code": null,
"e": 47219,
"s": 47191,
"text": "Utility for primitive byte."
},
{
"code": null,
"e": 47248,
"s": 47219,
"text": "Utility for primitive short."
},
{
"code": null,
"e": 47275,
"s": 47248,
"text": "Utility for primitive int."
},
{
"code": null,
"e": 47303,
"s": 47275,
"text": "Utility for primitive long."
},
{
"code": null,
"e": 47332,
"s": 47303,
"text": "Utility for primitive float."
},
{
"code": null,
"e": 47362,
"s": 47332,
"text": "Utility for primitive double."
},
{
"code": null,
"e": 47390,
"s": 47362,
"text": "Utility for primitive char."
},
{
"code": null,
"e": 47421,
"s": 47390,
"text": "Utility for primitive boolean."
},
{
"code": null,
"e": 47554,
"s": 47421,
"text": "Guava provides Mathematics related Utilities classes to handle int, long and BigInteger. Following is the list of useful utilities −"
},
{
"code": null,
"e": 47576,
"s": 47554,
"text": "Math utility for int."
},
{
"code": null,
"e": 47599,
"s": 47576,
"text": "Math utility for long."
},
{
"code": null,
"e": 47628,
"s": 47599,
"text": "Math utility for BigInteger."
},
{
"code": null,
"e": 47635,
"s": 47628,
"text": " Print"
},
{
"code": null,
"e": 47646,
"s": 47635,
"text": " Add Notes"
}
] |
C# Multiple Local Variable Declarations
|
In C#, you can use the comma to declare more than one local variable in a statement. The following displays the same −
int a = 20, b = 70, c = 40, d = 90;
Let us see an example in which we are declaring multiple local variables. Below four variable is declared and initialized in the same statement.
Live Demo
using System;
class Demo {
static void Main() {
int a = 20, b = 70, c = 40, d = 90;
Console.WriteLine("{0} {1} {2} {3}", a, b, c, d);
}
}
20 70 40 90
|
[
{
"code": null,
"e": 1181,
"s": 1062,
"text": "In C#, you can use the comma to declare more than one local variable in a statement. The following displays the same −"
},
{
"code": null,
"e": 1217,
"s": 1181,
"text": "int a = 20, b = 70, c = 40, d = 90;"
},
{
"code": null,
"e": 1362,
"s": 1217,
"text": "Let us see an example in which we are declaring multiple local variables. Below four variable is declared and initialized in the same statement."
},
{
"code": null,
"e": 1372,
"s": 1362,
"text": "Live Demo"
},
{
"code": null,
"e": 1528,
"s": 1372,
"text": "using System;\nclass Demo {\n static void Main() {\n int a = 20, b = 70, c = 40, d = 90;\n Console.WriteLine(\"{0} {1} {2} {3}\", a, b, c, d);\n }\n}"
},
{
"code": null,
"e": 1540,
"s": 1528,
"text": "20 70 40 90"
}
] |
C# Files
|
The File class from the
System.IO namespace, allows us to work with files:
using System.IO; // include the System.IO namespace
File.SomeFileMethod(); // use the file class with methods
The File class has many useful methods for creating and getting information
about files.
For example:
For a full list of File methods, go to Microsoft .Net File Class Reference.
In the
following example, we use the WriteAllText() method
to create a file named "filename.txt" and write some content to it. Then we use the ReadAllText()
method to read the contents of the file:
using System.IO; // include the System.IO namespace
string writeText = "Hello World!"; // Create a text string
File.WriteAllText("filename.txt", writeText); // Create a file and write the content of writeText to it
string readText = File.ReadAllText("filename.txt"); // Read the contents of the file
Console.WriteLine(readText); // Output the content
The output will be:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 76,
"s": 0,
"text": "The File class from the \nSystem.IO namespace, allows us to work with files:"
},
{
"code": null,
"e": 190,
"s": 76,
"text": "using System.IO; // include the System.IO namespace\n\nFile.SomeFileMethod(); // use the file class with methods\n"
},
{
"code": null,
"e": 294,
"s": 190,
"text": "The File class has many useful methods for creating and getting information \nabout files. \nFor example:"
},
{
"code": null,
"e": 370,
"s": 294,
"text": "For a full list of File methods, go to Microsoft .Net File Class Reference."
},
{
"code": null,
"e": 571,
"s": 370,
"text": "In the \nfollowing example, we use the WriteAllText() method \nto create a file named \"filename.txt\" and write some content to it. Then we use the ReadAllText() \nmethod to read the contents of the file:"
},
{
"code": null,
"e": 930,
"s": 571,
"text": "using System.IO; // include the System.IO namespace\n\nstring writeText = \"Hello World!\"; // Create a text string\nFile.WriteAllText(\"filename.txt\", writeText); // Create a file and write the content of writeText to it\n\nstring readText = File.ReadAllText(\"filename.txt\"); // Read the contents of the file\nConsole.WriteLine(readText); // Output the content\n"
},
{
"code": null,
"e": 950,
"s": 930,
"text": "The output will be:"
},
{
"code": null,
"e": 983,
"s": 950,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1025,
"s": 983,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1132,
"s": 1025,
"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": 1151,
"s": 1132,
"text": "help@w3schools.com"
}
] |
Interesting Fact about Python Multi-line Comments - GeeksforGeeks
|
09 Sep, 2021
Multi-line comments(comments block) are used for description of large text of code or comment out chunks of code at the time of debugging application.Does Python Support Multi-line Comments(like c/c++...)? Actually in many online tutorial and website you will find that multiline_comments are available in python(“”” or ”’). but let’s first look at what python creator, “Guido van Rossum” said about fake block commenting style :Python tip: You can use multi-line strings as multi-line comments. Unless used as docstring, they generate no code!. source_file
if writing a text in a single line then use double quotes or single quotes in python.
if writing a poem or songs or multi-line text then to use triple quotes(“”” or ”’).
if printing these lines or text then simply insert it in print() function.
Example:
Python3
# Write Python3 code here#this is only valid for single line "this is a text constant for single line you""can't use multi-line within single or double quotes" 'this is also text-constant for single line' #this is valid for multiline."""this is text constant for multior single line this will notgive any error""" #you can also print both look at below..print('this is also text-constant for single line')print("""this is text constant for mult-lineor single line this will notgive any error""")
The above technique does not create true comments. It simply inserts Text constant that does not change anything or say that this is a regular single line string somewhere in your code. Always keep in mind to indent the first ( “”” or ”’ ) match correctly, otherwise a SyntaxError is generated. Example:
Python3
# Write Python3 code heredef check_syntax(): """ look at your first ident below"""print("after this line interpreter gives error because your first ident doesnot match") """ <---- here first ident starts with 2nd column hence gives indentation error you must remember that your first ident must be correctly matched."""
How we comment out chunks of code easily? Simply select those lines(it means when to copy the text then first select those lines) and then press (cntrl+#) otherwise consecutive # in every lines is the only way. Summary:
Unlike other programming languages (c, c++, ...) “python” does not support multi-line comment blocks out of the box
One can consider triple quote “”” as multi-line comments but this is not a good idea because this type of comments lines may turn into accidental docstrings.
consecutive # is the only way to comments lines in python(if you want to comment more than one lines then you can select those lines and press (ctrl+#) in python3.
nidhi_biet
saurabh1990aror
rajeev0719singh
gulshankumarar231
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": 23927,
"s": 23899,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 24486,
"s": 23927,
"text": "Multi-line comments(comments block) are used for description of large text of code or comment out chunks of code at the time of debugging application.Does Python Support Multi-line Comments(like c/c++...)? Actually in many online tutorial and website you will find that multiline_comments are available in python(“”” or ”’). but let’s first look at what python creator, “Guido van Rossum” said about fake block commenting style :Python tip: You can use multi-line strings as multi-line comments. Unless used as docstring, they generate no code!. source_file "
},
{
"code": null,
"e": 24572,
"s": 24486,
"text": "if writing a text in a single line then use double quotes or single quotes in python."
},
{
"code": null,
"e": 24656,
"s": 24572,
"text": "if writing a poem or songs or multi-line text then to use triple quotes(“”” or ”’)."
},
{
"code": null,
"e": 24731,
"s": 24656,
"text": "if printing these lines or text then simply insert it in print() function."
},
{
"code": null,
"e": 24741,
"s": 24731,
"text": "Example: "
},
{
"code": null,
"e": 24749,
"s": 24741,
"text": "Python3"
},
{
"code": "# Write Python3 code here#this is only valid for single line \"this is a text constant for single line you\"\"can't use multi-line within single or double quotes\" 'this is also text-constant for single line' #this is valid for multiline.\"\"\"this is text constant for multior single line this will notgive any error\"\"\" #you can also print both look at below..print('this is also text-constant for single line')print(\"\"\"this is text constant for mult-lineor single line this will notgive any error\"\"\")",
"e": 25248,
"s": 24749,
"text": null
},
{
"code": null,
"e": 25552,
"s": 25248,
"text": "The above technique does not create true comments. It simply inserts Text constant that does not change anything or say that this is a regular single line string somewhere in your code. Always keep in mind to indent the first ( “”” or ”’ ) match correctly, otherwise a SyntaxError is generated. Example:"
},
{
"code": null,
"e": 25560,
"s": 25552,
"text": "Python3"
},
{
"code": "# Write Python3 code heredef check_syntax(): \"\"\" look at your first ident below\"\"\"print(\"after this line interpreter gives error because your first ident doesnot match\") \"\"\" <---- here first ident starts with 2nd column hence gives indentation error you must remember that your first ident must be correctly matched.\"\"\"",
"e": 25891,
"s": 25560,
"text": null
},
{
"code": null,
"e": 26113,
"s": 25891,
"text": "How we comment out chunks of code easily? Simply select those lines(it means when to copy the text then first select those lines) and then press (cntrl+#) otherwise consecutive # in every lines is the only way. Summary: "
},
{
"code": null,
"e": 26229,
"s": 26113,
"text": "Unlike other programming languages (c, c++, ...) “python” does not support multi-line comment blocks out of the box"
},
{
"code": null,
"e": 26387,
"s": 26229,
"text": "One can consider triple quote “”” as multi-line comments but this is not a good idea because this type of comments lines may turn into accidental docstrings."
},
{
"code": null,
"e": 26551,
"s": 26387,
"text": "consecutive # is the only way to comments lines in python(if you want to comment more than one lines then you can select those lines and press (ctrl+#) in python3."
},
{
"code": null,
"e": 26564,
"s": 26553,
"text": "nidhi_biet"
},
{
"code": null,
"e": 26580,
"s": 26564,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 26596,
"s": 26580,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 26614,
"s": 26596,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 26621,
"s": 26614,
"text": "Python"
},
{
"code": null,
"e": 26719,
"s": 26621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26728,
"s": 26719,
"text": "Comments"
},
{
"code": null,
"e": 26741,
"s": 26728,
"text": "Old Comments"
},
{
"code": null,
"e": 26773,
"s": 26741,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26829,
"s": 26773,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26871,
"s": 26829,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26913,
"s": 26871,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26949,
"s": 26913,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26988,
"s": 26949,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27010,
"s": 26988,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27041,
"s": 27010,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27068,
"s": 27041,
"text": "Python Classes and Objects"
}
] |
JDBC - Create Database Example
|
This tutorial provides an example on how to create a Database using JDBC application. Before executing the following example, make sure you have the following in place −
You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password.
You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password.
Your MySQL or whatever database is up and running.
Your MySQL or whatever database is up and running.
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server.
To create a new database, you need not give any database name while preparing database URL as mentioned in the below example.
Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server.
To create a new database, you need not give any database name while preparing database URL as mentioned in the below example.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database.
Clean up the environment . try with resources automatically closes the resources.
Clean up the environment . try with resources automatically closes the resources.
Copy and paste the following example in JDBCExample.java, compile and run as follows −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
) {
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database created successfully...
C:\>
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": 2332,
"s": 2162,
"text": "This tutorial provides an example on how to create a Database using JDBC application. Before executing the following example, make sure you have the following in place −"
},
{
"code": null,
"e": 2527,
"s": 2332,
"text": "You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 2722,
"s": 2527,
"text": "You should have admin privilege to create a database in the given schema. To execute the following example, you need to replace the username and password with your actual user name and password."
},
{
"code": null,
"e": 2773,
"s": 2722,
"text": "Your MySQL or whatever database is up and running."
},
{
"code": null,
"e": 2824,
"s": 2773,
"text": "Your MySQL or whatever database is up and running."
},
{
"code": null,
"e": 2907,
"s": 2824,
"text": "The following steps are required to create a new Database using JDBC application −"
},
{
"code": null,
"e": 3079,
"s": 2907,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3251,
"s": 3079,
"text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice."
},
{
"code": null,
"e": 3549,
"s": 3251,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server.\nTo create a new database, you need not give any database name while preparing database URL as mentioned in the below example."
},
{
"code": null,
"e": 3721,
"s": 3549,
"text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database server."
},
{
"code": null,
"e": 3847,
"s": 3721,
"text": "To create a new database, you need not give any database name while preparing database URL as mentioned in the below example."
},
{
"code": null,
"e": 3970,
"s": 3847,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 4093,
"s": 3970,
"text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to the database."
},
{
"code": null,
"e": 4176,
"s": 4093,
"text": "Clean up the environment . try with resources automatically closes the resources.\n"
},
{
"code": null,
"e": 4258,
"s": 4176,
"text": "Clean up the environment . try with resources automatically closes the resources."
},
{
"code": null,
"e": 4345,
"s": 4258,
"text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −"
},
{
"code": null,
"e": 5080,
"s": 4345,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"CREATE DATABASE STUDENTS\";\n stmt.executeUpdate(sql);\n System.out.println(\"Database created successfully...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}"
},
{
"code": null,
"e": 5130,
"s": 5080,
"text": "Now let us compile the above example as follows −"
},
{
"code": null,
"e": 5162,
"s": 5130,
"text": "C:\\>javac JDBCExample.java\nC:\\>"
},
{
"code": null,
"e": 5223,
"s": 5162,
"text": "When you run JDBCExample, it produces the following result −"
},
{
"code": null,
"e": 5283,
"s": 5223,
"text": "C:\\>java JDBCExample\nDatabase created successfully...\nC:\\>\n"
},
{
"code": null,
"e": 5316,
"s": 5283,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5332,
"s": 5316,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5365,
"s": 5332,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5381,
"s": 5365,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 5416,
"s": 5381,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5430,
"s": 5416,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5464,
"s": 5430,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5478,
"s": 5464,
"text": " Tushar Kale"
},
{
"code": null,
"e": 5515,
"s": 5478,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 5530,
"s": 5515,
"text": " Monica Mittal"
},
{
"code": null,
"e": 5563,
"s": 5530,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5582,
"s": 5563,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5589,
"s": 5582,
"text": " Print"
},
{
"code": null,
"e": 5600,
"s": 5589,
"text": " Add Notes"
}
] |
C# | Constructors - GeeksforGeeks
|
05 Nov, 2020
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class.
Example :
class Geek
{
.......
// Constructor
public Geek() {}
.......
}
// an object is created of Geek class,
// So above constructor is called
Geek obj = new Geek();
Constructor of a class must have the same name as the class name in which it resides.
A constructor can not be abstract, final, and Synchronized.
Within a class, you can create only one static constructor.
A constructor doesn’t have any return type, not even void.
A static constructor cannot be a parameterized constructor.
A class can have any number of constructors.
Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.
Default ConstructorParameterized ConstructorCopy ConstructorPrivate ConstructorStatic Constructor
Default Constructor
Parameterized Constructor
Copy Constructor
Private Constructor
Static Constructor
A constructor with no parameters is called a default constructor. A default constructor has every instance of the class to be initialized to the same values. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class.
Example :
C#
// C# Program to illustrate calling// a Default constructorusing System;namespace DefaultConstructorExample { class Geek { int num; string name; // this would be invoked while the // object of that class created. Geek() { Console.WriteLine("Constructor Called"); } // Main Method public static void Main() { // this would invoke default // constructor. Geek geek1 = new Geek(); // Default constructor provides // the default values to the // int and object as 0, null // Note: // It Give Warning because // Fields are not assign Console.WriteLine(geek1.name); Console.WriteLine(geek1.num); }}}
Output :
Constructor Called
0
Note : This will also show some warnings as follows:
prog.cs(8, 6): warning CS0649: Field `DefaultConstructorExample.Geek.num' is never assigned to, and will always have its default value `0'
prog.cs(9, 9): warning CS0649: Field `DefaultConstructorExample.Geek.name' is never assigned to, and will always have its default value `null'
A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values.
Example :
C#
// C# Program to illustrate calling of// parameterized constructor.using System;namespace ParameterizedConstructorExample { class Geek { // data members of the class. String name; int id; // parameterized constructor would // initialized data members with // the values of passed arguments // while object of that class created. Geek(String name, int id) { this.name = name; this.id = id; } // Main Method public static void Main() { // This will invoke parameterized // constructor. Geek geek1 = new Geek("GFG", 1); Console.WriteLine("GeekName = " + geek1.name + " and GeekId = " + geek1.id); }}}
Output :
GeekName = GFG and GeekId = 1
This constructor creates an object by copying variables from another object. Its main use is to initialize a new instance to the values of an existing instance.
Example :
C#
// C# Program to illustrate calling// a Copy constructorusing System;namespace copyConstructorExample { class Geeks { private string month; private int year; // declaring Copy constructor public Geeks(Geeks s) { month = s.month; year = s.year; } // Instance constructor public Geeks(string month, int year) { this.month = month; this.year = year; } // Get details of Geeks public string Details { get { return "Month: " + month.ToString() + "\nYear: " + year.ToString(); } } // Main Method public static void Main() { // Create a new Geeks object. Geeks g1 = new Geeks("June", 2018); // here is g1 details is copied to g2. Geeks g2 = new Geeks(g1); Console.WriteLine(g2.Details); }}}
Output :
Month: June
Year: 2018
If a constructor is created with private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class.
Points To Remember :
It is the implementation of a singleton class pattern.
use private constructor when we have only static members.
Using private constructor, prevents the creation of the instances of that class.
Example :
C#
// C# Program to illustrate calling// a Private constructorusing System;namespace privateConstructorExample { public class Geeks { // declare private Constructor private Geeks() { } // declare static variable field public static int count_geeks; // declare static method public static int geeks_Count() { return ++count_geeks; } // Main Method public static void Main() { // If you uncomment the following // statement, it will generate // an error because the constructor // is unaccessible: // Geeks s = new Geeks(); // Error Geeks.count_geeks = 99; // Accessing without any // instance of the class Geeks.geeks_Count(); Console.WriteLine(Geeks.count_geeks); // Accessing without any // instance of the class Geeks.geeks_Count(); Console.WriteLine(Geeks.count_geeks); }}}
Output :
100
101
Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and to be executed only once.
Points To Remember :
It can’t be called directly.
When it is executing then the user has no control.
It does not take access modifiers or any parameters.
It is called automatically to initialize the class before the first instance created.
Example :
C#
// C# Program to illustrate calling// a Static constructorusing System;namespace staticConstructorExample { class geeks { // It is invoked before the first // instance constructor is run. static geeks() { // The following statement produces // the first line of output, // and the line occurs only once. Console.WriteLine("Static Constructor"); } // Instance constructor. public geeks(int i) { Console.WriteLine("Instance Constructor " + i); } // Instance method. public string geeks_detail(string name, int id) { return "Name:" + name + " id:" + id; } // Main Method public static void Main() { // Here Both Static and instance // constructors are invoked for // first instance geeks obj = new geeks(1); Console.WriteLine(obj.geeks_detail("GFG", 1)); // Here only instance constructor // will be invoked geeks obj1 = new geeks(2); Console.WriteLine(obj1.geeks_detail("GeeksforGeeks", 2)); }}}
Output :
Static Constructor
Instance Constructor 1
Name:GFG id:1
Instance Constructor 2
Name:GeeksforGeeks id:2
ashumsd7
an_analyst
dhiman_saab
CSharp-Basics
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | IsNullOrEmpty() Method
C# | How to check whether a List contains a specified element
String.Split() Method in C# with Examples
C# | Arrays of Strings
C# | String.IndexOf( ) Method | Set - 1
Extension Method in C#
C# | Delegates
Difference between Ref and Out keywords in C#
C# | Replace() Method
|
[
{
"code": null,
"e": 25224,
"s": 25196,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 25549,
"s": 25224,
"text": "A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class. "
},
{
"code": null,
"e": 25561,
"s": 25549,
"text": "Example : "
},
{
"code": null,
"e": 25735,
"s": 25561,
"text": "class Geek\n{ \n .......\n // Constructor\n public Geek() {}\n .......\n}\n\n// an object is created of Geek class,\n// So above constructor is called\nGeek obj = new Geek(); \n\n"
},
{
"code": null,
"e": 25821,
"s": 25735,
"text": "Constructor of a class must have the same name as the class name in which it resides."
},
{
"code": null,
"e": 25881,
"s": 25821,
"text": "A constructor can not be abstract, final, and Synchronized."
},
{
"code": null,
"e": 25941,
"s": 25881,
"text": "Within a class, you can create only one static constructor."
},
{
"code": null,
"e": 26000,
"s": 25941,
"text": "A constructor doesn’t have any return type, not even void."
},
{
"code": null,
"e": 26060,
"s": 26000,
"text": "A static constructor cannot be a parameterized constructor."
},
{
"code": null,
"e": 26105,
"s": 26060,
"text": "A class can have any number of constructors."
},
{
"code": null,
"e": 26233,
"s": 26105,
"text": "Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor. "
},
{
"code": null,
"e": 26331,
"s": 26233,
"text": "Default ConstructorParameterized ConstructorCopy ConstructorPrivate ConstructorStatic Constructor"
},
{
"code": null,
"e": 26351,
"s": 26331,
"text": "Default Constructor"
},
{
"code": null,
"e": 26377,
"s": 26351,
"text": "Parameterized Constructor"
},
{
"code": null,
"e": 26394,
"s": 26377,
"text": "Copy Constructor"
},
{
"code": null,
"e": 26414,
"s": 26394,
"text": "Private Constructor"
},
{
"code": null,
"e": 26433,
"s": 26414,
"text": "Static Constructor"
},
{
"code": null,
"e": 26711,
"s": 26433,
"text": "A constructor with no parameters is called a default constructor. A default constructor has every instance of the class to be initialized to the same values. The default constructor initializes all numeric fields to zero and all string and object fields to null inside a class."
},
{
"code": null,
"e": 26722,
"s": 26711,
"text": "Example : "
},
{
"code": null,
"e": 26725,
"s": 26722,
"text": "C#"
},
{
"code": "// C# Program to illustrate calling// a Default constructorusing System;namespace DefaultConstructorExample { class Geek { int num; string name; // this would be invoked while the // object of that class created. Geek() { Console.WriteLine(\"Constructor Called\"); } // Main Method public static void Main() { // this would invoke default // constructor. Geek geek1 = new Geek(); // Default constructor provides // the default values to the // int and object as 0, null // Note: // It Give Warning because // Fields are not assign Console.WriteLine(geek1.name); Console.WriteLine(geek1.num); }}}",
"e": 27441,
"s": 26725,
"text": null
},
{
"code": null,
"e": 27451,
"s": 27441,
"text": "Output : "
},
{
"code": null,
"e": 27476,
"s": 27451,
"text": "Constructor Called\n\n0\n\n\n"
},
{
"code": null,
"e": 27530,
"s": 27476,
"text": "Note : This will also show some warnings as follows: "
},
{
"code": null,
"e": 27813,
"s": 27530,
"text": "prog.cs(8, 6): warning CS0649: Field `DefaultConstructorExample.Geek.num' is never assigned to, and will always have its default value `0'\nprog.cs(9, 9): warning CS0649: Field `DefaultConstructorExample.Geek.name' is never assigned to, and will always have its default value `null'\n"
},
{
"code": null,
"e": 27963,
"s": 27813,
"text": "A constructor having at least one parameter is called as parameterized constructor. It can initialize each instance of the class to different values."
},
{
"code": null,
"e": 27975,
"s": 27963,
"text": "Example : "
},
{
"code": null,
"e": 27978,
"s": 27975,
"text": "C#"
},
{
"code": "// C# Program to illustrate calling of// parameterized constructor.using System;namespace ParameterizedConstructorExample { class Geek { // data members of the class. String name; int id; // parameterized constructor would // initialized data members with // the values of passed arguments // while object of that class created. Geek(String name, int id) { this.name = name; this.id = id; } // Main Method public static void Main() { // This will invoke parameterized // constructor. Geek geek1 = new Geek(\"GFG\", 1); Console.WriteLine(\"GeekName = \" + geek1.name + \" and GeekId = \" + geek1.id); }}}",
"e": 28688,
"s": 27978,
"text": null
},
{
"code": null,
"e": 28698,
"s": 28688,
"text": "Output : "
},
{
"code": null,
"e": 28730,
"s": 28698,
"text": "GeekName = GFG and GeekId = 1 \n"
},
{
"code": null,
"e": 28892,
"s": 28730,
"text": "This constructor creates an object by copying variables from another object. Its main use is to initialize a new instance to the values of an existing instance. "
},
{
"code": null,
"e": 28903,
"s": 28892,
"text": "Example : "
},
{
"code": null,
"e": 28906,
"s": 28903,
"text": "C#"
},
{
"code": "// C# Program to illustrate calling// a Copy constructorusing System;namespace copyConstructorExample { class Geeks { private string month; private int year; // declaring Copy constructor public Geeks(Geeks s) { month = s.month; year = s.year; } // Instance constructor public Geeks(string month, int year) { this.month = month; this.year = year; } // Get details of Geeks public string Details { get { return \"Month: \" + month.ToString() + \"\\nYear: \" + year.ToString(); } } // Main Method public static void Main() { // Create a new Geeks object. Geeks g1 = new Geeks(\"June\", 2018); // here is g1 details is copied to g2. Geeks g2 = new Geeks(g1); Console.WriteLine(g2.Details); }}}",
"e": 29767,
"s": 28906,
"text": null
},
{
"code": null,
"e": 29777,
"s": 29767,
"text": "Output : "
},
{
"code": null,
"e": 29802,
"s": 29777,
"text": "Month: June\nYear: 2018\n\n"
},
{
"code": null,
"e": 30014,
"s": 29802,
"text": "If a constructor is created with private specifier is known as Private Constructor. It is not possible for other classes to derive from this class and also it’s not possible to create an instance of this class. "
},
{
"code": null,
"e": 30037,
"s": 30014,
"text": "Points To Remember : "
},
{
"code": null,
"e": 30092,
"s": 30037,
"text": "It is the implementation of a singleton class pattern."
},
{
"code": null,
"e": 30150,
"s": 30092,
"text": "use private constructor when we have only static members."
},
{
"code": null,
"e": 30231,
"s": 30150,
"text": "Using private constructor, prevents the creation of the instances of that class."
},
{
"code": null,
"e": 30242,
"s": 30231,
"text": "Example : "
},
{
"code": null,
"e": 30245,
"s": 30242,
"text": "C#"
},
{
"code": "// C# Program to illustrate calling// a Private constructorusing System;namespace privateConstructorExample { public class Geeks { // declare private Constructor private Geeks() { } // declare static variable field public static int count_geeks; // declare static method public static int geeks_Count() { return ++count_geeks; } // Main Method public static void Main() { // If you uncomment the following // statement, it will generate // an error because the constructor // is unaccessible: // Geeks s = new Geeks(); // Error Geeks.count_geeks = 99; // Accessing without any // instance of the class Geeks.geeks_Count(); Console.WriteLine(Geeks.count_geeks); // Accessing without any // instance of the class Geeks.geeks_Count(); Console.WriteLine(Geeks.count_geeks); }}}",
"e": 31176,
"s": 30245,
"text": null
},
{
"code": null,
"e": 31186,
"s": 31176,
"text": "Output : "
},
{
"code": null,
"e": 31196,
"s": 31186,
"text": "100\n101\n\n"
},
{
"code": null,
"e": 31458,
"s": 31196,
"text": "Static Constructor has to be invoked only once in the class and it has been invoked during the creation of the first reference to a static member in the class. A static constructor is initialized static fields or data of the class and to be executed only once. "
},
{
"code": null,
"e": 31481,
"s": 31458,
"text": "Points To Remember : "
},
{
"code": null,
"e": 31510,
"s": 31481,
"text": "It can’t be called directly."
},
{
"code": null,
"e": 31561,
"s": 31510,
"text": "When it is executing then the user has no control."
},
{
"code": null,
"e": 31614,
"s": 31561,
"text": "It does not take access modifiers or any parameters."
},
{
"code": null,
"e": 31700,
"s": 31614,
"text": "It is called automatically to initialize the class before the first instance created."
},
{
"code": null,
"e": 31710,
"s": 31700,
"text": "Example :"
},
{
"code": null,
"e": 31713,
"s": 31710,
"text": "C#"
},
{
"code": "// C# Program to illustrate calling// a Static constructorusing System;namespace staticConstructorExample { class geeks { // It is invoked before the first // instance constructor is run. static geeks() { // The following statement produces // the first line of output, // and the line occurs only once. Console.WriteLine(\"Static Constructor\"); } // Instance constructor. public geeks(int i) { Console.WriteLine(\"Instance Constructor \" + i); } // Instance method. public string geeks_detail(string name, int id) { return \"Name:\" + name + \" id:\" + id; } // Main Method public static void Main() { // Here Both Static and instance // constructors are invoked for // first instance geeks obj = new geeks(1); Console.WriteLine(obj.geeks_detail(\"GFG\", 1)); // Here only instance constructor // will be invoked geeks obj1 = new geeks(2); Console.WriteLine(obj1.geeks_detail(\"GeeksforGeeks\", 2)); }}}",
"e": 32772,
"s": 31713,
"text": null
},
{
"code": null,
"e": 32782,
"s": 32772,
"text": "Output : "
},
{
"code": null,
"e": 32888,
"s": 32782,
"text": "Static Constructor\nInstance Constructor 1\nName:GFG id:1\nInstance Constructor 2\nName:GeeksforGeeks id:2\n\n\n"
},
{
"code": null,
"e": 32899,
"s": 32890,
"text": "ashumsd7"
},
{
"code": null,
"e": 32910,
"s": 32899,
"text": "an_analyst"
},
{
"code": null,
"e": 32922,
"s": 32910,
"text": "dhiman_saab"
},
{
"code": null,
"e": 32936,
"s": 32922,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 32939,
"s": 32936,
"text": "C#"
},
{
"code": null,
"e": 33037,
"s": 32939,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33046,
"s": 33037,
"text": "Comments"
},
{
"code": null,
"e": 33059,
"s": 33046,
"text": "Old Comments"
},
{
"code": null,
"e": 33113,
"s": 33059,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 33141,
"s": 33113,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 33203,
"s": 33141,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 33245,
"s": 33203,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 33268,
"s": 33245,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 33308,
"s": 33268,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 33331,
"s": 33308,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 33346,
"s": 33331,
"text": "C# | Delegates"
},
{
"code": null,
"e": 33392,
"s": 33346,
"text": "Difference between Ref and Out keywords in C#"
}
] |
PyQt5 QScrollBar – Setting Value - GeeksforGeeks
|
04 Aug, 2021
In this article we will see how we can set the value of QScrollBar. QScrollBar is a control that enables the user to access parts of a document that is larger than the widget used to display it. Slider is the scroll-able object inside the bar. Value is basically depend upon the slider position, scroll bar value changes according to the position of the slider, value increases when slider goes down and decreases when slider moves up.
In order to do this we will use setValue method with the scroll bar object.Syntax : scroll.setValue(n)Argument : It takes integer as argumentReturn : It returns None
Example : Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): scroll = QScrollBar(self) # setting geometry of the scroll bar scroll.setGeometry(100, 50, 30, 200) # setting value of scroll bar scroll.setValue(25) # making its background color to green scroll.setStyleSheet("background : lightgrey;") # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(200, 100, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
kalrap615
Python PyQt-QScrollBar
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n04 Aug, 2021"
},
{
"code": null,
"e": 26084,
"s": 25647,
"text": "In this article we will see how we can set the value of QScrollBar. QScrollBar is a control that enables the user to access parts of a document that is larger than the widget used to display it. Slider is the scroll-able object inside the bar. Value is basically depend upon the slider position, scroll bar value changes according to the position of the slider, value increases when slider goes down and decreases when slider moves up. "
},
{
"code": null,
"e": 26252,
"s": 26084,
"text": "In order to do this we will use setValue method with the scroll bar object.Syntax : scroll.setValue(n)Argument : It takes integer as argumentReturn : It returns None "
},
{
"code": null,
"e": 26291,
"s": 26252,
"text": "Example : Below is the implementation "
},
{
"code": null,
"e": 26299,
"s": 26291,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): scroll = QScrollBar(self) # setting geometry of the scroll bar scroll.setGeometry(100, 50, 30, 200) # setting value of scroll bar scroll.setValue(25) # making its background color to green scroll.setStyleSheet(\"background : lightgrey;\") # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(200, 100, 300, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27462,
"s": 26299,
"text": null
},
{
"code": null,
"e": 27473,
"s": 27462,
"text": "Output : "
},
{
"code": null,
"e": 27485,
"s": 27475,
"text": "kalrap615"
},
{
"code": null,
"e": 27508,
"s": 27485,
"text": "Python PyQt-QScrollBar"
},
{
"code": null,
"e": 27519,
"s": 27508,
"text": "Python-gui"
},
{
"code": null,
"e": 27531,
"s": 27519,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27538,
"s": 27531,
"text": "Python"
},
{
"code": null,
"e": 27636,
"s": 27538,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27668,
"s": 27636,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27710,
"s": 27668,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27752,
"s": 27710,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27808,
"s": 27752,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27835,
"s": 27808,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27866,
"s": 27835,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27902,
"s": 27866,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 27931,
"s": 27902,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27953,
"s": 27931,
"text": "Defaultdict in Python"
}
] |
Decimal Functions in Python | Set 2 (logical_and(), normalize(), quantize(), rotate() ... ) - GeeksforGeeks
|
09 Feb, 2022
Some of the Decimal functions have been discussed in Set 1 below
Decimal Functions in Python | Set 1
More functions are discussed in this article.1. logical_and() :- This function computes digit-wise logical “and” operation of the number. Digits can only have the values 0 or 1.
2. logical_or() :- This function computes digit-wise logical “or” operation of the number. Digits can only have the values 0 or 1.
3. logical_xor() :- This function computes digit-wise logical “xor” operation of the number. Digits can only have the values 0 or 1.
4. logical_invert() :- This function computes digit-wise logical “invert” operation of the number. Digits can only have the values 0 or 1.
Python3
# Python code to demonstrate the working of# logical_and(), logical_or(), logical_xor()# and logical_invert() # importing "decimal" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(1000) # Initializing decimal numberb = decimal.Decimal(1110) # printing logical_and of two numbersprint ("The logical_and() of two numbers is : ",end="")print (a.logical_and(b)) # printing logical_or of two numbersprint ("The logical_or() of two numbers is : ",end="")print (a.logical_or(b)) # printing exclusive or of two numbersprint ("The exclusive or of two numbers is : ",end="")print (a.logical_xor(b)) # printing logical inversion of numberprint ("The logical inversion of number is : ",end="")print (a.logical_invert())
Output:
The logical_and() of two numbers is : 1000
The logical_or() of two numbers is : 1110
The exclusive or of two numbers is : 110
The logical inversion of number is : 1111111111111111111111110111
5. next_plus() :- This function returns the smallest number that can be represented, larger than the given number.
6. next_minus() :- This function returns the largest number that can be represented, smaller than the given number.
Python3
# Python code to demonstrate the working of# next_plus() and next_minus() # importing "decimal" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(101.34) # printing the actual decimal numberprint ("The original number is : ",end="")print (a) # printing number after using next_plus()print ("The smallest number larger than current number : ",end="")print (a.next_plus()) # printing number after using next_minus()print ("The largest number smaller than current number : ",end="")print (a.next_minus())
Output:
The original number is : 101.340000000000003410605131648480892181396484375
The smallest number larger than current number : 101.3400000000000034106051317
The largest number smaller than current number : 101.3400000000000034106051316
7. next_toward() :- This function returns the number nearest to the 1st argument in the direction of the second argument. In case Both the numbers are equal, returns the 2nd number with the sign of first number.
8. normalize() :- This function prints the number after erasing all the rightmost trailing zeroes in the number.
Python3
# Python code to demonstrate the working of# next_toward() and normalize() # importing "decimal" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(101.34) # Initializing decimal numberb = decimal.Decimal(-101.34) # Initializing decimal numberc = decimal.Decimal(-58.68) # Initializing decimal numberd = decimal.Decimal(14.010000000) # printing the number using next_toward()print ("The number closest to 1st number in direction of second number : ")print (a.next_toward(c)) # printing the number using next_toward()# when equalprint ("The second number with sign of first number is : ",end="")print (b.next_toward(a)) # printing number after erasing rightmost trailing zeroesprint ("Number after erasing rightmost trailing zeroes : ",end="")print (d.normalize())
Output:
The number closest to 1st number in direction of second number :
101.3400000000000034106051316
The second number with sign of first number is : -101.3400000000000034106051316
Number after erasing rightmost trailing zeroes : 14.01
9. quantize() :- This function returns the 1st argument with the number of digits in decimal part(exponent) shortened by the number of digits in decimal part(exponent) of 2nd argument.
10. same_quantum() :- This function returns 0 if both the numbers have different exponent and 1 if both numbers have same exponent.
Python3
# Python code to demonstrate the working of# quantize() and same_quantum() # importing "decimal" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(20.76548) # Initializing decimal numberb = decimal.Decimal(12.25) # Initializing decimal numberc = decimal.Decimal(6.25) # printing quantized first numberprint ("The quantized first number is : ",end="")print (a.quantize(b)) # checking if both number have same exponentif (b.same_quantum(c)): print ("Both the numbers have same exponent")else : print ("Both numbers have different exponent")
Output:
The quantized first number is : 20.77
Both the numbers have same exponent
11. rotate() :- This function rotates the first argument by the amount mentioned in the second argument. If the sign of second argument is positive, rotation is towards left, else the rotation is towards right. The sign of first argument is unchanged.
12. shift() :- This function shifts the first argument by the amount mentioned in the second argument. If the sign of second argument is positive, shifting is towards left, else the shifting is towards right. The sign of first argument is unchanged. Digit shifted are replaced by 0.
Python3
# Python code to demonstrate the working of# rotate() and shift() # importing "decimal" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(2343509394029424234334563465) # using rotate() to rotate the first argument# rotates to right by 2 positionsprint ("The rotated value is : ",end="")print (a.rotate(-2)) # using shift() to shift the first argument# rotates to left by 2 positionsprint ("The shifted value is : ",end="")print (a.shift(2))
Output:
The rotated value is : 6523435093940294242343345634
The shifted value is : 4350939402942423433456346500
13. remainder_near() :- Returns the value “1st – (n*2nd)” where n is the integer value nearest to the result of 1st/2nd. If 2 integers have exactly similar proximity, even one is chosen.
14. scaleb() :- This function shifts the exponent of 1st number by the value of second argument.
Python3
# Python code to demonstrate the working of# remainder_near() and scaleb() # importing "decimal" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(23.765) # Initializing decimal numberb = decimal.Decimal(12) # Initializing decimal numberc = decimal.Decimal(8) # using remainder_near to compute valueprint ("The computed value using remainder_near() is : ",end="")print (b.remainder_near(c)) # using scaleb() to shift exponentprint ("The value after shifting exponent : ",end="")print (a.scaleb(2))
Output:
The computed value using remainder_near() is : -4
The value after shifting exponent : 2376.500000000000056843418861
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vasudevanaidukilaparthi045
krishna_97
gabaa406
amartyaghoshgfg
rkbhola5
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 26367,
"s": 26339,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 26432,
"s": 26367,
"text": "Some of the Decimal functions have been discussed in Set 1 below"
},
{
"code": null,
"e": 26468,
"s": 26432,
"text": "Decimal Functions in Python | Set 1"
},
{
"code": null,
"e": 26646,
"s": 26468,
"text": "More functions are discussed in this article.1. logical_and() :- This function computes digit-wise logical “and” operation of the number. Digits can only have the values 0 or 1."
},
{
"code": null,
"e": 26777,
"s": 26646,
"text": "2. logical_or() :- This function computes digit-wise logical “or” operation of the number. Digits can only have the values 0 or 1."
},
{
"code": null,
"e": 26910,
"s": 26777,
"text": "3. logical_xor() :- This function computes digit-wise logical “xor” operation of the number. Digits can only have the values 0 or 1."
},
{
"code": null,
"e": 27049,
"s": 26910,
"text": "4. logical_invert() :- This function computes digit-wise logical “invert” operation of the number. Digits can only have the values 0 or 1."
},
{
"code": null,
"e": 27057,
"s": 27049,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# logical_and(), logical_or(), logical_xor()# and logical_invert() # importing \"decimal\" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(1000) # Initializing decimal numberb = decimal.Decimal(1110) # printing logical_and of two numbersprint (\"The logical_and() of two numbers is : \",end=\"\")print (a.logical_and(b)) # printing logical_or of two numbersprint (\"The logical_or() of two numbers is : \",end=\"\")print (a.logical_or(b)) # printing exclusive or of two numbersprint (\"The exclusive or of two numbers is : \",end=\"\")print (a.logical_xor(b)) # printing logical inversion of numberprint (\"The logical inversion of number is : \",end=\"\")print (a.logical_invert())",
"e": 27812,
"s": 27057,
"text": null
},
{
"code": null,
"e": 27821,
"s": 27812,
"text": "Output: "
},
{
"code": null,
"e": 28013,
"s": 27821,
"text": "The logical_and() of two numbers is : 1000\nThe logical_or() of two numbers is : 1110\nThe exclusive or of two numbers is : 110\nThe logical inversion of number is : 1111111111111111111111110111"
},
{
"code": null,
"e": 28128,
"s": 28013,
"text": "5. next_plus() :- This function returns the smallest number that can be represented, larger than the given number."
},
{
"code": null,
"e": 28245,
"s": 28128,
"text": "6. next_minus() :- This function returns the largest number that can be represented, smaller than the given number. "
},
{
"code": null,
"e": 28253,
"s": 28245,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# next_plus() and next_minus() # importing \"decimal\" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(101.34) # printing the actual decimal numberprint (\"The original number is : \",end=\"\")print (a) # printing number after using next_plus()print (\"The smallest number larger than current number : \",end=\"\")print (a.next_plus()) # printing number after using next_minus()print (\"The largest number smaller than current number : \",end=\"\")print (a.next_minus())",
"e": 28800,
"s": 28253,
"text": null
},
{
"code": null,
"e": 28809,
"s": 28800,
"text": "Output: "
},
{
"code": null,
"e": 29042,
"s": 28809,
"text": "The original number is : 101.340000000000003410605131648480892181396484375\nThe smallest number larger than current number : 101.3400000000000034106051317\nThe largest number smaller than current number : 101.3400000000000034106051316"
},
{
"code": null,
"e": 29254,
"s": 29042,
"text": "7. next_toward() :- This function returns the number nearest to the 1st argument in the direction of the second argument. In case Both the numbers are equal, returns the 2nd number with the sign of first number."
},
{
"code": null,
"e": 29368,
"s": 29254,
"text": "8. normalize() :- This function prints the number after erasing all the rightmost trailing zeroes in the number. "
},
{
"code": null,
"e": 29376,
"s": 29368,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# next_toward() and normalize() # importing \"decimal\" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(101.34) # Initializing decimal numberb = decimal.Decimal(-101.34) # Initializing decimal numberc = decimal.Decimal(-58.68) # Initializing decimal numberd = decimal.Decimal(14.010000000) # printing the number using next_toward()print (\"The number closest to 1st number in direction of second number : \")print (a.next_toward(c)) # printing the number using next_toward()# when equalprint (\"The second number with sign of first number is : \",end=\"\")print (b.next_toward(a)) # printing number after erasing rightmost trailing zeroesprint (\"Number after erasing rightmost trailing zeroes : \",end=\"\")print (d.normalize())",
"e": 30184,
"s": 29376,
"text": null
},
{
"code": null,
"e": 30193,
"s": 30184,
"text": "Output: "
},
{
"code": null,
"e": 30424,
"s": 30193,
"text": "The number closest to 1st number in direction of second number : \n101.3400000000000034106051316\nThe second number with sign of first number is : -101.3400000000000034106051316\nNumber after erasing rightmost trailing zeroes : 14.01"
},
{
"code": null,
"e": 30609,
"s": 30424,
"text": "9. quantize() :- This function returns the 1st argument with the number of digits in decimal part(exponent) shortened by the number of digits in decimal part(exponent) of 2nd argument."
},
{
"code": null,
"e": 30742,
"s": 30609,
"text": "10. same_quantum() :- This function returns 0 if both the numbers have different exponent and 1 if both numbers have same exponent. "
},
{
"code": null,
"e": 30750,
"s": 30742,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# quantize() and same_quantum() # importing \"decimal\" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(20.76548) # Initializing decimal numberb = decimal.Decimal(12.25) # Initializing decimal numberc = decimal.Decimal(6.25) # printing quantized first numberprint (\"The quantized first number is : \",end=\"\")print (a.quantize(b)) # checking if both number have same exponentif (b.same_quantum(c)): print (\"Both the numbers have same exponent\")else : print (\"Both numbers have different exponent\") ",
"e": 31345,
"s": 30750,
"text": null
},
{
"code": null,
"e": 31354,
"s": 31345,
"text": "Output: "
},
{
"code": null,
"e": 31428,
"s": 31354,
"text": "The quantized first number is : 20.77\nBoth the numbers have same exponent"
},
{
"code": null,
"e": 31680,
"s": 31428,
"text": "11. rotate() :- This function rotates the first argument by the amount mentioned in the second argument. If the sign of second argument is positive, rotation is towards left, else the rotation is towards right. The sign of first argument is unchanged."
},
{
"code": null,
"e": 31963,
"s": 31680,
"text": "12. shift() :- This function shifts the first argument by the amount mentioned in the second argument. If the sign of second argument is positive, shifting is towards left, else the shifting is towards right. The sign of first argument is unchanged. Digit shifted are replaced by 0."
},
{
"code": null,
"e": 31971,
"s": 31963,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# rotate() and shift() # importing \"decimal\" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(2343509394029424234334563465) # using rotate() to rotate the first argument# rotates to right by 2 positionsprint (\"The rotated value is : \",end=\"\")print (a.rotate(-2)) # using shift() to shift the first argument# rotates to left by 2 positionsprint (\"The shifted value is : \",end=\"\")print (a.shift(2))",
"e": 32460,
"s": 31971,
"text": null
},
{
"code": null,
"e": 32469,
"s": 32460,
"text": "Output: "
},
{
"code": null,
"e": 32573,
"s": 32469,
"text": "The rotated value is : 6523435093940294242343345634\nThe shifted value is : 4350939402942423433456346500"
},
{
"code": null,
"e": 32760,
"s": 32573,
"text": "13. remainder_near() :- Returns the value “1st – (n*2nd)” where n is the integer value nearest to the result of 1st/2nd. If 2 integers have exactly similar proximity, even one is chosen."
},
{
"code": null,
"e": 32858,
"s": 32760,
"text": "14. scaleb() :- This function shifts the exponent of 1st number by the value of second argument. "
},
{
"code": null,
"e": 32866,
"s": 32858,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# remainder_near() and scaleb() # importing \"decimal\" module to use decimal functionsimport decimal # Initializing decimal numbera = decimal.Decimal(23.765) # Initializing decimal numberb = decimal.Decimal(12) # Initializing decimal numberc = decimal.Decimal(8) # using remainder_near to compute valueprint (\"The computed value using remainder_near() is : \",end=\"\")print (b.remainder_near(c)) # using scaleb() to shift exponentprint (\"The value after shifting exponent : \",end=\"\")print (a.scaleb(2))",
"e": 33412,
"s": 32866,
"text": null
},
{
"code": null,
"e": 33421,
"s": 33412,
"text": "Output: "
},
{
"code": null,
"e": 33537,
"s": 33421,
"text": "The computed value using remainder_near() is : -4\nThe value after shifting exponent : 2376.500000000000056843418861"
},
{
"code": null,
"e": 33959,
"s": 33537,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 33986,
"s": 33959,
"text": "vasudevanaidukilaparthi045"
},
{
"code": null,
"e": 33997,
"s": 33986,
"text": "krishna_97"
},
{
"code": null,
"e": 34006,
"s": 33997,
"text": "gabaa406"
},
{
"code": null,
"e": 34022,
"s": 34006,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 34031,
"s": 34022,
"text": "rkbhola5"
},
{
"code": null,
"e": 34038,
"s": 34031,
"text": "Python"
},
{
"code": null,
"e": 34136,
"s": 34038,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34154,
"s": 34136,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34189,
"s": 34154,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 34221,
"s": 34189,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34243,
"s": 34221,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 34285,
"s": 34243,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 34315,
"s": 34285,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 34341,
"s": 34315,
"text": "Python String | replace()"
},
{
"code": null,
"e": 34385,
"s": 34341,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 34414,
"s": 34385,
"text": "*args and **kwargs in Python"
}
] |
Python - Print Heart Pattern - GeeksforGeeks
|
24 Feb, 2021
Given an even integer input, the task is to write a Python program to print a heart using loops and mathematical formulations.
For n = 8
* * * *
* * *
* *
* G F G *
* *
* *
* *
*
For n = 14
* * * *
* * * *
* * * *
* * *
* *
* G F G *
* *
* *
* *
* *
* *
* *
*
The following steps are used :
Form the worksheet of n X n+1 using two loops.
Apply the if-else conditions for printing stars.
Apply the if-else conditions for printing text “GFG”.
Apply else condition for rest spaces.
Note: The value of n must be greater than 8
Below is the implementation of the above approach :
Python3
# define size n = even onlyn = 8 # so this heart can be made n//2 part left,# n//2 part right, and one middle line# i.e; columns m = n + 1m = n+1 # loops for upper partfor i in range(n//2-1): for j in range(m): # condition for printing stars to GFG upper line if i == n//2-2 and (j == 0 or j == m-1): print("*", end=" ") # condition for printing stars to left upper elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \ or (j-i == m//2-n//2+3 and j > m//4)): print("*", end=" ") # condition for printing stars to right upper elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \ or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)): print("*", end=" ") # condition for printing spaces else: print(" ", end=" ") print() # loops for lower partfor i in range(n//2-1, n): for j in range(m): # condition for printing stars if (i-j == n//2-1) or (i+j == n-1+m//2): print('*', end=" ") # condition for printing GFG elif i == n//2-1: if j == m//2-1 or j == m//2+1: print('G', end=" ") elif j == m//2: print('F', end=" ") else: print(' ', end=" ") # condition for printing spaces else: print(' ', end=" ") print()
Output:
* * * *
* * * *
* * * *
* * *
* *
* G F G *
* *
* *
* *
* *
* *
* *
*
Python Pattern-printing
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 25708,
"s": 25581,
"text": "Given an even integer input, the task is to write a Python program to print a heart using loops and mathematical formulations."
},
{
"code": null,
"e": 26270,
"s": 25708,
"text": "For n = 8\n\n * * * * \n* * * \n* * \n* G F G * \n * * \n * * \n * * \n *\n\nFor n = 14\n\n * * * * \n * * * * \n * * * * \n* * * \n* * \n* G F G * \n * * \n * * \n * * \n * * \n * * \n * * \n * "
},
{
"code": null,
"e": 26301,
"s": 26270,
"text": "The following steps are used :"
},
{
"code": null,
"e": 26348,
"s": 26301,
"text": "Form the worksheet of n X n+1 using two loops."
},
{
"code": null,
"e": 26397,
"s": 26348,
"text": "Apply the if-else conditions for printing stars."
},
{
"code": null,
"e": 26451,
"s": 26397,
"text": "Apply the if-else conditions for printing text “GFG”."
},
{
"code": null,
"e": 26489,
"s": 26451,
"text": "Apply else condition for rest spaces."
},
{
"code": null,
"e": 26533,
"s": 26489,
"text": "Note: The value of n must be greater than 8"
},
{
"code": null,
"e": 26585,
"s": 26533,
"text": "Below is the implementation of the above approach :"
},
{
"code": null,
"e": 26593,
"s": 26585,
"text": "Python3"
},
{
"code": "# define size n = even onlyn = 8 # so this heart can be made n//2 part left,# n//2 part right, and one middle line# i.e; columns m = n + 1m = n+1 # loops for upper partfor i in range(n//2-1): for j in range(m): # condition for printing stars to GFG upper line if i == n//2-2 and (j == 0 or j == m-1): print(\"*\", end=\" \") # condition for printing stars to left upper elif j <= m//2 and ((i+j == n//2-3 and j <= m//4) \\ or (j-i == m//2-n//2+3 and j > m//4)): print(\"*\", end=\" \") # condition for printing stars to right upper elif j > m//2 and ((i+j == n//2-3+m//2 and j < 3*m//4) \\ or (j-i == m//2-n//2+3+m//2 and j >= 3*m//4)): print(\"*\", end=\" \") # condition for printing spaces else: print(\" \", end=\" \") print() # loops for lower partfor i in range(n//2-1, n): for j in range(m): # condition for printing stars if (i-j == n//2-1) or (i+j == n-1+m//2): print('*', end=\" \") # condition for printing GFG elif i == n//2-1: if j == m//2-1 or j == m//2+1: print('G', end=\" \") elif j == m//2: print('F', end=\" \") else: print(' ', end=\" \") # condition for printing spaces else: print(' ', end=\" \") print()",
"e": 28124,
"s": 26593,
"text": null
},
{
"code": null,
"e": 28132,
"s": 28124,
"text": "Output:"
},
{
"code": null,
"e": 28566,
"s": 28132,
"text": " \n * * * * \n * * * * \n * * * * \n* * * \n* * \n* G F G * \n * * \n * * \n * * \n * * \n * * \n * * \n * "
},
{
"code": null,
"e": 28590,
"s": 28566,
"text": "Python Pattern-printing"
},
{
"code": null,
"e": 28597,
"s": 28590,
"text": "Python"
},
{
"code": null,
"e": 28613,
"s": 28597,
"text": "Python Programs"
},
{
"code": null,
"e": 28711,
"s": 28613,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28743,
"s": 28711,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28785,
"s": 28743,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28827,
"s": 28785,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28883,
"s": 28827,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28910,
"s": 28883,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28932,
"s": 28910,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28971,
"s": 28932,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29017,
"s": 28971,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 29055,
"s": 29017,
"text": "Python | Convert a list to dictionary"
}
] |
Reverse a Stack using C#
|
Set a stack and add elements to it.
Stack st = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R');
Now set another stack to reverse it.
Stack rev = new Stack();
Until the count of ths Stack is not equal to 0, use the Push and Pop method to reverse it.
while (st.Count != 0) {
rev.Push(st.Pop());
}
The following is the complete code −
Live Demo
using System;
using System.Collections;
namespace CollectionsApplication {
public class Program {
public static void Main(string[] args) {
Stack st = new Stack();
Stack rev = new Stack();
st.Push('P');
st.Push('Q');
st.Push('R');
Console.WriteLine("Current stack: ");
foreach(char c in st) {
Console.Write(c + " ");
}
Console.WriteLine();
while (st.Count != 0) {
rev.Push(st.Pop());
}
Console.WriteLine("Reversed stack: ");
foreach(char c in rev) {
Console.Write(c + " ");
}
}
}
}
Current stack:
R Q P
Reversed stack:
P Q R
|
[
{
"code": null,
"e": 1098,
"s": 1062,
"text": "Set a stack and add elements to it."
},
{
"code": null,
"e": 1164,
"s": 1098,
"text": "Stack st = new Stack();\nst.Push('P');\nst.Push('Q');\nst.Push('R');"
},
{
"code": null,
"e": 1201,
"s": 1164,
"text": "Now set another stack to reverse it."
},
{
"code": null,
"e": 1226,
"s": 1201,
"text": "Stack rev = new Stack();"
},
{
"code": null,
"e": 1317,
"s": 1226,
"text": "Until the count of ths Stack is not equal to 0, use the Push and Pop method to reverse it."
},
{
"code": null,
"e": 1366,
"s": 1317,
"text": "while (st.Count != 0) {\n rev.Push(st.Pop());\n}"
},
{
"code": null,
"e": 1403,
"s": 1366,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 1414,
"s": 1403,
"text": " Live Demo"
},
{
"code": null,
"e": 2076,
"s": 1414,
"text": "using System;\nusing System.Collections;\n\nnamespace CollectionsApplication {\n public class Program {\n public static void Main(string[] args) {\n Stack st = new Stack();\n Stack rev = new Stack();\n st.Push('P');\n st.Push('Q');\n st.Push('R');\n Console.WriteLine(\"Current stack: \");\n foreach(char c in st) {\n Console.Write(c + \" \");\n }\n Console.WriteLine();\n while (st.Count != 0) {\n rev.Push(st.Pop());\n }\n Console.WriteLine(\"Reversed stack: \");\n foreach(char c in rev) {\n Console.Write(c + \" \");\n }\n }\n }\n}"
},
{
"code": null,
"e": 2119,
"s": 2076,
"text": "Current stack:\nR Q P\nReversed stack:\nP Q R"
}
] |
Git Revert
|
revert is the command we use when we want to take a previous commit and add it as a new commit, keeping the log intact.
Step 1: Find the previous commit:
Step 2: Use it to make a new commit:
Let's make a new commit, where we have "accidentally" deleted a file:
git commit -m "Just a regular update, definitely no accidents here..."
[master 16a6f19] Just a regular update, definitely no accidents here...
1 file changed, 0 insertions(+), 0 deletions(-)
delete mode 100644 img_hello_git.jpg
Now we have a part in our commit history we want to go back to. Let's try and do that with revert.
First thing, we need to find the point we want to return to. To do that, we need to go through the
log.
To avoid the very long log list, we are going to use the
--oneline option,
which gives just one line per commit showing:
The first seven characters of the commit hash
the commit message
So let's find the point we want to revert:
git log --oneline
52418f7 (HEAD -> master) Just a regular update, definitely no accidents here...
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
We want to revert to the previous commit:
52418f7 (HEAD -> master) Just a regular update, definitely no accidents here..., and we see that
it is the latest commit.
We revert the latest commit using git
revert HEAD (revert the latest change, and then
commit), adding the option
--no-edit to skip the commit message editor (getting the default
revert message):
git revert HEAD --no-edit
[master e56ba1f] Revert "Just a regular update, definitely no accidents here..."
Date: Thu Apr 22 10:50:13 2021 +0200
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 img_hello_git.jpg
Now let's check the log again:
git log --oneline
e56ba1f (HEAD -> master) Revert "Just a regular update, definitely no accidents here..."
52418f7 Just a regular update, definitely no accidents here...
9a9add8 (origin/master) Added .gitignore
81912ba Corrected spelling error
3fdaa5b Merge pull request #1 from w3schools-test/update-readme
836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches
daf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta
facaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world
e7de78f Updated index.html. Resized image
5a04b6f Updated README.md with a line about focus
d29d69f Updated README.md with a line about GitHub
e0b6038 merged with hello-world-images after fixing conflicts
1f1584e added new image
dfa79db updated index.html with emergency fix
0312c55 Added image to Hello World
09f4acd Updated index.html with a new line
221ec6e First release of Hello World!
Note: To revert to earlier commits, use
git revert HEAD~x (x being a number. 1 going back one more, 2 going back two more, etc.)
On the next page, we'll go over git reset, which brings the repository back to an earlier state in the commits without
making a new commit.
Show the log of the repository, showing just 1 line per commit:
git
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 120,
"s": 0,
"text": "revert is the command we use when we want to take a previous commit and add it as a new commit, keeping the log intact."
},
{
"code": null,
"e": 154,
"s": 120,
"text": "Step 1: Find the previous commit:"
},
{
"code": null,
"e": 191,
"s": 154,
"text": "Step 2: Use it to make a new commit:"
},
{
"code": null,
"e": 261,
"s": 191,
"text": "Let's make a new commit, where we have \"accidentally\" deleted a file:"
},
{
"code": null,
"e": 491,
"s": 261,
"text": "git commit -m \"Just a regular update, definitely no accidents here...\"\n[master 16a6f19] Just a regular update, definitely no accidents here...\n 1 file changed, 0 insertions(+), 0 deletions(-)\n delete mode 100644 img_hello_git.jpg"
},
{
"code": null,
"e": 590,
"s": 491,
"text": "Now we have a part in our commit history we want to go back to. Let's try and do that with revert."
},
{
"code": null,
"e": 695,
"s": 590,
"text": "First thing, we need to find the point we want to return to. To do that, we need to go through the \nlog."
},
{
"code": null,
"e": 818,
"s": 695,
"text": "To avoid the very long log list, we are going to use the \n--oneline option, \nwhich gives just one line per commit showing:"
},
{
"code": null,
"e": 864,
"s": 818,
"text": "The first seven characters of the commit hash"
},
{
"code": null,
"e": 883,
"s": 864,
"text": "the commit message"
},
{
"code": null,
"e": 926,
"s": 883,
"text": "So let's find the point we want to revert:"
},
{
"code": null,
"e": 1811,
"s": 926,
"text": "git log --oneline\n52418f7 (HEAD -> master) Just a regular update, definitely no accidents here...\n9a9add8 (origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 1977,
"s": 1811,
"text": "We want to revert to the previous commit: \n52418f7 (HEAD -> master) Just a regular update, definitely no accidents here..., and we see that \nit is the latest commit."
},
{
"code": null,
"e": 2176,
"s": 1977,
"text": "We revert the latest commit using git \nrevert HEAD (revert the latest change, and then \ncommit), adding the option\n--no-edit to skip the commit message editor (getting the default \nrevert message):"
},
{
"code": null,
"e": 2408,
"s": 2176,
"text": "git revert HEAD --no-edit\n[master e56ba1f] Revert \"Just a regular update, definitely no accidents here...\"\n Date: Thu Apr 22 10:50:13 2021 +0200\n 1 file changed, 0 insertions(+), 0 deletions(-)\n create mode 100644 img_hello_git.jpg"
},
{
"code": null,
"e": 2439,
"s": 2408,
"text": "Now let's check the log again:"
},
{
"code": null,
"e": 3396,
"s": 2439,
"text": "git log --oneline\ne56ba1f (HEAD -> master) Revert \"Just a regular update, definitely no accidents here...\"\n52418f7 Just a regular update, definitely no accidents here...\n9a9add8 (origin/master) Added .gitignore\n81912ba Corrected spelling error\n3fdaa5b Merge pull request #1 from w3schools-test/update-readme\n836e5bf (origin/update-readme, update-readme) Updated readme for GitHub Branches\ndaf4f7c (origin/html-skeleton, html-skeleton) Updated index.html with basic meta\nfacaeae (gh-page/master) Merge branch 'master' of https://github.com/w3schools-test/hello-world\ne7de78f Updated index.html. Resized image\n5a04b6f Updated README.md with a line about focus\nd29d69f Updated README.md with a line about GitHub\ne0b6038 merged with hello-world-images after fixing conflicts\n1f1584e added new image\ndfa79db updated index.html with emergency fix\n0312c55 Added image to Hello World\n09f4acd Updated index.html with a new line\n221ec6e First release of Hello World!"
},
{
"code": null,
"e": 3528,
"s": 3396,
"text": "Note: To revert to earlier commits, use \n git revert HEAD~x (x being a number. 1 going back one more, 2 going back two more, etc.)"
},
{
"code": null,
"e": 3669,
"s": 3528,
"text": "On the next page, we'll go over git reset, which brings the repository back to an earlier state in the commits without \nmaking a new commit."
},
{
"code": null,
"e": 3733,
"s": 3669,
"text": "Show the log of the repository, showing just 1 line per commit:"
},
{
"code": null,
"e": 3740,
"s": 3733,
"text": "git \n"
},
{
"code": null,
"e": 3760,
"s": 3740,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 3793,
"s": 3760,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3835,
"s": 3793,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3942,
"s": 3835,
"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": 3961,
"s": 3942,
"text": "help@w3schools.com"
}
] |
HTML | File Paths
|
12 Aug, 2021
A file path specifies the location of a file inside a web folder structure. Its like an address of a file which helps the web browser to access the files. File paths are used to link external resources such as images, videos, style sheets, JavaScript, displaying other web pages etc.To insert a file in a web page its source must be known. For example, the syntax (<img src=” ” alt=” “>) is used to insert an image file, where the path of the file is mentioned in the source (src). File paths are of two types:
Absolute File Paths
Relative File Paths
Absolute File Paths: It describes the full address(URL) to access an internet file.
<img src=”https://media.geeksforgeeks.org/wp-content/uploads/geek.png” alt=”My Image”>
Example:
html
<!DOCTYPE html><html> <head> <title>Absolute file path</title> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geek.png" alt="My Image" style="width:400px"> </body></html>
Output:
Relative File Path: It describes the path of the file relative to the location of the current web page file. Example 1: It shows the path of the file present in the same folder of the current web page file.
html
<!DOCTYPE html><html> <head> <title>Relative file path</title> </head> <body> <h2>File present in the same folder</h2> <img src="images/geeks.jpg" alt="My Image" style="width:400px"> </body></html>
Output:
Example 2: It shows the path of the file present in a folder above the folder of the current web page file. The image file present in a folder called images and current web page file exists inside a sub folder, then the code will be as follows:
html
<!DOCTYPE html><html> <head> <title>Relative file path</title> </head> <body> <h2>File present in a folder above the current folder</h2> <img src="../images/geeks.jpg" alt="My Image" style="width:400px"> </body></html>
Output:
Example 3: It shows the path of the file present in a folder which is located at the root of the current sub directories.
html
<!DOCTYPE html><html> <head> <title>Relative file path</title> </head> <body> <h2>File present in a folder which is located at<br> the root of the current subdirectories</h2> <img src="/images/picture.jpg" alt="My Image" style="width:400px"> </body></html>
Output:
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Akanksha_Rai
ysachin2314
HTML-Basics
Picked
CSS
HTML
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Aug, 2021"
},
{
"code": null,
"e": 566,
"s": 53,
"text": "A file path specifies the location of a file inside a web folder structure. Its like an address of a file which helps the web browser to access the files. File paths are used to link external resources such as images, videos, style sheets, JavaScript, displaying other web pages etc.To insert a file in a web page its source must be known. For example, the syntax (<img src=” ” alt=” “>) is used to insert an image file, where the path of the file is mentioned in the source (src). File paths are of two types: "
},
{
"code": null,
"e": 586,
"s": 566,
"text": "Absolute File Paths"
},
{
"code": null,
"e": 606,
"s": 586,
"text": "Relative File Paths"
},
{
"code": null,
"e": 692,
"s": 606,
"text": "Absolute File Paths: It describes the full address(URL) to access an internet file. "
},
{
"code": null,
"e": 779,
"s": 692,
"text": "<img src=”https://media.geeksforgeeks.org/wp-content/uploads/geek.png” alt=”My Image”>"
},
{
"code": null,
"e": 791,
"s": 779,
"text": " Example: "
},
{
"code": null,
"e": 796,
"s": 791,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Absolute file path</title> </head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geek.png\" alt=\"My Image\" style=\"width:400px\"> </body></html> ",
"e": 1048,
"s": 796,
"text": null
},
{
"code": null,
"e": 1058,
"s": 1048,
"text": "Output: "
},
{
"code": null,
"e": 1267,
"s": 1058,
"text": "Relative File Path: It describes the path of the file relative to the location of the current web page file. Example 1: It shows the path of the file present in the same folder of the current web page file. "
},
{
"code": null,
"e": 1272,
"s": 1267,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Relative file path</title> </head> <body> <h2>File present in the same folder</h2> <img src=\"images/geeks.jpg\" alt=\"My Image\" style=\"width:400px\"> </body></html> ",
"e": 1522,
"s": 1272,
"text": null
},
{
"code": null,
"e": 1532,
"s": 1522,
"text": "Output: "
},
{
"code": null,
"e": 1779,
"s": 1532,
"text": "Example 2: It shows the path of the file present in a folder above the folder of the current web page file. The image file present in a folder called images and current web page file exists inside a sub folder, then the code will be as follows: "
},
{
"code": null,
"e": 1784,
"s": 1779,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Relative file path</title> </head> <body> <h2>File present in a folder above the current folder</h2> <img src=\"../images/geeks.jpg\" alt=\"My Image\" style=\"width:400px\"> </body></html> ",
"e": 2055,
"s": 1784,
"text": null
},
{
"code": null,
"e": 2065,
"s": 2055,
"text": "Output: "
},
{
"code": null,
"e": 2189,
"s": 2065,
"text": "Example 3: It shows the path of the file present in a folder which is located at the root of the current sub directories. "
},
{
"code": null,
"e": 2194,
"s": 2189,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Relative file path</title> </head> <body> <h2>File present in a folder which is located at<br> the root of the current subdirectories</h2> <img src=\"/images/picture.jpg\" alt=\"My Image\" style=\"width:400px\"> </body></html> ",
"e": 2510,
"s": 2194,
"text": null
},
{
"code": null,
"e": 2520,
"s": 2510,
"text": "Output: "
},
{
"code": null,
"e": 2539,
"s": 2520,
"text": "Supported Browser:"
},
{
"code": null,
"e": 2553,
"s": 2539,
"text": "Google Chrome"
},
{
"code": null,
"e": 2568,
"s": 2553,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 2576,
"s": 2568,
"text": "Firefox"
},
{
"code": null,
"e": 2582,
"s": 2576,
"text": "Opera"
},
{
"code": null,
"e": 2590,
"s": 2582,
"text": "Safari "
},
{
"code": null,
"e": 2776,
"s": 2590,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 2791,
"s": 2778,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2803,
"s": 2791,
"text": "ysachin2314"
},
{
"code": null,
"e": 2815,
"s": 2803,
"text": "HTML-Basics"
},
{
"code": null,
"e": 2822,
"s": 2815,
"text": "Picked"
},
{
"code": null,
"e": 2826,
"s": 2822,
"text": "CSS"
},
{
"code": null,
"e": 2831,
"s": 2826,
"text": "HTML"
},
{
"code": null,
"e": 2858,
"s": 2831,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2863,
"s": 2858,
"text": "HTML"
}
] |
Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
|
22 Jan, 2022
Python has defined a module, “time” which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time is started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch” in Python.
Operations on Time :
1. time() :- This function is used to count the number of seconds elapsed since the epoch. 2. gmtime(sec) :- This function returns a structure with 9 values each representing a time attribute in sequence. It converts seconds into time attributes(days, years, months etc.) till specified seconds from epoch. If no seconds are mentioned, time is calculated till present. The structure attribute table is given below.
Index Attributes Values
0 tm_year 2008
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
5 tm_sec 0 to 61 (60 or 61 are leap-seconds)
6 tm_wday 0 to 6
7 tm_yday 1 to 366
8 tm_isdst -1, 0, 1 where -1 means
Library determines DST
Python3
# Python code to demonstrate the working of# time() and gmtime() # importing "time" module for time operationsimport time # using time() to display time since epochprint ("Seconds elapsed since the epoch are : ",end="")print (time.time()) # using gmtime() to return the time attribute structureprint ("Time calculated acc. to given seconds is : ")print (time.gmtime())
Output:
Seconds elapsed since the epoch are : 1470121951.9536893
Time calculated acc. to given seconds is :
time.struct_time(tm_year=2016, tm_mon=8, tm_mday=2,
tm_hour=7, tm_min=12, tm_sec=31, tm_wday=1,
tm_yday=215, tm_isdst=0)
3. asctime(“time”) :- This function takes a time attributed string produced by gmtime() and returns a 24 character string denoting time. 4. ctime(sec) :- This function returns a 24 character time string but takes seconds as argument and computes time till mentioned seconds. If no argument is passed, time is calculated till present.
Python3
# Python code to demonstrate the working of# asctime() and ctime() # importing "time" module for time operationsimport time # initializing time using gmtime()ti = time.gmtime() # using asctime() to display time acc. to time mentionedprint ("Time calculated using asctime() is : ",end="")print (time.asctime(ti)) # using ctime() to display time string using secondsprint ("Time calculated using ctime() is : ", end="")print (time.ctime())
Output:
Time calculated using asctime() is : Tue Aug 2 07:47:02 2016
Time calculated using ctime() is : Tue Aug 2 07:47:02 2016
5. sleep(sec) :- This method is used to halt the program execution for the time specified in the arguments.
Python3
# Python code to demonstrate the working of# sleep() # importing "time" module for time operationsimport time # using ctime() to show present timeprint ("Start Execution : ",end="")print (time.ctime()) # using sleep() to hault executiontime.sleep(4) # using ctime() to show present timeprint ("Stop Execution : ",end="")print (time.ctime())
Output:
Start Execution : Tue Aug 2 07:59:03 2016
Stop Execution : Tue Aug 2 07:59:07 2016
Python Programming Tutorial | Time functions in Python - Part 1 | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersPython Programming Tutorial | Time functions in Python - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GKiAFxVaTzw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
anikaseth98
amartyaghoshgfg
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
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 ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jan, 2022"
},
{
"code": null,
"e": 363,
"s": 52,
"text": "Python has defined a module, “time” which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time is started measuring from 1 January, 12:00 am, 1970 and this very time is termed as “epoch” in Python."
},
{
"code": null,
"e": 384,
"s": 363,
"text": "Operations on Time :"
},
{
"code": null,
"e": 800,
"s": 384,
"text": "1. time() :- This function is used to count the number of seconds elapsed since the epoch. 2. gmtime(sec) :- This function returns a structure with 9 values each representing a time attribute in sequence. It converts seconds into time attributes(days, years, months etc.) till specified seconds from epoch. If no seconds are mentioned, time is calculated till present. The structure attribute table is given below. "
},
{
"code": null,
"e": 1195,
"s": 800,
"text": "Index Attributes Values\n 0 tm_year 2008\n 1 tm_mon 1 to 12\n 2 tm_mday 1 to 31\n 3 tm_hour 0 to 23\n 4 tm_min 0 to 59\n 5 tm_sec 0 to 61 (60 or 61 are leap-seconds)\n 6 tm_wday 0 to 6 \n 7 tm_yday 1 to 366\n 8 tm_isdst -1, 0, 1 where -1 means \n Library determines DST"
},
{
"code": null,
"e": 1203,
"s": 1195,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# time() and gmtime() # importing \"time\" module for time operationsimport time # using time() to display time since epochprint (\"Seconds elapsed since the epoch are : \",end=\"\")print (time.time()) # using gmtime() to return the time attribute structureprint (\"Time calculated acc. to given seconds is : \")print (time.gmtime())",
"e": 1574,
"s": 1203,
"text": null
},
{
"code": null,
"e": 1583,
"s": 1574,
"text": "Output: "
},
{
"code": null,
"e": 1806,
"s": 1583,
"text": "Seconds elapsed since the epoch are : 1470121951.9536893\nTime calculated acc. to given seconds is : \ntime.struct_time(tm_year=2016, tm_mon=8, tm_mday=2,\ntm_hour=7, tm_min=12, tm_sec=31, tm_wday=1, \ntm_yday=215, tm_isdst=0)"
},
{
"code": null,
"e": 2141,
"s": 1806,
"text": " 3. asctime(“time”) :- This function takes a time attributed string produced by gmtime() and returns a 24 character string denoting time. 4. ctime(sec) :- This function returns a 24 character time string but takes seconds as argument and computes time till mentioned seconds. If no argument is passed, time is calculated till present."
},
{
"code": null,
"e": 2149,
"s": 2141,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# asctime() and ctime() # importing \"time\" module for time operationsimport time # initializing time using gmtime()ti = time.gmtime() # using asctime() to display time acc. to time mentionedprint (\"Time calculated using asctime() is : \",end=\"\")print (time.asctime(ti)) # using ctime() to display time string using secondsprint (\"Time calculated using ctime() is : \", end=\"\")print (time.ctime())",
"e": 2589,
"s": 2149,
"text": null
},
{
"code": null,
"e": 2598,
"s": 2589,
"text": "Output: "
},
{
"code": null,
"e": 2720,
"s": 2598,
"text": "Time calculated using asctime() is : Tue Aug 2 07:47:02 2016\nTime calculated using ctime() is : Tue Aug 2 07:47:02 2016"
},
{
"code": null,
"e": 2829,
"s": 2720,
"text": " 5. sleep(sec) :- This method is used to halt the program execution for the time specified in the arguments."
},
{
"code": null,
"e": 2837,
"s": 2829,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# sleep() # importing \"time\" module for time operationsimport time # using ctime() to show present timeprint (\"Start Execution : \",end=\"\")print (time.ctime()) # using sleep() to hault executiontime.sleep(4) # using ctime() to show present timeprint (\"Stop Execution : \",end=\"\")print (time.ctime())",
"e": 3179,
"s": 2837,
"text": null
},
{
"code": null,
"e": 3188,
"s": 3179,
"text": "Output: "
},
{
"code": null,
"e": 3273,
"s": 3188,
"text": "Start Execution : Tue Aug 2 07:59:03 2016\nStop Execution : Tue Aug 2 07:59:07 2016"
},
{
"code": null,
"e": 4217,
"s": 3273,
"text": "Python Programming Tutorial | Time functions in Python - Part 1 | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersPython Programming Tutorial | Time functions in Python - Part 1 | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=GKiAFxVaTzw\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 4639,
"s": 4217,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4651,
"s": 4639,
"text": "anikaseth98"
},
{
"code": null,
"e": 4667,
"s": 4651,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 4674,
"s": 4667,
"text": "Python"
},
{
"code": null,
"e": 4772,
"s": 4674,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4790,
"s": 4772,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4832,
"s": 4790,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4854,
"s": 4832,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4889,
"s": 4854,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4915,
"s": 4889,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4947,
"s": 4915,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4976,
"s": 4947,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5003,
"s": 4976,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5024,
"s": 5003,
"text": "Python OOPs Concepts"
}
] |
PyCairo – Saving SVG Image file to PNG file
|
12 Nov, 2020
In this article, we will see how we can save an SVG file to a PNG file using PyCairo in Python. We can create an SVG file using SVGSurface method. An SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web.
PNG : Portable Network Graphics is a raster-graphics file format that supports lossless data compression. PNG was developed as an improved, non-patented replacement for Graphics Interchange Format. PNG supports palette-based images, grayscale images, and full-color non-palette-based RGB or RGBA images.
PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read-only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format.
In order to this we will use write_to_png method with the SVGSurface objectSyntax : surface.write_to_png(‘geeks.png’)Argument : File name to be savedReturn : It returns None
Below is the implementation.
Python3
# importing pycairoimport cairo # creating a SVG surface# here geek is file name & 700, 700 is dimensionwith cairo.SVGSurface("geek.svg", 700, 700) as surface: # creating a cairo context object context = cairo.Context(surface) # creating a rectangle(square) for left eye context.rectangle(100, 100, 100, 100) # creating a rectangle(square) for right eye context.rectangle(500, 100, 100, 100) # creating position for the curves x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9 x2, y2, x3, y3 = 0.4, 0.1, 0.9, 0.6 # setting scale of the context context.scale(700, 700) # setting line width of the context context.set_line_width(0.04) # move the context to x,y position context.move_to(x, y) # draw the curve for smile context.curve_to(x1, y1, x2, y2, x3, y3) # setting color of the context context.set_source_rgba(0.4, 1, 0.4, 1) # stroke out the color and width property context.stroke() # Save as a SVG and PNG surface.write_to_png('geek.png') # printing message when file is savedprint("File Saved")
Output :
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Nov, 2020"
},
{
"code": null,
"e": 454,
"s": 28,
"text": "In this article, we will see how we can save an SVG file to a PNG file using PyCairo in Python. We can create an SVG file using SVGSurface method. An SVG file is a graphics file that uses a two-dimensional vector graphic format created by the World Wide Web Consortium (W3C). It describes images using a text format that is based on XML. SVG files are developed as a standard format for displaying vector graphics on the web."
},
{
"code": null,
"e": 758,
"s": 454,
"text": "PNG : Portable Network Graphics is a raster-graphics file format that supports lossless data compression. PNG was developed as an improved, non-patented replacement for Graphics Interchange Format. PNG supports palette-based images, grayscale images, and full-color non-palette-based RGB or RGBA images."
},
{
"code": null,
"e": 1149,
"s": 758,
"text": "PyCairo : Pycairo is a Python module providing bindings for the cairo graphics library. This library is used for creating SVG i.e vector files in python. The easiest and quickest way to open an SVG file to view it (read-only) is with a modern web browser like Chrome, Firefox, Edge, or Internet Explorer—nearly all of them should provide some sort of rendering support for the SVG format. "
},
{
"code": null,
"e": 1324,
"s": 1149,
"text": "In order to this we will use write_to_png method with the SVGSurface objectSyntax : surface.write_to_png(‘geeks.png’)Argument : File name to be savedReturn : It returns None "
},
{
"code": null,
"e": 1354,
"s": 1324,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 1362,
"s": 1354,
"text": "Python3"
},
{
"code": "# importing pycairoimport cairo # creating a SVG surface# here geek is file name & 700, 700 is dimensionwith cairo.SVGSurface(\"geek.svg\", 700, 700) as surface: # creating a cairo context object context = cairo.Context(surface) # creating a rectangle(square) for left eye context.rectangle(100, 100, 100, 100) # creating a rectangle(square) for right eye context.rectangle(500, 100, 100, 100) # creating position for the curves x, y, x1, y1 = 0.1, 0.5, 0.4, 0.9 x2, y2, x3, y3 = 0.4, 0.1, 0.9, 0.6 # setting scale of the context context.scale(700, 700) # setting line width of the context context.set_line_width(0.04) # move the context to x,y position context.move_to(x, y) # draw the curve for smile context.curve_to(x1, y1, x2, y2, x3, y3) # setting color of the context context.set_source_rgba(0.4, 1, 0.4, 1) # stroke out the color and width property context.stroke() # Save as a SVG and PNG surface.write_to_png('geek.png') # printing message when file is savedprint(\"File Saved\")",
"e": 2443,
"s": 1362,
"text": null
},
{
"code": null,
"e": 2453,
"s": 2443,
"text": "Output : "
},
{
"code": null,
"e": 2462,
"s": 2455,
"text": "Python"
}
] |
How to configure ESLint for React Projects ?
|
21 Sep, 2021
In this article, we will see how to configure ESLint for your React Project from scratch. Before getting started you may refer to a previous article on ESLint introduction although it’s not a necessity.Talking about ESLint it’s a linting tool that finds and many times fixes problems in your JavaScript code, but the question arises is Why use it? My code is running anyway without eslint so what’s great about it? For this consider a situation where you along with your friends/colleagues are working on a group project or it can be your personal project as well while working biases can occur about the proper code syntax or its styling and you will eventually end up focusing on those problems, but why not we have a tool which will do that work for us and we will just focus on problem-solving and building the project, it sounds good right? So let’s start using ESLint.
Installation: Install ESLint in your React Project as a devDependency by running the following command:
npm install -D eslint
Configuration: You can configure ESLint according to your use case. There are two ways two configure ESLint :
Configuration Comments: These are JavaScript comments which are embedded into individual files to configure themConfiguration File: ESLint will use JavaScript/JSON/YAML file which contain information to configure the entire directory.
Configuration Comments: These are JavaScript comments which are embedded into individual files to configure them
Configuration File: ESLint will use JavaScript/JSON/YAML file which contain information to configure the entire directory.
In this particular config, we will use JSON format i.e. `.eslintrc.json` to have our configurations, or else you can create the `eslintConfig` property in `package.json` and write these configurations in that property.
.eslintrc.json file in the root of the directory
“extends” and “plugins”: By adding a file name in extends property we can inherit its configuration, whereas “plugin” works as an extension to ESLint which can perform numerous functions.Inside our `.eslintrc.json` file add extends and plugin property similar to given below:
{
"extends": [
"eslint:recommended",
"plugin:import/errors",
"plugin:react/recommended",
"plugin:jsx-a11y/recommended"
],
"plugins": ["react", "import", "jsx-a11y"]
}
Note that as we have added various plugins we need to first install them so run the following command to install them as devDependencies :
npm install -D eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react
The `import-plugin` will help us identify common problems while importing and exporting; `jsx-a11y` will catch errors regarding accessibility and the `react` plugin is all about code practices used in React, since we are using `eslint-plugin-react` we will need to inform it which version of React we are using so let’s add this in our “settings” property, instead of stating the current React version we will handover this job to settings by using the keyword “detect” so that it will detect the current React version from `package.json`
..},
"settings": {
"react": {
"version": "detect"
}
}
“rules”: Rules are used for configuring purposes, you can see all the rules that you can use https://eslint.org/docs/rules/. You can set the error level of rules in three different types :
“off” or 0: This will turn off the rule.
“warn” or 1: This will turn the rule on as a warning.
“error” or 2: This will turn on the rule as an error.
Let’s add some rules to our config, you can add any other rules as per your choice from the list of all rules mentioned above.
"rules": {
"react/prop-types": 0,
"indent": ["error", 2],
"linebreak-style": 1,
"quotes": ["error", "double"]
},
“env” and “parserOptions”: In the “env” property, we will specify what environments we are working in. In parserOptions, we can specify JavaScript options like jsx support or ecma version
"parserOptions": {
"ecmaVersion": 2021,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"env": {
"es6": true,
"browser": true,
"node": true
},
.eslintrc.json
{ "extends": [ "eslint:recommended", "plugin:import/errors", "plugin:react/recommended", "plugin:jsx-a11y/recommended" ], "plugins": ["react", "import", "jsx-a11y"], "rules": { "react/prop-types": 0, "indent": ["error", 2], "linebreak-style": 1, "quotes": ["error", "double"] }, "parserOptions": { "ecmaVersion": 2021, "sourceType": "module", "ecmaFeatures": { "jsx": true } }, "env": { "es6": true, "browser": true, "node": true }, "settings": { "react": { "version": "detect" } }}
Last but not least, let’s add some commands in our package.json’s “scripts” property to run ESLint
"scripts": {
"lint": "eslint \"src/**/*.{js,jsx}\"",
"lint:fix": "eslint \"src/**/*.{js,jsx}\" --fix"
},
The “lint” command will run ESLint inside every file in the “src/”, even if your “src/” folder contains multiple directories in it, this regex command will go down recursively on them and run ESLint; If some problems are reported by ESLint which are auto-fixable, then “lint:fix” command will do those auto-fixes.
Step to run lint: Open the terminal and type the following command.
npm run lint
Output:
Running the lint command
Some errors are auto-fixed by running the lint:fix command
Blogathon-2021
JSON
React-Questions
Blogathon
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Consensus Problem of Distributed Systems
Stratified Sampling in Pandas
Changing CSS styling with React onClick() Event
How to parse JSON Data into React Table Component ?
How to write comments in ReactJS ?
How to create a multi-page website using React.js ?
ReactJS setState()
Create a Responsive Navbar using ReactJS
How to do crud operations in ReactJS ?
How to redirect to another page in ReactJS ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 927,
"s": 52,
"text": "In this article, we will see how to configure ESLint for your React Project from scratch. Before getting started you may refer to a previous article on ESLint introduction although it’s not a necessity.Talking about ESLint it’s a linting tool that finds and many times fixes problems in your JavaScript code, but the question arises is Why use it? My code is running anyway without eslint so what’s great about it? For this consider a situation where you along with your friends/colleagues are working on a group project or it can be your personal project as well while working biases can occur about the proper code syntax or its styling and you will eventually end up focusing on those problems, but why not we have a tool which will do that work for us and we will just focus on problem-solving and building the project, it sounds good right? So let’s start using ESLint."
},
{
"code": null,
"e": 1031,
"s": 927,
"text": "Installation: Install ESLint in your React Project as a devDependency by running the following command:"
},
{
"code": null,
"e": 1053,
"s": 1031,
"text": "npm install -D eslint"
},
{
"code": null,
"e": 1163,
"s": 1053,
"text": "Configuration: You can configure ESLint according to your use case. There are two ways two configure ESLint :"
},
{
"code": null,
"e": 1398,
"s": 1163,
"text": "Configuration Comments: These are JavaScript comments which are embedded into individual files to configure themConfiguration File: ESLint will use JavaScript/JSON/YAML file which contain information to configure the entire directory."
},
{
"code": null,
"e": 1511,
"s": 1398,
"text": "Configuration Comments: These are JavaScript comments which are embedded into individual files to configure them"
},
{
"code": null,
"e": 1634,
"s": 1511,
"text": "Configuration File: ESLint will use JavaScript/JSON/YAML file which contain information to configure the entire directory."
},
{
"code": null,
"e": 1855,
"s": 1634,
"text": "In this particular config, we will use JSON format i.e. `.eslintrc.json` to have our configurations, or else you can create the `eslintConfig` property in `package.json` and write these configurations in that property. "
},
{
"code": null,
"e": 1905,
"s": 1855,
"text": ".eslintrc.json file in the root of the directory"
},
{
"code": null,
"e": 2181,
"s": 1905,
"text": "“extends” and “plugins”: By adding a file name in extends property we can inherit its configuration, whereas “plugin” works as an extension to ESLint which can perform numerous functions.Inside our `.eslintrc.json` file add extends and plugin property similar to given below:"
},
{
"code": null,
"e": 2370,
"s": 2181,
"text": "{\n \"extends\": [\n \"eslint:recommended\",\n \"plugin:import/errors\",\n \"plugin:react/recommended\",\n \"plugin:jsx-a11y/recommended\"\n ],\n \"plugins\": [\"react\", \"import\", \"jsx-a11y\"]\n}"
},
{
"code": null,
"e": 2510,
"s": 2370,
"text": "Note that as we have added various plugins we need to first install them so run the following command to install them as devDependencies : "
},
{
"code": null,
"e": 2589,
"s": 2510,
"text": "npm install -D eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react"
},
{
"code": null,
"e": 3128,
"s": 2589,
"text": "The `import-plugin` will help us identify common problems while importing and exporting; `jsx-a11y` will catch errors regarding accessibility and the `react` plugin is all about code practices used in React, since we are using `eslint-plugin-react` we will need to inform it which version of React we are using so let’s add this in our “settings” property, instead of stating the current React version we will handover this job to settings by using the keyword “detect” so that it will detect the current React version from `package.json`"
},
{
"code": null,
"e": 3198,
"s": 3128,
"text": "..},\n \"settings\": {\n \"react\": {\n \"version\": \"detect\"\n }\n}"
},
{
"code": null,
"e": 3387,
"s": 3198,
"text": "“rules”: Rules are used for configuring purposes, you can see all the rules that you can use https://eslint.org/docs/rules/. You can set the error level of rules in three different types :"
},
{
"code": null,
"e": 3428,
"s": 3387,
"text": "“off” or 0: This will turn off the rule."
},
{
"code": null,
"e": 3482,
"s": 3428,
"text": "“warn” or 1: This will turn the rule on as a warning."
},
{
"code": null,
"e": 3536,
"s": 3482,
"text": "“error” or 2: This will turn on the rule as an error."
},
{
"code": null,
"e": 3663,
"s": 3536,
"text": "Let’s add some rules to our config, you can add any other rules as per your choice from the list of all rules mentioned above."
},
{
"code": null,
"e": 3792,
"s": 3663,
"text": "\"rules\": {\n \"react/prop-types\": 0,\n \"indent\": [\"error\", 2],\n \"linebreak-style\": 1,\n \"quotes\": [\"error\", \"double\"]\n},"
},
{
"code": null,
"e": 3980,
"s": 3792,
"text": "“env” and “parserOptions”: In the “env” property, we will specify what environments we are working in. In parserOptions, we can specify JavaScript options like jsx support or ecma version"
},
{
"code": null,
"e": 4169,
"s": 3980,
"text": "\"parserOptions\": {\n \"ecmaVersion\": 2021,\n \"sourceType\": \"module\",\n \"ecmaFeatures\": {\n \"jsx\": true\n }\n},\n\"env\": {\n \"es6\": true,\n \"browser\": true,\n \"node\": true\n}, "
},
{
"code": null,
"e": 4184,
"s": 4169,
"text": ".eslintrc.json"
},
{
"code": "{ \"extends\": [ \"eslint:recommended\", \"plugin:import/errors\", \"plugin:react/recommended\", \"plugin:jsx-a11y/recommended\" ], \"plugins\": [\"react\", \"import\", \"jsx-a11y\"], \"rules\": { \"react/prop-types\": 0, \"indent\": [\"error\", 2], \"linebreak-style\": 1, \"quotes\": [\"error\", \"double\"] }, \"parserOptions\": { \"ecmaVersion\": 2021, \"sourceType\": \"module\", \"ecmaFeatures\": { \"jsx\": true } }, \"env\": { \"es6\": true, \"browser\": true, \"node\": true }, \"settings\": { \"react\": { \"version\": \"detect\" } }}",
"e": 4739,
"s": 4184,
"text": null
},
{
"code": null,
"e": 4838,
"s": 4739,
"text": "Last but not least, let’s add some commands in our package.json’s “scripts” property to run ESLint"
},
{
"code": null,
"e": 4952,
"s": 4838,
"text": "\"scripts\": {\n \"lint\": \"eslint \\\"src/**/*.{js,jsx}\\\"\",\n \"lint:fix\": \"eslint \\\"src/**/*.{js,jsx}\\\" --fix\"\n}, "
},
{
"code": null,
"e": 5266,
"s": 4952,
"text": "The “lint” command will run ESLint inside every file in the “src/”, even if your “src/” folder contains multiple directories in it, this regex command will go down recursively on them and run ESLint; If some problems are reported by ESLint which are auto-fixable, then “lint:fix” command will do those auto-fixes."
},
{
"code": null,
"e": 5334,
"s": 5266,
"text": "Step to run lint: Open the terminal and type the following command."
},
{
"code": null,
"e": 5347,
"s": 5334,
"text": "npm run lint"
},
{
"code": null,
"e": 5355,
"s": 5347,
"text": "Output:"
},
{
"code": null,
"e": 5380,
"s": 5355,
"text": "Running the lint command"
},
{
"code": null,
"e": 5439,
"s": 5380,
"text": "Some errors are auto-fixed by running the lint:fix command"
},
{
"code": null,
"e": 5454,
"s": 5439,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 5459,
"s": 5454,
"text": "JSON"
},
{
"code": null,
"e": 5475,
"s": 5459,
"text": "React-Questions"
},
{
"code": null,
"e": 5485,
"s": 5475,
"text": "Blogathon"
},
{
"code": null,
"e": 5493,
"s": 5485,
"text": "ReactJS"
},
{
"code": null,
"e": 5510,
"s": 5493,
"text": "Web Technologies"
},
{
"code": null,
"e": 5608,
"s": 5510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5649,
"s": 5608,
"text": "Consensus Problem of Distributed Systems"
},
{
"code": null,
"e": 5679,
"s": 5649,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 5727,
"s": 5679,
"text": "Changing CSS styling with React onClick() Event"
},
{
"code": null,
"e": 5779,
"s": 5727,
"text": "How to parse JSON Data into React Table Component ?"
},
{
"code": null,
"e": 5814,
"s": 5779,
"text": "How to write comments in ReactJS ?"
},
{
"code": null,
"e": 5866,
"s": 5814,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 5885,
"s": 5866,
"text": "ReactJS setState()"
},
{
"code": null,
"e": 5926,
"s": 5885,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 5965,
"s": 5926,
"text": "How to do crud operations in ReactJS ?"
}
] |
Important differences between Python 2.x and Python 3.x with examples
|
01 Mar, 2021
Division operator
print function
Unicode
xrange
Error Handling
_future_ module
Division operator
If we are porting our code or executing python 3.x code in python 2.x, it can be dangerous if integer division changes go unnoticed (since it doesn’t raise any error). It is preferred to use the floating value (like 7.0/5 or 7/5.0) to get the expected result when porting our code.
Python
print 7 / 5 print -7 / 5 ''' Output in Python 2.x 1 -2 Output in Python 3.x : 1.4 -1.4 # Refer below link for details # https://www.geeksforgeeks.org/division-operator-in-python/ '''
print function
This is the most well-known change. In this, the print keyword in Python 2.x is replaced by the print() function in Python 3.x. However, parentheses work in Python 2 if space is added after the print keyword because the interpreter evaluates it as an expression.
Python
print 'Hello, Geeks' # Python 3.x doesn't support print('Hope You like these facts') ''' Output in Python 2.x : Hello, Geeks Hope You like these facts Output in Python 3.x : File "a.py", line 1 print 'Hello, Geeks' ^ SyntaxError: invalid syntax Refer below link for details https://www.geeksforgeeks.org/g-fact-25-print-single-multiple-variable-python/ '''
As we can see, if we use parentheses in python 2.x then there is no issue but if we don’t use parentheses in python 3.x, we get SyntaxError.
Unicode:
In Python 2, an implicit str type is ASCII. But in Python 3.x implicit str type is Unicode.
Python
print(type('default string ')) print(type(b'string with b ')) ''' Output in Python 2.x (Bytes is same as str) <type 'str'> <type 'str'> Output in Python 3.x (Bytes and str are different) <class 'str'> <class 'bytes'> '''
Python 2.x also supports Unicode
Python
print(type('default string ')) print(type(u'string with b ')) ''' Output in Python 2.x (Unicode and str are different) <type 'str'> <type 'unicode'> Output in Python 3.x (Unicode and str are same) <class 'str'> <class 'str'> '''
xrange:
xrange() of Python 2.x doesn’t exist in Python 3.x. In Python 2.x, range returns a list i.e. range(3) returns [0, 1, 2] while xrange returns a xrange object i. e., xrange(3) returns iterator object which works similar to Java iterator and generates number when needed. If we need to iterate over the same sequence multiple times, we prefer range() as range provides a static list. xrange() reconstructs the sequence every time. xrange() doesn’t support slices and other list methods. The advantage of xrange() is, it saves memory when the task is to iterate over a large range. In Python 3.x, the range function now does what xrange does in Python 2.x, so to keep our code portable, we might want to stick to using a range instead. So Python 3.x’s range function is xrange from Python 2.x.
Python
for x in xrange(1, 5): print(x), for x in range(1, 5): print(x), ''' Output in Python 2.x 1 2 3 4 1 2 3 4 Output in Python 3.x NameError: name 'xrange' is not defined '''
Error Handling:
There is a small change in error handling in both versions. In python 3.x, ‘as’ keyword is required.
Python
try: trying_to_check_error except NameError, err: print err, 'Error Caused' # Would not work in Python 3.x ''' Output in Python 2.x: name 'trying_to_check_error' is not defined Error Caused Output in Python 3.x : File "a.py", line 3 except NameError, err: ^ SyntaxError: invalid syntax '''
Python
try: trying_to_check_error except NameError as err: # 'as' is needed in Python 3.x print (err, 'Error Caused') ''' Output in Python 2.x: (NameError("name 'trying_to_check_error' is not defined",), 'Error Caused') Output in Python 3.x : name 'trying_to_check_error' is not defined Error Caused '''
__future__ module:
This is basically not a difference between the two versions, but a useful thing to mention here. The idea of the __future__ module is to help migrate to Python 3.x. If we are planning to have Python 3.x support in our 2.x code, we can use _future_ imports in our code. For example, in the Python 2.x code below, we use Python 3.x’s integer division behavior using the __future__ module.
Python
# In below python 2.x code, division works # same as Python 3.x because we use __future__ from __future__ import division print 7 / 5 print -7 / 5
Output :
1.4
-1.4
Another example where we use brackets in Python 2.x using __future__ module:
Python
from __future__ import print_function print('GeeksforGeeks')
Output:
GeeksforGeeks
Refer to this for more details of the __future__ module.
This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
priteshkanani
lalitshankarch
vaibhavsinghtanwar
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
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 ?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Mar, 2021"
},
{
"code": null,
"e": 70,
"s": 52,
"text": "Division operator"
},
{
"code": null,
"e": 85,
"s": 70,
"text": "print function"
},
{
"code": null,
"e": 93,
"s": 85,
"text": "Unicode"
},
{
"code": null,
"e": 100,
"s": 93,
"text": "xrange"
},
{
"code": null,
"e": 115,
"s": 100,
"text": "Error Handling"
},
{
"code": null,
"e": 131,
"s": 115,
"text": "_future_ module"
},
{
"code": null,
"e": 149,
"s": 131,
"text": "Division operator"
},
{
"code": null,
"e": 433,
"s": 149,
"text": "If we are porting our code or executing python 3.x code in python 2.x, it can be dangerous if integer division changes go unnoticed (since it doesn’t raise any error). It is preferred to use the floating value (like 7.0/5 or 7/5.0) to get the expected result when porting our code. "
},
{
"code": null,
"e": 440,
"s": 433,
"text": "Python"
},
{
"code": "print 7 / 5 print -7 / 5 ''' Output in Python 2.x 1 -2 Output in Python 3.x : 1.4 -1.4 # Refer below link for details # https://www.geeksforgeeks.org/division-operator-in-python/ '''",
"e": 635,
"s": 440,
"text": null
},
{
"code": null,
"e": 650,
"s": 635,
"text": "print function"
},
{
"code": null,
"e": 915,
"s": 650,
"text": "This is the most well-known change. In this, the print keyword in Python 2.x is replaced by the print() function in Python 3.x. However, parentheses work in Python 2 if space is added after the print keyword because the interpreter evaluates it as an expression. "
},
{
"code": null,
"e": 922,
"s": 915,
"text": "Python"
},
{
"code": "print 'Hello, Geeks' # Python 3.x doesn't support print('Hope You like these facts') ''' Output in Python 2.x : Hello, Geeks Hope You like these facts Output in Python 3.x : File \"a.py\", line 1 print 'Hello, Geeks' ^ SyntaxError: invalid syntax Refer below link for details https://www.geeksforgeeks.org/g-fact-25-print-single-multiple-variable-python/ '''",
"e": 1323,
"s": 922,
"text": null
},
{
"code": null,
"e": 1466,
"s": 1323,
"text": "As we can see, if we use parentheses in python 2.x then there is no issue but if we don’t use parentheses in python 3.x, we get SyntaxError. "
},
{
"code": null,
"e": 1475,
"s": 1466,
"text": "Unicode:"
},
{
"code": null,
"e": 1569,
"s": 1475,
"text": "In Python 2, an implicit str type is ASCII. But in Python 3.x implicit str type is Unicode. "
},
{
"code": null,
"e": 1576,
"s": 1569,
"text": "Python"
},
{
"code": "print(type('default string ')) print(type(b'string with b ')) ''' Output in Python 2.x (Bytes is same as str) <type 'str'> <type 'str'> Output in Python 3.x (Bytes and str are different) <class 'str'> <class 'bytes'> '''",
"e": 1805,
"s": 1576,
"text": null
},
{
"code": null,
"e": 1840,
"s": 1805,
"text": "Python 2.x also supports Unicode "
},
{
"code": null,
"e": 1847,
"s": 1840,
"text": "Python"
},
{
"code": "print(type('default string ')) print(type(u'string with b ')) ''' Output in Python 2.x (Unicode and str are different) <type 'str'> <type 'unicode'> Output in Python 3.x (Unicode and str are same) <class 'str'> <class 'str'> '''",
"e": 2084,
"s": 1847,
"text": null
},
{
"code": null,
"e": 2092,
"s": 2084,
"text": "xrange:"
},
{
"code": null,
"e": 2884,
"s": 2092,
"text": "xrange() of Python 2.x doesn’t exist in Python 3.x. In Python 2.x, range returns a list i.e. range(3) returns [0, 1, 2] while xrange returns a xrange object i. e., xrange(3) returns iterator object which works similar to Java iterator and generates number when needed. If we need to iterate over the same sequence multiple times, we prefer range() as range provides a static list. xrange() reconstructs the sequence every time. xrange() doesn’t support slices and other list methods. The advantage of xrange() is, it saves memory when the task is to iterate over a large range. In Python 3.x, the range function now does what xrange does in Python 2.x, so to keep our code portable, we might want to stick to using a range instead. So Python 3.x’s range function is xrange from Python 2.x. "
},
{
"code": null,
"e": 2891,
"s": 2884,
"text": "Python"
},
{
"code": "for x in xrange(1, 5): print(x), for x in range(1, 5): print(x), ''' Output in Python 2.x 1 2 3 4 1 2 3 4 Output in Python 3.x NameError: name 'xrange' is not defined '''",
"e": 3082,
"s": 2891,
"text": null
},
{
"code": null,
"e": 3098,
"s": 3082,
"text": "Error Handling:"
},
{
"code": null,
"e": 3201,
"s": 3098,
"text": "There is a small change in error handling in both versions. In python 3.x, ‘as’ keyword is required. "
},
{
"code": null,
"e": 3208,
"s": 3201,
"text": "Python"
},
{
"code": "try: trying_to_check_error except NameError, err: print err, 'Error Caused' # Would not work in Python 3.x ''' Output in Python 2.x: name 'trying_to_check_error' is not defined Error Caused Output in Python 3.x : File \"a.py\", line 3 except NameError, err: ^ SyntaxError: invalid syntax '''",
"e": 3540,
"s": 3208,
"text": null
},
{
"code": null,
"e": 3547,
"s": 3540,
"text": "Python"
},
{
"code": "try: trying_to_check_error except NameError as err: # 'as' is needed in Python 3.x print (err, 'Error Caused') ''' Output in Python 2.x: (NameError(\"name 'trying_to_check_error' is not defined\",), 'Error Caused') Output in Python 3.x : name 'trying_to_check_error' is not defined Error Caused '''",
"e": 3862,
"s": 3547,
"text": null
},
{
"code": null,
"e": 3881,
"s": 3862,
"text": "__future__ module:"
},
{
"code": null,
"e": 4270,
"s": 3881,
"text": "This is basically not a difference between the two versions, but a useful thing to mention here. The idea of the __future__ module is to help migrate to Python 3.x. If we are planning to have Python 3.x support in our 2.x code, we can use _future_ imports in our code. For example, in the Python 2.x code below, we use Python 3.x’s integer division behavior using the __future__ module. "
},
{
"code": null,
"e": 4277,
"s": 4270,
"text": "Python"
},
{
"code": "# In below python 2.x code, division works # same as Python 3.x because we use __future__ from __future__ import division print 7 / 5 print -7 / 5",
"e": 4429,
"s": 4277,
"text": null
},
{
"code": null,
"e": 4440,
"s": 4429,
"text": "Output : "
},
{
"code": null,
"e": 4452,
"s": 4440,
"text": "1.4 \n\n-1.4 "
},
{
"code": null,
"e": 4531,
"s": 4452,
"text": "Another example where we use brackets in Python 2.x using __future__ module: "
},
{
"code": null,
"e": 4538,
"s": 4531,
"text": "Python"
},
{
"code": "from __future__ import print_function print('GeeksforGeeks')",
"e": 4607,
"s": 4538,
"text": null
},
{
"code": null,
"e": 4617,
"s": 4607,
"text": "Output: "
},
{
"code": null,
"e": 4632,
"s": 4617,
"text": "GeeksforGeeks "
},
{
"code": null,
"e": 4691,
"s": 4632,
"text": "Refer to this for more details of the __future__ module. "
},
{
"code": null,
"e": 4958,
"s": 4691,
"text": "This article is contributed by Arpit Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 5085,
"s": 4958,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5099,
"s": 5085,
"text": "priteshkanani"
},
{
"code": null,
"e": 5114,
"s": 5099,
"text": "lalitshankarch"
},
{
"code": null,
"e": 5133,
"s": 5114,
"text": "vaibhavsinghtanwar"
},
{
"code": null,
"e": 5140,
"s": 5133,
"text": "Python"
},
{
"code": null,
"e": 5238,
"s": 5140,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5266,
"s": 5238,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5316,
"s": 5266,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5338,
"s": 5316,
"text": "Python map() function"
},
{
"code": null,
"e": 5382,
"s": 5338,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 5400,
"s": 5382,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5442,
"s": 5400,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5464,
"s": 5442,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5499,
"s": 5464,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5525,
"s": 5499,
"text": "Python String | replace()"
}
] |
Frequency count of multiple variables in R Dataframe
|
30 May, 2021
A data frame may contain repeated or missing values. Each column may contain any number of duplicate or repeated instances of the same variable. Data statistics and analysis mostly rely on the task of computing the frequency or count of the number of instances a particular variable contains within each column and in R Programming Language, there are multiple ways to do so.
Method 1: Using apply() method
The apply method in base R returns a vector or array or list of values obtained by applying a function to margins of an array or matrix. It has the following syntax :
apply ( df , axis , FUN)
The table() method takes the cross-classifying factors belonging in a vector to build a contingency table of the counts at each combination of factor levels. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table. This method can be used to cross-tabulation and statistical analysis.
Example 1: Here we return column-wise for all the columns of the data frame, indicating the frequencies of the variable value instances occurring in that particular column.
R
set.seed(1) # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE), col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE) ) print ("Original DataFrame")print (data_frame) # calculating frequency of multiple variablesmod_frame <- apply(data_frame, 2 , table)print ("Frequencies")print (mod_frame)
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 a b b a
2 c c b b
3 a c c a
4 b a a a
5 a a c b
6 c a a b
7 c b a b
8 b b a a
[1] "Frequencies"
$col1
a b c
3 2 3
$col2
a b c
3 3 2
$col3
a b c
4 2 2
$col4
a b
4 4
Example 2: Only for specific columns also, by specifying the desired column names in the form of a vector and addressing them using data frame indexing df[cols]. The output is returned to the form of a table, where column headings are column names desired and row heading are the different values found.
R
set.seed(1) # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE) ) print ("Original DataFrame")print (data_frame)sel_col <- c("col1", "col3") # calculating frequency of multiple variablesmod_frame <- apply(data_frame[sel_col], 2, table)print ("Frequencies")print (mod_frame)
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 a b b a
2 c c b b
3 a c c a
4 b a a a
5 a a c b
6 c a a b
7 c b a b
8 b b a a
[1] "Frequencies"
col1 col3
a 3 4
b 2 2
c 3 2
Method 2: Using plyr package
The plyr package is used preferably to experiment with the data, that is, create, modify and delete the columns of the data frame, on subjecting them to multiple conditions and user-defined functions. It can be downloaded and loaded into the workspace using the following command :
install.packages("lpyr")
The count() method of this package is used to return a frequency count of the variable contained in the specified columns respectively. It may contain multiple columns, and all the possible combinations are generated as per the cross join. The unique combinations out of the them are returned along with their respective counts.
count (df , args..) , where args.. are the column names
The output returns only the column specified in the count() method.
R
library("plyr")set.seed(1) # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print ("Original DataFrame")print (data_frame)sel_col <- c("col1") # calculating frequency of multiple variablesmod_frame <- count(data_frame, sel_col)print ("Frequencies")print (mod_frame)
Output:
[1] "Original DataFrame"
col1 col2 col3 col4
1 a b b a
2 c c b b
3 a c c a
4 b a a a
5 a a c b
6 c a a b
7 c b a b
8 b b a a
[1] "Frequencies"
col1 freq
1 a 3
2 b 2
3 c 3
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 405,
"s": 28,
"text": "A data frame may contain repeated or missing values. Each column may contain any number of duplicate or repeated instances of the same variable. Data statistics and analysis mostly rely on the task of computing the frequency or count of the number of instances a particular variable contains within each column and in R Programming Language, there are multiple ways to do so. "
},
{
"code": null,
"e": 436,
"s": 405,
"text": "Method 1: Using apply() method"
},
{
"code": null,
"e": 604,
"s": 436,
"text": "The apply method in base R returns a vector or array or list of values obtained by applying a function to margins of an array or matrix. It has the following syntax : "
},
{
"code": null,
"e": 629,
"s": 604,
"text": "apply ( df , axis , FUN)"
},
{
"code": null,
"e": 1103,
"s": 629,
"text": "The table() method takes the cross-classifying factors belonging in a vector to build a contingency table of the counts at each combination of factor levels. A contingency table is basically a tabulation of the counts and/or percentages for multiple variables. It excludes the counting of any missing values from the factor variable supplied to the method. The output returned is in the form of a table. This method can be used to cross-tabulation and statistical analysis."
},
{
"code": null,
"e": 1277,
"s": 1103,
"text": "Example 1: Here we return column-wise for all the columns of the data frame, indicating the frequencies of the variable value instances occurring in that particular column. "
},
{
"code": null,
"e": 1279,
"s": 1277,
"text": "R"
},
{
"code": "set.seed(1) # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE), col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE) ) print (\"Original DataFrame\")print (data_frame) # calculating frequency of multiple variablesmod_frame <- apply(data_frame, 2 , table)print (\"Frequencies\")print (mod_frame)",
"e": 1964,
"s": 1279,
"text": null
},
{
"code": null,
"e": 1972,
"s": 1964,
"text": "Output:"
},
{
"code": null,
"e": 2313,
"s": 1972,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 col4 \n1 a b b a \n2 c c b b \n3 a c c a \n4 b a a a \n5 a a c b \n6 c a a b \n7 c b a b \n8 b b a a \n[1] \"Frequencies\" \n$col1\n\na b c \n3 2 3 \n\n$col2 \na b c \n3 3 2 \n $col3 \na b c \n4 2 2 \n$col4 \na b \n4 4 "
},
{
"code": null,
"e": 2618,
"s": 2313,
"text": "Example 2: Only for specific columns also, by specifying the desired column names in the form of a vector and addressing them using data frame indexing df[cols]. The output is returned to the form of a table, where column headings are column names desired and row heading are the different values found. "
},
{
"code": null,
"e": 2620,
"s": 2618,
"text": "R"
},
{
"code": "set.seed(1) # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE) ) print (\"Original DataFrame\")print (data_frame)sel_col <- c(\"col1\", \"col3\") # calculating frequency of multiple variablesmod_frame <- apply(data_frame[sel_col], 2, table)print (\"Frequencies\")print (mod_frame)",
"e": 3344,
"s": 2620,
"text": null
},
{
"code": null,
"e": 3352,
"s": 3344,
"text": "Output:"
},
{
"code": null,
"e": 3642,
"s": 3352,
"text": "[1] \"Original DataFrame\"\ncol1 col2 col3 col4\n1 a b b a\n2 c c b b\n3 a c c a\n4 b a a a\n5 a a c b\n6 c a a b\n7 c b a b\n8 b b a a \n[1] \"Frequencies\" \ncol1 col3 \na 3 4 \nb 2 2 \nc 3 2"
},
{
"code": null,
"e": 3671,
"s": 3642,
"text": "Method 2: Using plyr package"
},
{
"code": null,
"e": 3953,
"s": 3671,
"text": "The plyr package is used preferably to experiment with the data, that is, create, modify and delete the columns of the data frame, on subjecting them to multiple conditions and user-defined functions. It can be downloaded and loaded into the workspace using the following command :"
},
{
"code": null,
"e": 3978,
"s": 3953,
"text": "install.packages(\"lpyr\")"
},
{
"code": null,
"e": 4308,
"s": 3978,
"text": "The count() method of this package is used to return a frequency count of the variable contained in the specified columns respectively. It may contain multiple columns, and all the possible combinations are generated as per the cross join. The unique combinations out of the them are returned along with their respective counts. "
},
{
"code": null,
"e": 4364,
"s": 4308,
"text": "count (df , args..) , where args.. are the column names"
},
{
"code": null,
"e": 4433,
"s": 4364,
"text": "The output returns only the column specified in the count() method. "
},
{
"code": null,
"e": 4435,
"s": 4433,
"text": "R"
},
{
"code": "library(\"plyr\")set.seed(1) # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:3], 8, replace = TRUE) , col2 = sample(letters[1:3], 8, replace = TRUE), col3 = sample(letters[1:3], 8, replace = TRUE), col4 = sample(letters[1:3], 8, replace = TRUE)) print (\"Original DataFrame\")print (data_frame)sel_col <- c(\"col1\") # calculating frequency of multiple variablesmod_frame <- count(data_frame, sel_col)print (\"Frequencies\")print (mod_frame)",
"e": 5130,
"s": 4435,
"text": null
},
{
"code": null,
"e": 5138,
"s": 5130,
"text": "Output:"
},
{
"code": null,
"e": 5429,
"s": 5138,
"text": "[1] \"Original DataFrame\"\ncol1 col2 col3 col4\n1 a b b a\n2 c c b b\n3 a c c a\n4 b a a a\n5 a a c b\n6 c a a b\n7 c b a b\n8 b b a a \n[1] \"Frequencies\"\n col1 freq \n1 a 3 \n2 b 2 \n3 c 3"
},
{
"code": null,
"e": 5436,
"s": 5429,
"text": "Picked"
},
{
"code": null,
"e": 5457,
"s": 5436,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 5469,
"s": 5457,
"text": "R-DataFrame"
},
{
"code": null,
"e": 5480,
"s": 5469,
"text": "R Language"
},
{
"code": null,
"e": 5491,
"s": 5480,
"text": "R Programs"
}
] |
time.strftime() function in Python
|
11 Nov, 2021
As time module provides various time-related functions. So it is necessary to import the time module otherwise it will through error because of the definition of time.strftime(format[, t]) is present in time module.time.strftime(format[, t]) function convert a tuprl or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. The format must be a string. ValueError is raised if any field in t is outside of the allowed range.Note: 0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one.
Syntax: time.strftime(format[, t])Parameters : t – time in number of seconds to be formatted format – This is of string type. i.e. the directives can be embedded in the format string.Return value: None
There are many directives that can be embedded in the format string, you can refer them here. Notes:
When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.
The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons.
When used with the strptime() function, %U and %W are only used in calculations when the day of the week and the year are specified.
Below is the implementation:
Python3
# Program To show How can we use different derivatives# Multiple at a time and single at a time # importing the srtftime() and gmtime()# if not used the gm time, time changes# to the local time from time import gmtime, strftime # using simple format of showing times = strftime("%a, %d %b %Y %H:%M:%S + 1010", gmtime())print("Example 1:", s) print() # only change in this is the full names# and the representations = strftime("%A, %D %B %Y %H:%M:%S + 0000", gmtime())print("Example 2:", s) print() # this will show you the preferred date time formats = strftime("%c")print("Example 3:", s) print() # this will tell about the centuriess = strftime("%C")print("Example 4:", s) print() # MOTY: month of the year# DOTY: Day of the year# Simple representation# % n - new lines = strftime("%A, %D %B %Y, %r, %nMOTY:%m %nDOTY:% j")print("Example 5:", s) print() # % R - time in 24 hour notations = strftime(" %R ")print("Example 6:", s) print() # % H - hour, using a 24-hour clock (00 to 23) in Example 1, 2, 3# % I - hour, using a 12-hour clock (01 to 12)s = strftime("%a, %d %b %Y %I:%M:%S + 0000", gmtime())print("Example 7:", s) print() # % T - current time, equal to % H:% M:% Ss = strftime("%r, %T ", gmtime())print("Example 8:", s) print() # % u an % U use (see difference)s = strftime("%r, %u, %U")print("Example 9:", s) print() # use of % V, % W, % ws = strftime("%r, %V, %W, %w")print("Example 10:", s) print() # use of % x, % X, % y, % Ys = strftime("%x, %X, %y, %Y")print("Example 11:", s) print() # use of % Z, % zs = strftime("%r, %z, %Z")print("Example 12:", s)
Example 1: Tue, 25 Jun 2019 10:09:52 + 1010
Example 2: Tuesday, 06/25/19 June 2019 10:09:52 + 0000
Example 3: Tue Jun 25 10:09:52 2019
Example 4: 20
Example 5: Tuesday, 06/25/19 June 2019, 10:09:52 AM,
MOTY:06
DOTY:% j
Example 6: 10:09
Example 7: Tue, 25 Jun 2019 10:09:52 + 0000
Example 8: 10:09:52 AM, 10:09:52
Example 9: 10:09:52 AM, 2, 25
Example 10: 10:09:52 AM, 26, 25, 2
Example 11: 06/25/19, 10:09:52, 19, 2019
Example 12: 10:09:52 AM, +0000, UTC
ManasChhabra2
sagar0719kumar
sooda367
kalrap615
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 722,
"s": 28,
"text": "As time module provides various time-related functions. So it is necessary to import the time module otherwise it will through error because of the definition of time.strftime(format[, t]) is present in time module.time.strftime(format[, t]) function convert a tuprl or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. The format must be a string. ValueError is raised if any field in t is outside of the allowed range.Note: 0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one. "
},
{
"code": null,
"e": 924,
"s": 722,
"text": "Syntax: time.strftime(format[, t])Parameters : t – time in number of seconds to be formatted format – This is of string type. i.e. the directives can be embedded in the format string.Return value: None"
},
{
"code": null,
"e": 1026,
"s": 924,
"text": "There are many directives that can be embedded in the format string, you can refer them here. Notes: "
},
{
"code": null,
"e": 1165,
"s": 1026,
"text": "When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour."
},
{
"code": null,
"e": 1302,
"s": 1165,
"text": "The range really is 0 to 61; value 60 is valid in timestamps representing leap seconds and value 61 is supported for historical reasons."
},
{
"code": null,
"e": 1435,
"s": 1302,
"text": "When used with the strptime() function, %U and %W are only used in calculations when the day of the week and the year are specified."
},
{
"code": null,
"e": 1465,
"s": 1435,
"text": "Below is the implementation: "
},
{
"code": null,
"e": 1473,
"s": 1465,
"text": "Python3"
},
{
"code": "# Program To show How can we use different derivatives# Multiple at a time and single at a time # importing the srtftime() and gmtime()# if not used the gm time, time changes# to the local time from time import gmtime, strftime # using simple format of showing times = strftime(\"%a, %d %b %Y %H:%M:%S + 1010\", gmtime())print(\"Example 1:\", s) print() # only change in this is the full names# and the representations = strftime(\"%A, %D %B %Y %H:%M:%S + 0000\", gmtime())print(\"Example 2:\", s) print() # this will show you the preferred date time formats = strftime(\"%c\")print(\"Example 3:\", s) print() # this will tell about the centuriess = strftime(\"%C\")print(\"Example 4:\", s) print() # MOTY: month of the year# DOTY: Day of the year# Simple representation# % n - new lines = strftime(\"%A, %D %B %Y, %r, %nMOTY:%m %nDOTY:% j\")print(\"Example 5:\", s) print() # % R - time in 24 hour notations = strftime(\" %R \")print(\"Example 6:\", s) print() # % H - hour, using a 24-hour clock (00 to 23) in Example 1, 2, 3# % I - hour, using a 12-hour clock (01 to 12)s = strftime(\"%a, %d %b %Y %I:%M:%S + 0000\", gmtime())print(\"Example 7:\", s) print() # % T - current time, equal to % H:% M:% Ss = strftime(\"%r, %T \", gmtime())print(\"Example 8:\", s) print() # % u an % U use (see difference)s = strftime(\"%r, %u, %U\")print(\"Example 9:\", s) print() # use of % V, % W, % ws = strftime(\"%r, %V, %W, %w\")print(\"Example 10:\", s) print() # use of % x, % X, % y, % Ys = strftime(\"%x, %X, %y, %Y\")print(\"Example 11:\", s) print() # use of % Z, % zs = strftime(\"%r, %z, %Z\")print(\"Example 12:\", s)",
"e": 3044,
"s": 1473,
"text": null
},
{
"code": null,
"e": 3515,
"s": 3044,
"text": "Example 1: Tue, 25 Jun 2019 10:09:52 + 1010\n\nExample 2: Tuesday, 06/25/19 June 2019 10:09:52 + 0000\n\nExample 3: Tue Jun 25 10:09:52 2019\n\nExample 4: 20\n\nExample 5: Tuesday, 06/25/19 June 2019, 10:09:52 AM, \nMOTY:06 \nDOTY:% j\n\nExample 6: 10:09 \n\nExample 7: Tue, 25 Jun 2019 10:09:52 + 0000\n\nExample 8: 10:09:52 AM, 10:09:52 \n\nExample 9: 10:09:52 AM, 2, 25\n\nExample 10: 10:09:52 AM, 26, 25, 2\n\nExample 11: 06/25/19, 10:09:52, 19, 2019\n\nExample 12: 10:09:52 AM, +0000, UTC"
},
{
"code": null,
"e": 3531,
"s": 3517,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 3546,
"s": 3531,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 3555,
"s": 3546,
"text": "sooda367"
},
{
"code": null,
"e": 3565,
"s": 3555,
"text": "kalrap615"
},
{
"code": null,
"e": 3582,
"s": 3565,
"text": "Python-Functions"
},
{
"code": null,
"e": 3589,
"s": 3582,
"text": "Python"
},
{
"code": null,
"e": 3687,
"s": 3589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3705,
"s": 3687,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3747,
"s": 3705,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3769,
"s": 3747,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3801,
"s": 3769,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3830,
"s": 3801,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3857,
"s": 3830,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3878,
"s": 3857,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3914,
"s": 3878,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3937,
"s": 3914,
"text": "Introduction To PYTHON"
}
] |
Convert String to Double in Java
|
22 Apr, 2022
Here, we will convert String to Double in Java. There are 3 methods for this conversion as mentioned below:
Illustration:
Input : String = "20.156"
Output: 20.156
Input : String = "456.21"
Output : 456.21
Using parseDouble() method of Double classUsing valueOf() method of Double classUsing constructor of Double class
Using parseDouble() method of Double class
Using valueOf() method of Double class
Using constructor of Double class
Syntax:
double str1 = Double.parseDouble(str);
Example:
Java
// Java program to convert String to Double// Using parseDouble() Method of Double Class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Create and initializing a string String str = "2033.12244"; // Converting the above string into Double // using parseDouble() Method double str1 = Double.parseDouble(str); // Printing string as Double type System.out.println(str1); }}
2033.12244
Syntax:
double str1 = Double.valueOf(str);
Example:
Java
// Java program to convert String to Double// using valueOf() Method of Double Class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating and initializing a string String str = "2033.12244"; // Converting the above string to Double type double str1 = Double.valueOf(str); // Printing above string as double type System.out.println(str1); }}
2033.12244
Syntax:
Double str1 = new Double(str);
Example:
Java
// Java program to convert String to Double// Using Constructor of Double class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating and initializing a string String str = "2033.12244"; // Converting above string into double type Double str1 = new Double(str); // print above string as Double type System.out.println(str1); }}
2033.12244
solankimayank
Java-Double
Java-String-Programs
Java-Strings
Technical Scripter 2018
Java
Technical Scripter
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 161,
"s": 53,
"text": "Here, we will convert String to Double in Java. There are 3 methods for this conversion as mentioned below:"
},
{
"code": null,
"e": 177,
"s": 161,
"text": "Illustration: "
},
{
"code": null,
"e": 218,
"s": 177,
"text": "Input : String = \"20.156\"\nOutput: 20.156"
},
{
"code": null,
"e": 261,
"s": 218,
"text": "Input : String = \"456.21\"\nOutput : 456.21"
},
{
"code": null,
"e": 376,
"s": 261,
"text": "Using parseDouble() method of Double classUsing valueOf() method of Double classUsing constructor of Double class "
},
{
"code": null,
"e": 419,
"s": 376,
"text": "Using parseDouble() method of Double class"
},
{
"code": null,
"e": 458,
"s": 419,
"text": "Using valueOf() method of Double class"
},
{
"code": null,
"e": 493,
"s": 458,
"text": "Using constructor of Double class "
},
{
"code": null,
"e": 502,
"s": 493,
"text": "Syntax: "
},
{
"code": null,
"e": 542,
"s": 502,
"text": "double str1 = Double.parseDouble(str); "
},
{
"code": null,
"e": 551,
"s": 542,
"text": "Example:"
},
{
"code": null,
"e": 556,
"s": 551,
"text": "Java"
},
{
"code": "// Java program to convert String to Double// Using parseDouble() Method of Double Class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Create and initializing a string String str = \"2033.12244\"; // Converting the above string into Double // using parseDouble() Method double str1 = Double.parseDouble(str); // Printing string as Double type System.out.println(str1); }}",
"e": 1043,
"s": 556,
"text": null
},
{
"code": null,
"e": 1054,
"s": 1043,
"text": "2033.12244"
},
{
"code": null,
"e": 1064,
"s": 1056,
"text": "Syntax:"
},
{
"code": null,
"e": 1100,
"s": 1064,
"text": "double str1 = Double.valueOf(str); "
},
{
"code": null,
"e": 1109,
"s": 1100,
"text": "Example:"
},
{
"code": null,
"e": 1114,
"s": 1109,
"text": "Java"
},
{
"code": "// Java program to convert String to Double// using valueOf() Method of Double Class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating and initializing a string String str = \"2033.12244\"; // Converting the above string to Double type double str1 = Double.valueOf(str); // Printing above string as double type System.out.println(str1); }}",
"e": 1567,
"s": 1114,
"text": null
},
{
"code": null,
"e": 1578,
"s": 1567,
"text": "2033.12244"
},
{
"code": null,
"e": 1588,
"s": 1580,
"text": "Syntax:"
},
{
"code": null,
"e": 1620,
"s": 1588,
"text": "Double str1 = new Double(str); "
},
{
"code": null,
"e": 1629,
"s": 1620,
"text": "Example:"
},
{
"code": null,
"e": 1634,
"s": 1629,
"text": "Java"
},
{
"code": "// Java program to convert String to Double// Using Constructor of Double class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating and initializing a string String str = \"2033.12244\"; // Converting above string into double type Double str1 = new Double(str); // print above string as Double type System.out.println(str1); }}",
"e": 2073,
"s": 1634,
"text": null
},
{
"code": null,
"e": 2084,
"s": 2073,
"text": "2033.12244"
},
{
"code": null,
"e": 2100,
"s": 2086,
"text": "solankimayank"
},
{
"code": null,
"e": 2112,
"s": 2100,
"text": "Java-Double"
},
{
"code": null,
"e": 2133,
"s": 2112,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 2146,
"s": 2133,
"text": "Java-Strings"
},
{
"code": null,
"e": 2170,
"s": 2146,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2175,
"s": 2170,
"text": "Java"
},
{
"code": null,
"e": 2194,
"s": 2175,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2207,
"s": 2194,
"text": "Java-Strings"
},
{
"code": null,
"e": 2212,
"s": 2207,
"text": "Java"
},
{
"code": null,
"e": 2310,
"s": 2212,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2361,
"s": 2310,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2392,
"s": 2361,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2411,
"s": 2392,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2441,
"s": 2411,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2459,
"s": 2441,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2474,
"s": 2459,
"text": "Stream In Java"
},
{
"code": null,
"e": 2494,
"s": 2474,
"text": "Collections in Java"
},
{
"code": null,
"e": 2526,
"s": 2494,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2550,
"s": 2526,
"text": "Singleton Class in Java"
}
] |
Sum of elements whose square root is present in the array
|
02 Jun, 2021
Given an array arr[], the task is to find the sum of all those elements from the given array whose square root is present in the same array.
Examples:
Input: arr[] = {1, 2, 3, 4, 6, 9, 10} Output: 13 4 and 9 are the only numbers whose square roots 2 and 3 are present in the array
Input: arr[] = {4, 2, 36, 6, 10, 100} Output: 140
Naive Approach: To find the sum of elements whose square root is present in the given array, check for square root of every element by iterating from arr[0] to arr[n] which will do the job but in O(n*n) complexity.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the sum of all the elements// from the array whose square root is present// in the same array #include<bits/stdc++.h>using namespace std; // Function to return the required sumint getSum(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) { double sqrtCurrent = sqrt(arr[i]); for (int j = 0; j < n; j++) { double x = arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } // Driver code int main() { int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = sizeof(arr)/sizeof(arr[0]); cout<<(getSum(arr, n)); }// This code is contributed by// Surendra_Gangwar
// Java program to find the sum of all the elements// from the array whose square root is present// in the same arraypublic class GFG { // Function to return the required sum public static int getSum(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) { double sqrtCurrent = Math.sqrt(arr[i]); for (int j = 0; j < n; j++) { double x = arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } // Driver code public static void main(String args[]) { int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.length; System.out.println(getSum(arr, n)); }}
# Python3 program to find the sum of# all the elements from the array# whose square root is present in# the same arrayimport math # Function to return the required sumdef getSum(arr, n): sum = 0 for i in range(0, n): sqrtCurrent = math.sqrt(arr[i]) for j in range(0, n): x = arr[j] # If sqrtCurrent is present in array if (x == sqrtCurrent): sum += (sqrtCurrent * sqrtCurrent) break return int(sum) # Driver codeif __name__ == '__main__': arr = [ 2, 4, 5, 6, 7, 8, 9, 3] n = len(arr) print(getSum(arr, n)) # This code is contributed# by 29AjayKumar
// C# program to find the sum of all the elements// from the array whose square root is present// in the same arrayusing System ; public class GFG { // Function to return the required sum public static float getSum(int []arr, int n) { float sum = 0; for (int i = 0; i < n; i++) { float sqrtCurrent = (float)Math.Sqrt(arr[i]); for (int j = 0; j < n; j++) { float x = (float)arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } // Driver code public static void Main() { int []arr = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.Length; Console.WriteLine(getSum(arr, n)); } // This code is contributed by Ryuga}
<?php// PHP program to find the sum of all// the elements from the array whose// square root is present in the same array // Function to return the required sumfunction getSum(&$arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sqrtCurrent = sqrt($arr[$i]); for ($j = 0; $j < $n; $j++) { $x = $arr[$j]; // If sqrtCurrent is present in array if ($x == $sqrtCurrent) { $sum += ($sqrtCurrent * $sqrtCurrent); break; } } } return $sum;} // Driver code$arr = array(2, 4, 5, 6, 7, 8, 9, 3);$n = sizeof($arr);echo (getSum($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>
<script> // Javascript program to find the sum of all the elements // from the array whose square root is present // in the same array // Function to return the required sum function getSum(arr, n) { let sum = 0; for (let i = 0; i < n; i++) { let sqrtCurrent = Math.sqrt(arr[i]); for (let j = 0; j < n; j++) { let x = arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } let arr = [ 2, 4, 5, 6, 7, 8, 9, 3 ]; let n = arr.length; document.write(getSum(arr, n)); // This code is contributed by suresh07.</script>
13
Efficient Approach: We can create a HashSet of all the elements present in the array and than check for the square root of each element of the array in O(n) time.
Below is the implementation of the above approach:
C++
Java
C#
Python3
PHP
Javascript
// C++ program to find the sum of all the elements// from the array whose square root is present// in the same array#include<bits/stdc++.h>using namespace std; // Function to return the required sumint getSum(int arr[], int n){ int i, sum = 0; // Initialization of hash map set<int> hashSet; // Store each element in the hash map for (i = 0; i < n; i++) hashSet.insert(arr[i]); for (i = 0; i < n; i++) { double sqrtCurrent = sqrt(arr[i]); // If sqrtCurrent is a decimal number if (floor(sqrtCurrent) != ceil(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.find((int)sqrtCurrent) != hashSet.end()) { sum += (sqrtCurrent * sqrtCurrent); } } return sum;} // Driver codeint main(){ int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (getSum(arr, n)); return 0;} // This code is contributed by Rajput-Ji
// Java program to find the sum of all the elements// from the array whose square root is present// in the same array import java.util.*;public class GFG { // Function to return the required sum public static int getSum(int arr[], int n) { int i, sum = 0; // Initialization of hash map Set<Integer> hashSet = new HashSet<>(); // Store each element in the hash map for (i = 0; i < n; i++) hashSet.add(arr[i]); for (i = 0; i < n; i++) { double sqrtCurrent = Math.sqrt(arr[i]); // If sqrtCurrent is a decimal number if (Math.floor(sqrtCurrent) != Math.ceil(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.contains((int)sqrtCurrent)) { sum += (sqrtCurrent * sqrtCurrent); } } return sum; } // Driver code public static void main(String args[]) { int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.length; System.out.println(getSum(arr, n)); }}
// C# program to find the sum of all the elements// from the array whose square root is present// in the same arrayusing System;using System.Collections.Generic; class GFG{ // Function to return the required sum public static int getSum(int []arr, int n) { int i, sum = 0; // Initialization of hash map HashSet<int> hashSet = new HashSet<int>(); // Store each element in the hash map for (i = 0; i < n; i++) hashSet.Add(arr[i]); for (i = 0; i < n; i++) { double sqrtCurrent = Math.Sqrt(arr[i]); // If sqrtCurrent is a decimal number if (Math.Floor(sqrtCurrent) != Math.Ceiling(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.Contains((int)sqrtCurrent)) { sum += (int)(sqrtCurrent * sqrtCurrent); } } return sum; } // Driver code public static void Main(String []args) { int []arr = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.Length; Console.WriteLine(getSum(arr, n)); }} // This code contributed by Rajput-Ji
# Python3 program to find the sum of all the# elements from the array whose square# root is present in the same arrayimport math # Function to return the required sumdef getSum(arr, n): sum = 0; # Initialization of hash map hashSet = set(); # Store each element in the hash map for i in range(n): hashSet.add(arr[i]); for i in range(n): sqrtCurrent = math.sqrt(arr[i]); # If sqrtCurrent is a decimal number if (math.floor(sqrtCurrent) != math.ceil(sqrtCurrent)): continue; # If hash set contains sqrtCurrent if (int(sqrtCurrent) in hashSet): sum += int(sqrtCurrent * sqrtCurrent); return sum; # Driver codearr = [ 2, 4, 5, 6, 7, 8, 9, 3 ];n = len(arr);print(getSum(arr, n)); # This code is contributed by mits
<?php// PHP program to find the sum of all the// elements from the array whose square// root is present in the same array // Function to return the required sumfunction getSum($arr, $n){ $sum = 0; // Initialization of hash map $hashSet = array(); // Store each element in the hash map for ($i = 0; $i < $n; $i++) array_push($hashSet, $arr[$i]); $hashSet = array_unique($hashSet); for ($i = 0; $i < $n; $i++) { $sqrtCurrent = sqrt($arr[$i]); // If sqrtCurrent is a decimal number if (floor($sqrtCurrent) != ceil($sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (in_array((int)$sqrtCurrent, $hashSet)) { $sum += ($sqrtCurrent * $sqrtCurrent); } } return $sum;} // Driver code$arr = array( 2, 4, 5, 6, 7, 8, 9, 3 );$n = count($arr);print(getSum($arr, $n)); // This code is contributed by mits?>
<script> // Javascript program to find the sum of// all the elements from the array whose// square root is present in the same array // Function to return the required sumfunction getSum(arr, n){ let i, sum = 0; // Initialization of hash map let hashSet = new Set(); // Store each element in the hash map for(i = 0; i < n; i++) hashSet.add(arr[i]); for(i = 0; i < n; i++) { let sqrtCurrent = Math.sqrt(arr[i]); // If sqrtCurrent is a decimal number if (Math.floor(sqrtCurrent) != Math.ceil(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.has(sqrtCurrent)) { sum += (sqrtCurrent * sqrtCurrent); } } return sum;} // Driver codelet arr = [ 2, 4, 5, 6, 7, 8, 9, 3 ];let n = arr.length; document.write(getSum(arr, n)); // This code is contributed by unknown2108 </script>
13
SURENDRA_GANGWAR
ankthon
Shivi_Aggarwal
29AjayKumar
Rajput-Ji
Mithun Kumar
unknown2108
suresh07
Hash
HashSet
Arrays
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Jun, 2021"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "Given an array arr[], the task is to find the sum of all those elements from the given array whose square root is present in the same array."
},
{
"code": null,
"e": 180,
"s": 169,
"text": "Examples: "
},
{
"code": null,
"e": 310,
"s": 180,
"text": "Input: arr[] = {1, 2, 3, 4, 6, 9, 10} Output: 13 4 and 9 are the only numbers whose square roots 2 and 3 are present in the array"
},
{
"code": null,
"e": 362,
"s": 310,
"text": "Input: arr[] = {4, 2, 36, 6, 10, 100} Output: 140 "
},
{
"code": null,
"e": 577,
"s": 362,
"text": "Naive Approach: To find the sum of elements whose square root is present in the given array, check for square root of every element by iterating from arr[0] to arr[n] which will do the job but in O(n*n) complexity."
},
{
"code": null,
"e": 629,
"s": 577,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 633,
"s": 629,
"text": "C++"
},
{
"code": null,
"e": 638,
"s": 633,
"text": "Java"
},
{
"code": null,
"e": 646,
"s": 638,
"text": "Python3"
},
{
"code": null,
"e": 649,
"s": 646,
"text": "C#"
},
{
"code": null,
"e": 653,
"s": 649,
"text": "PHP"
},
{
"code": null,
"e": 664,
"s": 653,
"text": "Javascript"
},
{
"code": "// CPP program to find the sum of all the elements// from the array whose square root is present// in the same array #include<bits/stdc++.h>using namespace std; // Function to return the required sumint getSum(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) { double sqrtCurrent = sqrt(arr[i]); for (int j = 0; j < n; j++) { double x = arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } // Driver code int main() { int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = sizeof(arr)/sizeof(arr[0]); cout<<(getSum(arr, n)); }// This code is contributed by// Surendra_Gangwar",
"e": 1533,
"s": 664,
"text": null
},
{
"code": "// Java program to find the sum of all the elements// from the array whose square root is present// in the same arraypublic class GFG { // Function to return the required sum public static int getSum(int arr[], int n) { int sum = 0; for (int i = 0; i < n; i++) { double sqrtCurrent = Math.sqrt(arr[i]); for (int j = 0; j < n; j++) { double x = arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } // Driver code public static void main(String args[]) { int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.length; System.out.println(getSum(arr, n)); }}",
"e": 2375,
"s": 1533,
"text": null
},
{
"code": "# Python3 program to find the sum of# all the elements from the array# whose square root is present in# the same arrayimport math # Function to return the required sumdef getSum(arr, n): sum = 0 for i in range(0, n): sqrtCurrent = math.sqrt(arr[i]) for j in range(0, n): x = arr[j] # If sqrtCurrent is present in array if (x == sqrtCurrent): sum += (sqrtCurrent * sqrtCurrent) break return int(sum) # Driver codeif __name__ == '__main__': arr = [ 2, 4, 5, 6, 7, 8, 9, 3] n = len(arr) print(getSum(arr, n)) # This code is contributed# by 29AjayKumar",
"e": 3060,
"s": 2375,
"text": null
},
{
"code": "// C# program to find the sum of all the elements// from the array whose square root is present// in the same arrayusing System ; public class GFG { // Function to return the required sum public static float getSum(int []arr, int n) { float sum = 0; for (int i = 0; i < n; i++) { float sqrtCurrent = (float)Math.Sqrt(arr[i]); for (int j = 0; j < n; j++) { float x = (float)arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } // Driver code public static void Main() { int []arr = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.Length; Console.WriteLine(getSum(arr, n)); } // This code is contributed by Ryuga}",
"e": 3962,
"s": 3060,
"text": null
},
{
"code": "<?php// PHP program to find the sum of all// the elements from the array whose// square root is present in the same array // Function to return the required sumfunction getSum(&$arr, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) { $sqrtCurrent = sqrt($arr[$i]); for ($j = 0; $j < $n; $j++) { $x = $arr[$j]; // If sqrtCurrent is present in array if ($x == $sqrtCurrent) { $sum += ($sqrtCurrent * $sqrtCurrent); break; } } } return $sum;} // Driver code$arr = array(2, 4, 5, 6, 7, 8, 9, 3);$n = sizeof($arr);echo (getSum($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>",
"e": 4676,
"s": 3962,
"text": null
},
{
"code": "<script> // Javascript program to find the sum of all the elements // from the array whose square root is present // in the same array // Function to return the required sum function getSum(arr, n) { let sum = 0; for (let i = 0; i < n; i++) { let sqrtCurrent = Math.sqrt(arr[i]); for (let j = 0; j < n; j++) { let x = arr[j]; // If sqrtCurrent is present in array if (x == sqrtCurrent) { sum += (sqrtCurrent * sqrtCurrent); break; } } } return sum; } let arr = [ 2, 4, 5, 6, 7, 8, 9, 3 ]; let n = arr.length; document.write(getSum(arr, n)); // This code is contributed by suresh07.</script>",
"e": 5484,
"s": 4676,
"text": null
},
{
"code": null,
"e": 5487,
"s": 5484,
"text": "13"
},
{
"code": null,
"e": 5652,
"s": 5489,
"text": "Efficient Approach: We can create a HashSet of all the elements present in the array and than check for the square root of each element of the array in O(n) time."
},
{
"code": null,
"e": 5705,
"s": 5652,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 5709,
"s": 5705,
"text": "C++"
},
{
"code": null,
"e": 5714,
"s": 5709,
"text": "Java"
},
{
"code": null,
"e": 5717,
"s": 5714,
"text": "C#"
},
{
"code": null,
"e": 5725,
"s": 5717,
"text": "Python3"
},
{
"code": null,
"e": 5729,
"s": 5725,
"text": "PHP"
},
{
"code": null,
"e": 5740,
"s": 5729,
"text": "Javascript"
},
{
"code": "// C++ program to find the sum of all the elements// from the array whose square root is present// in the same array#include<bits/stdc++.h>using namespace std; // Function to return the required sumint getSum(int arr[], int n){ int i, sum = 0; // Initialization of hash map set<int> hashSet; // Store each element in the hash map for (i = 0; i < n; i++) hashSet.insert(arr[i]); for (i = 0; i < n; i++) { double sqrtCurrent = sqrt(arr[i]); // If sqrtCurrent is a decimal number if (floor(sqrtCurrent) != ceil(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.find((int)sqrtCurrent) != hashSet.end()) { sum += (sqrtCurrent * sqrtCurrent); } } return sum;} // Driver codeint main(){ int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (getSum(arr, n)); return 0;} // This code is contributed by Rajput-Ji",
"e": 6731,
"s": 5740,
"text": null
},
{
"code": "// Java program to find the sum of all the elements// from the array whose square root is present// in the same array import java.util.*;public class GFG { // Function to return the required sum public static int getSum(int arr[], int n) { int i, sum = 0; // Initialization of hash map Set<Integer> hashSet = new HashSet<>(); // Store each element in the hash map for (i = 0; i < n; i++) hashSet.add(arr[i]); for (i = 0; i < n; i++) { double sqrtCurrent = Math.sqrt(arr[i]); // If sqrtCurrent is a decimal number if (Math.floor(sqrtCurrent) != Math.ceil(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.contains((int)sqrtCurrent)) { sum += (sqrtCurrent * sqrtCurrent); } } return sum; } // Driver code public static void main(String args[]) { int arr[] = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.length; System.out.println(getSum(arr, n)); }}",
"e": 7813,
"s": 6731,
"text": null
},
{
"code": "// C# program to find the sum of all the elements// from the array whose square root is present// in the same arrayusing System;using System.Collections.Generic; class GFG{ // Function to return the required sum public static int getSum(int []arr, int n) { int i, sum = 0; // Initialization of hash map HashSet<int> hashSet = new HashSet<int>(); // Store each element in the hash map for (i = 0; i < n; i++) hashSet.Add(arr[i]); for (i = 0; i < n; i++) { double sqrtCurrent = Math.Sqrt(arr[i]); // If sqrtCurrent is a decimal number if (Math.Floor(sqrtCurrent) != Math.Ceiling(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.Contains((int)sqrtCurrent)) { sum += (int)(sqrtCurrent * sqrtCurrent); } } return sum; } // Driver code public static void Main(String []args) { int []arr = { 2, 4, 5, 6, 7, 8, 9, 3 }; int n = arr.Length; Console.WriteLine(getSum(arr, n)); }} // This code contributed by Rajput-Ji",
"e": 8993,
"s": 7813,
"text": null
},
{
"code": "# Python3 program to find the sum of all the# elements from the array whose square# root is present in the same arrayimport math # Function to return the required sumdef getSum(arr, n): sum = 0; # Initialization of hash map hashSet = set(); # Store each element in the hash map for i in range(n): hashSet.add(arr[i]); for i in range(n): sqrtCurrent = math.sqrt(arr[i]); # If sqrtCurrent is a decimal number if (math.floor(sqrtCurrent) != math.ceil(sqrtCurrent)): continue; # If hash set contains sqrtCurrent if (int(sqrtCurrent) in hashSet): sum += int(sqrtCurrent * sqrtCurrent); return sum; # Driver codearr = [ 2, 4, 5, 6, 7, 8, 9, 3 ];n = len(arr);print(getSum(arr, n)); # This code is contributed by mits",
"e": 9803,
"s": 8993,
"text": null
},
{
"code": "<?php// PHP program to find the sum of all the// elements from the array whose square// root is present in the same array // Function to return the required sumfunction getSum($arr, $n){ $sum = 0; // Initialization of hash map $hashSet = array(); // Store each element in the hash map for ($i = 0; $i < $n; $i++) array_push($hashSet, $arr[$i]); $hashSet = array_unique($hashSet); for ($i = 0; $i < $n; $i++) { $sqrtCurrent = sqrt($arr[$i]); // If sqrtCurrent is a decimal number if (floor($sqrtCurrent) != ceil($sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (in_array((int)$sqrtCurrent, $hashSet)) { $sum += ($sqrtCurrent * $sqrtCurrent); } } return $sum;} // Driver code$arr = array( 2, 4, 5, 6, 7, 8, 9, 3 );$n = count($arr);print(getSum($arr, $n)); // This code is contributed by mits?>",
"e": 10737,
"s": 9803,
"text": null
},
{
"code": "<script> // Javascript program to find the sum of// all the elements from the array whose// square root is present in the same array // Function to return the required sumfunction getSum(arr, n){ let i, sum = 0; // Initialization of hash map let hashSet = new Set(); // Store each element in the hash map for(i = 0; i < n; i++) hashSet.add(arr[i]); for(i = 0; i < n; i++) { let sqrtCurrent = Math.sqrt(arr[i]); // If sqrtCurrent is a decimal number if (Math.floor(sqrtCurrent) != Math.ceil(sqrtCurrent)) continue; // If hash set contains sqrtCurrent if (hashSet.has(sqrtCurrent)) { sum += (sqrtCurrent * sqrtCurrent); } } return sum;} // Driver codelet arr = [ 2, 4, 5, 6, 7, 8, 9, 3 ];let n = arr.length; document.write(getSum(arr, n)); // This code is contributed by unknown2108 </script>",
"e": 11677,
"s": 10737,
"text": null
},
{
"code": null,
"e": 11680,
"s": 11677,
"text": "13"
},
{
"code": null,
"e": 11699,
"s": 11682,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 11707,
"s": 11699,
"text": "ankthon"
},
{
"code": null,
"e": 11722,
"s": 11707,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 11734,
"s": 11722,
"text": "29AjayKumar"
},
{
"code": null,
"e": 11744,
"s": 11734,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11757,
"s": 11744,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 11769,
"s": 11757,
"text": "unknown2108"
},
{
"code": null,
"e": 11778,
"s": 11769,
"text": "suresh07"
},
{
"code": null,
"e": 11783,
"s": 11778,
"text": "Hash"
},
{
"code": null,
"e": 11791,
"s": 11783,
"text": "HashSet"
},
{
"code": null,
"e": 11798,
"s": 11791,
"text": "Arrays"
},
{
"code": null,
"e": 11805,
"s": 11798,
"text": "Arrays"
},
{
"code": null,
"e": 11810,
"s": 11805,
"text": "Hash"
}
] |
How to encrypt and decrypt data in Python
|
What is cryptography? Cryptography deals with the conversion of plain text into cipher text which is called encryption of data and cipher text back to plain text which is called decryption of data.
We will be using the fernet module in the cryptography package to encrypt and decrypt data using Python. While using the fernet module, a unique key is generated without which you cannot read or manipulate the encrypted data.
Now that you know what we will be dealing with, let’s get started.
The cryptography module does not come packaged with Python, which means you will have to install it using the pip package manager. To do so, launch your terminal and type in the code below.
pip install cryptography
Once you have the package downloaded and installed, you can import its modules.
We will be using the fernet module to encrypt and decrypt data. So, let us import it into the Python script.
from cryptography.fernet import Fernet
Note − Make sure you get the capitalization’s correct.
You are all set to start writing your script.
In order to start encrypting data, you must first create a fernet key.
key = Fernet.generate_key()
f = Fernet(key)
In the above lines, we generated a key using the generate_key() method and then assigned that key to a variable “f” in the next line.
And that’s it, you now have a key stored in a variable ready to be used.
We can print the key and store it, if needed. Make sure to use the decode function while printing.
print(key.decode())
Bq64GE−−93K1RVro4go1frN−8twBSvXdbCPSPLIKz9U=
In order to encrypt data from the above key, you must use the encrypt method.
encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")
And that’s it, the above sentence has been encrypted.
To view your encrypted message, you must print it.
print(encrypted_data)
b'gAAAAABgILy91p_wqMntdT3mDkh0IBXSLjuBMQAfnGZAFkZCX1U6Q7TU2PthgFBwVz0QbKXpuNTHRzAgbdDV4zfuuzkGCXqVD--xJdkTycKH2iurC_oqHySLc9xJEXz93LkhTbKUa5HCxfJtB-Um_YkxqjclftXXZQ=='
Note − We had the b before the sentence in order to convert it into byte format. You can choose use the encode() method instead as well.
Now that you have the cipher text, let us see how we can convert it back to plain readable text.
We can achieve decryption using the decrypt method in the fernet module.
decrypted_data = f.decrypt(encrypted_data) # f is the variable that has the value of the key.
print(decrypted_data)
b'This message is being encrypted and cannot be seen!'
Note − If you look at the above output, you can notice that there is b’ before the printed plaintext, this is because encrypted data is being converted back into byte format. In order to get just the plain text, we need to use the decode function.
print(decrypted_data.decode())
This message is being encrypted and cannot be seen!
Note − You can encrypt and decrypt data using the same key. That is, if you print the value of the key and save it. You can use the same key by assigning it to a variable. Example −>
f = Fernet(Bq64GE--93K1RVro4go1frN-8twBSvXdbCPSPLIKz9U=) # Value of an actual key is given.
from cryptography.fernet import Fernet
key = Fernet.generate_key()
print("Key : ", key.decode())
f = Fernet(key)
encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")
print("After encryption : ", encrypted_data)
decrypted_data = f.decrypt(encrypted_data)
print(decrypted_data)
print("After decryption : ", decrypted_data.decode())
Key : u4dM7xw8sNNU3Rm_lwDbixudWSeaM0Z4TTDdQNKsouI=
After encryption : b'gAAAAABgIL3_qbfM_oMgQn653gpk6a7hqxXiR0dl0vrmOmqnr5b6MqrsjGkK1IknxMLLtOCq6_YlX4x3nBedbZqtCqy4os55pttrl-pBO6-dJf6kVP50IpIaKSXbpAsuWl4h_2o_E-4YEqZ5kkgxWrwnqojmkMyuSQ=='
b'This message is being encrypted and cannot be seen!'
After decryption : This message is being encrypted and cannot be seen!
You have now learnt to encrypt and decrypt data using the cryptography package in Python.
You can even save the key as a .txt file and then retrieve it to encrypt and store password or decrypt password from database to verify if it matches. There are various other cases where you can use this, be it a mini−project or a large scale project.
For more information on the cryptography module, you can read through their official documentation at − https://pypi.org/project/cryptography/
|
[
{
"code": null,
"e": 1385,
"s": 1187,
"text": "What is cryptography? Cryptography deals with the conversion of plain text into cipher text which is called encryption of data and cipher text back to plain text which is called decryption of data."
},
{
"code": null,
"e": 1611,
"s": 1385,
"text": "We will be using the fernet module in the cryptography package to encrypt and decrypt data using Python. While using the fernet module, a unique key is generated without which you cannot read or manipulate the encrypted data."
},
{
"code": null,
"e": 1678,
"s": 1611,
"text": "Now that you know what we will be dealing with, let’s get started."
},
{
"code": null,
"e": 1868,
"s": 1678,
"text": "The cryptography module does not come packaged with Python, which means you will have to install it using the pip package manager. To do so, launch your terminal and type in the code below."
},
{
"code": null,
"e": 1893,
"s": 1868,
"text": "pip install cryptography"
},
{
"code": null,
"e": 1973,
"s": 1893,
"text": "Once you have the package downloaded and installed, you can import its modules."
},
{
"code": null,
"e": 2082,
"s": 1973,
"text": "We will be using the fernet module to encrypt and decrypt data. So, let us import it into the Python script."
},
{
"code": null,
"e": 2121,
"s": 2082,
"text": "from cryptography.fernet import Fernet"
},
{
"code": null,
"e": 2176,
"s": 2121,
"text": "Note − Make sure you get the capitalization’s correct."
},
{
"code": null,
"e": 2222,
"s": 2176,
"text": "You are all set to start writing your script."
},
{
"code": null,
"e": 2293,
"s": 2222,
"text": "In order to start encrypting data, you must first create a fernet key."
},
{
"code": null,
"e": 2337,
"s": 2293,
"text": "key = Fernet.generate_key()\nf = Fernet(key)"
},
{
"code": null,
"e": 2471,
"s": 2337,
"text": "In the above lines, we generated a key using the generate_key() method and then assigned that key to a variable “f” in the next line."
},
{
"code": null,
"e": 2544,
"s": 2471,
"text": "And that’s it, you now have a key stored in a variable ready to be used."
},
{
"code": null,
"e": 2643,
"s": 2544,
"text": "We can print the key and store it, if needed. Make sure to use the decode function while printing."
},
{
"code": null,
"e": 2663,
"s": 2643,
"text": "print(key.decode())"
},
{
"code": null,
"e": 2708,
"s": 2663,
"text": "Bq64GE−−93K1RVro4go1frN−8twBSvXdbCPSPLIKz9U="
},
{
"code": null,
"e": 2786,
"s": 2708,
"text": "In order to encrypt data from the above key, you must use the encrypt method."
},
{
"code": null,
"e": 2869,
"s": 2786,
"text": "encrypted_data = f.encrypt(b\"This message is being encrypted and cannot be seen!\")"
},
{
"code": null,
"e": 2923,
"s": 2869,
"text": "And that’s it, the above sentence has been encrypted."
},
{
"code": null,
"e": 2974,
"s": 2923,
"text": "To view your encrypted message, you must print it."
},
{
"code": null,
"e": 2996,
"s": 2974,
"text": "print(encrypted_data)"
},
{
"code": null,
"e": 3164,
"s": 2996,
"text": "b'gAAAAABgILy91p_wqMntdT3mDkh0IBXSLjuBMQAfnGZAFkZCX1U6Q7TU2PthgFBwVz0QbKXpuNTHRzAgbdDV4zfuuzkGCXqVD--xJdkTycKH2iurC_oqHySLc9xJEXz93LkhTbKUa5HCxfJtB-Um_YkxqjclftXXZQ=='"
},
{
"code": null,
"e": 3301,
"s": 3164,
"text": "Note − We had the b before the sentence in order to convert it into byte format. You can choose use the encode() method instead as well."
},
{
"code": null,
"e": 3398,
"s": 3301,
"text": "Now that you have the cipher text, let us see how we can convert it back to plain readable text."
},
{
"code": null,
"e": 3471,
"s": 3398,
"text": "We can achieve decryption using the decrypt method in the fernet module."
},
{
"code": null,
"e": 3587,
"s": 3471,
"text": "decrypted_data = f.decrypt(encrypted_data) # f is the variable that has the value of the key.\nprint(decrypted_data)"
},
{
"code": null,
"e": 3642,
"s": 3587,
"text": "b'This message is being encrypted and cannot be seen!'"
},
{
"code": null,
"e": 3890,
"s": 3642,
"text": "Note − If you look at the above output, you can notice that there is b’ before the printed plaintext, this is because encrypted data is being converted back into byte format. In order to get just the plain text, we need to use the decode function."
},
{
"code": null,
"e": 3921,
"s": 3890,
"text": "print(decrypted_data.decode())"
},
{
"code": null,
"e": 3973,
"s": 3921,
"text": "This message is being encrypted and cannot be seen!"
},
{
"code": null,
"e": 4156,
"s": 3973,
"text": "Note − You can encrypt and decrypt data using the same key. That is, if you print the value of the key and save it. You can use the same key by assigning it to a variable. Example −>"
},
{
"code": null,
"e": 4248,
"s": 4156,
"text": "f = Fernet(Bq64GE--93K1RVro4go1frN-8twBSvXdbCPSPLIKz9U=) # Value of an actual key is given."
},
{
"code": null,
"e": 4608,
"s": 4248,
"text": "from cryptography.fernet import Fernet\nkey = Fernet.generate_key()\nprint(\"Key : \", key.decode())\nf = Fernet(key)\nencrypted_data = f.encrypt(b\"This message is being encrypted and cannot be seen!\")\nprint(\"After encryption : \", encrypted_data)\ndecrypted_data = f.decrypt(encrypted_data)\nprint(decrypted_data)\nprint(\"After decryption : \", decrypted_data.decode())"
},
{
"code": null,
"e": 4972,
"s": 4608,
"text": "Key : u4dM7xw8sNNU3Rm_lwDbixudWSeaM0Z4TTDdQNKsouI=\nAfter encryption : b'gAAAAABgIL3_qbfM_oMgQn653gpk6a7hqxXiR0dl0vrmOmqnr5b6MqrsjGkK1IknxMLLtOCq6_YlX4x3nBedbZqtCqy4os55pttrl-pBO6-dJf6kVP50IpIaKSXbpAsuWl4h_2o_E-4YEqZ5kkgxWrwnqojmkMyuSQ=='\nb'This message is being encrypted and cannot be seen!'\nAfter decryption : This message is being encrypted and cannot be seen!"
},
{
"code": null,
"e": 5062,
"s": 4972,
"text": "You have now learnt to encrypt and decrypt data using the cryptography package in Python."
},
{
"code": null,
"e": 5314,
"s": 5062,
"text": "You can even save the key as a .txt file and then retrieve it to encrypt and store password or decrypt password from database to verify if it matches. There are various other cases where you can use this, be it a mini−project or a large scale project."
},
{
"code": null,
"e": 5457,
"s": 5314,
"text": "For more information on the cryptography module, you can read through their official documentation at − https://pypi.org/project/cryptography/"
}
] |
How to find first value from any table in SQL Server
|
23 Nov, 2020
We could use FIRST_VALUE() in SQL Server to find the first value from any table. FIRST_VALUE() function used in SQL server is a type of window function that results in the first value in an ordered partition of the given data set.
Syntax :
SELECT *,
FROM tablename;
FIRST_VALUE ( scalar_value )
OVER (
[PARTITION BY partition_value ]
ORDER BY sort_value [ASC | DESC]
) AS columname ;
Syntax descriptions :
scalar_value –scalar_value is a value examined over the value of the first row in an ordered partition of the provided data set.
PARTITION BY –PARTITION BY is optional, it differs the rows of the provided data set into the partitions where the FIRST_VALUE() function is used.
ORDER BY –ORDER BY states the order of the rows in each of the partition where the FIRST_VALUE()function is used.
Examples :
Let us suppose we have a table named ‘geek_demo’:
SELECT TOP 1000 [Name]
,[City], [Year]
FROM [geek_demo];
Example-1 :
Find FIRST VALUE without PARTITION BY clause.
To find the first city for the table ‘geek-demo’ use below query:
SELECT [Name], [Year],
FIRST_VALUE(City) OVER (
ORDER BY City ASC
) AS First_City
FROM geek_demo;
Output :
Example-2 :
Find FIRST VALUE with PARTITION BY clause.
To find the first city according to the year for the table ‘geek-demo’ use below query:
SELECT TOP 1000 [Name] , [Year] ,
FIRST_VALUE(City) OVER (
PARTITION BY Year
ORDER BY City ASC
) AS First_City
FROM geek_demo;
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Nov, 2020"
},
{
"code": null,
"e": 284,
"s": 53,
"text": "We could use FIRST_VALUE() in SQL Server to find the first value from any table. FIRST_VALUE() function used in SQL server is a type of window function that results in the first value in an ordered partition of the given data set."
},
{
"code": null,
"e": 293,
"s": 284,
"text": "Syntax :"
},
{
"code": null,
"e": 449,
"s": 293,
"text": "SELECT *,\nFROM tablename;\nFIRST_VALUE ( scalar_value ) \nOVER ( \n [PARTITION BY partition_value ]\n ORDER BY sort_value [ASC | DESC]\n ) AS columname ; \n"
},
{
"code": null,
"e": 471,
"s": 449,
"text": "Syntax descriptions :"
},
{
"code": null,
"e": 600,
"s": 471,
"text": "scalar_value –scalar_value is a value examined over the value of the first row in an ordered partition of the provided data set."
},
{
"code": null,
"e": 747,
"s": 600,
"text": "PARTITION BY –PARTITION BY is optional, it differs the rows of the provided data set into the partitions where the FIRST_VALUE() function is used."
},
{
"code": null,
"e": 863,
"s": 747,
"text": "ORDER BY –ORDER BY states the order of the rows in each of the partition where the FIRST_VALUE()function is used."
},
{
"code": null,
"e": 874,
"s": 863,
"text": "Examples :"
},
{
"code": null,
"e": 924,
"s": 874,
"text": "Let us suppose we have a table named ‘geek_demo’:"
},
{
"code": null,
"e": 986,
"s": 924,
"text": "SELECT TOP 1000 [Name]\n ,[City], [Year]\nFROM [geek_demo];"
},
{
"code": null,
"e": 999,
"s": 986,
"text": "Example-1 : "
},
{
"code": null,
"e": 1045,
"s": 999,
"text": "Find FIRST VALUE without PARTITION BY clause."
},
{
"code": null,
"e": 1111,
"s": 1045,
"text": "To find the first city for the table ‘geek-demo’ use below query:"
},
{
"code": null,
"e": 1236,
"s": 1111,
"text": "SELECT [Name], [Year],\n FIRST_VALUE(City) OVER (\n ORDER BY City ASC\n ) AS First_City\nFROM geek_demo;"
},
{
"code": null,
"e": 1245,
"s": 1236,
"text": "Output :"
},
{
"code": null,
"e": 1258,
"s": 1245,
"text": "Example-2 : "
},
{
"code": null,
"e": 1301,
"s": 1258,
"text": "Find FIRST VALUE with PARTITION BY clause."
},
{
"code": null,
"e": 1389,
"s": 1301,
"text": "To find the first city according to the year for the table ‘geek-demo’ use below query:"
},
{
"code": null,
"e": 1549,
"s": 1389,
"text": "SELECT TOP 1000 [Name] , [Year] ,\n FIRST_VALUE(City) OVER (\n PARTITION BY Year\n ORDER BY City ASC\n ) AS First_City\nFROM geek_demo;"
},
{
"code": null,
"e": 1558,
"s": 1549,
"text": "Output :"
},
{
"code": null,
"e": 1567,
"s": 1558,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1578,
"s": 1567,
"text": "SQL-Server"
},
{
"code": null,
"e": 1582,
"s": 1578,
"text": "SQL"
},
{
"code": null,
"e": 1586,
"s": 1582,
"text": "SQL"
}
] |
sync command in Linux with Examples
|
18 Jan, 2022
sync command in Linux is used to synchronize cached writes to persistent storage. If one or more files are specified, sync only them, or their containing file systems.
Syntax:
sync [OPTION] [FILE]...
Note: Nothing is being shown in the screenshots just because sync command makes the cache in the background.
Example: It will be going to sync all cached file data that belongs to the current user.
Options:
sync -d: This option sync only file data, no unneeded metadata. Example:
Example:
sync -d /home/algoscale/Desktop/aricleslist.txt /home/algoscale/Desktop/advance.html
sync -f: This option will sync the file systems which contains the files. Example:
Example:
sync -f /home/algoscale/Desktop/aricleslist.txt
sync –help: This option display the help text and exit.
sync --help
sync –version: This option will output version information and exit.
sync --version
sumitgumber28
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 197,
"s": 28,
"text": "sync command in Linux is used to synchronize cached writes to persistent storage. If one or more files are specified, sync only them, or their containing file systems. "
},
{
"code": null,
"e": 207,
"s": 197,
"text": "Syntax: "
},
{
"code": null,
"e": 231,
"s": 207,
"text": "sync [OPTION] [FILE]..."
},
{
"code": null,
"e": 341,
"s": 231,
"text": "Note: Nothing is being shown in the screenshots just because sync command makes the cache in the background. "
},
{
"code": null,
"e": 431,
"s": 341,
"text": "Example: It will be going to sync all cached file data that belongs to the current user. "
},
{
"code": null,
"e": 441,
"s": 431,
"text": "Options: "
},
{
"code": null,
"e": 515,
"s": 441,
"text": "sync -d: This option sync only file data, no unneeded metadata. Example: "
},
{
"code": null,
"e": 525,
"s": 515,
"text": "Example: "
},
{
"code": null,
"e": 610,
"s": 525,
"text": "sync -d /home/algoscale/Desktop/aricleslist.txt /home/algoscale/Desktop/advance.html"
},
{
"code": null,
"e": 696,
"s": 612,
"text": "sync -f: This option will sync the file systems which contains the files. Example: "
},
{
"code": null,
"e": 706,
"s": 696,
"text": "Example: "
},
{
"code": null,
"e": 754,
"s": 706,
"text": "sync -f /home/algoscale/Desktop/aricleslist.txt"
},
{
"code": null,
"e": 813,
"s": 756,
"text": "sync –help: This option display the help text and exit. "
},
{
"code": null,
"e": 825,
"s": 813,
"text": "sync --help"
},
{
"code": null,
"e": 897,
"s": 827,
"text": "sync –version: This option will output version information and exit. "
},
{
"code": null,
"e": 912,
"s": 897,
"text": "sync --version"
},
{
"code": null,
"e": 928,
"s": 914,
"text": "sumitgumber28"
},
{
"code": null,
"e": 942,
"s": 928,
"text": "linux-command"
},
{
"code": null,
"e": 962,
"s": 942,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 973,
"s": 962,
"text": "Linux-Unix"
}
] |
How to Install Code Blocks for C++ on Linux?
|
06 Oct, 2021
Code::Blocks is a free IDE( an integrated development environment), for C/C++ and FORTRAN languages. It is a cross-platform IDE and available for Windows, Mac, and Linux, In this article, we are going to discuss various methods using which we can install Code Blocks on Linux.:
Follow the below steps to install Code Blocks for C++ on Linux using the apt install terminal command:
Step 1: Before starting the actual installation, we must have the GCC compiler installed on our system. To install GCC run the following command in your terminal.
sudo apt install g++
Output:
installing GCC compiler.
As we have already installed the GCC compiler it is displaying, g++ is already installed with the newer version.
Step 2: Now, we just have to install the code blocks using the following command and confirm the installation by pressing “Y”:
sudo apt install codeblocks
Output:
installing codeblocks
Step 3: To open the code blocks navigate to the activities launcher (search) and type code blocks, you will see code blocks icons, click on the icon to install the code block.
Opening Code blocks
Follow the below steps to install Code Blocks for C++ on Linux:
Step 1: Open up the software manager that you have using the activity launcher.
Installing through the software center
Step 2: Search for Code blocks and click on the code blocks.
Downloading code blocks
Step 3: Select the first one the Code::Blocks and click on the install button, wait for the installation to be finished, then open the code blocks
installing code blocks.
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Installation of Node.js on Linux
Installation of Node.js on Windows
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "Code::Blocks is a free IDE( an integrated development environment), for C/C++ and FORTRAN languages. It is a cross-platform IDE and available for Windows, Mac, and Linux, In this article, we are going to discuss various methods using which we can install Code Blocks on Linux.:"
},
{
"code": null,
"e": 409,
"s": 306,
"text": "Follow the below steps to install Code Blocks for C++ on Linux using the apt install terminal command:"
},
{
"code": null,
"e": 572,
"s": 409,
"text": "Step 1: Before starting the actual installation, we must have the GCC compiler installed on our system. To install GCC run the following command in your terminal."
},
{
"code": null,
"e": 593,
"s": 572,
"text": "sudo apt install g++"
},
{
"code": null,
"e": 601,
"s": 593,
"text": "Output:"
},
{
"code": null,
"e": 626,
"s": 601,
"text": "installing GCC compiler."
},
{
"code": null,
"e": 739,
"s": 626,
"text": "As we have already installed the GCC compiler it is displaying, g++ is already installed with the newer version."
},
{
"code": null,
"e": 867,
"s": 739,
"text": " Step 2: Now, we just have to install the code blocks using the following command and confirm the installation by pressing “Y”:"
},
{
"code": null,
"e": 895,
"s": 867,
"text": "sudo apt install codeblocks"
},
{
"code": null,
"e": 903,
"s": 895,
"text": "Output:"
},
{
"code": null,
"e": 925,
"s": 903,
"text": "installing codeblocks"
},
{
"code": null,
"e": 1102,
"s": 925,
"text": " Step 3: To open the code blocks navigate to the activities launcher (search) and type code blocks, you will see code blocks icons, click on the icon to install the code block."
},
{
"code": null,
"e": 1122,
"s": 1102,
"text": "Opening Code blocks"
},
{
"code": null,
"e": 1186,
"s": 1122,
"text": "Follow the below steps to install Code Blocks for C++ on Linux:"
},
{
"code": null,
"e": 1267,
"s": 1186,
"text": " Step 1: Open up the software manager that you have using the activity launcher."
},
{
"code": null,
"e": 1306,
"s": 1267,
"text": "Installing through the software center"
},
{
"code": null,
"e": 1367,
"s": 1306,
"text": "Step 2: Search for Code blocks and click on the code blocks."
},
{
"code": null,
"e": 1391,
"s": 1367,
"text": "Downloading code blocks"
},
{
"code": null,
"e": 1538,
"s": 1391,
"text": "Step 3: Select the first one the Code::Blocks and click on the install button, wait for the installation to be finished, then open the code blocks"
},
{
"code": null,
"e": 1562,
"s": 1538,
"text": "installing code blocks."
},
{
"code": null,
"e": 1577,
"s": 1562,
"text": "how-to-install"
},
{
"code": null,
"e": 1584,
"s": 1577,
"text": "Picked"
},
{
"code": null,
"e": 1591,
"s": 1584,
"text": "How To"
},
{
"code": null,
"e": 1610,
"s": 1591,
"text": "Installation Guide"
},
{
"code": null,
"e": 1708,
"s": 1610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1757,
"s": 1708,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 1799,
"s": 1757,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 1838,
"s": 1799,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 1892,
"s": 1838,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 1950,
"s": 1892,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 1983,
"s": 1950,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2018,
"s": 1983,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 2060,
"s": 2018,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2099,
"s": 2060,
"text": "How to Install and Use NVM on Windows?"
}
] |
Python Lists
|
08 Jul, 2022
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In a simple language, a list is a collection of things, enclosed in [ ] and separated by commas. Lists are the simplest containers that are an integral part of the Python language. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.
List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility.
Note: Lists are a useful tool for preserving a sequence of data and further iterating over it.
Table of content:
Creating a List
Knowing the size of the List
Adding Elements to a List: Using append() methodUsing insert() methodUsing extend() method
Using append() method
Using insert() method
Using extend() method
Accessing elements from the List
Removing Elements from the List: Using remove() methodUsing pop() method
Using remove() method
Using pop() method
Slicing of a List
List Comprehension
Operations on List
List Methods
Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, a list doesn’t need a built-in function for the creation of a list.
Note: Unlike Sets, the list may contain mutable elements.
Python3
# Python program to demonstrate# Creation of List # Creating a ListList = []print("Blank List: ")print(List) # Creating a List of numbersList = [10, 20, 14]print("\nList of numbers: ")print(List) # Creating a List of strings and accessing# using indexList = ["Geeks", "For", "Geeks"]print("\nList Items: ")print(List[0])print(List[2]) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'], ['Geeks']]print("\nMulti-Dimensional List: ")print(List)
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Time Complexity: O(1)
Space Complexity: O(n)
A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.
Python3
# Creating a List with# the use of Numbers# (Having duplicate values)List = [1, 2, 4, 4, 3, 3, 3, 6, 5]print("\nList with the use of Numbers: ")print(List) # Creating a List with# mixed type of values# (Having numbers and strings)List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']print("\nList with the use of Mixed Values: ")print(List)
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
List with the use of Mixed Values:
[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
Python3
# Creating a ListList1 = []print(len(List1)) # Creating a List of numbersList2 = [10, 20, 14]print(len(List2))
0
3
Python3
f = [1, 1, 2, 3, 5, 8]p = [2, 3, 5, 7]grading = ["Tests", "Quizzes", "Individual Labs", "Group Labs", "Hackathons"]grades = [300, 60, 120, 60, 120]oddjob = [1, 5.6, True, 4-7j, "Hello", [1, 2], [3.9, "World"]]print(len(grading))print(sum(f), sum(p))
5
20 17
Python3
grading = ["Tests", "Quizzes", "Individual Labs", "Group Labs", "Hackathons"]grades = [300, 60, 120, 60, 120]oddjob = [1, 5.6, True, 4-7j, "Hello", [1, 2], [3.9, "World"]]# We access individual elements using the index# The first element is at index 0print(grades[1], oddjob[4])# We access the elements from the back using negative indices# -1 is the last, -2 is the last but one and so onprint(grading[-1], grading[-3])print(max(grades), min(grades))
60 Hello
Hackathons Individual Labs
300 60
We can take input of a list elements as string, integer, float, etc. But the default one is a string.
Python3
# Python program to take space separated input as a string# split and store it to a list and print the string list # input the list as stringstring = input("Enter elements of a list (Space-Separated): ")lst = string.split() # split the strings and store it to a listprint('The list is:', lst) # printing the list #This code is contributed by Susobhan AKhuli
Output:
Enter elements of a list (Space-Separated): GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
Python
# Python program to store integrs in a list in one line # input size of the listn = int(input("Enter the size of list : "))# store integrs in a list using map, split and strip functionslst = list(map(int, input("Enter the integer elements of list(Space-Separated): ").strip().split()))[:n]print('The list is:', lst) # printing the list #This code is contributed by Susobhan AKhuli
Output:
Enter the size of list : 4
Enter the integer elements of list(Space-Separated): 6 3 9 10
The list is: [6, 3, 9, 10]
To know more see this.
Elements can be added to the List by using the built-in append() function. Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used. Tuples can also be added to the list with the use of the append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing list with the use of the append() method.
Python3
# Python program to demonstrate# Addition of elements in a List # Creating a ListList = []print("Initial blank List: ")print(List) # Addition of Elements# in the ListList.append(1)List.append(2)List.append(4)print("\nList after Addition of Three elements: ")print(List) # Adding elements to the List# using Iteratorfor i in range(1, 4): List.append(i)print("\nList after Addition of elements from 1-3: ")print(List) # Adding Tuples to the ListList.append((5, 6))print("\nList after Addition of a Tuple: ")print(List) # Addition of List to a ListList2 = ['For', 'Geeks']List.append(List2)print("\nList after Addition of a List: ")print(List)
Initial blank List:
[]
List after Addition of Three elements:
[1, 2, 4]
List after Addition of elements from 1-3:
[1, 2, 4, 1, 2, 3]
List after Addition of a Tuple:
[1, 2, 4, 1, 2, 3, (5, 6)]
List after Addition of a List:
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]
Time Complexity: O(1)
Space Complexity: O(1)
append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two arguments(position, value).
Python3
# Python program to demonstrate # Addition of elements in a List # Creating a ListList = [1,2,3,4]print("Initial List: ")print(List) # Addition of Element at # specific Position# (using Insert Method)List.insert(3, 12)List.insert(0, 'Geeks')print("\nList after performing Insert Operation: ")print(List)
Initial List:
[1, 2, 3, 4]
List after performing Insert Operation:
['Geeks', 1, 2, 3, 12, 4]
Time Complexity: O(n)
Space Complexity: O(1)
Other than append() and insert() methods, there’s one more method for the Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list.
Note: append() and extend() methods can only add elements at the end.
Python3
# Python program to demonstrate# Addition of elements in a List # Creating a ListList = [1, 2, 3, 4]print("Initial List: ")print(List) # Addition of multiple elements# to the List at the end# (using Extend Method)List.extend([8, 'Geeks', 'Always'])print("\nList after performing Extend Operation: ")print(List)
Initial List:
[1, 2, 3, 4]
List after performing Extend Operation:
[1, 2, 3, 4, 8, 'Geeks', 'Always']
Time Complexity: O(n)
Space Complexity: O(1)
In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing.
Python3
# Python program to demonstrate# accessing of element from list # Creating a List with# the use of multiple valuesList = ["Geeks", "For", "Geeks"] # accessing a element from the# list using index numberprint("Accessing a element from the list")print(List[0])print(List[2]) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'], ['Geeks']] # accessing an element from the# Multi-Dimensional List using# index numberprint("Accessing a element from a Multi-Dimensional list")print(List[0][1])print(List[1][0])
Accessing a element from the list
Geeks
Geeks
Accessing a element from a Multi-Dimensional list
For
Geeks
In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
Python3
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks'] # accessing an element using# negative indexingprint("Accessing element using negative indexing") # print the last element of listprint(List[-1]) # print the third last element of listprint(List[-3])
Accessing element using negative indexing
Geeks
For
Time Complexity: O(1)
Space Complexity: O(1)
A list can be reversed by using the (.reverse) method.
Python3
# Reversing a listmylist = [1, 2, 3, 4, 5, 'Geek', 'Python']mylist.reverse()print(mylist)
['Python', 'Geek', 5, 4, 3, 2, 1]
Elements can be removed from the List by using the built-in remove() function but an Error arises if the element doesn’t exist in the list. Remove() method only removes one element at a time, to remove a range of elements, the iterator is used. The remove() method removes the specified item.
Note: Remove method in List will only remove the first occurrence of the searched element.
Python3
# Python program to demonstrate# Removal of elements in a List # Creating a ListList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]print("Initial List: ")print(List) # Removing elements from List# using Remove() methodList.remove(5)List.remove(6)print("\nList after Removal of two elements: ")print(List) # Removing elements from List# using iterator methodfor i in range(1, 5): List.remove(i)print("\nList after Removing a range of elements: ")print(List)
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
List after Removing a range of elements:
[7, 8, 9, 10, 11, 12]
Time Complexity: O(n)
Space Complexity: O(1)
pop() function can also be used to remove and return an element from the list, but by default it removes only the last element of the list, to remove an element from a specific position of the List, the index of the element is passed as an argument to the pop() method.
Python3
List = [1, 2, 3, 4, 5] # Removing element from the# Set using the pop() methodList.pop()print("\nList after popping an element: ")print(List) # Removing element at a# specific location from the# Set using the pop() methodList.pop(2)print("\nList after popping a specific element: ")print(List)
List after popping an element:
[1, 2, 3, 4]
List after popping a specific element:
[1, 2, 4]
Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for removing the first and middle elements)
Space Complexity: O(1)
We can get substrings and sublists using a slice. In Python List, there are multiple ways to print the whole List with all the elements, but to print a specific range of elements from the list, we use the Slice operation. Slice operation is performed on Lists with the use of a colon(:). To print elements from beginning to a range use [: Index], to print elements from end-use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index: End Index] and to print the whole List with the use of slicing operation, use [:]. Further, to print the whole List in reverse order, use [::-1].
Note – To print elements of List from rear-end, use Negative Indexes.
UNDERSTANDING SLICING OF LISTS:
pr[0] accesses the first item, 2.
pr[-4] accesses the fourth item from the end, 5.
pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.
pr[2:4] accesses [5, 7], a list of items from third to fifth.
pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.
Python3
# Python program to demonstrate# Removal of elements in a List # Creating a ListList = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']print("Initial List: ")print(List) # Print elements of a range# using Slice operationSliced_List = List[3:8]print("\nSlicing elements in a range 3-8: ")print(Sliced_List) # Print elements from a# pre-defined point to endSliced_List = List[5:]print("\nElements sliced from 5th " "element till the end: ")print(Sliced_List) # Printing elements from# beginning till endSliced_List = List[:]print("\nPrinting all elements using slice operation: ")print(Sliced_List)
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Slicing elements in a range 3-8:
['K', 'S', 'F', 'O', 'R']
Elements sliced from 5th element till the end:
['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Printing all elements using slice operation:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Python3
f = [1, 1, 2, 3, 5, 8]print(f)print(f[2:7])print(f[2:11:3])print(f[::-1])
[1, 1, 2, 3, 5, 8]
[2, 3, 5, 8]
[2, 8]
[8, 5, 3, 2, 1, 1]
Python3
# Creating a ListList = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']print("Initial List: ")print(List) # Print elements from beginning# to a pre-defined point using SliceSliced_List = List[:-6]print("\nElements sliced till 6th element from last: ")print(Sliced_List) # Print elements of a range# using negative index List slicingSliced_List = List[-6:-1]print("\nElements sliced from index -6 to -1")print(Sliced_List) # Printing elements in reverse# using Slice operationSliced_List = List[::-1]print("\nPrinting List in reverse: ")print(Sliced_List)
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Elements sliced till 6th element from last:
['G', 'E', 'E', 'K', 'S', 'F', 'O']
Elements sliced from index -6 to -1
['R', 'G', 'E', 'E', 'K']
Printing List in reverse:
['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G']
List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Example:
Python3
# Python program to demonstrate list# comprehension in Python # below list contains square of all# odd numbers from range 1 to 10odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]print(odd_square)
[1, 9, 25, 49, 81]
For better understanding, the above code is similar to as follows:
Python3
# for understanding, above generation is same as,odd_square = [] for x in range(1, 11): if x % 2 == 1: odd_square.append(x**2) print(odd_square)
[1, 9, 25, 49, 81]
Refer to the below articles to get detailed information about List Comprehension.
Python List Comprehension and Slicing
Nested List Comprehensions in Python
List comprehension and ord() in Python
Find the length of a list
Iterate over a list in Python
Concatenating two lists in Python
List Membership Test
The operations mentioned above modify the list Itself.
Do go through recent articles on Lists
Creating a 3D List
Iterate over a list in Python
Iterate over multiple lists simultaneously
Internal working of list in Python
Python Slicing
Using lists as Stacks
Using lists as Queues
Python List Comprehensions vs Generator Expressions
List Methods in Python – Set 1 Set 2
Lambda expression and filter function
Useful Links:
Recent Articles on Python List
Python Tutorials
Python Output Programs in List: Set 6, Set 11, Set 12, Set 13
Multiple Choice Questions
All articles in Python Category
More on lists
saifi_zakir
VidushiAgrawal
cffjob
nikhilaggarwal3
RajuKumar19
simranarora5sos
akshaysingh98088
kumaripunam984122
vinayaka2000
anvesha19jain
sarajadhav12052009
susobhanakhuli
santeswar
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
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 ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 589,
"s": 52,
"text": "Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In a simple language, a list is a collection of things, enclosed in [ ] and separated by commas. Lists are the simplest containers that are an integral part of the Python language. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation."
},
{
"code": null,
"e": 952,
"s": 589,
"text": "List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility."
},
{
"code": null,
"e": 1047,
"s": 952,
"text": "Note: Lists are a useful tool for preserving a sequence of data and further iterating over it."
},
{
"code": null,
"e": 1066,
"s": 1047,
"text": "Table of content: "
},
{
"code": null,
"e": 1082,
"s": 1066,
"text": "Creating a List"
},
{
"code": null,
"e": 1111,
"s": 1082,
"text": "Knowing the size of the List"
},
{
"code": null,
"e": 1202,
"s": 1111,
"text": "Adding Elements to a List: Using append() methodUsing insert() methodUsing extend() method"
},
{
"code": null,
"e": 1224,
"s": 1202,
"text": "Using append() method"
},
{
"code": null,
"e": 1246,
"s": 1224,
"text": "Using insert() method"
},
{
"code": null,
"e": 1268,
"s": 1246,
"text": "Using extend() method"
},
{
"code": null,
"e": 1301,
"s": 1268,
"text": "Accessing elements from the List"
},
{
"code": null,
"e": 1374,
"s": 1301,
"text": "Removing Elements from the List: Using remove() methodUsing pop() method"
},
{
"code": null,
"e": 1396,
"s": 1374,
"text": "Using remove() method"
},
{
"code": null,
"e": 1415,
"s": 1396,
"text": "Using pop() method"
},
{
"code": null,
"e": 1433,
"s": 1415,
"text": "Slicing of a List"
},
{
"code": null,
"e": 1452,
"s": 1433,
"text": "List Comprehension"
},
{
"code": null,
"e": 1471,
"s": 1452,
"text": "Operations on List"
},
{
"code": null,
"e": 1484,
"s": 1471,
"text": "List Methods"
},
{
"code": null,
"e": 1656,
"s": 1484,
"text": "Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, a list doesn’t need a built-in function for the creation of a list. "
},
{
"code": null,
"e": 1716,
"s": 1656,
"text": "Note: Unlike Sets, the list may contain mutable elements. "
},
{
"code": null,
"e": 1724,
"s": 1716,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# Creation of List # Creating a ListList = []print(\"Blank List: \")print(List) # Creating a List of numbersList = [10, 20, 14]print(\"\\nList of numbers: \")print(List) # Creating a List of strings and accessing# using indexList = [\"Geeks\", \"For\", \"Geeks\"]print(\"\\nList Items: \")print(List[0])print(List[2]) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'], ['Geeks']]print(\"\\nMulti-Dimensional List: \")print(List)",
"e": 2216,
"s": 1724,
"text": null
},
{
"code": null,
"e": 2346,
"s": 2216,
"text": "Blank List: \n[]\n\nList of numbers: \n[10, 20, 14]\n\nList Items: \nGeeks\nGeeks\n\nMulti-Dimensional List: \n[['Geeks', 'For'], ['Geeks']]"
},
{
"code": null,
"e": 2368,
"s": 2346,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 2391,
"s": 2368,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 2564,
"s": 2391,
"text": "A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation."
},
{
"code": null,
"e": 2572,
"s": 2564,
"text": "Python3"
},
{
"code": "# Creating a List with# the use of Numbers# (Having duplicate values)List = [1, 2, 4, 4, 3, 3, 3, 6, 5]print(\"\\nList with the use of Numbers: \")print(List) # Creating a List with# mixed type of values# (Having numbers and strings)List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']print(\"\\nList with the use of Mixed Values: \")print(List)",
"e": 2905,
"s": 2572,
"text": null
},
{
"code": null,
"e": 3039,
"s": 2905,
"text": "List with the use of Numbers: \n[1, 2, 4, 4, 3, 3, 3, 6, 5]\n\nList with the use of Mixed Values: \n[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']"
},
{
"code": null,
"e": 3047,
"s": 3039,
"text": "Python3"
},
{
"code": "# Creating a ListList1 = []print(len(List1)) # Creating a List of numbersList2 = [10, 20, 14]print(len(List2))",
"e": 3159,
"s": 3047,
"text": null
},
{
"code": null,
"e": 3163,
"s": 3159,
"text": "0\n3"
},
{
"code": null,
"e": 3171,
"s": 3163,
"text": "Python3"
},
{
"code": "f = [1, 1, 2, 3, 5, 8]p = [2, 3, 5, 7]grading = [\"Tests\", \"Quizzes\", \"Individual Labs\", \"Group Labs\", \"Hackathons\"]grades = [300, 60, 120, 60, 120]oddjob = [1, 5.6, True, 4-7j, \"Hello\", [1, 2], [3.9, \"World\"]]print(len(grading))print(sum(f), sum(p))",
"e": 3421,
"s": 3171,
"text": null
},
{
"code": null,
"e": 3429,
"s": 3421,
"text": "5\n20 17"
},
{
"code": null,
"e": 3437,
"s": 3429,
"text": "Python3"
},
{
"code": "grading = [\"Tests\", \"Quizzes\", \"Individual Labs\", \"Group Labs\", \"Hackathons\"]grades = [300, 60, 120, 60, 120]oddjob = [1, 5.6, True, 4-7j, \"Hello\", [1, 2], [3.9, \"World\"]]# We access individual elements using the index# The first element is at index 0print(grades[1], oddjob[4])# We access the elements from the back using negative indices# -1 is the last, -2 is the last but one and so onprint(grading[-1], grading[-3])print(max(grades), min(grades))",
"e": 3889,
"s": 3437,
"text": null
},
{
"code": null,
"e": 3932,
"s": 3889,
"text": "60 Hello\nHackathons Individual Labs\n300 60"
},
{
"code": null,
"e": 4034,
"s": 3932,
"text": "We can take input of a list elements as string, integer, float, etc. But the default one is a string."
},
{
"code": null,
"e": 4042,
"s": 4034,
"text": "Python3"
},
{
"code": "# Python program to take space separated input as a string# split and store it to a list and print the string list # input the list as stringstring = input(\"Enter elements of a list (Space-Separated): \")lst = string.split() # split the strings and store it to a listprint('The list is:', lst) # printing the list #This code is contributed by Susobhan AKhuli",
"e": 4405,
"s": 4042,
"text": null
},
{
"code": null,
"e": 4413,
"s": 4405,
"text": "Output:"
},
{
"code": null,
"e": 4512,
"s": 4413,
"text": "Enter elements of a list (Space-Separated): GEEKS FOR GEEKS\nThe list is: ['GEEKS', 'FOR', 'GEEKS']"
},
{
"code": null,
"e": 4519,
"s": 4512,
"text": "Python"
},
{
"code": "# Python program to store integrs in a list in one line # input size of the listn = int(input(\"Enter the size of list : \"))# store integrs in a list using map, split and strip functionslst = list(map(int, input(\"Enter the integer elements of list(Space-Separated): \").strip().split()))[:n]print('The list is:', lst) # printing the list #This code is contributed by Susobhan AKhuli",
"e": 4904,
"s": 4519,
"text": null
},
{
"code": null,
"e": 4912,
"s": 4904,
"text": "Output:"
},
{
"code": null,
"e": 5028,
"s": 4912,
"text": "Enter the size of list : 4\nEnter the integer elements of list(Space-Separated): 6 3 9 10\nThe list is: [6, 3, 9, 10]"
},
{
"code": null,
"e": 5051,
"s": 5028,
"text": "To know more see this."
},
{
"code": null,
"e": 5484,
"s": 5051,
"text": "Elements can be added to the List by using the built-in append() function. Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used. Tuples can also be added to the list with the use of the append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing list with the use of the append() method."
},
{
"code": null,
"e": 5492,
"s": 5484,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# Addition of elements in a List # Creating a ListList = []print(\"Initial blank List: \")print(List) # Addition of Elements# in the ListList.append(1)List.append(2)List.append(4)print(\"\\nList after Addition of Three elements: \")print(List) # Adding elements to the List# using Iteratorfor i in range(1, 4): List.append(i)print(\"\\nList after Addition of elements from 1-3: \")print(List) # Adding Tuples to the ListList.append((5, 6))print(\"\\nList after Addition of a Tuple: \")print(List) # Addition of List to a ListList2 = ['For', 'Geeks']List.append(List2)print(\"\\nList after Addition of a List: \")print(List)",
"e": 6141,
"s": 5492,
"text": null
},
{
"code": null,
"e": 6418,
"s": 6141,
"text": "Initial blank List: \n[]\n\nList after Addition of Three elements: \n[1, 2, 4]\n\nList after Addition of elements from 1-3: \n[1, 2, 4, 1, 2, 3]\n\nList after Addition of a Tuple: \n[1, 2, 4, 1, 2, 3, (5, 6)]\n\nList after Addition of a List: \n[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]"
},
{
"code": null,
"e": 6440,
"s": 6418,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 6463,
"s": 6440,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 6731,
"s": 6463,
"text": "append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two arguments(position, value). "
},
{
"code": null,
"e": 6739,
"s": 6731,
"text": "Python3"
},
{
"code": "# Python program to demonstrate # Addition of elements in a List # Creating a ListList = [1,2,3,4]print(\"Initial List: \")print(List) # Addition of Element at # specific Position# (using Insert Method)List.insert(3, 12)List.insert(0, 'Geeks')print(\"\\nList after performing Insert Operation: \")print(List)",
"e": 7046,
"s": 6739,
"text": null
},
{
"code": null,
"e": 7142,
"s": 7046,
"text": "Initial List: \n[1, 2, 3, 4]\n\nList after performing Insert Operation: \n['Geeks', 1, 2, 3, 12, 4]"
},
{
"code": null,
"e": 7164,
"s": 7142,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 7187,
"s": 7164,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 7379,
"s": 7187,
"text": "Other than append() and insert() methods, there’s one more method for the Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list."
},
{
"code": null,
"e": 7449,
"s": 7379,
"text": "Note: append() and extend() methods can only add elements at the end."
},
{
"code": null,
"e": 7457,
"s": 7449,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# Addition of elements in a List # Creating a ListList = [1, 2, 3, 4]print(\"Initial List: \")print(List) # Addition of multiple elements# to the List at the end# (using Extend Method)List.extend([8, 'Geeks', 'Always'])print(\"\\nList after performing Extend Operation: \")print(List)",
"e": 7770,
"s": 7457,
"text": null
},
{
"code": null,
"e": 7875,
"s": 7770,
"text": "Initial List: \n[1, 2, 3, 4]\n\nList after performing Extend Operation: \n[1, 2, 3, 4, 8, 'Geeks', 'Always']"
},
{
"code": null,
"e": 7897,
"s": 7875,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 7920,
"s": 7897,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 8117,
"s": 7920,
"text": "In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing. "
},
{
"code": null,
"e": 8125,
"s": 8117,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# accessing of element from list # Creating a List with# the use of multiple valuesList = [\"Geeks\", \"For\", \"Geeks\"] # accessing a element from the# list using index numberprint(\"Accessing a element from the list\")print(List[0])print(List[2]) # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'], ['Geeks']] # accessing an element from the# Multi-Dimensional List using# index numberprint(\"Accessing a element from a Multi-Dimensional list\")print(List[0][1])print(List[1][0])",
"e": 8677,
"s": 8125,
"text": null
},
{
"code": null,
"e": 8783,
"s": 8677,
"text": "Accessing a element from the list\nGeeks\nGeeks\nAccessing a element from a Multi-Dimensional list\nFor\nGeeks"
},
{
"code": null,
"e": 9085,
"s": 8783,
"text": "In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc."
},
{
"code": null,
"e": 9093,
"s": 9085,
"text": "Python3"
},
{
"code": "List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks'] # accessing an element using# negative indexingprint(\"Accessing element using negative indexing\") # print the last element of listprint(List[-1]) # print the third last element of listprint(List[-3])",
"e": 9341,
"s": 9093,
"text": null
},
{
"code": null,
"e": 9393,
"s": 9341,
"text": "Accessing element using negative indexing\nGeeks\nFor"
},
{
"code": null,
"e": 9415,
"s": 9393,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 9438,
"s": 9415,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 9493,
"s": 9438,
"text": "A list can be reversed by using the (.reverse) method."
},
{
"code": null,
"e": 9501,
"s": 9493,
"text": "Python3"
},
{
"code": "# Reversing a listmylist = [1, 2, 3, 4, 5, 'Geek', 'Python']mylist.reverse()print(mylist)",
"e": 9591,
"s": 9501,
"text": null
},
{
"code": null,
"e": 9625,
"s": 9591,
"text": "['Python', 'Geek', 5, 4, 3, 2, 1]"
},
{
"code": null,
"e": 9918,
"s": 9625,
"text": "Elements can be removed from the List by using the built-in remove() function but an Error arises if the element doesn’t exist in the list. Remove() method only removes one element at a time, to remove a range of elements, the iterator is used. The remove() method removes the specified item."
},
{
"code": null,
"e": 10009,
"s": 9918,
"text": "Note: Remove method in List will only remove the first occurrence of the searched element."
},
{
"code": null,
"e": 10017,
"s": 10009,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# Removal of elements in a List # Creating a ListList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]print(\"Initial List: \")print(List) # Removing elements from List# using Remove() methodList.remove(5)List.remove(6)print(\"\\nList after Removal of two elements: \")print(List) # Removing elements from List# using iterator methodfor i in range(1, 5): List.remove(i)print(\"\\nList after Removing a range of elements: \")print(List)",
"e": 10482,
"s": 10017,
"text": null
},
{
"code": null,
"e": 10674,
"s": 10482,
"text": "Initial List: \n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\nList after Removal of two elements: \n[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]\n\nList after Removing a range of elements: \n[7, 8, 9, 10, 11, 12]"
},
{
"code": null,
"e": 10696,
"s": 10674,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 10719,
"s": 10696,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 10989,
"s": 10719,
"text": "pop() function can also be used to remove and return an element from the list, but by default it removes only the last element of the list, to remove an element from a specific position of the List, the index of the element is passed as an argument to the pop() method."
},
{
"code": null,
"e": 10997,
"s": 10989,
"text": "Python3"
},
{
"code": "List = [1, 2, 3, 4, 5] # Removing element from the# Set using the pop() methodList.pop()print(\"\\nList after popping an element: \")print(List) # Removing element at a# specific location from the# Set using the pop() methodList.pop(2)print(\"\\nList after popping a specific element: \")print(List)",
"e": 11293,
"s": 10997,
"text": null
},
{
"code": null,
"e": 11389,
"s": 11293,
"text": "List after popping an element: \n[1, 2, 3, 4]\n\nList after popping a specific element: \n[1, 2, 4]"
},
{
"code": null,
"e": 11502,
"s": 11389,
"text": "Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for removing the first and middle elements)"
},
{
"code": null,
"e": 11525,
"s": 11502,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 12177,
"s": 11525,
"text": "We can get substrings and sublists using a slice. In Python List, there are multiple ways to print the whole List with all the elements, but to print a specific range of elements from the list, we use the Slice operation. Slice operation is performed on Lists with the use of a colon(:). To print elements from beginning to a range use [: Index], to print elements from end-use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index: End Index] and to print the whole List with the use of slicing operation, use [:]. Further, to print the whole List in reverse order, use [::-1]."
},
{
"code": null,
"e": 12248,
"s": 12177,
"text": "Note – To print elements of List from rear-end, use Negative Indexes. "
},
{
"code": null,
"e": 12282,
"s": 12250,
"text": "UNDERSTANDING SLICING OF LISTS:"
},
{
"code": null,
"e": 12316,
"s": 12282,
"text": "pr[0] accesses the first item, 2."
},
{
"code": null,
"e": 12365,
"s": 12316,
"text": "pr[-4] accesses the fourth item from the end, 5."
},
{
"code": null,
"e": 12433,
"s": 12365,
"text": "pr[2:] accesses [5, 7, 11, 13], a list of items from third to last."
},
{
"code": null,
"e": 12501,
"s": 12433,
"text": "pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth."
},
{
"code": null,
"e": 12563,
"s": 12501,
"text": "pr[2:4] accesses [5, 7], a list of items from third to fifth."
},
{
"code": null,
"e": 12641,
"s": 12563,
"text": "pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item."
},
{
"code": null,
"e": 12649,
"s": 12641,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# Removal of elements in a List # Creating a ListList = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']print(\"Initial List: \")print(List) # Print elements of a range# using Slice operationSliced_List = List[3:8]print(\"\\nSlicing elements in a range 3-8: \")print(Sliced_List) # Print elements from a# pre-defined point to endSliced_List = List[5:]print(\"\\nElements sliced from 5th \" \"element till the end: \")print(Sliced_List) # Printing elements from# beginning till endSliced_List = List[:]print(\"\\nPrinting all elements using slice operation: \")print(Sliced_List)",
"e": 13279,
"s": 12649,
"text": null
},
{
"code": null,
"e": 13624,
"s": 13279,
"text": "Initial List: \n['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']\n\nSlicing elements in a range 3-8: \n['K', 'S', 'F', 'O', 'R']\n\nElements sliced from 5th element till the end: \n['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']\n\nPrinting all elements using slice operation: \n['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']"
},
{
"code": null,
"e": 13632,
"s": 13624,
"text": "Python3"
},
{
"code": "f = [1, 1, 2, 3, 5, 8]print(f)print(f[2:7])print(f[2:11:3])print(f[::-1])",
"e": 13706,
"s": 13632,
"text": null
},
{
"code": null,
"e": 13764,
"s": 13706,
"text": "[1, 1, 2, 3, 5, 8]\n[2, 3, 5, 8]\n[2, 8]\n[8, 5, 3, 2, 1, 1]"
},
{
"code": null,
"e": 13772,
"s": 13764,
"text": "Python3"
},
{
"code": "# Creating a ListList = ['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']print(\"Initial List: \")print(List) # Print elements from beginning# to a pre-defined point using SliceSliced_List = List[:-6]print(\"\\nElements sliced till 6th element from last: \")print(Sliced_List) # Print elements of a range# using negative index List slicingSliced_List = List[-6:-1]print(\"\\nElements sliced from index -6 to -1\")print(Sliced_List) # Printing elements in reverse# using Slice operationSliced_List = List[::-1]print(\"\\nPrinting List in reverse: \")print(Sliced_List)",
"e": 14355,
"s": 13772,
"text": null
},
{
"code": null,
"e": 14675,
"s": 14355,
"text": "Initial List: \n['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']\n\nElements sliced till 6th element from last: \n['G', 'E', 'E', 'K', 'S', 'F', 'O']\n\nElements sliced from index -6 to -1\n['R', 'G', 'E', 'E', 'K']\n\nPrinting List in reverse: \n['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G']"
},
{
"code": null,
"e": 14949,
"s": 14675,
"text": "List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. "
},
{
"code": null,
"e": 14957,
"s": 14949,
"text": "Syntax:"
},
{
"code": null,
"e": 15027,
"s": 14957,
"text": "newList = [ expression(element) for element in oldList if condition ]"
},
{
"code": null,
"e": 15037,
"s": 15027,
"text": "Example: "
},
{
"code": null,
"e": 15045,
"s": 15037,
"text": "Python3"
},
{
"code": "# Python program to demonstrate list# comprehension in Python # below list contains square of all# odd numbers from range 1 to 10odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]print(odd_square)",
"e": 15250,
"s": 15045,
"text": null
},
{
"code": null,
"e": 15269,
"s": 15250,
"text": "[1, 9, 25, 49, 81]"
},
{
"code": null,
"e": 15337,
"s": 15269,
"text": "For better understanding, the above code is similar to as follows: "
},
{
"code": null,
"e": 15345,
"s": 15337,
"text": "Python3"
},
{
"code": "# for understanding, above generation is same as,odd_square = [] for x in range(1, 11): if x % 2 == 1: odd_square.append(x**2) print(odd_square)",
"e": 15502,
"s": 15345,
"text": null
},
{
"code": null,
"e": 15521,
"s": 15502,
"text": "[1, 9, 25, 49, 81]"
},
{
"code": null,
"e": 15603,
"s": 15521,
"text": "Refer to the below articles to get detailed information about List Comprehension."
},
{
"code": null,
"e": 15641,
"s": 15603,
"text": "Python List Comprehension and Slicing"
},
{
"code": null,
"e": 15678,
"s": 15641,
"text": "Nested List Comprehensions in Python"
},
{
"code": null,
"e": 15717,
"s": 15678,
"text": "List comprehension and ord() in Python"
},
{
"code": null,
"e": 15743,
"s": 15717,
"text": "Find the length of a list"
},
{
"code": null,
"e": 15773,
"s": 15743,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 15807,
"s": 15773,
"text": "Concatenating two lists in Python"
},
{
"code": null,
"e": 15828,
"s": 15807,
"text": "List Membership Test"
},
{
"code": null,
"e": 15883,
"s": 15828,
"text": "The operations mentioned above modify the list Itself."
},
{
"code": null,
"e": 15922,
"s": 15883,
"text": "Do go through recent articles on Lists"
},
{
"code": null,
"e": 15941,
"s": 15922,
"text": "Creating a 3D List"
},
{
"code": null,
"e": 15971,
"s": 15941,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 16014,
"s": 15971,
"text": "Iterate over multiple lists simultaneously"
},
{
"code": null,
"e": 16049,
"s": 16014,
"text": "Internal working of list in Python"
},
{
"code": null,
"e": 16064,
"s": 16049,
"text": "Python Slicing"
},
{
"code": null,
"e": 16086,
"s": 16064,
"text": "Using lists as Stacks"
},
{
"code": null,
"e": 16108,
"s": 16086,
"text": "Using lists as Queues"
},
{
"code": null,
"e": 16160,
"s": 16108,
"text": "Python List Comprehensions vs Generator Expressions"
},
{
"code": null,
"e": 16197,
"s": 16160,
"text": "List Methods in Python – Set 1 Set 2"
},
{
"code": null,
"e": 16235,
"s": 16197,
"text": "Lambda expression and filter function"
},
{
"code": null,
"e": 16250,
"s": 16235,
"text": "Useful Links: "
},
{
"code": null,
"e": 16281,
"s": 16250,
"text": "Recent Articles on Python List"
},
{
"code": null,
"e": 16298,
"s": 16281,
"text": "Python Tutorials"
},
{
"code": null,
"e": 16360,
"s": 16298,
"text": "Python Output Programs in List: Set 6, Set 11, Set 12, Set 13"
},
{
"code": null,
"e": 16386,
"s": 16360,
"text": "Multiple Choice Questions"
},
{
"code": null,
"e": 16418,
"s": 16386,
"text": "All articles in Python Category"
},
{
"code": null,
"e": 16432,
"s": 16418,
"text": "More on lists"
},
{
"code": null,
"e": 16444,
"s": 16432,
"text": "saifi_zakir"
},
{
"code": null,
"e": 16459,
"s": 16444,
"text": "VidushiAgrawal"
},
{
"code": null,
"e": 16466,
"s": 16459,
"text": "cffjob"
},
{
"code": null,
"e": 16482,
"s": 16466,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 16494,
"s": 16482,
"text": "RajuKumar19"
},
{
"code": null,
"e": 16510,
"s": 16494,
"text": "simranarora5sos"
},
{
"code": null,
"e": 16527,
"s": 16510,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 16545,
"s": 16527,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 16558,
"s": 16545,
"text": "vinayaka2000"
},
{
"code": null,
"e": 16572,
"s": 16558,
"text": "anvesha19jain"
},
{
"code": null,
"e": 16591,
"s": 16572,
"text": "sarajadhav12052009"
},
{
"code": null,
"e": 16606,
"s": 16591,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 16616,
"s": 16606,
"text": "santeswar"
},
{
"code": null,
"e": 16628,
"s": 16616,
"text": "python-list"
},
{
"code": null,
"e": 16635,
"s": 16628,
"text": "Python"
},
{
"code": null,
"e": 16647,
"s": 16635,
"text": "python-list"
},
{
"code": null,
"e": 16745,
"s": 16647,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 16773,
"s": 16745,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 16823,
"s": 16773,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 16845,
"s": 16823,
"text": "Python map() function"
},
{
"code": null,
"e": 16889,
"s": 16845,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 16931,
"s": 16889,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 16953,
"s": 16931,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 16988,
"s": 16953,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 17014,
"s": 16988,
"text": "Python String | replace()"
},
{
"code": null,
"e": 17046,
"s": 17014,
"text": "How to Install PIP on Windows ?"
}
] |
A C Programming Language Puzzle - GeeksforGeeks
|
21 Jun, 2018
Give a = 12 and b = 36 write a C function/macro that returns 3612 without using arithmetic, strings and predefined functions.
We strongly recommend you to minimize your browser and try this yourself first.
Below is one solution that uses String Token-Pasting Operator (##) of C macros. For example, the expression “a##b” prints concatenation of ‘a’ and ‘b’.
Below is a working C code.
#include <stdio.h>#define merge(a, b) b##aint main(void){ printf("%d ", merge(12, 36)); return 0;}
Output:
3612
Thanks to an anonymous user to suggest this solution.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
C-Macro & Preprocessor
cpp-macros
cpp-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
Arrow operator -> in C/C++ with Examples
'this' pointer in C++
How to split a string in C/C++, Python and Java?
Smart Pointers in C++ and How to Use Them
How to dynamically allocate a 2D array in C?
UDP Server-Client implementation in C
Input-output system calls in C | Create, Open, Close, Read, Write
|
[
{
"code": null,
"e": 23841,
"s": 23813,
"text": "\n21 Jun, 2018"
},
{
"code": null,
"e": 23967,
"s": 23841,
"text": "Give a = 12 and b = 36 write a C function/macro that returns 3612 without using arithmetic, strings and predefined functions."
},
{
"code": null,
"e": 24047,
"s": 23967,
"text": "We strongly recommend you to minimize your browser and try this yourself first."
},
{
"code": null,
"e": 24199,
"s": 24047,
"text": "Below is one solution that uses String Token-Pasting Operator (##) of C macros. For example, the expression “a##b” prints concatenation of ‘a’ and ‘b’."
},
{
"code": null,
"e": 24226,
"s": 24199,
"text": "Below is a working C code."
},
{
"code": "#include <stdio.h>#define merge(a, b) b##aint main(void){ printf(\"%d \", merge(12, 36)); return 0;}",
"e": 24331,
"s": 24226,
"text": null
},
{
"code": null,
"e": 24339,
"s": 24331,
"text": "Output:"
},
{
"code": null,
"e": 24344,
"s": 24339,
"text": "3612"
},
{
"code": null,
"e": 24398,
"s": 24344,
"text": "Thanks to an anonymous user to suggest this solution."
},
{
"code": null,
"e": 24522,
"s": 24398,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 24545,
"s": 24522,
"text": "C-Macro & Preprocessor"
},
{
"code": null,
"e": 24556,
"s": 24545,
"text": "cpp-macros"
},
{
"code": null,
"e": 24567,
"s": 24556,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 24578,
"s": 24567,
"text": "C Language"
},
{
"code": null,
"e": 24676,
"s": 24578,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24685,
"s": 24676,
"text": "Comments"
},
{
"code": null,
"e": 24698,
"s": 24685,
"text": "Old Comments"
},
{
"code": null,
"e": 24736,
"s": 24698,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 24762,
"s": 24736,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 24782,
"s": 24762,
"text": "Multithreading in C"
},
{
"code": null,
"e": 24823,
"s": 24782,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 24845,
"s": 24823,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 24894,
"s": 24845,
"text": "How to split a string in C/C++, Python and Java?"
},
{
"code": null,
"e": 24936,
"s": 24894,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 24981,
"s": 24936,
"text": "How to dynamically allocate a 2D array in C?"
},
{
"code": null,
"e": 25019,
"s": 24981,
"text": "UDP Server-Client implementation in C"
}
] |
Understanding Logistic Regression step by step | by Gustavo Chávez | Towards Data Science
|
Logistic Regression is a popular statistical model used for binary classification, that is for predictions of the type this or that, yes or no, A or B, etc. Logistic regression can, however, be used for multiclass classification, but here we will focus on its simplest application.
As an example, consider the task of predicting someone’s gender (Male/Female) based on their Weight and Height.
For this, we will train a machine learning model from a data set of 10,000 samples of people’s weight and height. The data set is taken from the Conway & Myles Machine Learning for Hackers book, Chapter 2, and can it can be directly downloaded here.
This is a preview of what the data looks like:
Each sample contains three columns: Height, Weight, and Male.
Height in inches
Weight in pounds
Male: 1 means that the measurement corresponds to a male person, and 0 means that the measurement corresponds to a female person.
There are 5,000 samples from males, and 5,000 samples for females, thus the data set is balanced and we can proceed to training.
The Python’s scikit-learn code to train a logistic regression classifier and make a prediction is very straightforward:
The general workflow is:
get a datasettrain a classifiermake a prediction using such classifier
get a dataset
train a classifier
make a prediction using such classifier
The logistic regression classifier can be derived by analogy to the linear regression hypothesis which is:
However, the logistic regression hypothesis generalizes from the linear regression hypothesis in that it uses the logistic function:
The result is the logistic regression hypothesis:
The function g(z) is the logistic function, also known as the sigmoid function.
The logistic function has asymptotes at 0 and 1, and it crosses the y-axis at 0.5.
Since our data set has two features: height and weight, the logistic regression hypothesis is the following:
The logistic regression classifier will predict “Male” if:
This is because the logistic regression “threshold” is set at g(z)=0.5, see the plot of the logistic regression function above for verification.
For our data set the values of θ are:
To get access to the θ parameters computed by scikit-learn one can do:
# For theta_0:print( fitted_model.intercept_ )# For theta_1 and theta_2:print( fitted_model.coef_ )
With the coefficients at hand, a manual prediction (that is, without using the function clf.predict()) would simply require to compute the vector product
and to check if the resulting scalar is bigger than or equal to zero (to predict Male), or otherwise (to predict Female).
As an example, say we want to predict the gender of someone with Height=70 inches and Weight = 180 pounds, like at line 14 at the script LogisticRegression.py above, one can simply do:
Since the result of the product is bigger than zero, the classifier will predict Male.
A visualization of the decision boundary and the complete data set can be seen here:
As you can see, above the decision boundary lie most of the blue points that correspond to the Male class, and below it all the pink points that correspond to the Female class.
Also, from just looking at the data you can tell that the predictions won’t be perfect. This can be improved by including more features (beyond weight and height), and by potentially using a different decision boundary.
Logistic regression decision boundaries can also be non-linear functions, such as higher degree polynomials.
The scikit-learn library does a great job of abstracting the computation of the logistic regression parameter θ, and the way it is done is by solving an optimization problem.
Let’s start by defining the logistic regression cost function for the two points of interest: y=1, and y=0, that is, when the hypothesis function predicts Male or Female.
Then, we take a convex combination in y of these two terms to come up with the logistic regression cost function:
The logistic regression cost function is convex. Thus, in order to compute θ, one needs to solve the following (unconstrained) optimization problem:
There is a variety of methods that can be used to solve this unconstrained optimization problem, such as the 1st order method gradient descent that requires the gradient of the logistic regression cost function, or a 2nd order method such as Newton’s method that requires the gradient and the Hessian of the logistic regression cost function — this was the method prescribed in the scikit-learn script above.
For the case of gradient descent, the search direction is the negative partial derivative of the logistic regression cost function with respect to the parameter θ:
In its most basic form, gradient descent will iterate along the negative gradient direction of θ (known as a minimizing sequence) until reaching convergence.
Notice that the constant α is usually called the learning rate or the search step and that it has to be carefully tuned to reach convergence. Algorithms such as backtracking line search aid in the determination of α.
In summary, these are the three fundamental concepts that you should remember next time you are using, or implementing, a logistic regression classifier:
1. Logistic regression hypothesis
2. Logistic regression decision boundary
3. Logistic regression cost function
For a discussion of the Logistic regression classifier applied to a data set with more features (using Python too) I recommend this Medium post of Susan Li.
https://github.com/gchavez2/code_machine_learning_algorithms
Andrew Ng’s lectures on Logistic Regression
scikit-learn’s logistic regression class
I am a postdoctoral fellow at the Lawrence Berkeley National Laboratory, where I work at the intersection of machine learning and high-performance computing.
If you find this article interesting, feel free to say hello over LinkedIn, I’m always happy to connect with other professionals in the field.
And as always: comments, questions, and shares are highly appreciated! ❤️
|
[
{
"code": null,
"e": 454,
"s": 172,
"text": "Logistic Regression is a popular statistical model used for binary classification, that is for predictions of the type this or that, yes or no, A or B, etc. Logistic regression can, however, be used for multiclass classification, but here we will focus on its simplest application."
},
{
"code": null,
"e": 566,
"s": 454,
"text": "As an example, consider the task of predicting someone’s gender (Male/Female) based on their Weight and Height."
},
{
"code": null,
"e": 816,
"s": 566,
"text": "For this, we will train a machine learning model from a data set of 10,000 samples of people’s weight and height. The data set is taken from the Conway & Myles Machine Learning for Hackers book, Chapter 2, and can it can be directly downloaded here."
},
{
"code": null,
"e": 863,
"s": 816,
"text": "This is a preview of what the data looks like:"
},
{
"code": null,
"e": 925,
"s": 863,
"text": "Each sample contains three columns: Height, Weight, and Male."
},
{
"code": null,
"e": 942,
"s": 925,
"text": "Height in inches"
},
{
"code": null,
"e": 959,
"s": 942,
"text": "Weight in pounds"
},
{
"code": null,
"e": 1089,
"s": 959,
"text": "Male: 1 means that the measurement corresponds to a male person, and 0 means that the measurement corresponds to a female person."
},
{
"code": null,
"e": 1218,
"s": 1089,
"text": "There are 5,000 samples from males, and 5,000 samples for females, thus the data set is balanced and we can proceed to training."
},
{
"code": null,
"e": 1338,
"s": 1218,
"text": "The Python’s scikit-learn code to train a logistic regression classifier and make a prediction is very straightforward:"
},
{
"code": null,
"e": 1363,
"s": 1338,
"text": "The general workflow is:"
},
{
"code": null,
"e": 1434,
"s": 1363,
"text": "get a datasettrain a classifiermake a prediction using such classifier"
},
{
"code": null,
"e": 1448,
"s": 1434,
"text": "get a dataset"
},
{
"code": null,
"e": 1467,
"s": 1448,
"text": "train a classifier"
},
{
"code": null,
"e": 1507,
"s": 1467,
"text": "make a prediction using such classifier"
},
{
"code": null,
"e": 1614,
"s": 1507,
"text": "The logistic regression classifier can be derived by analogy to the linear regression hypothesis which is:"
},
{
"code": null,
"e": 1747,
"s": 1614,
"text": "However, the logistic regression hypothesis generalizes from the linear regression hypothesis in that it uses the logistic function:"
},
{
"code": null,
"e": 1797,
"s": 1747,
"text": "The result is the logistic regression hypothesis:"
},
{
"code": null,
"e": 1877,
"s": 1797,
"text": "The function g(z) is the logistic function, also known as the sigmoid function."
},
{
"code": null,
"e": 1960,
"s": 1877,
"text": "The logistic function has asymptotes at 0 and 1, and it crosses the y-axis at 0.5."
},
{
"code": null,
"e": 2069,
"s": 1960,
"text": "Since our data set has two features: height and weight, the logistic regression hypothesis is the following:"
},
{
"code": null,
"e": 2128,
"s": 2069,
"text": "The logistic regression classifier will predict “Male” if:"
},
{
"code": null,
"e": 2273,
"s": 2128,
"text": "This is because the logistic regression “threshold” is set at g(z)=0.5, see the plot of the logistic regression function above for verification."
},
{
"code": null,
"e": 2311,
"s": 2273,
"text": "For our data set the values of θ are:"
},
{
"code": null,
"e": 2382,
"s": 2311,
"text": "To get access to the θ parameters computed by scikit-learn one can do:"
},
{
"code": null,
"e": 2482,
"s": 2382,
"text": "# For theta_0:print( fitted_model.intercept_ )# For theta_1 and theta_2:print( fitted_model.coef_ )"
},
{
"code": null,
"e": 2636,
"s": 2482,
"text": "With the coefficients at hand, a manual prediction (that is, without using the function clf.predict()) would simply require to compute the vector product"
},
{
"code": null,
"e": 2758,
"s": 2636,
"text": "and to check if the resulting scalar is bigger than or equal to zero (to predict Male), or otherwise (to predict Female)."
},
{
"code": null,
"e": 2943,
"s": 2758,
"text": "As an example, say we want to predict the gender of someone with Height=70 inches and Weight = 180 pounds, like at line 14 at the script LogisticRegression.py above, one can simply do:"
},
{
"code": null,
"e": 3030,
"s": 2943,
"text": "Since the result of the product is bigger than zero, the classifier will predict Male."
},
{
"code": null,
"e": 3115,
"s": 3030,
"text": "A visualization of the decision boundary and the complete data set can be seen here:"
},
{
"code": null,
"e": 3292,
"s": 3115,
"text": "As you can see, above the decision boundary lie most of the blue points that correspond to the Male class, and below it all the pink points that correspond to the Female class."
},
{
"code": null,
"e": 3512,
"s": 3292,
"text": "Also, from just looking at the data you can tell that the predictions won’t be perfect. This can be improved by including more features (beyond weight and height), and by potentially using a different decision boundary."
},
{
"code": null,
"e": 3621,
"s": 3512,
"text": "Logistic regression decision boundaries can also be non-linear functions, such as higher degree polynomials."
},
{
"code": null,
"e": 3796,
"s": 3621,
"text": "The scikit-learn library does a great job of abstracting the computation of the logistic regression parameter θ, and the way it is done is by solving an optimization problem."
},
{
"code": null,
"e": 3967,
"s": 3796,
"text": "Let’s start by defining the logistic regression cost function for the two points of interest: y=1, and y=0, that is, when the hypothesis function predicts Male or Female."
},
{
"code": null,
"e": 4081,
"s": 3967,
"text": "Then, we take a convex combination in y of these two terms to come up with the logistic regression cost function:"
},
{
"code": null,
"e": 4230,
"s": 4081,
"text": "The logistic regression cost function is convex. Thus, in order to compute θ, one needs to solve the following (unconstrained) optimization problem:"
},
{
"code": null,
"e": 4639,
"s": 4230,
"text": "There is a variety of methods that can be used to solve this unconstrained optimization problem, such as the 1st order method gradient descent that requires the gradient of the logistic regression cost function, or a 2nd order method such as Newton’s method that requires the gradient and the Hessian of the logistic regression cost function — this was the method prescribed in the scikit-learn script above."
},
{
"code": null,
"e": 4803,
"s": 4639,
"text": "For the case of gradient descent, the search direction is the negative partial derivative of the logistic regression cost function with respect to the parameter θ:"
},
{
"code": null,
"e": 4961,
"s": 4803,
"text": "In its most basic form, gradient descent will iterate along the negative gradient direction of θ (known as a minimizing sequence) until reaching convergence."
},
{
"code": null,
"e": 5178,
"s": 4961,
"text": "Notice that the constant α is usually called the learning rate or the search step and that it has to be carefully tuned to reach convergence. Algorithms such as backtracking line search aid in the determination of α."
},
{
"code": null,
"e": 5332,
"s": 5178,
"text": "In summary, these are the three fundamental concepts that you should remember next time you are using, or implementing, a logistic regression classifier:"
},
{
"code": null,
"e": 5366,
"s": 5332,
"text": "1. Logistic regression hypothesis"
},
{
"code": null,
"e": 5407,
"s": 5366,
"text": "2. Logistic regression decision boundary"
},
{
"code": null,
"e": 5444,
"s": 5407,
"text": "3. Logistic regression cost function"
},
{
"code": null,
"e": 5601,
"s": 5444,
"text": "For a discussion of the Logistic regression classifier applied to a data set with more features (using Python too) I recommend this Medium post of Susan Li."
},
{
"code": null,
"e": 5662,
"s": 5601,
"text": "https://github.com/gchavez2/code_machine_learning_algorithms"
},
{
"code": null,
"e": 5706,
"s": 5662,
"text": "Andrew Ng’s lectures on Logistic Regression"
},
{
"code": null,
"e": 5747,
"s": 5706,
"text": "scikit-learn’s logistic regression class"
},
{
"code": null,
"e": 5905,
"s": 5747,
"text": "I am a postdoctoral fellow at the Lawrence Berkeley National Laboratory, where I work at the intersection of machine learning and high-performance computing."
},
{
"code": null,
"e": 6048,
"s": 5905,
"text": "If you find this article interesting, feel free to say hello over LinkedIn, I’m always happy to connect with other professionals in the field."
}
] |
Recursive program to find the Sum of the series 1 - 1/2 + 1/3 - 1/4 ... 1/N - GeeksforGeeks
|
23 Apr, 2021
Given a positive integer N, the task is to find the sum of the series 1 – (1/2) + (1/3) – (1/4) +.... (1/N) using recursion.
Examples:
Input: N = 3 Output: 0.8333333333333333 Explanation: 1 – (1/2) + (1/3) = 0.8333333333333333
Input: N = 4 Output: 0.5833333333333333 Explanation: 1- (1/2) + (1/3) – (1/4) = 0.5833333333333333
Approach: The idea is to form a recursive case and base case in order to solve this problem using recursion. Therefore:
Base Case: The base case for this problem is when we have calculated the sum till the value of N in the denominator. Therefore, we stop the recursion when the counter variable ‘i’ reaches the value N.
Recursive Case: The recursive case for this problem is to find whether the denominator is an even or odd. This is because, clearly, for every odd number, the preceding sign is a ‘+’ and for every even number, the preceding sign is a ‘-‘. Therefore, we check whether the counter variable is an even or odd number and accordingly add or subtract the value. Then, the function is recursively called for the next value of the value ‘i’.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the value of// the given series#include<bits/stdc++.h>using namespace std; // Recursive program to find the// value of the given seriesfloat sumOfSeries(int i, int n, float s){ // Base case if (i > n ) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= (float)1 / i; // If we are currently looking // at the odd number else s+= (float)1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codeint main(){ // cout<<sumOfSeries(1,3,0); float sum = sumOfSeries(1, 3, 0); printf("%f", sum); return 0;} // This code is contributed by Rohit_ranjan
// Java program to find the value of// the given seriesimport java.util.*; class GFG{ // Recursive program to find the// value of the given seriesstatic float sumOfSeries(int i, int n, float s){ // Base case if (i > n) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= (float)1 / i; // If we are currently looking // at the odd number else s += (float)1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codepublic static void main(String[] args){ float sum = sumOfSeries(1, 3, 0); System.out.printf("%f", sum);}} // This code is contributed by Amit Katiyar
# Python program to find the value of# the given series # Recursive program to find the# value of the given seriesdef sumOfSeries(i, n, s) : # Base case if i>n : return s # Recursive case else : # If we are currently looking # at the even number if i % 2 == 0 : s-= 1 / i # If we are currently looking # at the odd number else : s+= 1 / i return sumOfSeries(i + 1, n, s) # Driver codeif __name__ == "__main__": print(sumOfSeries(1, 3, 0))
// C# program to find the value of// the given seriesusing System;class GFG{ // Recursive program to find the// value of the given seriesstatic float sumOfSeries(int i, int n, float s){ // Base case if (i > n ) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= (float)1 / i; // If we are currently looking // at the odd number else s += (float)1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codepublic static void Main(){ float sum = sumOfSeries(1, 3, 0); Console.Write(sum);}} // This code is contributed by Code_Mech
<script> // Javascript program to find the// value of the given series // Recursive program to find the// value of the given seriesfunction sumOfSeries(i, n, s){ // Base case if (i > n) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= 1 / i; // If we are currently looking // at the odd number else s += 1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codelet sum = sumOfSeries(1, 3, 0); document.write(sum); // This code is contributed by sravan kumar G </script>
0.8333333333333333
Rohit_ranjan
Code_Mech
amit143katiyar
sravankumar8128
Recursion
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Recursive Insertion Sort
Program to calculate Height and Depth of a node in a Binary Tree
Sum of natural numbers using recursion
Decimal to binary number using recursion
Recursively Reversing a linked list (A simple implementation)
Practice Questions for Recursion | Set 1
How will you print numbers from 1 to 100 without using loop?
Types of Recursions
Print all possible words from phone digits
Program to reverse a string (Iterative and Recursive)
|
[
{
"code": null,
"e": 24587,
"s": 24559,
"text": "\n23 Apr, 2021"
},
{
"code": null,
"e": 24712,
"s": 24587,
"text": "Given a positive integer N, the task is to find the sum of the series 1 – (1/2) + (1/3) – (1/4) +.... (1/N) using recursion."
},
{
"code": null,
"e": 24723,
"s": 24712,
"text": "Examples: "
},
{
"code": null,
"e": 24815,
"s": 24723,
"text": "Input: N = 3 Output: 0.8333333333333333 Explanation: 1 – (1/2) + (1/3) = 0.8333333333333333"
},
{
"code": null,
"e": 24914,
"s": 24815,
"text": "Input: N = 4 Output: 0.5833333333333333 Explanation: 1- (1/2) + (1/3) – (1/4) = 0.5833333333333333"
},
{
"code": null,
"e": 25036,
"s": 24914,
"text": "Approach: The idea is to form a recursive case and base case in order to solve this problem using recursion. Therefore: "
},
{
"code": null,
"e": 25237,
"s": 25036,
"text": "Base Case: The base case for this problem is when we have calculated the sum till the value of N in the denominator. Therefore, we stop the recursion when the counter variable ‘i’ reaches the value N."
},
{
"code": null,
"e": 25670,
"s": 25237,
"text": "Recursive Case: The recursive case for this problem is to find whether the denominator is an even or odd. This is because, clearly, for every odd number, the preceding sign is a ‘+’ and for every even number, the preceding sign is a ‘-‘. Therefore, we check whether the counter variable is an even or odd number and accordingly add or subtract the value. Then, the function is recursively called for the next value of the value ‘i’."
},
{
"code": null,
"e": 25722,
"s": 25670,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25726,
"s": 25722,
"text": "C++"
},
{
"code": null,
"e": 25731,
"s": 25726,
"text": "Java"
},
{
"code": null,
"e": 25739,
"s": 25731,
"text": "Python3"
},
{
"code": null,
"e": 25742,
"s": 25739,
"text": "C#"
},
{
"code": null,
"e": 25753,
"s": 25742,
"text": "Javascript"
},
{
"code": "// C++ program to find the value of// the given series#include<bits/stdc++.h>using namespace std; // Recursive program to find the// value of the given seriesfloat sumOfSeries(int i, int n, float s){ // Base case if (i > n ) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= (float)1 / i; // If we are currently looking // at the odd number else s+= (float)1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codeint main(){ // cout<<sumOfSeries(1,3,0); float sum = sumOfSeries(1, 3, 0); printf(\"%f\", sum); return 0;} // This code is contributed by Rohit_ranjan",
"e": 26496,
"s": 25753,
"text": null
},
{
"code": "// Java program to find the value of// the given seriesimport java.util.*; class GFG{ // Recursive program to find the// value of the given seriesstatic float sumOfSeries(int i, int n, float s){ // Base case if (i > n) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= (float)1 / i; // If we are currently looking // at the odd number else s += (float)1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codepublic static void main(String[] args){ float sum = sumOfSeries(1, 3, 0); System.out.printf(\"%f\", sum);}} // This code is contributed by Amit Katiyar",
"e": 27250,
"s": 26496,
"text": null
},
{
"code": "# Python program to find the value of# the given series # Recursive program to find the# value of the given seriesdef sumOfSeries(i, n, s) : # Base case if i>n : return s # Recursive case else : # If we are currently looking # at the even number if i % 2 == 0 : s-= 1 / i # If we are currently looking # at the odd number else : s+= 1 / i return sumOfSeries(i + 1, n, s) # Driver codeif __name__ == \"__main__\": print(sumOfSeries(1, 3, 0))",
"e": 27786,
"s": 27250,
"text": null
},
{
"code": "// C# program to find the value of// the given seriesusing System;class GFG{ // Recursive program to find the// value of the given seriesstatic float sumOfSeries(int i, int n, float s){ // Base case if (i > n ) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= (float)1 / i; // If we are currently looking // at the odd number else s += (float)1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codepublic static void Main(){ float sum = sumOfSeries(1, 3, 0); Console.Write(sum);}} // This code is contributed by Code_Mech",
"e": 28475,
"s": 27786,
"text": null
},
{
"code": "<script> // Javascript program to find the// value of the given series // Recursive program to find the// value of the given seriesfunction sumOfSeries(i, n, s){ // Base case if (i > n) return s; // Recursive case else { // If we are currently looking // at the even number if (i % 2 == 0) s -= 1 / i; // If we are currently looking // at the odd number else s += 1 / i; return sumOfSeries(i + 1, n, s); }} // Driver codelet sum = sumOfSeries(1, 3, 0); document.write(sum); // This code is contributed by sravan kumar G </script>",
"e": 29130,
"s": 28475,
"text": null
},
{
"code": null,
"e": 29149,
"s": 29130,
"text": "0.8333333333333333"
},
{
"code": null,
"e": 29164,
"s": 29151,
"text": "Rohit_ranjan"
},
{
"code": null,
"e": 29174,
"s": 29164,
"text": "Code_Mech"
},
{
"code": null,
"e": 29189,
"s": 29174,
"text": "amit143katiyar"
},
{
"code": null,
"e": 29205,
"s": 29189,
"text": "sravankumar8128"
},
{
"code": null,
"e": 29215,
"s": 29205,
"text": "Recursion"
},
{
"code": null,
"e": 29225,
"s": 29215,
"text": "Recursion"
},
{
"code": null,
"e": 29323,
"s": 29225,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29332,
"s": 29323,
"text": "Comments"
},
{
"code": null,
"e": 29345,
"s": 29332,
"text": "Old Comments"
},
{
"code": null,
"e": 29370,
"s": 29345,
"text": "Recursive Insertion Sort"
},
{
"code": null,
"e": 29435,
"s": 29370,
"text": "Program to calculate Height and Depth of a node in a Binary Tree"
},
{
"code": null,
"e": 29474,
"s": 29435,
"text": "Sum of natural numbers using recursion"
},
{
"code": null,
"e": 29515,
"s": 29474,
"text": "Decimal to binary number using recursion"
},
{
"code": null,
"e": 29577,
"s": 29515,
"text": "Recursively Reversing a linked list (A simple implementation)"
},
{
"code": null,
"e": 29618,
"s": 29577,
"text": "Practice Questions for Recursion | Set 1"
},
{
"code": null,
"e": 29679,
"s": 29618,
"text": "How will you print numbers from 1 to 100 without using loop?"
},
{
"code": null,
"e": 29699,
"s": 29679,
"text": "Types of Recursions"
},
{
"code": null,
"e": 29742,
"s": 29699,
"text": "Print all possible words from phone digits"
}
] |
Groovy - equals()
|
The method determines whether the Number object that invokes the method is equal to the object that is passed as argument.
public boolean equals(Object o)
o - Any object.
The methods returns True if the argument is not null and is an object of the same type and with the same numeric value.
Following is an example of the usage of this method −
class Example {
static void main(String[] args) {
Integer x = 5;
Integer y = 10;
Integer z = 5;
//Comparison against an Integer of different value
System.out.println(x.equals(y));
//Comparison against an Integer of same value
System.out.println(x.equals(z));
}
}
When we run the above program, we will get the following result −
false
true
52 Lectures
8 hours
Krishna Sakinala
49 Lectures
2.5 hours
Packt Publishing
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2361,
"s": 2238,
"text": "The method determines whether the Number object that invokes the method is equal to the object that is passed as argument."
},
{
"code": null,
"e": 2394,
"s": 2361,
"text": "public boolean equals(Object o)\n"
},
{
"code": null,
"e": 2410,
"s": 2394,
"text": "o - Any object."
},
{
"code": null,
"e": 2530,
"s": 2410,
"text": "The methods returns True if the argument is not null and is an object of the same type and with the same numeric value."
},
{
"code": null,
"e": 2584,
"s": 2530,
"text": "Following is an example of the usage of this method −"
},
{
"code": null,
"e": 2911,
"s": 2584,
"text": "class Example { \n static void main(String[] args) { \n Integer x = 5; \n Integer y = 10; \n Integer z = 5; \n\t\t\n //Comparison against an Integer of different value \n System.out.println(x.equals(y));\n\t\t\n //Comparison against an Integer of same value \n System.out.println(x.equals(z)); \n } \n}"
},
{
"code": null,
"e": 2977,
"s": 2911,
"text": "When we run the above program, we will get the following result −"
},
{
"code": null,
"e": 2990,
"s": 2977,
"text": "false \ntrue\n"
},
{
"code": null,
"e": 3023,
"s": 2990,
"text": "\n 52 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3041,
"s": 3023,
"text": " Krishna Sakinala"
},
{
"code": null,
"e": 3076,
"s": 3041,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3094,
"s": 3076,
"text": " Packt Publishing"
},
{
"code": null,
"e": 3101,
"s": 3094,
"text": " Print"
},
{
"code": null,
"e": 3112,
"s": 3101,
"text": " Add Notes"
}
] |
MathML - Quick Guide
|
MathML stands for Mathematical Markup Language and is an XML based application. It is used to describe mathematical and scientific notations. It's 1 and 2 version were created and developed by The Math Working Group which is one of the oldest W3C Working Groups during 1996-2004. MathML version 3 was created during Math Working Group's second activity period (2006-2016)and is an ISO standard.
MathML is XML based and have limited number of tags which can be used to mark up a mathematical equation in terms of format and its semantics. MathML intends to capture meaning of syntax as well as formatting of the equation. Considering the fact the mathematical equations are often meaningful to many applications so writing them using MathML handles formatting as well as meaning of an equation. MathML provides low-level format to describing mathematics as a basis taken for machine to machine communication.
Various applications like algebra systems, print typesetters can use MathML to encode mathematical notation for high-quality visual display, and mathematical content and scientific software, voice synthesizers can use MathML for semantics.
MathML provides two ways to represent a mathematical notation.
Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc.
Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc.
Semantic Way − It uses mark up tags like apply, eq, power etc.
Semantic Way − It uses mark up tags like apply, eq, power etc.
We are using MathJax library to render MathML syntax so that it can run on all major browsers. It currently supports presentational way only.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mrow>
<msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo>
<mrow>
<mn>4</mn>
<mo></mo>
<mi>x</mi>
</mrow>
<mo>+</mo>
<mn>4</mn>
</mrow>
<mo>=</mo>
<mn>0</mn>
</mrow>
</math>
<maction> − Provides option to bind actions to subexpressions/expressions.
<maction> − Provides option to bind actions to subexpressions/expressions.
<math> − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag.
<math> − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag.
<menclose> − Renders its content inside an enclosing notation specified by the notation attribute.
<menclose> − Renders its content inside an enclosing notation specified by the notation attribute.
<merror> − Used to display contents as error message.
<merror> − Used to display contents as error message.
<mfenced> − Provides the option to add custom opening and closing parentheses and separators to an expression.
<mfenced> − Provides the option to add custom opening and closing parentheses and separators to an expression.
<mfrac> − Used to display fractions.
<mfrac> − Used to display fractions.
<mglyph> − Used to display non-standard symbols where existing Unicode characters are not available.
<mglyph> − Used to display non-standard symbols where existing Unicode characters are not available.
<mi> − Used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> .
<mi> − Used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> .
<mlabeledtr> − Used to represent a label in a row either on the left or on the right side using side attribute of mtable. Child elements of mlabeledtr must be mtd elements.
<mlabeledtr> − Used to represent a label in a row either on the left or on the right side using side attribute of mtable. Child elements of mlabeledtr must be mtd elements.
<mmultiscripts> − Provides options to create tensor-like objects.
<mmultiscripts> − Provides options to create tensor-like objects.
<mn> − Used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>.
<mn> − Used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>.
<mo> − Used to specify an operator like +, - etc. For example, <mo>+</mo>.
<mo> − Used to specify an operator like +, - etc. For example, <mo>+</mo>.
<mover> − Used to attach an accent or a limit over an expression.
<mover> − Used to attach an accent or a limit over an expression.
<mpadded> − Used to add extra padding and to set the general adjustment of position and size of enclosed contents.
<mpadded> − Used to add extra padding and to set the general adjustment of position and size of enclosed contents.
<mphantom> − Used to create space as it is rendered invisibly, keeping height, width, and baseline position intact.
<mphantom> − Used to create space as it is rendered invisibly, keeping height, width, and baseline position intact.
<mroot> − Used to display roots with an explicit index.
<mroot> − Used to display roots with an explicit index.
<mrow> − Used to group any number of sub expressions in horizontal way.
<mrow> − Used to group any number of sub expressions in horizontal way.
<ms> − Used to represent a string literal meant to be interpreted by programming languages and computer algebra systems.
<ms> − Used to represent a string literal meant to be interpreted by programming languages and computer algebra systems.
<mspace> − Used to display a blank space, where its size is set using its attributes.
<mspace> − Used to display a blank space, where its size is set using its attributes.
<msqrt> − Used to display square root.
<msqrt> − Used to display square root.
<mstyle> − Used to apply the style on its children.
<mstyle> − Used to apply the style on its children.
<msub> − Used to attach a subscript to an expression. It uses the following syntax: <msub> base subscript </msub>.
<msub> − Used to attach a subscript to an expression. It uses the following syntax: <msub> base subscript </msub>.
<msubsup> − Used to attach both a subscript and a superscript, together, to an expression. It uses the following syntax: <msubsup> base subscript superscript </msubsup>.
<msubsup> − Used to attach both a subscript and a superscript, together, to an expression. It uses the following syntax: <msubsup> base subscript superscript </msubsup>.
<msup> − Used to attach a superscript to an expression. It uses the following syntax: msup base superscript </msup>.
<msup> − Used to attach a superscript to an expression. It uses the following syntax: msup base superscript </msup>.
<mtable> − Provides options to create tables or matrices.
<mtable> − Provides options to create tables or matrices.
<mtd> − To represent a cell in a table or a matrix.
<mtd> − To represent a cell in a table or a matrix.
<mtext> − Used to render text with no notational meaning, such as comments or annotations.
<mtext> − Used to render text with no notational meaning, such as comments or annotations.
<mtr> − Represents a row in a table or a matrix.
<mtr> − Represents a row in a table or a matrix.
<munder> − Provides option to attach an accent or a limit under an expression. It uses the following syntax: <munder> base underscript </munder>
<munder> − Provides option to attach an accent or a limit under an expression. It uses the following syntax: <munder> base underscript </munder>
<munderover> − Provides option to attach accents or limits both under and over an expression. It uses the following syntax: </munderover> base underscript overscript </munderover>
<munderover> − Provides option to attach accents or limits both under and over an expression. It uses the following syntax: </munderover> base underscript overscript </munderover>
<semantics> − <semantics>,<annotation> and <annotation-xml> are used to add presentation and content markup and provides both, layout information and semantic meaning of mathematical expressions.
<semantics> − <semantics>,<annotation> and <annotation-xml> are used to add presentation and content markup and provides both, layout information and semantic meaning of mathematical expressions.
There are five basic elements of a MathML expression.
<math> element − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag.
<math> element − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag.
<mrow> element − It is used to group any number of sub expressions in horizontal way.
<mrow> element − It is used to group any number of sub expressions in horizontal way.
<mi> element − It is used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> .
<mi> element − It is used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> .
<mo> element − It is used to specify an operator like +, - etc. For example, <mo>+</mo>.
<mo> element − It is used to specify an operator like +, - etc. For example, <mo>+</mo>.
<mn> element − It is used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>.
<mn> element − It is used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>.
Let's build a simple mathematical equation a + b = 5 using MathML notation.
Here a, b are variables. + is an operator and 5 is a number. We'll enclose them as <mi>a</mi> , <mi>b</mi>, <mo>+</mo> and <mn>+</mn>
Syntax
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>a</mi>
<mo>+</mo>
<mi>b</mi>
</mrow>
</math>
Output
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mrow>
<mi>a</mi>
<mo>+</mo>
<mi>b</mi>
</mrow>
<mo>=</mo>
<mn>5</mn>
</mrow>
</math>
Output
The <mscarries> element can be used to create carries, borrows, and crossouts that occur in elementary math. The children of mscarries are associated with elements in the following row of the mstack. Each child of mscarries except <mscarry> or <none> is treated as being implicitly surrounded by mscarry. <none> is used when particular column don't need a carry. The mscarries element sets displaystyle to false, and increments scriptlevel by 1, so the children are typically displayed in a smaller font.
Here is the simple syntax to use this tag −
<mscarries> expression <mscarry> <none/> </mscarry> </mscarries>
Here is the description of all the parameters of this tag −
expression − expression on which carry/borrow is to be applied.
expression − expression on which carry/borrow is to be applied.
mscarry − carry tag.
mscarry − carry tag.
Here is the description of all the attributes of this tag −
position − to specify the horizontal position of the rows within this group relative the position determined by the containing msgroup.
position − to specify the horizontal position of the rows within this group relative the position determined by the containing msgroup.
location − to specify location of the carry or borrow relative to the character below it in the associated column. values are w, nw, n, ne, e, se, s, sw.
location − to specify location of the carry or borrow relative to the character below it in the associated column. values are w, nw, n, ne, e, se, s, sw.
crossout − to specify how the column content below each carry is crossed out; one or more values may be given and all values are drawn. Values are none, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike. Default is none.
crossout − to specify how the column content below each carry is crossed out; one or more values may be given and all values are drawn. Values are none, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike. Default is none.
scriptsizemultiplier − to specify the factor to change the font size by.
scriptsizemultiplier − to specify the factor to change the font size by.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mstack>
<mscarries crossout='updiagonalstrike'>
<mn>2</mn>
<mn>12</mn>
<mscarry crossout='none'>
<none/>
</mscarry>
</mscarries>
<mn>2,327</mn>
<msrow>
<mo>-</mo>
<mn> 1,156</mn>
</msrow>
<msline/>
<mn>1,171</mn>
</mstack>
</math>
<menclose> tag is used to renders content inside the enclosing notation as specified by its notation attribute. it accepts a single argument as an inferred mrow of multiple children.
Here is the simple syntax to use this tag −
<menclose> expression </menclose>
Here is the description of all the parameters of this tag −
expression − expression.
expression − expression.
Here is the description of all the attributes of this tag −
notation − to specify a space separated list of notations to be used to enclose the children. Valid values are longdiv, actuarial, phasorangle, radical, box, roundedbox, circle, left, right, top, bottom, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike, northeastarrow, madruwb, text. Default is longdiv.
notation − to specify a space separated list of notations to be used to enclose the children. Valid values are longdiv, actuarial, phasorangle, radical, box, roundedbox, circle, left, right, top, bottom, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike, northeastarrow, madruwb, text. Default is longdiv.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mi>C</mi>
<mrow>
<menclose notation = 'phasorangle'>
<mrow>
<mo>−</mo>
<mfrac>
<mi>π</mi>
<mn>2</mn>
</mfrac>
</mrow>
</menclose>
</mrow>
</math>
<mfenced> tag is a convenient method to use fencing operators like curly braces, brackets and parentheses instead of using <mo> tags for them.
Here is the simple syntax to use this tag −
<mfenced> expression </mfenced>
Here is the description of all the parameters of this tag −
expression − expression.
expression − expression.
Here is the description of all the attributes of this tag −
open − To specify the opening delimiter. Default is '('.
open − To specify the opening delimiter. Default is '('.
close − To specify the closing delimiter. Default is ')'.
close − To specify the closing delimiter. Default is ')'.
separators − To specify a sequence of zero or more separator characters, optionally separated by whitespace. Default is ','.
separators − To specify a sequence of zero or more separator characters, optionally separated by whitespace. Default is ','.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mo>(</mo>
<mi>x</mi>
<mo>)</mo>
</mrow>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mfenced>
<mi>x</mi>
</mfenced>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mi> f </mi>
<mo> </mo>
<mfenced>
<mi> x </mi>
<mi> y </mi>
</mfenced>
</mrow>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mfenced>
<mrow>
<mi> a </mi>
<mo> + </mo>
<mi> b </mi>
</mrow>
</mfenced>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mfenced open="[">
<mn> 0 </mn>
<mn> 1 </mn>
</mfenced>
</math>
<mfrac> tag is used to draw fractions.
Here is the simple syntax to use this tag −
<mfrac> numerator denominator </mfrac>
Here is the description of all the parameters of this tag −
numerator − numerator of the fraction.
numerator − numerator of the fraction.
denominator − denominator of the fraction.
denominator − denominator of the fraction.
Here is the description of all the attributes of this tag −
linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc.
linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc.
numalign − to specify alignment of numerator. values are left, right or center.
numalign − to specify alignment of numerator. values are left, right or center.
denomalign − to specify alignment of denominator. values are left, right or center.
denomalign − to specify alignment of denominator. values are left, right or center.
bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false.
bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false.
Let's draw a simple fraction for 1/x.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mfrac>
<mn>1</mn>
<mi>x</mi>
</mfrac>
</math>
Let's build a complex fraction.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mfrac linethickness = '3px'>
<mfrac bevelled = 'true'>
<mn>1</mn>
<mi>x</mi>
</mfrac>
<mrow>
<mi>y</mi>
<mo>-</mo>
<mn>2</mn>
</mrow>
</mfrac>
</math>
<mlongdiv> tag is used to draw long divisions.
Here is the simple syntax to use this tag −
<mlongdiv> divisor dividend result expression </mlongdiv>
Here is the description of all the parameters of this tag −
divisor − divisor of the long division.
divisor − divisor of the long division.
dividend − dividend of the long division.
dividend − dividend of the long division.
result − result of the long division.
result − result of the long division.
expression − mstack element or children of mstack.
expression − mstack element or children of mstack.
Here is the description of all the attributes of this tag −
longdivstyle − to control the style of the long division layout. Valid values are lefttop, stackedrightright, mediumstackedrightright, shortstackedrightright, righttop, left/\right, left)(right, :right=right, stackedleftleft, stackedleftlinetop. Default is lefttop.
longdivstyle − to control the style of the long division layout. Valid values are lefttop, stackedrightright, mediumstackedrightright, shortstackedrightright, righttop, left/\right, left)(right, :right=right, stackedleftleft, stackedleftlinetop. Default is lefttop.
Let's draw a simple fraction for 1/x.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mlongdiv longdivstyle = "lefttop">
<mn> 3 </mn>
<mn> 435.3</mn>
<mn> 1306</mn>
<msgroup position = "2" shift = "-1">
<msgroup>
<mn> 12</mn>
<msline length = "2"/>
</msgroup>
<msgroup>
<mn> 10</mn>
<mn> 9</mn>
<msline length = "2"/>
</msgroup>
<msgroup>
<mn> 16</mn>
<mn> 15</mn>
<msline length = "2"/>
<mn> 1.0</mn>
</msgroup>
<msgroup position='-1'>
<mn> 9</mn>
<msline length = "3"/>
<mn> 1</mn>
</msgroup>
</msgroup>
</mlongdiv>
</math>
<mtable> tag is used to draw matrices.
mtable is similar to table tag of HTML and this tag uses mtr, mtd elements which are similar to tr and td tags of HTML.
<mtable> <mtr> <mtd></mtd></mtr></mfrac>
Here is the description of all the attributes of this tag −
align − To specify the vertical alignment of the table . Valid values are: axis, baseline, bottom, center, top. Default is axis.
align − To specify the vertical alignment of the table . Valid values are: axis, baseline, bottom, center, top. Default is axis.
class, id, style − Used with stylesheets.
class, id, style − Used with stylesheets.
columnalign − To specify the horizontal alignment of the cells. Valid values are: left, center and right. Default is center.
columnalign − To specify the horizontal alignment of the cells. Valid values are: left, center and right. Default is center.
columnlines − To specify column borders. Valid values are: none, solid and dashed. Default is none.
columnlines − To specify column borders. Valid values are: none, solid and dashed. Default is none.
columnspacing − To specify the space between table columns.
columnspacing − To specify the space between table columns.
displaystyle − If true more vertical space is used for displayed equations , if false, a more compact layout is used to display formulas.
displaystyle − If true more vertical space is used for displayed equations , if false, a more compact layout is used to display formulas.
frame − To specify borders of the entire table. Valid values are: none, solid and dashed. Default is none.
frame − To specify borders of the entire table. Valid values are: none, solid and dashed. Default is none.
framespacing − To specify additional space added between the table and frame.
framespacing − To specify additional space added between the table and frame.
href − To specify a hyperlink to a specified uri.
href − To specify a hyperlink to a specified uri.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
rowalign − To specify vertical alignment of the cells. Valid values are axis, baseline, bottom, center and top. Default is baseline
rowalign − To specify vertical alignment of the cells. Valid values are axis, baseline, bottom, center and top. Default is baseline
rowlines − To specify row borders. Valid values are: none, solid and dashed. Default is none.
rowlines − To specify row borders. Valid values are: none, solid and dashed. Default is none.
width − To specify width of the entire table.
width − To specify width of the entire table.
Let's draw a 3 x 3 metric.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mo>[</mo>
<mtable>
<mtr>
<mtd><mn>1</mn></mtd>
<mtd><mn>0</mn></mtd>
<mtd><mn>0</mn></mtd>
</mtr>
<mtr>
<mtd><mn>0</mn></mtd>
<mtd><mn>1</mn></mtd>
<mtd><mn>0</mn></mtd>
</mtr>
<mtr>
<mtd><mn>0</mn></mtd>
<mtd><mn>0</mn></mtd>
<mtd><mn>1</mn></mtd>
</mtr>
</mtable>
<mo>]</mo>
</mrow>
</math>
<msgroup> is used to group rows inside <mstack> element and <mlongdiv> elements to have position relative to the alignment of stack. <msgroup> element with shift attribute can be used to create simple multiplications.
Here is the simple syntax to use this tag −
<msgroup> expression </msgroup>
Here is the description of all the parameters of this tag −
expression − expression.
expression − expression.
Here is the description of all the attributes of this tag −
position − to specify the horizontal position of the rows within the group relative the position controlled by the containing msgroup (as per its position and shift attributes). Default value is 0.
position − to specify the horizontal position of the rows within the group relative the position controlled by the containing msgroup (as per its position and shift attributes). Default value is 0.
shift − to specify an incremental shift of position for successive children (rows or groups) within the group. Default value is 0.
shift − to specify an incremental shift of position for successive children (rows or groups) within the group. Default value is 0.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mstack>
<msgroup>
<mn>123</mn>
<msrow>
<mo>×</mo>
<mn>321</mn>
</msrow>
</msgroup>
<msline/>
<msgroup shift = "1">
<mn>123</mn>
<mn>246</mn>
<mn>369</mn>
</msgroup>
<msline/>
<mn>39483</mn>
</mstack>
</math>
<mover> tag is used to draw overscript. It adds an accent or a limit over an expression.
Here is the simple syntax to use this tag −
<mover> base overscript </mover>
Here is the description of all the parameters of this tag −
base − base expression on which the overscript is to be drawn.
base − base expression on which the overscript is to be drawn.
overscript − overscript.
overscript − overscript.
Here is the description of all the attributes of this tag −
accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false.
accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false.
align − To specify the alignment of the over-script. Valid are: left, center, and right.
align − To specify the alignment of the over-script. Valid are: left, center, and right.
class, id, style − Used with stylesheets.
class, id, style − Used with stylesheets.
href − To specify a hyperlink to a specified uri.
href − To specify a hyperlink to a specified uri.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
Let's draw an overscript.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mover accent = "true">
<mrow>
<mi> x </mi>
<mo> + </mo>
<mi> y </mi>
<mo> + </mo>
<mi> z </mi>
</mrow>
<mo>⏞</mo>
</mover>
</math>
<mpadded> element is used to add padding, or extra space, around its content. It can be used to adjust size and positioning e.g. negative padding,which can cause the content of mpadded to overlap the rendering of neighboring content.
Here is the simple syntax to use this tag −
<mpadded> expression </mpadded>
Here is the description of all the parameters of this tag −
expression − inferred mrow of multiple children.
expression − inferred mrow of multiple children.
Here is the description of all the attributes of this tag −
height − To sets or increment the height of the mpadded element.
height − To sets or increment the height of the mpadded element.
depth − To sets or increment the depth of the mpadded element.
depth − To sets or increment the depth of the mpadded element.
width − To sets or increment the width of the mpadded element.
width − To sets or increment the width of the mpadded element.
lspace − To sets the horizontal space of the child content.
lspace − To sets the horizontal space of the child content.
voffset − To sets the vertical space of the child content.
voffset − To sets the vertical space of the child content.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>x</mi>
<mpadded lspace = "0.2em" voffset = "0.3ex">
<mi>y</mi>
</mpadded>
<mi>z</mi>
</mrow>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>x</mi>
<mpadded width = "+90%width" height = "+0.3ex" depth = "+0.3ex">
<mi>y</mi>
</mpadded>
<mi>z</mi>
</mrow>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>x</mi>
<mpadded lspace = "0.3em" width = "+0.6em">
<mi>y</mi>
</mpadded>
<mi>z</mi>
</mrow>
</math>
<mphantom> element renders invisibly keeping same size and other dimensions, including baseline position, as its contents would have if they were rendered normally. It is used to align parts of an expression by invisibly duplicating sub-expressions.
Here is the simple syntax to use this tag −
<mphantom> expression </mphantom>
Here is the description of all the parameters of this tag −
expression − inferred mrow of multiple children.
expression − inferred mrow of multiple children.
Here is the description of all the attributes of this tag −
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mfrac>
<mrow>
<mi> x </mi>
<mo> + </mo>
<mi> y </mi>
<mo> + </mo>
<mi> z </mi>
</mrow>
<mrow>
<mi> x </mi>
<mphantom>
<mo> + </mo>
</mphantom>
<mphantom>
<mi> y </mi>
</mphantom>
<mo> + </mo>
<mi> z </mi>
</mrow>
</mfrac>
</math>
msqrt and mroot elements construct radicals. The msqrt element constructs square roots, while the mroot element constructs radicals with indices, for example a cube root.
<msqrt> tag is used to draw square root.
Here is the simple syntax to use this tag −
<msqrt> base </msqrt>
Here is the description of all the parameters of this tag −
base − base expression on which the square root is to be drawn.
base − base expression on which the square root is to be drawn.
Here is the description of all the attributes of this tag −
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
Let's draw a square root.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<msqrt>
<mn>4</mn>
</msqrt>
</math>
<mroot> tag is used to draw radicals with indices.
Here is the simple syntax to use this tag −
<mroot> base index </mroot>
Here is the description of all the parameters of this tag −
base − base expression on which the square root is to be drawn.
base − base expression on which the square root is to be drawn.
index − index of the root to be drawn.
index − index of the root to be drawn.
Here is the description of all the attributes of this tag −
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
Let's draw a cube root.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mroot>
<mn>8</mn>
<mn>3</mn>
</mroot>
</math>
Decimal numbers having digit(s) that repeat(s) infinitely such as 1/3 (.3333...) are represented by putting a horizontal line over or below the digits that repeat. <mstack> , <msrow>, and <msline> elements can be used to create decimal numbers with repeated digits as shown below.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mstack stackalign = "right">
<msline length = "1"/>
<mn> 0.3333 </mn>
</mstack>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mstack stackalign="right">
<msline length="6"/>
<mn> 0.142857 </mn>
</mstack>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mstack stackalign="right">
<mn> 0.142857 </mn>
<msline length="6"/>
</mstack>
</math>
<mstyle> tag is used to make style changes that affect the rendering of its contents.
Here is the simple syntax to use this tag −
<mstyle> expression </mstyle>
Here is the description of all the parameters of this tag −
expression − inferred mrow elements.
expression − inferred mrow elements.
Here is the description of all the attributes of this tag −
scriptlevel − To specify the scriptlevel for the children. Without a sign, it sets scriptlevel to the specified value; With a sign it increments ("+") or decrements ("-") the current value.
scriptlevel − To specify the scriptlevel for the children. Without a sign, it sets scriptlevel to the specified value; With a sign it increments ("+") or decrements ("-") the current value.
displaystyle − To specify the displaystyle.
displaystyle − To specify the displaystyle.
scriptsizemultiplier − To specify the multiplier to be used to adjust font size due to changes in scriptlevel.
scriptsizemultiplier − To specify the multiplier to be used to adjust font size due to changes in scriptlevel.
scriptminsize − To specify the minimum font size allowed due to changes in scriptlevel.
scriptminsize − To specify the minimum font size allowed due to changes in scriptlevel.
infixlinebreakstyle − To specify he default linebreakstyle to use for infix operators.
infixlinebreakstyle − To specify he default linebreakstyle to use for infix operators.
decimalpoint − To specify the character used to determine the alignment point within <mstack> and <mtable> columns when the "decimalpoint" value is used to specify the alignment. Default is '.'.
decimalpoint − To specify the character used to determine the alignment point within <mstack> and <mtable> columns when the "decimalpoint" value is used to specify the alignment. Default is '.'.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mo maxsize = "100%"> ( </mo>
<mfrac>
<mi> a </mi>
<mi> b </mi>
</mfrac>
<mo maxsize = "100%"> ) </mo>
</mrow>
</math>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mstyle maxsize = "100%">
<mrow>
<mo> ( </mo>
<mfrac>
<mi> a </mi>
<mi> b </mi>
</mfrac>
<mo> ) </mo>
</mrow>
</mstyle>
</math>
<msub> tag is used to draw subscript to an expression.
Here is the simple syntax to use this tag −
<msub> base subscript </msub>
Here is the description of all the parameters of this tag −
base − base expression on which the subscript is to be drawn.
base − base expression on which the subscript is to be drawn.
subscript − subscript.
subscript − subscript.
Here is the description of all the attributes of this tag −
subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression.
subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression.
class, id, style − Used with stylesheets.
class, id, style − Used with stylesheets.
href − To specify a hyperlink to a specified uri.
href − To specify a hyperlink to a specified uri.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
Let's draw a subscript.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<msub>
<mi>x</mi>
<mn>1</mn>
</msub>
</math>
<msubsup> tag is used to attach both subscript and superscript to an expression.
Here is the simple syntax to use this tag −
<msubsup> base subscript superscript</msubsup>
Here is the description of all the parameters of this tag −
base − base expression on which the subscript and superscript is to be drawn.
base − base expression on which the subscript and superscript is to be drawn.
subscript − subscript.
subscript − subscript.
superscript − superscript.
superscript − superscript.
Here is the description of all the attributes of this tag −
subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression.
subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression.
superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression.
superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression.
Let's draw a subscript and superscript.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<msubsup>
<mo> ∫</mo>
<mn> 0 </mn>
<mn> 1 </mn>
</msubsup>
<mrow>
<msup>
<mi> e</mi>
<mi> x </mi>
</msup>
<mo> </mo>
<mrow>
<mi> d</mi>
<mi> x </mi>
</mrow>
</mrow>
</mrow>
</math>
<msup> tag is used to draw superscript to an expression.
Here is the simple syntax to use this tag −
<msup> base superscript </msup>
Here is the description of all the parameters of this tag −
base − base expression on which the superscript is to be drawn.
base − base expression on which the superscript is to be drawn.
superscript − superscript.
superscript − superscript.
Here is the description of all the attributes of this tag −
superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression.
superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression.
class, id, style − Used with stylesheets.
class, id, style − Used with stylesheets.
href − To specify a hyperlink to a specified uri.
href − To specify a hyperlink to a specified uri.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
Let's draw a superscript.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<msup>
<mi>x</mi>
<mn>1</mn>
</msup>
</math>
Use mrow in order to add sub-expressions in superscripts.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<msup>
<mi>e</mi>
<mrow>
<mn>2</mn>
<mi>x</mi>
<mo>+</mo>
<mn>1</mn>
</mrow>
</msup>
</math>
<munder> tag is used to draw underscript. It adds an accent or a limit under an expression.
Here is the simple syntax to use this tag −
<munder> base underscript </munder>
Here is the description of all the parameters of this tag −
base − base expression on which the underscript is to be drawn.
base − base expression on which the underscript is to be drawn.
underscript − underscript.
underscript − underscript.
Here is the description of all the attributes of this tag −
accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false.
accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false.
align − To specify the alignment of the under-script. Valid are: left, center, and right.
align − To specify the alignment of the under-script. Valid are: left, center, and right.
class, id, style − Used with stylesheets.
class, id, style − Used with stylesheets.
href − To specify a hyperlink to a specified uri.
href − To specify a hyperlink to a specified uri.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
Let's draw an underscript.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<munder accent="true">
<mrow>
<mi> x </mi>
<mo> + </mo>
<mi> y </mi>
<mo> + </mo>
<mi> z </mi>
</mrow>
<mo>ȿ</mo>
</munder>
</math>
<munderover> tag is used to draw both over and under underscript. It adds an accent or a limit over and under an expression.
Here is the simple syntax to use this tag −
<munderover> base underscript overscript </munderover>
Here is the description of all the parameters of this tag −
base − base expression on which the underscript is to be drawn.
base − base expression on which the underscript is to be drawn.
underscript − underscript.
underscript − underscript.
overscript − overscript.
overscript − overscript.
Here is the description of all the attributes of this tag −
accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false.
accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false.
accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false.
accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false.
align − To specify the alignment of the under-script. Valid are: left, center, and right. Default is center.
align − To specify the alignment of the under-script. Valid are: left, center, and right. Default is center.
Let's draw an underscript.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<munderover>
<mo> ∫</mo>
<mn> 0 </mn>
<mi> ∞</mi>
</munderover>
</mrow>
</math>
Following is a list of Algebra symbols available in MathML.
Following is a list of Calculus symbols available in MathML.
Following is a list of ellipses symbols available in MathML.
Following is a list of function symbols available in MathML.
Following is a list of geometry symbols available in MathML.
Following is a list of greek letters available in MathML.
Following is a list of invisible operators available in MathML.
Following is a list of logic symbols available in MathML.
Following is a list of set symbols available in MathML.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2652,
"s": 2257,
"text": "MathML stands for Mathematical Markup Language and is an XML based application. It is used to describe mathematical and scientific notations. It's 1 and 2 version were created and developed by The Math Working Group which is one of the oldest W3C Working Groups during 1996-2004. MathML version 3 was created during Math Working Group's second activity period (2006-2016)and is an ISO standard."
},
{
"code": null,
"e": 3165,
"s": 2652,
"text": "MathML is XML based and have limited number of tags which can be used to mark up a mathematical equation in terms of format and its semantics. MathML intends to capture meaning of syntax as well as formatting of the equation. Considering the fact the mathematical equations are often meaningful to many applications so writing them using MathML handles formatting as well as meaning of an equation. MathML provides low-level format to describing mathematics as a basis taken for machine to machine communication."
},
{
"code": null,
"e": 3405,
"s": 3165,
"text": "Various applications like algebra systems, print typesetters can use MathML to encode mathematical notation for high-quality visual display, and mathematical content and scientific software, voice synthesizers can use MathML for semantics."
},
{
"code": null,
"e": 3468,
"s": 3405,
"text": "MathML provides two ways to represent a mathematical notation."
},
{
"code": null,
"e": 3567,
"s": 3468,
"text": "Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc."
},
{
"code": null,
"e": 3666,
"s": 3567,
"text": "Presentational Way − It uses mark up tags like mrow, mi, mo along with mathematical operators etc."
},
{
"code": null,
"e": 3729,
"s": 3666,
"text": "Semantic Way − It uses mark up tags like apply, eq, power etc."
},
{
"code": null,
"e": 3792,
"s": 3729,
"text": "Semantic Way − It uses mark up tags like apply, eq, power etc."
},
{
"code": null,
"e": 3934,
"s": 3792,
"text": "We are using MathJax library to render MathML syntax so that it can run on all major browsers. It currently supports presentational way only."
},
{
"code": null,
"e": 4282,
"s": 3934,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mrow>\n <msup> <mi>x</mi> <mn>2</mn> </msup> <mo>+</mo>\n <mrow>\n <mn>4</mn>\n <mo></mo>\n <mi>x</mi>\n </mrow>\n <mo>+</mo>\n <mn>4</mn>\n </mrow>\n \n <mo>=</mo>\n <mn>0</mn>\n </mrow>\n</math>"
},
{
"code": null,
"e": 4357,
"s": 4282,
"text": "<maction> − Provides option to bind actions to subexpressions/expressions."
},
{
"code": null,
"e": 4432,
"s": 4357,
"text": "<maction> − Provides option to bind actions to subexpressions/expressions."
},
{
"code": null,
"e": 4706,
"s": 4432,
"text": "<math> − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag."
},
{
"code": null,
"e": 4980,
"s": 4706,
"text": "<math> − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag."
},
{
"code": null,
"e": 5079,
"s": 4980,
"text": "<menclose> − Renders its content inside an enclosing notation specified by the notation attribute."
},
{
"code": null,
"e": 5178,
"s": 5079,
"text": "<menclose> − Renders its content inside an enclosing notation specified by the notation attribute."
},
{
"code": null,
"e": 5232,
"s": 5178,
"text": "<merror> − Used to display contents as error message."
},
{
"code": null,
"e": 5286,
"s": 5232,
"text": "<merror> − Used to display contents as error message."
},
{
"code": null,
"e": 5397,
"s": 5286,
"text": "<mfenced> − Provides the option to add custom opening and closing parentheses and separators to an expression."
},
{
"code": null,
"e": 5508,
"s": 5397,
"text": "<mfenced> − Provides the option to add custom opening and closing parentheses and separators to an expression."
},
{
"code": null,
"e": 5545,
"s": 5508,
"text": "<mfrac> − Used to display fractions."
},
{
"code": null,
"e": 5582,
"s": 5545,
"text": "<mfrac> − Used to display fractions."
},
{
"code": null,
"e": 5683,
"s": 5582,
"text": "<mglyph> − Used to display non-standard symbols where existing Unicode characters are not available."
},
{
"code": null,
"e": 5784,
"s": 5683,
"text": "<mglyph> − Used to display non-standard symbols where existing Unicode characters are not available."
},
{
"code": null,
"e": 5904,
"s": 5784,
"text": "<mi> − Used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> ."
},
{
"code": null,
"e": 6024,
"s": 5904,
"text": "<mi> − Used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> ."
},
{
"code": null,
"e": 6198,
"s": 6024,
"text": "<mlabeledtr> − Used to represent a label in a row either on the left or on the right side using side attribute of mtable. Child elements of mlabeledtr must be mtd elements."
},
{
"code": null,
"e": 6372,
"s": 6198,
"text": "<mlabeledtr> − Used to represent a label in a row either on the left or on the right side using side attribute of mtable. Child elements of mlabeledtr must be mtd elements."
},
{
"code": null,
"e": 6438,
"s": 6372,
"text": "<mmultiscripts> − Provides options to create tensor-like objects."
},
{
"code": null,
"e": 6504,
"s": 6438,
"text": "<mmultiscripts> − Provides options to create tensor-like objects."
},
{
"code": null,
"e": 6590,
"s": 6504,
"text": "<mn> − Used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>."
},
{
"code": null,
"e": 6676,
"s": 6590,
"text": "<mn> − Used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>."
},
{
"code": null,
"e": 6751,
"s": 6676,
"text": "<mo> − Used to specify an operator like +, - etc. For example, <mo>+</mo>."
},
{
"code": null,
"e": 6826,
"s": 6751,
"text": "<mo> − Used to specify an operator like +, - etc. For example, <mo>+</mo>."
},
{
"code": null,
"e": 6892,
"s": 6826,
"text": "<mover> − Used to attach an accent or a limit over an expression."
},
{
"code": null,
"e": 6958,
"s": 6892,
"text": "<mover> − Used to attach an accent or a limit over an expression."
},
{
"code": null,
"e": 7073,
"s": 6958,
"text": "<mpadded> − Used to add extra padding and to set the general adjustment of position and size of enclosed contents."
},
{
"code": null,
"e": 7188,
"s": 7073,
"text": "<mpadded> − Used to add extra padding and to set the general adjustment of position and size of enclosed contents."
},
{
"code": null,
"e": 7304,
"s": 7188,
"text": "<mphantom> − Used to create space as it is rendered invisibly, keeping height, width, and baseline position intact."
},
{
"code": null,
"e": 7420,
"s": 7304,
"text": "<mphantom> − Used to create space as it is rendered invisibly, keeping height, width, and baseline position intact."
},
{
"code": null,
"e": 7476,
"s": 7420,
"text": "<mroot> − Used to display roots with an explicit index."
},
{
"code": null,
"e": 7532,
"s": 7476,
"text": "<mroot> − Used to display roots with an explicit index."
},
{
"code": null,
"e": 7604,
"s": 7532,
"text": "<mrow> − Used to group any number of sub expressions in horizontal way."
},
{
"code": null,
"e": 7676,
"s": 7604,
"text": "<mrow> − Used to group any number of sub expressions in horizontal way."
},
{
"code": null,
"e": 7797,
"s": 7676,
"text": "<ms> − Used to represent a string literal meant to be interpreted by programming languages and computer algebra systems."
},
{
"code": null,
"e": 7918,
"s": 7797,
"text": "<ms> − Used to represent a string literal meant to be interpreted by programming languages and computer algebra systems."
},
{
"code": null,
"e": 8004,
"s": 7918,
"text": "<mspace> − Used to display a blank space, where its size is set using its attributes."
},
{
"code": null,
"e": 8090,
"s": 8004,
"text": "<mspace> − Used to display a blank space, where its size is set using its attributes."
},
{
"code": null,
"e": 8129,
"s": 8090,
"text": "<msqrt> − Used to display square root."
},
{
"code": null,
"e": 8168,
"s": 8129,
"text": "<msqrt> − Used to display square root."
},
{
"code": null,
"e": 8220,
"s": 8168,
"text": "<mstyle> − Used to apply the style on its children."
},
{
"code": null,
"e": 8272,
"s": 8220,
"text": "<mstyle> − Used to apply the style on its children."
},
{
"code": null,
"e": 8387,
"s": 8272,
"text": "<msub> − Used to attach a subscript to an expression. It uses the following syntax: <msub> base subscript </msub>."
},
{
"code": null,
"e": 8502,
"s": 8387,
"text": "<msub> − Used to attach a subscript to an expression. It uses the following syntax: <msub> base subscript </msub>."
},
{
"code": null,
"e": 8672,
"s": 8502,
"text": "<msubsup> − Used to attach both a subscript and a superscript, together, to an expression. It uses the following syntax: <msubsup> base subscript superscript </msubsup>."
},
{
"code": null,
"e": 8842,
"s": 8672,
"text": "<msubsup> − Used to attach both a subscript and a superscript, together, to an expression. It uses the following syntax: <msubsup> base subscript superscript </msubsup>."
},
{
"code": null,
"e": 8959,
"s": 8842,
"text": "<msup> − Used to attach a superscript to an expression. It uses the following syntax: msup base superscript </msup>."
},
{
"code": null,
"e": 9076,
"s": 8959,
"text": "<msup> − Used to attach a superscript to an expression. It uses the following syntax: msup base superscript </msup>."
},
{
"code": null,
"e": 9134,
"s": 9076,
"text": "<mtable> − Provides options to create tables or matrices."
},
{
"code": null,
"e": 9192,
"s": 9134,
"text": "<mtable> − Provides options to create tables or matrices."
},
{
"code": null,
"e": 9244,
"s": 9192,
"text": "<mtd> − To represent a cell in a table or a matrix."
},
{
"code": null,
"e": 9296,
"s": 9244,
"text": "<mtd> − To represent a cell in a table or a matrix."
},
{
"code": null,
"e": 9387,
"s": 9296,
"text": "<mtext> − Used to render text with no notational meaning, such as comments or annotations."
},
{
"code": null,
"e": 9478,
"s": 9387,
"text": "<mtext> − Used to render text with no notational meaning, such as comments or annotations."
},
{
"code": null,
"e": 9527,
"s": 9478,
"text": "<mtr> − Represents a row in a table or a matrix."
},
{
"code": null,
"e": 9576,
"s": 9527,
"text": "<mtr> − Represents a row in a table or a matrix."
},
{
"code": null,
"e": 9721,
"s": 9576,
"text": "<munder> − Provides option to attach an accent or a limit under an expression. It uses the following syntax: <munder> base underscript </munder>"
},
{
"code": null,
"e": 9866,
"s": 9721,
"text": "<munder> − Provides option to attach an accent or a limit under an expression. It uses the following syntax: <munder> base underscript </munder>"
},
{
"code": null,
"e": 10046,
"s": 9866,
"text": "<munderover> − Provides option to attach accents or limits both under and over an expression. It uses the following syntax: </munderover> base underscript overscript </munderover>"
},
{
"code": null,
"e": 10226,
"s": 10046,
"text": "<munderover> − Provides option to attach accents or limits both under and over an expression. It uses the following syntax: </munderover> base underscript overscript </munderover>"
},
{
"code": null,
"e": 10422,
"s": 10226,
"text": "<semantics> − <semantics>,<annotation> and <annotation-xml> are used to add presentation and content markup and provides both, layout information and semantic meaning of mathematical expressions."
},
{
"code": null,
"e": 10618,
"s": 10422,
"text": "<semantics> − <semantics>,<annotation> and <annotation-xml> are used to add presentation and content markup and provides both, layout information and semantic meaning of mathematical expressions."
},
{
"code": null,
"e": 10672,
"s": 10618,
"text": "There are five basic elements of a MathML expression."
},
{
"code": null,
"e": 10954,
"s": 10672,
"text": "<math> element − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag."
},
{
"code": null,
"e": 11236,
"s": 10954,
"text": "<math> element − It is top or root level element and is used to encapsulate each instance of MathML instance. Every valid MathML expression should be wrapped in outer <math> tag. It can contain any number of child elements. One math element cannot contain another math element tag."
},
{
"code": null,
"e": 11322,
"s": 11236,
"text": "<mrow> element − It is used to group any number of sub expressions in horizontal way."
},
{
"code": null,
"e": 11408,
"s": 11322,
"text": "<mrow> element − It is used to group any number of sub expressions in horizontal way."
},
{
"code": null,
"e": 11542,
"s": 11408,
"text": "<mi> element − It is used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> ."
},
{
"code": null,
"e": 11676,
"s": 11542,
"text": "<mi> element − It is used to specify an identifier such as name of a variable, function or a constant etc. For example, <mi>PI</mi> ."
},
{
"code": null,
"e": 11765,
"s": 11676,
"text": "<mo> element − It is used to specify an operator like +, - etc. For example, <mo>+</mo>."
},
{
"code": null,
"e": 11854,
"s": 11765,
"text": "<mo> element − It is used to specify an operator like +, - etc. For example, <mo>+</mo>."
},
{
"code": null,
"e": 11954,
"s": 11854,
"text": "<mn> element − It is used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>."
},
{
"code": null,
"e": 12054,
"s": 11954,
"text": "<mn> element − It is used to specify a numerical literal like 3.14 etc. For example, <mn>3.14</mn>."
},
{
"code": null,
"e": 12130,
"s": 12054,
"text": "Let's build a simple mathematical equation a + b = 5 using MathML notation."
},
{
"code": null,
"e": 12264,
"s": 12130,
"text": "Here a, b are variables. + is an operator and 5 is a number. We'll enclose them as <mi>a</mi> , <mi>b</mi>, <mo>+</mo> and <mn>+</mn>"
},
{
"code": null,
"e": 12271,
"s": 12264,
"text": "Syntax"
},
{
"code": null,
"e": 12411,
"s": 12271,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow> \n <mi>a</mi> \n <mo>+</mo> \n <mi>b</mi> \n </mrow>\n</math>"
},
{
"code": null,
"e": 12418,
"s": 12411,
"text": "Output"
},
{
"code": null,
"e": 12633,
"s": 12418,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow> \n <mrow> \n <mi>a</mi> \n <mo>+</mo> \n <mi>b</mi> \n </mrow>\n <mo>=</mo> \n <mn>5</mn> \n </mrow>\n</math>"
},
{
"code": null,
"e": 12640,
"s": 12633,
"text": "Output"
},
{
"code": null,
"e": 13145,
"s": 12640,
"text": "The <mscarries> element can be used to create carries, borrows, and crossouts that occur in elementary math. The children of mscarries are associated with elements in the following row of the mstack. Each child of mscarries except <mscarry> or <none> is treated as being implicitly surrounded by mscarry. <none> is used when particular column don't need a carry. The mscarries element sets displaystyle to false, and increments scriptlevel by 1, so the children are typically displayed in a smaller font."
},
{
"code": null,
"e": 13189,
"s": 13145,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 13255,
"s": 13189,
"text": "<mscarries> expression <mscarry> <none/> </mscarry> </mscarries>\n"
},
{
"code": null,
"e": 13315,
"s": 13255,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 13379,
"s": 13315,
"text": "expression − expression on which carry/borrow is to be applied."
},
{
"code": null,
"e": 13443,
"s": 13379,
"text": "expression − expression on which carry/borrow is to be applied."
},
{
"code": null,
"e": 13464,
"s": 13443,
"text": "mscarry − carry tag."
},
{
"code": null,
"e": 13485,
"s": 13464,
"text": "mscarry − carry tag."
},
{
"code": null,
"e": 13545,
"s": 13485,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 13681,
"s": 13545,
"text": "position − to specify the horizontal position of the rows within this group relative the position determined by the containing msgroup."
},
{
"code": null,
"e": 13817,
"s": 13681,
"text": "position − to specify the horizontal position of the rows within this group relative the position determined by the containing msgroup."
},
{
"code": null,
"e": 13971,
"s": 13817,
"text": "location − to specify location of the carry or borrow relative to the character below it in the associated column. values are w, nw, n, ne, e, se, s, sw."
},
{
"code": null,
"e": 14125,
"s": 13971,
"text": "location − to specify location of the carry or borrow relative to the character below it in the associated column. values are w, nw, n, ne, e, se, s, sw."
},
{
"code": null,
"e": 14367,
"s": 14125,
"text": "crossout − to specify how the column content below each carry is crossed out; one or more values may be given and all values are drawn. Values are none, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike. Default is none."
},
{
"code": null,
"e": 14609,
"s": 14367,
"text": "crossout − to specify how the column content below each carry is crossed out; one or more values may be given and all values are drawn. Values are none, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike. Default is none."
},
{
"code": null,
"e": 14682,
"s": 14609,
"text": "scriptsizemultiplier − to specify the factor to change the font size by."
},
{
"code": null,
"e": 14755,
"s": 14682,
"text": "scriptsizemultiplier − to specify the factor to change the font size by."
},
{
"code": null,
"e": 15165,
"s": 14755,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mstack>\n <mscarries crossout='updiagonalstrike'>\n <mn>2</mn>\n <mn>12</mn> \n <mscarry crossout='none'>\n <none/> \n </mscarry>\n </mscarries>\n <mn>2,327</mn>\n \n <msrow>\n <mo>-</mo> \n <mn> 1,156</mn> \n </msrow>\n <msline/>\n <mn>1,171</mn>\n </mstack>\n</math>"
},
{
"code": null,
"e": 15348,
"s": 15165,
"text": "<menclose> tag is used to renders content inside the enclosing notation as specified by its notation attribute. it accepts a single argument as an inferred mrow of multiple children."
},
{
"code": null,
"e": 15392,
"s": 15348,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 15427,
"s": 15392,
"text": "<menclose> expression </menclose>\n"
},
{
"code": null,
"e": 15487,
"s": 15427,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 15512,
"s": 15487,
"text": "expression − expression."
},
{
"code": null,
"e": 15537,
"s": 15512,
"text": "expression − expression."
},
{
"code": null,
"e": 15597,
"s": 15537,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 15924,
"s": 15597,
"text": "notation − to specify a space separated list of notations to be used to enclose the children. Valid values are longdiv, actuarial, phasorangle, radical, box, roundedbox, circle, left, right, top, bottom, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike, northeastarrow, madruwb, text. Default is longdiv."
},
{
"code": null,
"e": 16251,
"s": 15924,
"text": "notation − to specify a space separated list of notations to be used to enclose the children. Valid values are longdiv, actuarial, phasorangle, radical, box, roundedbox, circle, left, right, top, bottom, updiagonalstrike, downdiagonalstrike, verticalstrike, horizontalstrike, northeastarrow, madruwb, text. Default is longdiv."
},
{
"code": null,
"e": 16555,
"s": 16251,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mi>C</mi>\n <mrow>\n <menclose notation = 'phasorangle'>\n <mrow>\n <mo>−</mo>\n <mfrac>\n <mi>π</mi>\n <mn>2</mn>\n </mfrac>\n </mrow>\n </menclose>\n </mrow>\n</math>"
},
{
"code": null,
"e": 16698,
"s": 16555,
"text": "<mfenced> tag is a convenient method to use fencing operators like curly braces, brackets and parentheses instead of using <mo> tags for them."
},
{
"code": null,
"e": 16742,
"s": 16698,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 16775,
"s": 16742,
"text": "<mfenced> expression </mfenced>\n"
},
{
"code": null,
"e": 16835,
"s": 16775,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 16860,
"s": 16835,
"text": "expression − expression."
},
{
"code": null,
"e": 16885,
"s": 16860,
"text": "expression − expression."
},
{
"code": null,
"e": 16945,
"s": 16885,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 17002,
"s": 16945,
"text": "open − To specify the opening delimiter. Default is '('."
},
{
"code": null,
"e": 17059,
"s": 17002,
"text": "open − To specify the opening delimiter. Default is '('."
},
{
"code": null,
"e": 17117,
"s": 17059,
"text": "close − To specify the closing delimiter. Default is ')'."
},
{
"code": null,
"e": 17175,
"s": 17117,
"text": "close − To specify the closing delimiter. Default is ')'."
},
{
"code": null,
"e": 17300,
"s": 17175,
"text": "separators − To specify a sequence of zero or more separator characters, optionally separated by whitespace. Default is ','."
},
{
"code": null,
"e": 17425,
"s": 17300,
"text": "separators − To specify a sequence of zero or more separator characters, optionally separated by whitespace. Default is ','."
},
{
"code": null,
"e": 17557,
"s": 17425,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mo>(</mo>\n <mi>x</mi>\n <mo>)</mo>\n </mrow>\n</math>"
},
{
"code": null,
"e": 17661,
"s": 17557,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfenced>\n <mi>x</mi>\n </mfenced>\n</math>"
},
{
"code": null,
"e": 17856,
"s": 17661,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mi> f </mi>\n <mo> </mo>\n <mfenced>\n <mi> x </mi>\n <mi> y </mi>\n </mfenced>\n </mrow>\n</math>"
},
{
"code": null,
"e": 18036,
"s": 17856,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfenced>\n <mrow>\n <mi> a </mi>\n <mo> + </mo>\n <mi> b </mi>\n </mrow>\n </mfenced>\n</math>"
},
{
"code": null,
"e": 18170,
"s": 18036,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfenced open=\"[\">\n <mn> 0 </mn>\n <mn> 1 </mn>\n </mfenced>\n</math>"
},
{
"code": null,
"e": 18209,
"s": 18170,
"text": "<mfrac> tag is used to draw fractions."
},
{
"code": null,
"e": 18253,
"s": 18209,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 18293,
"s": 18253,
"text": "<mfrac> numerator denominator </mfrac>\n"
},
{
"code": null,
"e": 18353,
"s": 18293,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 18392,
"s": 18353,
"text": "numerator − numerator of the fraction."
},
{
"code": null,
"e": 18431,
"s": 18392,
"text": "numerator − numerator of the fraction."
},
{
"code": null,
"e": 18474,
"s": 18431,
"text": "denominator − denominator of the fraction."
},
{
"code": null,
"e": 18517,
"s": 18474,
"text": "denominator − denominator of the fraction."
},
{
"code": null,
"e": 18577,
"s": 18517,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 18681,
"s": 18577,
"text": "linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc."
},
{
"code": null,
"e": 18785,
"s": 18681,
"text": "linethickness − to specify the stroke width of the fraction bar. values are measured in px, pt, em etc."
},
{
"code": null,
"e": 18865,
"s": 18785,
"text": "numalign − to specify alignment of numerator. values are left, right or center."
},
{
"code": null,
"e": 18945,
"s": 18865,
"text": "numalign − to specify alignment of numerator. values are left, right or center."
},
{
"code": null,
"e": 19029,
"s": 18945,
"text": "denomalign − to specify alignment of denominator. values are left, right or center."
},
{
"code": null,
"e": 19113,
"s": 19029,
"text": "denomalign − to specify alignment of denominator. values are left, right or center."
},
{
"code": null,
"e": 19224,
"s": 19113,
"text": "bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false."
},
{
"code": null,
"e": 19335,
"s": 19224,
"text": "bevelled − to specify whether the fraction should be displayed vertically or inline. values are true or false."
},
{
"code": null,
"e": 19373,
"s": 19335,
"text": "Let's draw a simple fraction for 1/x."
},
{
"code": null,
"e": 19490,
"s": 19373,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfrac>\n <mn>1</mn>\n <mi>x</mi>\n </mfrac>\n</math>"
},
{
"code": null,
"e": 19522,
"s": 19490,
"text": "Let's build a complex fraction."
},
{
"code": null,
"e": 19808,
"s": 19522,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfrac linethickness = '3px'>\n <mfrac bevelled = 'true'>\n <mn>1</mn>\n <mi>x</mi>\n </mfrac>\n \n <mrow>\n <mi>y</mi>\n <mo>-</mo>\n <mn>2</mn>\n </mrow>\n </mfrac>\n</math>"
},
{
"code": null,
"e": 19855,
"s": 19808,
"text": "<mlongdiv> tag is used to draw long divisions."
},
{
"code": null,
"e": 19899,
"s": 19855,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 19958,
"s": 19899,
"text": "<mlongdiv> divisor dividend result expression </mlongdiv>\n"
},
{
"code": null,
"e": 20018,
"s": 19958,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 20058,
"s": 20018,
"text": "divisor − divisor of the long division."
},
{
"code": null,
"e": 20098,
"s": 20058,
"text": "divisor − divisor of the long division."
},
{
"code": null,
"e": 20140,
"s": 20098,
"text": "dividend − dividend of the long division."
},
{
"code": null,
"e": 20182,
"s": 20140,
"text": "dividend − dividend of the long division."
},
{
"code": null,
"e": 20220,
"s": 20182,
"text": "result − result of the long division."
},
{
"code": null,
"e": 20258,
"s": 20220,
"text": "result − result of the long division."
},
{
"code": null,
"e": 20309,
"s": 20258,
"text": "expression − mstack element or children of mstack."
},
{
"code": null,
"e": 20360,
"s": 20309,
"text": "expression − mstack element or children of mstack."
},
{
"code": null,
"e": 20420,
"s": 20360,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 20686,
"s": 20420,
"text": "longdivstyle − to control the style of the long division layout. Valid values are lefttop, stackedrightright, mediumstackedrightright, shortstackedrightright, righttop, left/\\right, left)(right, :right=right, stackedleftleft, stackedleftlinetop. Default is lefttop."
},
{
"code": null,
"e": 20952,
"s": 20686,
"text": "longdivstyle − to control the style of the long division layout. Valid values are lefttop, stackedrightright, mediumstackedrightright, shortstackedrightright, righttop, left/\\right, left)(right, :right=right, stackedleftleft, stackedleftlinetop. Default is lefttop."
},
{
"code": null,
"e": 20990,
"s": 20952,
"text": "Let's draw a simple fraction for 1/x."
},
{
"code": null,
"e": 21782,
"s": 20990,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mlongdiv longdivstyle = \"lefttop\">\n <mn> 3 </mn>\n <mn> 435.3</mn>\n <mn> 1306</mn>\n <msgroup position = \"2\" shift = \"-1\">\n <msgroup>\n <mn> 12</mn>\n <msline length = \"2\"/>\n </msgroup>\n \n <msgroup>\n <mn> 10</mn>\n <mn> 9</mn>\n <msline length = \"2\"/>\n </msgroup>\n \n <msgroup>\n <mn> 16</mn>\n <mn> 15</mn>\n <msline length = \"2\"/>\n <mn> 1.0</mn> \n </msgroup> \n \n <msgroup position='-1'> \n <mn> 9</mn>\n <msline length = \"3\"/>\n <mn> 1</mn>\n </msgroup>\n </msgroup>\n </mlongdiv>\n</math>"
},
{
"code": null,
"e": 21821,
"s": 21782,
"text": "<mtable> tag is used to draw matrices."
},
{
"code": null,
"e": 21941,
"s": 21821,
"text": "mtable is similar to table tag of HTML and this tag uses mtr, mtd elements which are similar to tr and td tags of HTML."
},
{
"code": null,
"e": 21983,
"s": 21941,
"text": "<mtable> <mtr> <mtd></mtd></mtr></mfrac>\n"
},
{
"code": null,
"e": 22043,
"s": 21983,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 22172,
"s": 22043,
"text": "align − To specify the vertical alignment of the table . Valid values are: axis, baseline, bottom, center, top. Default is axis."
},
{
"code": null,
"e": 22301,
"s": 22172,
"text": "align − To specify the vertical alignment of the table . Valid values are: axis, baseline, bottom, center, top. Default is axis."
},
{
"code": null,
"e": 22343,
"s": 22301,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 22385,
"s": 22343,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 22510,
"s": 22385,
"text": "columnalign − To specify the horizontal alignment of the cells. Valid values are: left, center and right. Default is center."
},
{
"code": null,
"e": 22635,
"s": 22510,
"text": "columnalign − To specify the horizontal alignment of the cells. Valid values are: left, center and right. Default is center."
},
{
"code": null,
"e": 22735,
"s": 22635,
"text": "columnlines − To specify column borders. Valid values are: none, solid and dashed. Default is none."
},
{
"code": null,
"e": 22835,
"s": 22735,
"text": "columnlines − To specify column borders. Valid values are: none, solid and dashed. Default is none."
},
{
"code": null,
"e": 22895,
"s": 22835,
"text": "columnspacing − To specify the space between table columns."
},
{
"code": null,
"e": 22955,
"s": 22895,
"text": "columnspacing − To specify the space between table columns."
},
{
"code": null,
"e": 23093,
"s": 22955,
"text": "displaystyle − If true more vertical space is used for displayed equations , if false, a more compact layout is used to display formulas."
},
{
"code": null,
"e": 23231,
"s": 23093,
"text": "displaystyle − If true more vertical space is used for displayed equations , if false, a more compact layout is used to display formulas."
},
{
"code": null,
"e": 23338,
"s": 23231,
"text": "frame − To specify borders of the entire table. Valid values are: none, solid and dashed. Default is none."
},
{
"code": null,
"e": 23445,
"s": 23338,
"text": "frame − To specify borders of the entire table. Valid values are: none, solid and dashed. Default is none."
},
{
"code": null,
"e": 23523,
"s": 23445,
"text": "framespacing − To specify additional space added between the table and frame."
},
{
"code": null,
"e": 23601,
"s": 23523,
"text": "framespacing − To specify additional space added between the table and frame."
},
{
"code": null,
"e": 23651,
"s": 23601,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 23701,
"s": 23651,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 23805,
"s": 23701,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 23909,
"s": 23805,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 24002,
"s": 23909,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 24095,
"s": 24002,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 24227,
"s": 24095,
"text": "rowalign − To specify vertical alignment of the cells. Valid values are axis, baseline, bottom, center and top. Default is baseline"
},
{
"code": null,
"e": 24359,
"s": 24227,
"text": "rowalign − To specify vertical alignment of the cells. Valid values are axis, baseline, bottom, center and top. Default is baseline"
},
{
"code": null,
"e": 24453,
"s": 24359,
"text": "rowlines − To specify row borders. Valid values are: none, solid and dashed. Default is none."
},
{
"code": null,
"e": 24547,
"s": 24453,
"text": "rowlines − To specify row borders. Valid values are: none, solid and dashed. Default is none."
},
{
"code": null,
"e": 24593,
"s": 24547,
"text": "width − To specify width of the entire table."
},
{
"code": null,
"e": 24639,
"s": 24593,
"text": "width − To specify width of the entire table."
},
{
"code": null,
"e": 24666,
"s": 24639,
"text": "Let's draw a 3 x 3 metric."
},
{
"code": null,
"e": 25232,
"s": 24666,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mo>[</mo>\n <mtable>\n <mtr>\n <mtd><mn>1</mn></mtd>\n <mtd><mn>0</mn></mtd>\n <mtd><mn>0</mn></mtd>\n </mtr>\n \n <mtr>\n <mtd><mn>0</mn></mtd>\n <mtd><mn>1</mn></mtd>\n <mtd><mn>0</mn></mtd>\n </mtr>\n \n <mtr>\n <mtd><mn>0</mn></mtd>\n <mtd><mn>0</mn></mtd>\n <mtd><mn>1</mn></mtd>\n </mtr>\n </mtable>\n <mo>]</mo>\n </mrow>\n</math> "
},
{
"code": null,
"e": 25450,
"s": 25232,
"text": "<msgroup> is used to group rows inside <mstack> element and <mlongdiv> elements to have position relative to the alignment of stack. <msgroup> element with shift attribute can be used to create simple multiplications."
},
{
"code": null,
"e": 25494,
"s": 25450,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 25527,
"s": 25494,
"text": "<msgroup> expression </msgroup>\n"
},
{
"code": null,
"e": 25587,
"s": 25527,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 25612,
"s": 25587,
"text": "expression − expression."
},
{
"code": null,
"e": 25637,
"s": 25612,
"text": "expression − expression."
},
{
"code": null,
"e": 25697,
"s": 25637,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 25895,
"s": 25697,
"text": "position − to specify the horizontal position of the rows within the group relative the position controlled by the containing msgroup (as per its position and shift attributes). Default value is 0."
},
{
"code": null,
"e": 26093,
"s": 25895,
"text": "position − to specify the horizontal position of the rows within the group relative the position controlled by the containing msgroup (as per its position and shift attributes). Default value is 0."
},
{
"code": null,
"e": 26224,
"s": 26093,
"text": "shift − to specify an incremental shift of position for successive children (rows or groups) within the group. Default value is 0."
},
{
"code": null,
"e": 26355,
"s": 26224,
"text": "shift − to specify an incremental shift of position for successive children (rows or groups) within the group. Default value is 0."
},
{
"code": null,
"e": 26749,
"s": 26355,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mstack>\n <msgroup>\n <mn>123</mn>\n <msrow>\n <mo>×</mo>\n <mn>321</mn>\n </msrow>\n </msgroup>\n <msline/>\n \n <msgroup shift = \"1\">\n <mn>123</mn>\n <mn>246</mn>\n <mn>369</mn>\n </msgroup>\n <msline/>\n <mn>39483</mn>\n </mstack>\n</math>"
},
{
"code": null,
"e": 26838,
"s": 26749,
"text": "<mover> tag is used to draw overscript. It adds an accent or a limit over an expression."
},
{
"code": null,
"e": 26882,
"s": 26838,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 26916,
"s": 26882,
"text": "<mover> base overscript </mover>\n"
},
{
"code": null,
"e": 26976,
"s": 26916,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 27039,
"s": 26976,
"text": "base − base expression on which the overscript is to be drawn."
},
{
"code": null,
"e": 27102,
"s": 27039,
"text": "base − base expression on which the overscript is to be drawn."
},
{
"code": null,
"e": 27127,
"s": 27102,
"text": "overscript − overscript."
},
{
"code": null,
"e": 27152,
"s": 27127,
"text": "overscript − overscript."
},
{
"code": null,
"e": 27212,
"s": 27152,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 27377,
"s": 27212,
"text": "accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 27542,
"s": 27377,
"text": "accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 27631,
"s": 27542,
"text": "align − To specify the alignment of the over-script. Valid are: left, center, and right."
},
{
"code": null,
"e": 27720,
"s": 27631,
"text": "align − To specify the alignment of the over-script. Valid are: left, center, and right."
},
{
"code": null,
"e": 27762,
"s": 27720,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 27804,
"s": 27762,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 27854,
"s": 27804,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 27904,
"s": 27854,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 28008,
"s": 27904,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 28112,
"s": 28008,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 28205,
"s": 28112,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 28298,
"s": 28205,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 28324,
"s": 28298,
"text": "Let's draw an overscript."
},
{
"code": null,
"e": 28607,
"s": 28324,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mover accent = \"true\"> \n <mrow> \n <mi> x </mi> \n <mo> + </mo> \n <mi> y </mi> \n <mo> + </mo> \n <mi> z </mi> \n </mrow> \n <mo>⏞</mo> \n </mover>\n</math>"
},
{
"code": null,
"e": 28841,
"s": 28607,
"text": "<mpadded> element is used to add padding, or extra space, around its content. It can be used to adjust size and positioning e.g. negative padding,which can cause the content of mpadded to overlap the rendering of neighboring content."
},
{
"code": null,
"e": 28885,
"s": 28841,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 28918,
"s": 28885,
"text": "<mpadded> expression </mpadded>\n"
},
{
"code": null,
"e": 28978,
"s": 28918,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 29027,
"s": 28978,
"text": "expression − inferred mrow of multiple children."
},
{
"code": null,
"e": 29076,
"s": 29027,
"text": "expression − inferred mrow of multiple children."
},
{
"code": null,
"e": 29136,
"s": 29076,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 29201,
"s": 29136,
"text": "height − To sets or increment the height of the mpadded element."
},
{
"code": null,
"e": 29266,
"s": 29201,
"text": "height − To sets or increment the height of the mpadded element."
},
{
"code": null,
"e": 29329,
"s": 29266,
"text": "depth − To sets or increment the depth of the mpadded element."
},
{
"code": null,
"e": 29392,
"s": 29329,
"text": "depth − To sets or increment the depth of the mpadded element."
},
{
"code": null,
"e": 29455,
"s": 29392,
"text": "width − To sets or increment the width of the mpadded element."
},
{
"code": null,
"e": 29518,
"s": 29455,
"text": "width − To sets or increment the width of the mpadded element."
},
{
"code": null,
"e": 29578,
"s": 29518,
"text": "lspace − To sets the horizontal space of the child content."
},
{
"code": null,
"e": 29638,
"s": 29578,
"text": "lspace − To sets the horizontal space of the child content."
},
{
"code": null,
"e": 29697,
"s": 29638,
"text": "voffset − To sets the vertical space of the child content."
},
{
"code": null,
"e": 29756,
"s": 29697,
"text": "voffset − To sets the vertical space of the child content."
},
{
"code": null,
"e": 29959,
"s": 29756,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mi>x</mi>\n <mpadded lspace = \"0.2em\" voffset = \"0.3ex\">\n <mi>y</mi>\n </mpadded>\n <mi>z</mi>\n </mrow>\n</math>"
},
{
"code": null,
"e": 30182,
"s": 29959,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mi>x</mi>\n <mpadded width = \"+90%width\" height = \"+0.3ex\" depth = \"+0.3ex\">\n <mi>y</mi>\n </mpadded>\n <mi>z</mi>\n </mrow>\n</math>"
},
{
"code": null,
"e": 30384,
"s": 30182,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mi>x</mi>\n <mpadded lspace = \"0.3em\" width = \"+0.6em\">\n <mi>y</mi>\n </mpadded>\n <mi>z</mi>\n </mrow>\n</math>"
},
{
"code": null,
"e": 30634,
"s": 30384,
"text": "<mphantom> element renders invisibly keeping same size and other dimensions, including baseline position, as its contents would have if they were rendered normally. It is used to align parts of an expression by invisibly duplicating sub-expressions."
},
{
"code": null,
"e": 30678,
"s": 30634,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 30713,
"s": 30678,
"text": "<mphantom> expression </mphantom>\n"
},
{
"code": null,
"e": 30773,
"s": 30713,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 30822,
"s": 30773,
"text": "expression − inferred mrow of multiple children."
},
{
"code": null,
"e": 30871,
"s": 30822,
"text": "expression − inferred mrow of multiple children."
},
{
"code": null,
"e": 30931,
"s": 30871,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 31035,
"s": 30931,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 31139,
"s": 31035,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 31603,
"s": 31139,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mfrac>\n <mrow>\n <mi> x </mi>\n <mo> + </mo>\n <mi> y </mi>\n <mo> + </mo>\n <mi> z </mi>\n </mrow>\n \n <mrow>\n <mi> x </mi>\n <mphantom>\n <mo> + </mo>\n </mphantom>\n \n <mphantom>\n <mi> y </mi>\n </mphantom>\n <mo> + </mo>\n <mi> z </mi>\n </mrow>\n </mfrac>\n</math> "
},
{
"code": null,
"e": 31774,
"s": 31603,
"text": "msqrt and mroot elements construct radicals. The msqrt element constructs square roots, while the mroot element constructs radicals with indices, for example a cube root."
},
{
"code": null,
"e": 31815,
"s": 31774,
"text": "<msqrt> tag is used to draw square root."
},
{
"code": null,
"e": 31859,
"s": 31815,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 31882,
"s": 31859,
"text": "<msqrt> base </msqrt>\n"
},
{
"code": null,
"e": 31942,
"s": 31882,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 32006,
"s": 31942,
"text": "base − base expression on which the square root is to be drawn."
},
{
"code": null,
"e": 32070,
"s": 32006,
"text": "base − base expression on which the square root is to be drawn."
},
{
"code": null,
"e": 32130,
"s": 32070,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 32234,
"s": 32130,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 32338,
"s": 32234,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 32431,
"s": 32338,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 32524,
"s": 32431,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 32550,
"s": 32524,
"text": "Let's draw a square root."
},
{
"code": null,
"e": 32654,
"s": 32550,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <msqrt> \n <mn>4</mn> \n </msqrt>\n</math>"
},
{
"code": null,
"e": 32705,
"s": 32654,
"text": "<mroot> tag is used to draw radicals with indices."
},
{
"code": null,
"e": 32749,
"s": 32705,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 32778,
"s": 32749,
"text": "<mroot> base index </mroot>\n"
},
{
"code": null,
"e": 32838,
"s": 32778,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 32902,
"s": 32838,
"text": "base − base expression on which the square root is to be drawn."
},
{
"code": null,
"e": 32966,
"s": 32902,
"text": "base − base expression on which the square root is to be drawn."
},
{
"code": null,
"e": 33005,
"s": 32966,
"text": "index − index of the root to be drawn."
},
{
"code": null,
"e": 33044,
"s": 33005,
"text": "index − index of the root to be drawn."
},
{
"code": null,
"e": 33104,
"s": 33044,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 33208,
"s": 33104,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 33312,
"s": 33208,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 33405,
"s": 33312,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 33498,
"s": 33405,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 33522,
"s": 33498,
"text": "Let's draw a cube root."
},
{
"code": null,
"e": 33646,
"s": 33522,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mroot> \n <mn>8</mn> \n <mn>3</mn> \n </mroot>\n</math> "
},
{
"code": null,
"e": 33927,
"s": 33646,
"text": "Decimal numbers having digit(s) that repeat(s) infinitely such as 1/3 (.3333...) are represented by putting a horizontal line over or below the digits that repeat. <mstack> , <msrow>, and <msline> elements can be used to create decimal numbers with repeated digits as shown below."
},
{
"code": null,
"e": 34086,
"s": 33927,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mstack stackalign = \"right\">\n <msline length = \"1\"/>\n <mn> 0.3333 </mn>\n </mstack>\n</math>"
},
{
"code": null,
"e": 34244,
"s": 34086,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mstack stackalign=\"right\">\n <msline length=\"6\"/>\n <mn> 0.142857 </mn>\n </mstack>\n</math> "
},
{
"code": null,
"e": 34405,
"s": 34244,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mstack stackalign=\"right\"> \n <mn> 0.142857 </mn>\n <msline length=\"6\"/>\n </mstack>\n</math> "
},
{
"code": null,
"e": 34491,
"s": 34405,
"text": "<mstyle> tag is used to make style changes that affect the rendering of its contents."
},
{
"code": null,
"e": 34535,
"s": 34491,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 34566,
"s": 34535,
"text": "<mstyle> expression </mstyle>\n"
},
{
"code": null,
"e": 34626,
"s": 34566,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 34663,
"s": 34626,
"text": "expression − inferred mrow elements."
},
{
"code": null,
"e": 34700,
"s": 34663,
"text": "expression − inferred mrow elements."
},
{
"code": null,
"e": 34760,
"s": 34700,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 34950,
"s": 34760,
"text": "scriptlevel − To specify the scriptlevel for the children. Without a sign, it sets scriptlevel to the specified value; With a sign it increments (\"+\") or decrements (\"-\") the current value."
},
{
"code": null,
"e": 35140,
"s": 34950,
"text": "scriptlevel − To specify the scriptlevel for the children. Without a sign, it sets scriptlevel to the specified value; With a sign it increments (\"+\") or decrements (\"-\") the current value."
},
{
"code": null,
"e": 35184,
"s": 35140,
"text": "displaystyle − To specify the displaystyle."
},
{
"code": null,
"e": 35228,
"s": 35184,
"text": "displaystyle − To specify the displaystyle."
},
{
"code": null,
"e": 35339,
"s": 35228,
"text": "scriptsizemultiplier − To specify the multiplier to be used to adjust font size due to changes in scriptlevel."
},
{
"code": null,
"e": 35450,
"s": 35339,
"text": "scriptsizemultiplier − To specify the multiplier to be used to adjust font size due to changes in scriptlevel."
},
{
"code": null,
"e": 35538,
"s": 35450,
"text": "scriptminsize − To specify the minimum font size allowed due to changes in scriptlevel."
},
{
"code": null,
"e": 35626,
"s": 35538,
"text": "scriptminsize − To specify the minimum font size allowed due to changes in scriptlevel."
},
{
"code": null,
"e": 35713,
"s": 35626,
"text": "infixlinebreakstyle − To specify he default linebreakstyle to use for infix operators."
},
{
"code": null,
"e": 35800,
"s": 35713,
"text": "infixlinebreakstyle − To specify he default linebreakstyle to use for infix operators."
},
{
"code": null,
"e": 35995,
"s": 35800,
"text": "decimalpoint − To specify the character used to determine the alignment point within <mstack> and <mtable> columns when the \"decimalpoint\" value is used to specify the alignment. Default is '.'."
},
{
"code": null,
"e": 36190,
"s": 35995,
"text": "decimalpoint − To specify the character used to determine the alignment point within <mstack> and <mtable> columns when the \"decimalpoint\" value is used to specify the alignment. Default is '.'."
},
{
"code": null,
"e": 36419,
"s": 36190,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <mo maxsize = \"100%\"> ( </mo>\n <mfrac> \n <mi> a </mi> \n <mi> b </mi> \n </mfrac>\n <mo maxsize = \"100%\"> ) </mo>\n </mrow>\n</math>"
},
{
"code": null,
"e": 36680,
"s": 36419,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mstyle maxsize = \"100%\">\n <mrow>\n <mo> ( </mo>\n <mfrac> \n <mi> a </mi> \n <mi> b </mi> \n </mfrac>\n <mo> ) </mo>\n </mrow>\n </mstyle>\n</math>"
},
{
"code": null,
"e": 36735,
"s": 36680,
"text": "<msub> tag is used to draw subscript to an expression."
},
{
"code": null,
"e": 36779,
"s": 36735,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 36810,
"s": 36779,
"text": "<msub> base subscript </msub>\n"
},
{
"code": null,
"e": 36870,
"s": 36810,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 36932,
"s": 36870,
"text": "base − base expression on which the subscript is to be drawn."
},
{
"code": null,
"e": 36994,
"s": 36932,
"text": "base − base expression on which the subscript is to be drawn."
},
{
"code": null,
"e": 37017,
"s": 36994,
"text": "subscript − subscript."
},
{
"code": null,
"e": 37040,
"s": 37017,
"text": "subscript − subscript."
},
{
"code": null,
"e": 37100,
"s": 37040,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 37207,
"s": 37100,
"text": "subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression."
},
{
"code": null,
"e": 37314,
"s": 37207,
"text": "subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression."
},
{
"code": null,
"e": 37356,
"s": 37314,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 37398,
"s": 37356,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 37448,
"s": 37398,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 37498,
"s": 37448,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 37602,
"s": 37498,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 37706,
"s": 37602,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 37799,
"s": 37706,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 37892,
"s": 37799,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 37916,
"s": 37892,
"text": "Let's draw a subscript."
},
{
"code": null,
"e": 38038,
"s": 37916,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <msub> \n <mi>x</mi> \n <mn>1</mn> \n </msub>\n</math> "
},
{
"code": null,
"e": 38119,
"s": 38038,
"text": "<msubsup> tag is used to attach both subscript and superscript to an expression."
},
{
"code": null,
"e": 38163,
"s": 38119,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 38211,
"s": 38163,
"text": "<msubsup> base subscript superscript</msubsup>\n"
},
{
"code": null,
"e": 38271,
"s": 38211,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 38349,
"s": 38271,
"text": "base − base expression on which the subscript and superscript is to be drawn."
},
{
"code": null,
"e": 38427,
"s": 38349,
"text": "base − base expression on which the subscript and superscript is to be drawn."
},
{
"code": null,
"e": 38450,
"s": 38427,
"text": "subscript − subscript."
},
{
"code": null,
"e": 38473,
"s": 38450,
"text": "subscript − subscript."
},
{
"code": null,
"e": 38500,
"s": 38473,
"text": "superscript − superscript."
},
{
"code": null,
"e": 38527,
"s": 38500,
"text": "superscript − superscript."
},
{
"code": null,
"e": 38587,
"s": 38527,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 38694,
"s": 38587,
"text": "subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression."
},
{
"code": null,
"e": 38801,
"s": 38694,
"text": "subscriptshift − To specify the minimum space to shift the subscript below the baseline of the expression."
},
{
"code": null,
"e": 38912,
"s": 38801,
"text": "superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression."
},
{
"code": null,
"e": 39023,
"s": 38912,
"text": "superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression."
},
{
"code": null,
"e": 39063,
"s": 39023,
"text": "Let's draw a subscript and superscript."
},
{
"code": null,
"e": 39472,
"s": 39063,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <msubsup>\n <mo> ∫</mo>\n <mn> 0 </mn>\n <mn> 1 </mn>\n </msubsup>\n \n <mrow>\n <msup>\n <mi> e</mi>\n <mi> x </mi>\n </msup>\n <mo> </mo>\n \n <mrow>\n <mi> d</mi>\n <mi> x </mi>\n </mrow>\n </mrow>\n </mrow>\n</math> "
},
{
"code": null,
"e": 39529,
"s": 39472,
"text": "<msup> tag is used to draw superscript to an expression."
},
{
"code": null,
"e": 39573,
"s": 39529,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 39606,
"s": 39573,
"text": "<msup> base superscript </msup>\n"
},
{
"code": null,
"e": 39666,
"s": 39606,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 39730,
"s": 39666,
"text": "base − base expression on which the superscript is to be drawn."
},
{
"code": null,
"e": 39794,
"s": 39730,
"text": "base − base expression on which the superscript is to be drawn."
},
{
"code": null,
"e": 39821,
"s": 39794,
"text": "superscript − superscript."
},
{
"code": null,
"e": 39848,
"s": 39821,
"text": "superscript − superscript."
},
{
"code": null,
"e": 39908,
"s": 39848,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 40019,
"s": 39908,
"text": "superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression."
},
{
"code": null,
"e": 40130,
"s": 40019,
"text": "superscriptshift − To specify the minimum space to shift the superscript above the baseline of the expression."
},
{
"code": null,
"e": 40172,
"s": 40130,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 40214,
"s": 40172,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 40264,
"s": 40214,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 40314,
"s": 40264,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 40418,
"s": 40314,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 40522,
"s": 40418,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 40615,
"s": 40522,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 40708,
"s": 40615,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 40734,
"s": 40708,
"text": "Let's draw a superscript."
},
{
"code": null,
"e": 40856,
"s": 40734,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <msup> \n <mi>x</mi> \n <mn>1</mn> \n </msup>\n</math> "
},
{
"code": null,
"e": 40914,
"s": 40856,
"text": "Use mrow in order to add sub-expressions in superscripts."
},
{
"code": null,
"e": 41139,
"s": 40914,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <msup> \n <mi>e</mi> \n <mrow> \n <mn>2</mn> \n <mi>x</mi> \n <mo>+</mo> \n <mn>1</mn> \n </mrow> \n </msup>\n</math> "
},
{
"code": null,
"e": 41231,
"s": 41139,
"text": "<munder> tag is used to draw underscript. It adds an accent or a limit under an expression."
},
{
"code": null,
"e": 41275,
"s": 41231,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 41312,
"s": 41275,
"text": "<munder> base underscript </munder>\n"
},
{
"code": null,
"e": 41372,
"s": 41312,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 41436,
"s": 41372,
"text": "base − base expression on which the underscript is to be drawn."
},
{
"code": null,
"e": 41500,
"s": 41436,
"text": "base − base expression on which the underscript is to be drawn."
},
{
"code": null,
"e": 41527,
"s": 41500,
"text": "underscript − underscript."
},
{
"code": null,
"e": 41554,
"s": 41527,
"text": "underscript − underscript."
},
{
"code": null,
"e": 41614,
"s": 41554,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 41786,
"s": 41614,
"text": "accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 41958,
"s": 41786,
"text": "accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 42048,
"s": 41958,
"text": "align − To specify the alignment of the under-script. Valid are: left, center, and right."
},
{
"code": null,
"e": 42138,
"s": 42048,
"text": "align − To specify the alignment of the under-script. Valid are: left, center, and right."
},
{
"code": null,
"e": 42180,
"s": 42138,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 42222,
"s": 42180,
"text": "class, id, style − Used with stylesheets."
},
{
"code": null,
"e": 42272,
"s": 42222,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 42322,
"s": 42272,
"text": "href − To specify a hyperlink to a specified uri."
},
{
"code": null,
"e": 42426,
"s": 42322,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 42530,
"s": 42426,
"text": "mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 42623,
"s": 42530,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 42716,
"s": 42623,
"text": "mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names."
},
{
"code": null,
"e": 42743,
"s": 42716,
"text": "Let's draw an underscript."
},
{
"code": null,
"e": 43025,
"s": 42743,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <munder accent=\"true\"> \n <mrow> \n <mi> x </mi> \n <mo> + </mo> \n <mi> y </mi> \n <mo> + </mo> \n <mi> z </mi> \n </mrow> \n <mo>ȿ</mo> \n </munder>\n</math>"
},
{
"code": null,
"e": 43150,
"s": 43025,
"text": "<munderover> tag is used to draw both over and under underscript. It adds an accent or a limit over and under an expression."
},
{
"code": null,
"e": 43194,
"s": 43150,
"text": "Here is the simple syntax to use this tag −"
},
{
"code": null,
"e": 43250,
"s": 43194,
"text": "<munderover> base underscript overscript </munderover>\n"
},
{
"code": null,
"e": 43310,
"s": 43250,
"text": "Here is the description of all the parameters of this tag −"
},
{
"code": null,
"e": 43374,
"s": 43310,
"text": "base − base expression on which the underscript is to be drawn."
},
{
"code": null,
"e": 43438,
"s": 43374,
"text": "base − base expression on which the underscript is to be drawn."
},
{
"code": null,
"e": 43465,
"s": 43438,
"text": "underscript − underscript."
},
{
"code": null,
"e": 43492,
"s": 43465,
"text": "underscript − underscript."
},
{
"code": null,
"e": 43517,
"s": 43492,
"text": "overscript − overscript."
},
{
"code": null,
"e": 43542,
"s": 43517,
"text": "overscript − overscript."
},
{
"code": null,
"e": 43602,
"s": 43542,
"text": "Here is the description of all the attributes of this tag −"
},
{
"code": null,
"e": 43767,
"s": 43602,
"text": "accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 43932,
"s": 43767,
"text": "accent − If true, over-script is an accent, and is drawn closer to the base expression. If false, over-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 44104,
"s": 43932,
"text": "accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 44276,
"s": 44104,
"text": "accentunder − If true, under-script is an accent, and is drawn closer to the base expression. If false, under-script is a limit over the base expression. Default is false."
},
{
"code": null,
"e": 44385,
"s": 44276,
"text": "align − To specify the alignment of the under-script. Valid are: left, center, and right. Default is center."
},
{
"code": null,
"e": 44494,
"s": 44385,
"text": "align − To specify the alignment of the under-script. Valid are: left, center, and right. Default is center."
},
{
"code": null,
"e": 44521,
"s": 44494,
"text": "Let's draw an underscript."
},
{
"code": null,
"e": 44719,
"s": 44521,
"text": "<math xmlns = \"http://www.w3.org/1998/Math/MathML\">\n <mrow>\n <munderover>\n <mo> ∫</mo>\n <mn> 0 </mn>\n <mi> ∞</mi>\n </munderover>\n </mrow>\n</math>"
},
{
"code": null,
"e": 44779,
"s": 44719,
"text": "Following is a list of Algebra symbols available in MathML."
},
{
"code": null,
"e": 44840,
"s": 44779,
"text": "Following is a list of Calculus symbols available in MathML."
},
{
"code": null,
"e": 44901,
"s": 44840,
"text": "Following is a list of ellipses symbols available in MathML."
},
{
"code": null,
"e": 44962,
"s": 44901,
"text": "Following is a list of function symbols available in MathML."
},
{
"code": null,
"e": 45023,
"s": 44962,
"text": "Following is a list of geometry symbols available in MathML."
},
{
"code": null,
"e": 45081,
"s": 45023,
"text": "Following is a list of greek letters available in MathML."
},
{
"code": null,
"e": 45145,
"s": 45081,
"text": "Following is a list of invisible operators available in MathML."
},
{
"code": null,
"e": 45203,
"s": 45145,
"text": "Following is a list of logic symbols available in MathML."
},
{
"code": null,
"e": 45259,
"s": 45203,
"text": "Following is a list of set symbols available in MathML."
},
{
"code": null,
"e": 45266,
"s": 45259,
"text": " Print"
},
{
"code": null,
"e": 45277,
"s": 45266,
"text": " Add Notes"
}
] |
Apache Pig - SIZE()
|
The SIZE() function of Pig Latin is used to compute the number of elements based on any Pig data type.
Given below is the syntax of the SIZE() function.
grunt> SIZE(expression)
The return values vary according to the data types in Apache Pig.
Assume that we have a file named employee.txt in the HDFS directory /pig_data/ as shown below.
employee.txt
1,John,2007-01-24,250
2,Ram,2007-05-27,220
3,Jack,2007-05-06,170
3,Jack,2007-04-06,100
4,Jill,2007-04-06,220
5,Zara,2007-06-06,300
5,Zara,2007-02-06,350
And we have loaded this file into Pig with the relation name employee_data as shown below.
grunt> employee_data = LOAD 'hdfs://localhost:9000/pig_data/ employee.txt' USING PigStorage(',')
as (id:int, name:chararray, workdate:chararray, daily_typing_pages:int);
To calculate the size of the type of a particular column, we can use the SIZE() function. Let’s calculate the size of the name type as shown below.
grunt> size = FOREACH employee_data GENERATE SIZE(name);
Verify the relation size using the DUMP operator as shown below.
grunt> Dump size;
It will produce the following output, displaying the contents of the relation size as follows. In the example, we have calculated the size of the name column. Since it is of varchar type, the SIZE() function gives you the number of characters in the name of each employee.
(4)
(3)
(4)
(4)
(4)
(4)
(4)
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2787,
"s": 2684,
"text": "The SIZE() function of Pig Latin is used to compute the number of elements based on any Pig data type."
},
{
"code": null,
"e": 2837,
"s": 2787,
"text": "Given below is the syntax of the SIZE() function."
},
{
"code": null,
"e": 2862,
"s": 2837,
"text": "grunt> SIZE(expression)\n"
},
{
"code": null,
"e": 2928,
"s": 2862,
"text": "The return values vary according to the data types in Apache Pig."
},
{
"code": null,
"e": 3023,
"s": 2928,
"text": "Assume that we have a file named employee.txt in the HDFS directory /pig_data/ as shown below."
},
{
"code": null,
"e": 3036,
"s": 3023,
"text": "employee.txt"
},
{
"code": null,
"e": 3201,
"s": 3036,
"text": "1,John,2007-01-24,250\n2,Ram,2007-05-27,220 \n3,Jack,2007-05-06,170 \n3,Jack,2007-04-06,100 \n4,Jill,2007-04-06,220 \n5,Zara,2007-06-06,300 \n5,Zara,2007-02-06,350 \n"
},
{
"code": null,
"e": 3292,
"s": 3201,
"text": "And we have loaded this file into Pig with the relation name employee_data as shown below."
},
{
"code": null,
"e": 3465,
"s": 3292,
"text": "grunt> employee_data = LOAD 'hdfs://localhost:9000/pig_data/ employee.txt' USING PigStorage(',')\n as (id:int, name:chararray, workdate:chararray, daily_typing_pages:int);"
},
{
"code": null,
"e": 3614,
"s": 3465,
"text": "To calculate the size of the type of a particular column, we can use the SIZE() function. Let’s calculate the size of the name type as shown below."
},
{
"code": null,
"e": 3671,
"s": 3614,
"text": "grunt> size = FOREACH employee_data GENERATE SIZE(name);"
},
{
"code": null,
"e": 3736,
"s": 3671,
"text": "Verify the relation size using the DUMP operator as shown below."
},
{
"code": null,
"e": 3754,
"s": 3736,
"text": "grunt> Dump size;"
},
{
"code": null,
"e": 4027,
"s": 3754,
"text": "It will produce the following output, displaying the contents of the relation size as follows. In the example, we have calculated the size of the name column. Since it is of varchar type, the SIZE() function gives you the number of characters in the name of each employee."
},
{
"code": null,
"e": 4063,
"s": 4027,
"text": "(4) \n(3) \n(4) \n(4) \n(4) \n(4) \n(4) \n"
},
{
"code": null,
"e": 4098,
"s": 4063,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4117,
"s": 4098,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4152,
"s": 4117,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4173,
"s": 4152,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 4206,
"s": 4173,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4219,
"s": 4206,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 4254,
"s": 4219,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4272,
"s": 4254,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4305,
"s": 4272,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4323,
"s": 4305,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4356,
"s": 4323,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4374,
"s": 4356,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 4381,
"s": 4374,
"text": " Print"
},
{
"code": null,
"e": 4392,
"s": 4381,
"text": " Add Notes"
}
] |
Program to find the Encrypted word - GeeksforGeeks
|
02 Mar, 2020
Given a string, the given string is an encrypted word, the task is to decrypt the given string to get the original word.
Examples:
Input: str = "abcd"
Output: bdee
Explanation:
a -> a + 1 -> b
b -> b + 2 -> d
c -> c + 2 -> e
d -> d + 1 -> e
Input: str = "xyz"
Output: yaa
Explanation:
x -> x + 1 -> y
y -> y + 2 -> a
z -> z + 1 -> a
Approach:
Let the length of the string be n.
then the encrypted string will be:
Print the string after finding the scrypted word.
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; // Function to find the encrypted stringvoid findWord(string c, int n){ int co = 0, i; // to store the encrypted string string s(n, ' '); for (i = 0; i < n; i++) { if (i < n / 2) co++; else co = n - i; // after 'z', it should go to a. if (c[i] + co <= 122) s[i] = (char)((int)c[i] + co); else s[i] = (char)((int)c[i] + co - 26); } cout << s;} // Driver codeint main(){ string s = "abcd"; findWord(s, s.length()); return 0;}
// Java program to implement the above approachimport java.util.*;import java.io.*; class GFG{ // Static function declared to find// the encrypted stringpublic static void findWord(String c, int n){ int co = 0, i; // Character array to store //the encrypted string char s[] = new char[n]; for (i = 0; i < n ; i++) { if (i < n / 2) co++; else co = n - i; // after 'z', it should go to a. if ((c.charAt(i) + co) <= 122) s[i] = (char)((int)c.charAt(i) + co); else s[i] = (char)((int)c.charAt(i) + co - 26); } // storing the character array in the string. String str = Arrays.toString(s); System.out.println(str);} // Driver codepublic static void main(String args[]){ String s = "abcd"; findWord(s, s.length());}} // This code is contributed by Animesh_Gupta
# Python3 program to implement # the above approach # Function to find the encrypted stringdef findWord(c, n): co = 0 # to store the encrypted string s = [0] * n for i in range(n): if (i < n / 2): co += 1 else: co = n - i # after 'z', it should go to a. if (ord(c[i]) + co <= 122): s[i] = chr(ord(c[i]) + co) else: s[i] = chr(ord(c[i]) + co - 26) print(*s, sep = "") # Driver codes = "abcd"findWord(s, len(s)) # This code is contributed by SHUBHAMSINGH10
// C# program to implement the above approachusing System; class GFG{ // Static function declared to find// the encrypted stringpublic static void findWord(String c, int n){ int co = 0, i; // Character array to store // the encrypted string char []s = new char[n]; for (i = 0; i < n ; i++) { if (i < n / 2) co++; else co = n - i; // after 'z', it should go to a. if ((c[i] + co) <= 122) s[i] = (char)((int)c[i] + co); else s[i] = (char)((int)c[i] + co - 26); } // storing the character array in the string. String str = String.Join("",s); Console.WriteLine(str);} // Driver codepublic static void Main(String []args){ String s = "abcd"; findWord(s, s.Length);}} // This code is contributed by PrinciRaj1992
bdee
Time Complexity: O(N)
Animesh_Gupta
princiraj1992
SHUBHAMSINGH10
cryptography
School Programming
Strings
Strings
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Ternary Operator in Python
Difference between Abstract Class and Interface in Java
Destructors in C++
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
KMP Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 23839,
"s": 23811,
"text": "\n02 Mar, 2020"
},
{
"code": null,
"e": 23960,
"s": 23839,
"text": "Given a string, the given string is an encrypted word, the task is to decrypt the given string to get the original word."
},
{
"code": null,
"e": 23970,
"s": 23960,
"text": "Examples:"
},
{
"code": null,
"e": 24174,
"s": 23970,
"text": "Input: str = \"abcd\"\nOutput: bdee\nExplanation:\na -> a + 1 -> b\nb -> b + 2 -> d\nc -> c + 2 -> e\nd -> d + 1 -> e\n\nInput: str = \"xyz\"\nOutput: yaa\nExplanation:\nx -> x + 1 -> y\ny -> y + 2 -> a\nz -> z + 1 -> a\n"
},
{
"code": null,
"e": 24184,
"s": 24174,
"text": "Approach:"
},
{
"code": null,
"e": 24219,
"s": 24184,
"text": "Let the length of the string be n."
},
{
"code": null,
"e": 24254,
"s": 24219,
"text": "then the encrypted string will be:"
},
{
"code": null,
"e": 24304,
"s": 24254,
"text": "Print the string after finding the scrypted word."
},
{
"code": null,
"e": 24355,
"s": 24304,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 24359,
"s": 24355,
"text": "C++"
},
{
"code": null,
"e": 24364,
"s": 24359,
"text": "Java"
},
{
"code": null,
"e": 24372,
"s": 24364,
"text": "Python3"
},
{
"code": null,
"e": 24375,
"s": 24372,
"text": "C#"
},
{
"code": "// C++ program to implement // the above approach #include <bits/stdc++.h>using namespace std; // Function to find the encrypted stringvoid findWord(string c, int n){ int co = 0, i; // to store the encrypted string string s(n, ' '); for (i = 0; i < n; i++) { if (i < n / 2) co++; else co = n - i; // after 'z', it should go to a. if (c[i] + co <= 122) s[i] = (char)((int)c[i] + co); else s[i] = (char)((int)c[i] + co - 26); } cout << s;} // Driver codeint main(){ string s = \"abcd\"; findWord(s, s.length()); return 0;}",
"e": 25009,
"s": 24375,
"text": null
},
{
"code": "// Java program to implement the above approachimport java.util.*;import java.io.*; class GFG{ // Static function declared to find// the encrypted stringpublic static void findWord(String c, int n){ int co = 0, i; // Character array to store //the encrypted string char s[] = new char[n]; for (i = 0; i < n ; i++) { if (i < n / 2) co++; else co = n - i; // after 'z', it should go to a. if ((c.charAt(i) + co) <= 122) s[i] = (char)((int)c.charAt(i) + co); else s[i] = (char)((int)c.charAt(i) + co - 26); } // storing the character array in the string. String str = Arrays.toString(s); System.out.println(str);} // Driver codepublic static void main(String args[]){ String s = \"abcd\"; findWord(s, s.length());}} // This code is contributed by Animesh_Gupta",
"e": 25900,
"s": 25009,
"text": null
},
{
"code": "# Python3 program to implement # the above approach # Function to find the encrypted stringdef findWord(c, n): co = 0 # to store the encrypted string s = [0] * n for i in range(n): if (i < n / 2): co += 1 else: co = n - i # after 'z', it should go to a. if (ord(c[i]) + co <= 122): s[i] = chr(ord(c[i]) + co) else: s[i] = chr(ord(c[i]) + co - 26) print(*s, sep = \"\") # Driver codes = \"abcd\"findWord(s, len(s)) # This code is contributed by SHUBHAMSINGH10",
"e": 26468,
"s": 25900,
"text": null
},
{
"code": "// C# program to implement the above approachusing System; class GFG{ // Static function declared to find// the encrypted stringpublic static void findWord(String c, int n){ int co = 0, i; // Character array to store // the encrypted string char []s = new char[n]; for (i = 0; i < n ; i++) { if (i < n / 2) co++; else co = n - i; // after 'z', it should go to a. if ((c[i] + co) <= 122) s[i] = (char)((int)c[i] + co); else s[i] = (char)((int)c[i] + co - 26); } // storing the character array in the string. String str = String.Join(\"\",s); Console.WriteLine(str);} // Driver codepublic static void Main(String []args){ String s = \"abcd\"; findWord(s, s.Length);}} // This code is contributed by PrinciRaj1992",
"e": 27310,
"s": 26468,
"text": null
},
{
"code": null,
"e": 27316,
"s": 27310,
"text": "bdee\n"
},
{
"code": null,
"e": 27338,
"s": 27316,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 27352,
"s": 27338,
"text": "Animesh_Gupta"
},
{
"code": null,
"e": 27366,
"s": 27352,
"text": "princiraj1992"
},
{
"code": null,
"e": 27381,
"s": 27366,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 27394,
"s": 27381,
"text": "cryptography"
},
{
"code": null,
"e": 27413,
"s": 27394,
"text": "School Programming"
},
{
"code": null,
"e": 27421,
"s": 27413,
"text": "Strings"
},
{
"code": null,
"e": 27429,
"s": 27421,
"text": "Strings"
},
{
"code": null,
"e": 27442,
"s": 27429,
"text": "cryptography"
},
{
"code": null,
"e": 27540,
"s": 27442,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27549,
"s": 27540,
"text": "Comments"
},
{
"code": null,
"e": 27562,
"s": 27549,
"text": "Old Comments"
},
{
"code": null,
"e": 27583,
"s": 27562,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27602,
"s": 27583,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27629,
"s": 27602,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 27685,
"s": 27629,
"text": "Difference between Abstract Class and Interface in Java"
},
{
"code": null,
"e": 27704,
"s": 27685,
"text": "Destructors in C++"
},
{
"code": null,
"e": 27750,
"s": 27704,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 27784,
"s": 27750,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 27844,
"s": 27784,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 27919,
"s": 27844,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
C++ program to print unique words in a file
|
A file is a memory location that stores word streams. In a file, there are various words. In this program, we will find all unique words from the file and print them.
A unique word means the number of occurrences of the word is one in the file.
For example,
Tutorials point is best for programming tutorials.
Here, the word tutorial occurs more than once, hence it is not unique. Rest all words are unique.
To check for unique words in the given file.
Using iterator with two variables : data and occurence.
Input : File
Step 1 : Read each line from the file and follow step 2
Step 2 : check for the occurence of the word in the data structure using interator.data.
Step 2.1 : if data matches increase the occurrence by one corresponding to the data.
Step 2.2 : if data does not match add new value and set its occurence to one.
Step 3: Iterate over the date structure. And check for occurence value of each value.
Step 3.1 : If the occerence is equals to 1 then prints the data corresponding it else do nothing.
#include <bits/stdc++.h>
using namespace std;
int main(){
char filename[] = "test.txt";
ofstream fs("test.txt", ios::trunc);
fs << "tutorials point is best for programming tutorials";
fs.close();
fstream fs("test.txt");
map<string, int> mp;
string word;
while (fs >> word){
if (!mp.count(word))
mp.insert(make_pair(word, 1));
else
mp[word]++;
}
fs.close();
for (map<string, int> :: iterator p = mp.begin();
p != mp.end(); p++){
if (p->second == 1)
cout << p->first << endl;
}
return 0;
}
best
for
is
point
Programming
|
[
{
"code": null,
"e": 1229,
"s": 1062,
"text": "A file is a memory location that stores word streams. In a file, there are various words. In this program, we will find all unique words from the file and print them."
},
{
"code": null,
"e": 1307,
"s": 1229,
"text": "A unique word means the number of occurrences of the word is one in the file."
},
{
"code": null,
"e": 1320,
"s": 1307,
"text": "For example,"
},
{
"code": null,
"e": 1371,
"s": 1320,
"text": "Tutorials point is best for programming tutorials."
},
{
"code": null,
"e": 1469,
"s": 1371,
"text": "Here, the word tutorial occurs more than once, hence it is not unique. Rest all words are unique."
},
{
"code": null,
"e": 2084,
"s": 1469,
"text": "To check for unique words in the given file.\nUsing iterator with two variables : data and occurence.\nInput : File\nStep 1 : Read each line from the file and follow step 2\nStep 2 : check for the occurence of the word in the data structure using interator.data.\n Step 2.1 : if data matches increase the occurrence by one corresponding to the data.\n Step 2.2 : if data does not match add new value and set its occurence to one.\nStep 3: Iterate over the date structure. And check for occurence value of each value.\n Step 3.1 : If the occerence is equals to 1 then prints the data corresponding it else do nothing."
},
{
"code": null,
"e": 2659,
"s": 2084,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n char filename[] = \"test.txt\";\n ofstream fs(\"test.txt\", ios::trunc);\n fs << \"tutorials point is best for programming tutorials\";\n fs.close();\n fstream fs(\"test.txt\");\n map<string, int> mp;\n string word;\n while (fs >> word){\n if (!mp.count(word))\n mp.insert(make_pair(word, 1));\n else\n mp[word]++;\n }\n fs.close();\n for (map<string, int> :: iterator p = mp.begin();\n p != mp.end(); p++){\n if (p->second == 1)\n cout << p->first << endl;\n }\n return 0;\n}"
},
{
"code": null,
"e": 2689,
"s": 2659,
"text": "best\nfor\nis\npoint\nProgramming"
}
] |
How to get multiple selected values of select box in php? - GeeksforGeeks
|
31 Aug, 2021
Given a list of items and the task is to retrieve the multiple selected value from a select box using PHP.Use multiple attribute in HTML to select multiple value from drop down list. Selecting multiple values in HTML depends on operating system and browser.
For window users – hold down + CTRL key to select multiple option
For mac users – hold down command key to select multiple option
Example: This example creates a list of items using HTML.
html
<html> <body> <form method = "post" action = "name.php"> <h4>SELECT SUBJECTS</h4> <!--Using multiple to select multiple value--> <select name = "subject" multiple size = 6> <option value = "english">ENGLISH</option> <option value = "maths">MATHS</option> <option value = "computer">COMPUTER</option> <option value = "physics">PHYSICS</option> <option value = "chemistry">CHEMISTRY</option> <option value = "hindi">HINDI</option> </select> <input type = "submit" name = "submit" value = Submit> </form> </body></html>
Now, the task is to retrieve or print multiple selected value from list. Use form method and loop to retrieve selected value in PHP.Example:
php
<html> <body> <!--name.php to be called on form submission--> <form method = 'post'> <h4>SELECT SUBJECTS</h4> <select name = 'subject[]' multiple size = 6> <option value = 'english'>ENGLISH</option> <option value = 'maths'>MATHS</option> <option value = 'computer'>COMPUTER</option> <option value = 'physics'>PHYSICS</option> <option value = 'chemistry'>CHEMISTRY</option> <option value = 'hindi'>HINDI</option> </select> <input type = 'submit' name = 'submit' value = Submit> </form> </body></html><?php // Check if form is submitted successfully if(isset($_POST["submit"])) { // Check if any option is selected if(isset($_POST["subject"])) { // Retrieving each selected option foreach ($_POST['subject'] as $subject) print "You selected $subject<br/>"; } else echo "Select an option first !!"; }?>
Output:
Note: The form can be submitted using $_GET method. It depends on the form method=”?” value.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
rs1686740
Picked
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
How to receive JSON POST with PHP ?
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
|
[
{
"code": null,
"e": 24961,
"s": 24933,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 25221,
"s": 24961,
"text": "Given a list of items and the task is to retrieve the multiple selected value from a select box using PHP.Use multiple attribute in HTML to select multiple value from drop down list. Selecting multiple values in HTML depends on operating system and browser. "
},
{
"code": null,
"e": 25287,
"s": 25221,
"text": "For window users – hold down + CTRL key to select multiple option"
},
{
"code": null,
"e": 25351,
"s": 25287,
"text": "For mac users – hold down command key to select multiple option"
},
{
"code": null,
"e": 25411,
"s": 25351,
"text": "Example: This example creates a list of items using HTML. "
},
{
"code": null,
"e": 25416,
"s": 25411,
"text": "html"
},
{
"code": "<html> <body> <form method = \"post\" action = \"name.php\"> <h4>SELECT SUBJECTS</h4> <!--Using multiple to select multiple value--> <select name = \"subject\" multiple size = 6> <option value = \"english\">ENGLISH</option> <option value = \"maths\">MATHS</option> <option value = \"computer\">COMPUTER</option> <option value = \"physics\">PHYSICS</option> <option value = \"chemistry\">CHEMISTRY</option> <option value = \"hindi\">HINDI</option> </select> <input type = \"submit\" name = \"submit\" value = Submit> </form> </body></html>",
"e": 26099,
"s": 25416,
"text": null
},
{
"code": null,
"e": 26242,
"s": 26099,
"text": "Now, the task is to retrieve or print multiple selected value from list. Use form method and loop to retrieve selected value in PHP.Example: "
},
{
"code": null,
"e": 26246,
"s": 26242,
"text": "php"
},
{
"code": "<html> <body> <!--name.php to be called on form submission--> <form method = 'post'> <h4>SELECT SUBJECTS</h4> <select name = 'subject[]' multiple size = 6> <option value = 'english'>ENGLISH</option> <option value = 'maths'>MATHS</option> <option value = 'computer'>COMPUTER</option> <option value = 'physics'>PHYSICS</option> <option value = 'chemistry'>CHEMISTRY</option> <option value = 'hindi'>HINDI</option> </select> <input type = 'submit' name = 'submit' value = Submit> </form> </body></html><?php // Check if form is submitted successfully if(isset($_POST[\"submit\"])) { // Check if any option is selected if(isset($_POST[\"subject\"])) { // Retrieving each selected option foreach ($_POST['subject'] as $subject) print \"You selected $subject<br/>\"; } else echo \"Select an option first !!\"; }?>",
"e": 27313,
"s": 26246,
"text": null
},
{
"code": null,
"e": 27323,
"s": 27313,
"text": "Output: "
},
{
"code": null,
"e": 27417,
"s": 27323,
"text": "Note: The form can be submitted using $_GET method. It depends on the form method=”?” value. "
},
{
"code": null,
"e": 27586,
"s": 27417,
"text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples."
},
{
"code": null,
"e": 27598,
"s": 27588,
"text": "rs1686740"
},
{
"code": null,
"e": 27605,
"s": 27598,
"text": "Picked"
},
{
"code": null,
"e": 27609,
"s": 27605,
"text": "PHP"
},
{
"code": null,
"e": 27622,
"s": 27609,
"text": "PHP Programs"
},
{
"code": null,
"e": 27641,
"s": 27622,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27658,
"s": 27641,
"text": "Web Technologies"
},
{
"code": null,
"e": 27662,
"s": 27658,
"text": "PHP"
},
{
"code": null,
"e": 27760,
"s": 27662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27769,
"s": 27760,
"text": "Comments"
},
{
"code": null,
"e": 27782,
"s": 27769,
"text": "Old Comments"
},
{
"code": null,
"e": 27832,
"s": 27782,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27872,
"s": 27832,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27922,
"s": 27872,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 27958,
"s": 27922,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 27985,
"s": 27958,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 28035,
"s": 27985,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 28075,
"s": 28035,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 28127,
"s": 28075,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 28177,
"s": 28127,
"text": "How to check whether an array is empty using PHP?"
}
] |
How to align Text in React Material UI? - GeeksforGeeks
|
23 Dec, 2020
The Typography component of Material UI is used to present your text and content as clearly and efficiently as possible.
Import:
import Typography from '@material-ui/core/Typography';
// OR
import { Typography } from '@material-ui/core';
Syntax: It sets the alignment property.
<object align="value"> Text </object>
Property Values:
left: It aligns text along the left side of a page or containing element. It is the default value.
right: It aligns text along the right side of a page or containing element.
center: Text is aligned around a midpoint.
justify: To make sure that both edges of each line are aligned with both margins, space is added between words. The last line in the paragraph is aligned left.
Return Value: It returns the aligned text according to the set value.
Example 1: This example describes the left alignment value.
App.js:JavascriptJavascript// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState(""); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id="h3" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment("left")}>Press</button> </div> );} export default App;
App.js:
Javascript
// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState(""); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id="h3" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment("left")}>Press</button> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Before clicking on the button:
Before clicking on the button:
After clicking on the button:
After clicking on the button:
Example 2: This example describes the right alignment value.
App.js:JavascriptJavascript// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState(""); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id="h3" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment("right")}>Press</button> </div> );} export default App;
App.js:
Javascript
// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState(""); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id="h3" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment("right")}>Press</button> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Before clicking on the button:
Before clicking on the button:
After clicking on the button:
After clicking on the button:
Example 3: This example describes the center alignment value.
App.jsJavascriptJavascript// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState(""); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id="h3" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment("center")}>Press</button> </div> );} export default App;
App.js
Javascript
// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState(""); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id="h3" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment("center")}>Press</button> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Before clicking on the button:
Before clicking on the button:
After clicking on the button:
After clicking on the button:
Example 4: This example describes the justify alignment value.
App.js:JavascriptJavascript// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState("right"); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science - GeeksforGeeks </h2> <h3 id="h3" align={alignment}> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </h3> </Typography> <button onClick={() => setAlignment("justify")}>Press</button> </div> );} export default App;
App.js:
Javascript
// This code will be written in App.js file of your React Project import Typography from "@material-ui/core/Typography";import { useState } from "react"; function App() { const [alignment, setAlignment] = useState("right"); return ( <div className="App"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science - GeeksforGeeks </h2> <h3 id="h3" align={alignment}> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </h3> </Typography> <button onClick={() => setAlignment("justify")}>Press</button> </div> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
Before clicking on the button:
Before clicking on the button:
After clicking on the button:
After clicking on the button:
Picked
Technical Scripter 2020
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 24121,
"s": 24093,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 24242,
"s": 24121,
"text": "The Typography component of Material UI is used to present your text and content as clearly and efficiently as possible."
},
{
"code": null,
"e": 24250,
"s": 24242,
"text": "Import:"
},
{
"code": null,
"e": 24359,
"s": 24250,
"text": "import Typography from '@material-ui/core/Typography';\n// OR\nimport { Typography } from '@material-ui/core';"
},
{
"code": null,
"e": 24399,
"s": 24359,
"text": "Syntax: It sets the alignment property."
},
{
"code": null,
"e": 24437,
"s": 24399,
"text": "<object align=\"value\"> Text </object>"
},
{
"code": null,
"e": 24454,
"s": 24437,
"text": "Property Values:"
},
{
"code": null,
"e": 24553,
"s": 24454,
"text": "left: It aligns text along the left side of a page or containing element. It is the default value."
},
{
"code": null,
"e": 24629,
"s": 24553,
"text": "right: It aligns text along the right side of a page or containing element."
},
{
"code": null,
"e": 24672,
"s": 24629,
"text": "center: Text is aligned around a midpoint."
},
{
"code": null,
"e": 24832,
"s": 24672,
"text": "justify: To make sure that both edges of each line are aligned with both margins, space is added between words. The last line in the paragraph is aligned left."
},
{
"code": null,
"e": 24902,
"s": 24832,
"text": "Return Value: It returns the aligned text according to the set value."
},
{
"code": null,
"e": 24962,
"s": 24902,
"text": "Example 1: This example describes the left alignment value."
},
{
"code": null,
"e": 25569,
"s": 24962,
"text": "App.js:JavascriptJavascript// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id=\"h3\" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment(\"left\")}>Press</button> </div> );} export default App;"
},
{
"code": null,
"e": 25577,
"s": 25569,
"text": "App.js:"
},
{
"code": null,
"e": 25588,
"s": 25577,
"text": "Javascript"
},
{
"code": "// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id=\"h3\" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment(\"left\")}>Press</button> </div> );} export default App;",
"e": 26168,
"s": 25588,
"text": null
},
{
"code": null,
"e": 26356,
"s": 26168,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:"
},
{
"code": null,
"e": 26469,
"s": 26356,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 26479,
"s": 26469,
"text": "npm start"
},
{
"code": null,
"e": 26487,
"s": 26479,
"text": "Output:"
},
{
"code": null,
"e": 26518,
"s": 26487,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26549,
"s": 26518,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26579,
"s": 26549,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26609,
"s": 26579,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26670,
"s": 26609,
"text": "Example 2: This example describes the right alignment value."
},
{
"code": null,
"e": 27278,
"s": 26670,
"text": "App.js:JavascriptJavascript// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id=\"h3\" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment(\"right\")}>Press</button> </div> );} export default App;"
},
{
"code": null,
"e": 27286,
"s": 27278,
"text": "App.js:"
},
{
"code": null,
"e": 27297,
"s": 27286,
"text": "Javascript"
},
{
"code": "// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id=\"h3\" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment(\"right\")}>Press</button> </div> );} export default App;",
"e": 27878,
"s": 27297,
"text": null
},
{
"code": null,
"e": 28066,
"s": 27878,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:"
},
{
"code": null,
"e": 28179,
"s": 28066,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 28189,
"s": 28179,
"text": "npm start"
},
{
"code": null,
"e": 28197,
"s": 28189,
"text": "Output:"
},
{
"code": null,
"e": 28228,
"s": 28197,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28259,
"s": 28228,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28289,
"s": 28259,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28319,
"s": 28289,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28381,
"s": 28319,
"text": "Example 3: This example describes the center alignment value."
},
{
"code": null,
"e": 28989,
"s": 28381,
"text": "App.jsJavascriptJavascript// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id=\"h3\" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment(\"center\")}>Press</button> </div> );} export default App;"
},
{
"code": null,
"e": 28996,
"s": 28989,
"text": "App.js"
},
{
"code": null,
"e": 29007,
"s": 28996,
"text": "Javascript"
},
{
"code": "// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science.</h2> <h3 id=\"h3\" align={alignment}> GeeksforGeeks </h3> </Typography> <button onClick={() => setAlignment(\"center\")}>Press</button> </div> );} export default App;",
"e": 29589,
"s": 29007,
"text": null
},
{
"code": null,
"e": 29777,
"s": 29589,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:"
},
{
"code": null,
"e": 29890,
"s": 29777,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 29900,
"s": 29890,
"text": "npm start"
},
{
"code": null,
"e": 29908,
"s": 29900,
"text": "Output:"
},
{
"code": null,
"e": 29939,
"s": 29908,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 29970,
"s": 29939,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 30000,
"s": 29970,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 30030,
"s": 30000,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 30093,
"s": 30030,
"text": "Example 4: This example describes the justify alignment value."
},
{
"code": null,
"e": 31029,
"s": 30093,
"text": "App.js:JavascriptJavascript// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"right\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science - GeeksforGeeks </h2> <h3 id=\"h3\" align={alignment}> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </h3> </Typography> <button onClick={() => setAlignment(\"justify\")}>Press</button> </div> );} export default App;"
},
{
"code": null,
"e": 31037,
"s": 31029,
"text": "App.js:"
},
{
"code": null,
"e": 31048,
"s": 31037,
"text": "Javascript"
},
{
"code": "// This code will be written in App.js file of your React Project import Typography from \"@material-ui/core/Typography\";import { useState } from \"react\"; function App() { const [alignment, setAlignment] = useState(\"right\"); return ( <div className=\"App\"> <Typography> <h1>Typography - A Material-UI component</h1> <h2>Best website to learn Computer Science - GeeksforGeeks </h2> <h3 id=\"h3\" align={alignment}> How many times were you frustrated while looking out for a good collection of programming/algorithm/interview questions? What did you expect and what did you get? This portal has been created to provide well written, well thought and well explained solutions for selected questions. </h3> </Typography> <button onClick={() => setAlignment(\"justify\")}>Press</button> </div> );} export default App;",
"e": 31957,
"s": 31048,
"text": null
},
{
"code": null,
"e": 32145,
"s": 31957,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:npm startOutput:Before clicking on the button:After clicking on the button:"
},
{
"code": null,
"e": 32258,
"s": 32145,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 32268,
"s": 32258,
"text": "npm start"
},
{
"code": null,
"e": 32276,
"s": 32268,
"text": "Output:"
},
{
"code": null,
"e": 32307,
"s": 32276,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 32338,
"s": 32307,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 32368,
"s": 32338,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 32398,
"s": 32368,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 32405,
"s": 32398,
"text": "Picked"
},
{
"code": null,
"e": 32429,
"s": 32405,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 32448,
"s": 32429,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32465,
"s": 32448,
"text": "Web Technologies"
},
{
"code": null,
"e": 32563,
"s": 32465,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32572,
"s": 32563,
"text": "Comments"
},
{
"code": null,
"e": 32585,
"s": 32572,
"text": "Old Comments"
},
{
"code": null,
"e": 32641,
"s": 32585,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 32674,
"s": 32641,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32736,
"s": 32674,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 32779,
"s": 32736,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32829,
"s": 32779,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 32890,
"s": 32829,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32935,
"s": 32890,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 33007,
"s": 32935,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 33065,
"s": 33007,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
What are the differences between a dictionary and an array in C#?
|
Dictionary is a collection of keys and values in C#. Dictionary is included in the System.Collection.Generics namespace.
To declare a Dictionary −
IDictionary<int, int> d = new Dictionary<int, int>();
To add elements −
IDictionary<int, int> d = new Dictionary<int, int>();
d.Add(1,97);
d.Add(2,89);
d.Add(3,77);
d.Add(4,88);
Array stores a fixed-size sequential collection of elements of the same type. It consists of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To define Arrays −
int[] arr = new int[5];
To initialize and set elements to Arrays.
int[] arr = new int[10] {3, 5, 35, 87, 56, 99, 44, 36, 78};
|
[
{
"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": 1209,
"s": 1183,
"text": "To declare a Dictionary −"
},
{
"code": null,
"e": 1263,
"s": 1209,
"text": "IDictionary<int, int> d = new Dictionary<int, int>();"
},
{
"code": null,
"e": 1281,
"s": 1263,
"text": "To add elements −"
},
{
"code": null,
"e": 1387,
"s": 1281,
"text": "IDictionary<int, int> d = new Dictionary<int, int>();\nd.Add(1,97);\nd.Add(2,89);\nd.Add(3,77);\nd.Add(4,88);"
},
{
"code": null,
"e": 1606,
"s": 1387,
"text": "Array stores a fixed-size sequential collection of elements of the same type. It consists of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element."
},
{
"code": null,
"e": 1625,
"s": 1606,
"text": "To define Arrays −"
},
{
"code": null,
"e": 1650,
"s": 1625,
"text": "int[] arr = new int[5];\n"
},
{
"code": null,
"e": 1692,
"s": 1650,
"text": "To initialize and set elements to Arrays."
},
{
"code": null,
"e": 1752,
"s": 1692,
"text": "int[] arr = new int[10] {3, 5, 35, 87, 56, 99, 44, 36, 78};"
}
] |
How we built an easy-to-use image segmentation tool with transfer learning | by Jenny Huang | Towards Data Science
|
Authors: Jenny Huang, Ian Hunt-Isaak, William Palmer
GitHub Repo
Training an image segmentation model on new images can be daunting, especially when you need to label your own data. To make this task easier and faster, we built a user-friendly tool that lets you build this entire process in a single Jupyter notebook. In the sections below, we will show you how our tool lets you:
Manually label your own imagesBuild an effective segmentation model through transfer learningVisualize the model and its resultsShare your project as a Docker image
Manually label your own images
Build an effective segmentation model through transfer learning
Visualize the model and its results
Share your project as a Docker image
The main benefits of this tool are that it is easy-to-use, all in one platform, and well-integrated with existing data science workflows. Through interactive widgets and command prompts, we built a user-friendly way to label images and train the model. On top of that, everything can run in a single Jupyter notebook, making it quick and easy to spin up a model, without much overhead. Lastly, by working in a Python environment and using standard libraries like Tensorflow and Matplotlib, this tool can be well-integrated into existing data science workflows, making it ideal for uses like scientific research.
For instance, in microbiology, it can be very useful to segment microscopy images of cells. However, tracking cells over time can easily result in the need to segment hundreds of images, which can be very difficult to do manually. In this article, we will use microscopy images of yeast cells as our dataset and show how we built our tool to differentiate between the background, mother cells, and daughter cells.
There are many existing tools to create labelled masks for images, including Labelme, ImageJ, and even the graphics editor GIMP. While these are all great tools, they can’t be integrated within a Jupyter notebook, making them harder to use with many existing workflows. Fortunately, Jupyter Widgets make it easy for us to make interactive components and connect them with the rest of our Python code.
To create training masks in the notebook, we have two problems to solve:
Select parts of an image with a mouseEasily switch between images and select the class to label
Select parts of an image with a mouse
Easily switch between images and select the class to label
To solve the first problem, we used the Matplotlib widget backend and the built-in LassoSelector. The LassoSelector handles drawing a line to show what you are selecting, but we need a little bit of custom code to draw the masks as an overlay:
For the second problem, we added nice looking buttons and other controls using ipywidgets:
We combined these elements (along with improvements like scroll to zoom) to make a single labelling controller object. Now we can take microscopy images of yeast and segment the mother cells and daughter cells:
You can check out the full object, which lets you scroll to zoom, right click to pan, and select multiple classes here.
Now we can label a small number of images in the notebook, save them into the correct folder structure, and start to train CNN!
U-net is a convolutional neural network that was initially designed to segment biomedical images but has been successful for many other types of images. It builds upon existing convolutional networks to work better with very few training images and make more precise segmentations. It is a state-of-the-art model that is also easy to implement using the segmentation_models library.
U-net is unique because it combines an encoder and a decoder using cross-connections (the gray arrows in the figure above). These skip connections cross from the same sized part in the downsampling path to the upsampling path. This creates awareness of the original pixels inputted into the model when you upsample, which has been shown to improve performance on segmentation tasks.
As great as U-net is, it won’t work well if we don’t give it enough training examples. And given how tedious it is to manually segment images, we only manually labelled 13 images. With so few training examples, it seems impossible to train a neural network with millions of parameters. To overcome this, we need both Data Augmentation and Transfer Learning.
Naturally, if your model has a lot of parameters, you would need a proportional amount of training examples to get good performance. Using our small dataset of images and masks, we can create new images that will be as insightful and useful to our model as our original images.
How do we do that? We can flip the image, rotate it at an angle, scale it inward or outward, crop it, translate it, or even blur the image by adding noise, but most importantly, we can do a combination of those operations to create many new training examples.
Image data augmentation has one more complication in segmentation compared to classification. For classification, you just need to augment the image as the label will remain the same (0 or 1 or 2...). However, for segmentation, the label (which is a mask) needs to also be transformed in sync with the image. To do this, we used the albumentations library with a custom data generator since, to our knowledge, the Keras ImageDataGenerator does not currently support the combination “Image + mask”.
Even though we have now created 100 or more images, this still isn’t enough as the U-net model has more than 6 million parameters. This is where transfer learning comes into play.
Transfer Learning lets you take a model trained on one task and reuse it for another similar task. It reduces your training time drastically and more importantly, it can lead to effective models even with a small training set like ours. For example, neural networks like MobileNet, Inception, and DeepNet, learn a feature space, shapes, colors, texture, and more, by training on a great number of images. We can then transfer what was learned by taking these model weights and modifying them slightly to activate for patterns in our own training images.
Now how do we use transfer learning with U-net? We used the segmentation_models library to do this. We use the layers of a deep neural network of your choosing (MobileNet, Inception, ResNet) and the parameters found training on image classification (ImageNet) and use them as the first half (encoder) of your U-net. Then, you train the decoder layers with your own augmented dataset.
Putting it Together
We put this all together in a Segmentation model class that you can find here. When creating your model object, you get an interactive command prompt where you can customize aspects of your U-net like the loss function, backbone, and more:
After 30 epochs of training, we achieved 95% accuracy. Note that it is important to choose a good loss function. We first tried cross-entropy loss, but the model was unable to distinguish between the similar looking mother and daughter cells and had poor performance due to the class imbalance of seeing many more non-yeast pixels than yeast pixels. We found that using dice loss gave us much better results. The dice loss is linked to the Intersection over Union Score (IOU) and is usually better adapted to segmentation tasks as it gives incentive to maximize the overlap between the predicted and ground truth masks.
Now that our model is trained, let’s use some visualization techniques to see how it works. We follow Ankit Paliwal’s tutorial to do so. You can find the implementation in his corresponding GitHub repository. In this section, we will visualize two of his techniques, Intermediate Layer Activations and Heatmaps of Class Activations, on our yeast cell segmentation model.
This first technique shows the output of intermediate layers in a forward pass of the network on a test image. This lets us see what features of the input image are highlighted at each layer. After inputting a test image, we visualized the first few outputs for some convolutional layers in our network:
In the encoder layers, filters close to the input detect more detail and those close to the output of the model detect more general features, which is to be expected. In the decoder layers, we see the opposite pattern, of going from abstract to more specific details, which is also to be expected.
Next, we look at class activation maps. These heat maps let you see how important each location of the image is for predicting an output class. Here, we visualize the final layer of our yeast cell model, since the class prediction label will largely depend on it.
We see from the heat maps that the cell locations are correctly activated, along with parts of the image border, which is somewhat surprising.
We also looked at the last technique in the tutorial, which shows what images each convolutional filter maximally responds to, but the visualizations were not very informative for our specific yeast cell model.
Finding an awesome model and trying to run it, only to find that it doesn’t work in your environment due to mysterious dependency issues, is very frustrating. We addressed this by creating a Docker image for our tool. This allows us to completely define the environment that the code is run in, all the way down to the operating system. For this project, we based our Docker image off of the jupyter/tensorflow-notebook image from Jupyter Docker Stacks. Then we just added a few lines to install the libraries we needed and to copy the contents of our GitHub repository into the Docker image. If you’re curious, you can see our final Dockerfile here. Finally, we pushed this image to Docker Hub for easy distribution. You can try it out by running:
sudo docker run -p 8888:8888 ianhuntisaak/ac295-final-project:v3 \-e JUPYTER_LAB_ENABLE=yes
This tool lets you easily train a segmentation model on new images in a user-friendly way. While it works, there is still room for improvement in usability, customization, and model performance. In the future, we hope to:
Improve the lasso tool by building a custom Jupyter Widget using the html5 canvas to reduce lag when manually segmentingExplore new loss functions and models (like this U-net pre-trained on broad nucleus dataset) as a basis for transfer learningMake it easier to interpret visualizations and suggest methods of improving the results to the user
Improve the lasso tool by building a custom Jupyter Widget using the html5 canvas to reduce lag when manually segmenting
Explore new loss functions and models (like this U-net pre-trained on broad nucleus dataset) as a basis for transfer learning
Make it easier to interpret visualizations and suggest methods of improving the results to the user
We would like to thank our professor Pavlos Protopapas and the Harvard Applied Computation 295 course teaching staff for their guidance and support.
|
[
{
"code": null,
"e": 225,
"s": 172,
"text": "Authors: Jenny Huang, Ian Hunt-Isaak, William Palmer"
},
{
"code": null,
"e": 237,
"s": 225,
"text": "GitHub Repo"
},
{
"code": null,
"e": 554,
"s": 237,
"text": "Training an image segmentation model on new images can be daunting, especially when you need to label your own data. To make this task easier and faster, we built a user-friendly tool that lets you build this entire process in a single Jupyter notebook. In the sections below, we will show you how our tool lets you:"
},
{
"code": null,
"e": 719,
"s": 554,
"text": "Manually label your own imagesBuild an effective segmentation model through transfer learningVisualize the model and its resultsShare your project as a Docker image"
},
{
"code": null,
"e": 750,
"s": 719,
"text": "Manually label your own images"
},
{
"code": null,
"e": 814,
"s": 750,
"text": "Build an effective segmentation model through transfer learning"
},
{
"code": null,
"e": 850,
"s": 814,
"text": "Visualize the model and its results"
},
{
"code": null,
"e": 887,
"s": 850,
"text": "Share your project as a Docker image"
},
{
"code": null,
"e": 1499,
"s": 887,
"text": "The main benefits of this tool are that it is easy-to-use, all in one platform, and well-integrated with existing data science workflows. Through interactive widgets and command prompts, we built a user-friendly way to label images and train the model. On top of that, everything can run in a single Jupyter notebook, making it quick and easy to spin up a model, without much overhead. Lastly, by working in a Python environment and using standard libraries like Tensorflow and Matplotlib, this tool can be well-integrated into existing data science workflows, making it ideal for uses like scientific research."
},
{
"code": null,
"e": 1913,
"s": 1499,
"text": "For instance, in microbiology, it can be very useful to segment microscopy images of cells. However, tracking cells over time can easily result in the need to segment hundreds of images, which can be very difficult to do manually. In this article, we will use microscopy images of yeast cells as our dataset and show how we built our tool to differentiate between the background, mother cells, and daughter cells."
},
{
"code": null,
"e": 2314,
"s": 1913,
"text": "There are many existing tools to create labelled masks for images, including Labelme, ImageJ, and even the graphics editor GIMP. While these are all great tools, they can’t be integrated within a Jupyter notebook, making them harder to use with many existing workflows. Fortunately, Jupyter Widgets make it easy for us to make interactive components and connect them with the rest of our Python code."
},
{
"code": null,
"e": 2387,
"s": 2314,
"text": "To create training masks in the notebook, we have two problems to solve:"
},
{
"code": null,
"e": 2483,
"s": 2387,
"text": "Select parts of an image with a mouseEasily switch between images and select the class to label"
},
{
"code": null,
"e": 2521,
"s": 2483,
"text": "Select parts of an image with a mouse"
},
{
"code": null,
"e": 2580,
"s": 2521,
"text": "Easily switch between images and select the class to label"
},
{
"code": null,
"e": 2824,
"s": 2580,
"text": "To solve the first problem, we used the Matplotlib widget backend and the built-in LassoSelector. The LassoSelector handles drawing a line to show what you are selecting, but we need a little bit of custom code to draw the masks as an overlay:"
},
{
"code": null,
"e": 2915,
"s": 2824,
"text": "For the second problem, we added nice looking buttons and other controls using ipywidgets:"
},
{
"code": null,
"e": 3126,
"s": 2915,
"text": "We combined these elements (along with improvements like scroll to zoom) to make a single labelling controller object. Now we can take microscopy images of yeast and segment the mother cells and daughter cells:"
},
{
"code": null,
"e": 3246,
"s": 3126,
"text": "You can check out the full object, which lets you scroll to zoom, right click to pan, and select multiple classes here."
},
{
"code": null,
"e": 3374,
"s": 3246,
"text": "Now we can label a small number of images in the notebook, save them into the correct folder structure, and start to train CNN!"
},
{
"code": null,
"e": 3757,
"s": 3374,
"text": "U-net is a convolutional neural network that was initially designed to segment biomedical images but has been successful for many other types of images. It builds upon existing convolutional networks to work better with very few training images and make more precise segmentations. It is a state-of-the-art model that is also easy to implement using the segmentation_models library."
},
{
"code": null,
"e": 4140,
"s": 3757,
"text": "U-net is unique because it combines an encoder and a decoder using cross-connections (the gray arrows in the figure above). These skip connections cross from the same sized part in the downsampling path to the upsampling path. This creates awareness of the original pixels inputted into the model when you upsample, which has been shown to improve performance on segmentation tasks."
},
{
"code": null,
"e": 4498,
"s": 4140,
"text": "As great as U-net is, it won’t work well if we don’t give it enough training examples. And given how tedious it is to manually segment images, we only manually labelled 13 images. With so few training examples, it seems impossible to train a neural network with millions of parameters. To overcome this, we need both Data Augmentation and Transfer Learning."
},
{
"code": null,
"e": 4776,
"s": 4498,
"text": "Naturally, if your model has a lot of parameters, you would need a proportional amount of training examples to get good performance. Using our small dataset of images and masks, we can create new images that will be as insightful and useful to our model as our original images."
},
{
"code": null,
"e": 5036,
"s": 4776,
"text": "How do we do that? We can flip the image, rotate it at an angle, scale it inward or outward, crop it, translate it, or even blur the image by adding noise, but most importantly, we can do a combination of those operations to create many new training examples."
},
{
"code": null,
"e": 5534,
"s": 5036,
"text": "Image data augmentation has one more complication in segmentation compared to classification. For classification, you just need to augment the image as the label will remain the same (0 or 1 or 2...). However, for segmentation, the label (which is a mask) needs to also be transformed in sync with the image. To do this, we used the albumentations library with a custom data generator since, to our knowledge, the Keras ImageDataGenerator does not currently support the combination “Image + mask”."
},
{
"code": null,
"e": 5714,
"s": 5534,
"text": "Even though we have now created 100 or more images, this still isn’t enough as the U-net model has more than 6 million parameters. This is where transfer learning comes into play."
},
{
"code": null,
"e": 6268,
"s": 5714,
"text": "Transfer Learning lets you take a model trained on one task and reuse it for another similar task. It reduces your training time drastically and more importantly, it can lead to effective models even with a small training set like ours. For example, neural networks like MobileNet, Inception, and DeepNet, learn a feature space, shapes, colors, texture, and more, by training on a great number of images. We can then transfer what was learned by taking these model weights and modifying them slightly to activate for patterns in our own training images."
},
{
"code": null,
"e": 6652,
"s": 6268,
"text": "Now how do we use transfer learning with U-net? We used the segmentation_models library to do this. We use the layers of a deep neural network of your choosing (MobileNet, Inception, ResNet) and the parameters found training on image classification (ImageNet) and use them as the first half (encoder) of your U-net. Then, you train the decoder layers with your own augmented dataset."
},
{
"code": null,
"e": 6672,
"s": 6652,
"text": "Putting it Together"
},
{
"code": null,
"e": 6912,
"s": 6672,
"text": "We put this all together in a Segmentation model class that you can find here. When creating your model object, you get an interactive command prompt where you can customize aspects of your U-net like the loss function, backbone, and more:"
},
{
"code": null,
"e": 7532,
"s": 6912,
"text": "After 30 epochs of training, we achieved 95% accuracy. Note that it is important to choose a good loss function. We first tried cross-entropy loss, but the model was unable to distinguish between the similar looking mother and daughter cells and had poor performance due to the class imbalance of seeing many more non-yeast pixels than yeast pixels. We found that using dice loss gave us much better results. The dice loss is linked to the Intersection over Union Score (IOU) and is usually better adapted to segmentation tasks as it gives incentive to maximize the overlap between the predicted and ground truth masks."
},
{
"code": null,
"e": 7903,
"s": 7532,
"text": "Now that our model is trained, let’s use some visualization techniques to see how it works. We follow Ankit Paliwal’s tutorial to do so. You can find the implementation in his corresponding GitHub repository. In this section, we will visualize two of his techniques, Intermediate Layer Activations and Heatmaps of Class Activations, on our yeast cell segmentation model."
},
{
"code": null,
"e": 8207,
"s": 7903,
"text": "This first technique shows the output of intermediate layers in a forward pass of the network on a test image. This lets us see what features of the input image are highlighted at each layer. After inputting a test image, we visualized the first few outputs for some convolutional layers in our network:"
},
{
"code": null,
"e": 8505,
"s": 8207,
"text": "In the encoder layers, filters close to the input detect more detail and those close to the output of the model detect more general features, which is to be expected. In the decoder layers, we see the opposite pattern, of going from abstract to more specific details, which is also to be expected."
},
{
"code": null,
"e": 8769,
"s": 8505,
"text": "Next, we look at class activation maps. These heat maps let you see how important each location of the image is for predicting an output class. Here, we visualize the final layer of our yeast cell model, since the class prediction label will largely depend on it."
},
{
"code": null,
"e": 8912,
"s": 8769,
"text": "We see from the heat maps that the cell locations are correctly activated, along with parts of the image border, which is somewhat surprising."
},
{
"code": null,
"e": 9123,
"s": 8912,
"text": "We also looked at the last technique in the tutorial, which shows what images each convolutional filter maximally responds to, but the visualizations were not very informative for our specific yeast cell model."
},
{
"code": null,
"e": 9872,
"s": 9123,
"text": "Finding an awesome model and trying to run it, only to find that it doesn’t work in your environment due to mysterious dependency issues, is very frustrating. We addressed this by creating a Docker image for our tool. This allows us to completely define the environment that the code is run in, all the way down to the operating system. For this project, we based our Docker image off of the jupyter/tensorflow-notebook image from Jupyter Docker Stacks. Then we just added a few lines to install the libraries we needed and to copy the contents of our GitHub repository into the Docker image. If you’re curious, you can see our final Dockerfile here. Finally, we pushed this image to Docker Hub for easy distribution. You can try it out by running:"
},
{
"code": null,
"e": 9964,
"s": 9872,
"text": "sudo docker run -p 8888:8888 ianhuntisaak/ac295-final-project:v3 \\-e JUPYTER_LAB_ENABLE=yes"
},
{
"code": null,
"e": 10186,
"s": 9964,
"text": "This tool lets you easily train a segmentation model on new images in a user-friendly way. While it works, there is still room for improvement in usability, customization, and model performance. In the future, we hope to:"
},
{
"code": null,
"e": 10531,
"s": 10186,
"text": "Improve the lasso tool by building a custom Jupyter Widget using the html5 canvas to reduce lag when manually segmentingExplore new loss functions and models (like this U-net pre-trained on broad nucleus dataset) as a basis for transfer learningMake it easier to interpret visualizations and suggest methods of improving the results to the user"
},
{
"code": null,
"e": 10652,
"s": 10531,
"text": "Improve the lasso tool by building a custom Jupyter Widget using the html5 canvas to reduce lag when manually segmenting"
},
{
"code": null,
"e": 10778,
"s": 10652,
"text": "Explore new loss functions and models (like this U-net pre-trained on broad nucleus dataset) as a basis for transfer learning"
},
{
"code": null,
"e": 10878,
"s": 10778,
"text": "Make it easier to interpret visualizations and suggest methods of improving the results to the user"
}
] |
Understanding Graph Mining. Your first baby step to learn Deep... | by Vincent Tatan | Towards Data Science
|
Imagine Facebook: How do you get connected within layers of friends?
Imagine Recommendation System: How do you know a person’s preference is closely related to its clusters?
Welcome to Graph Mining
Graph classification generates graphs among a vast amount of connected data (e.g: Social, Biological, and Payment) and uses the graphs to identify labels (supervised) or clusters (unsupervised).
If this sounds tough to you, you can look no further than your brain because it is the master at inferencing connections among graphs quickly.
For example, your brain knows how to get from point A to point B without even thinking. Imagine your last grocery trip after being on shopping duty for a long time. You can skim through the catalogues and make multiple beelines of different categories of aisles to compare products while bringing your children to shop.
All these actions require consolidations to infer the best action based on series of sub actions to reach your end goal. All done in the most effortless methods as possible.
Graph mining uses features to see how a set of observations are related from a user facing similarity signal.
Graphs represent relationships (edges) between entities (nodes) which are formulated based on distance.
There are two characteristics commonly found:
Natural graphs which come from an external source. For example payment networks, social media, and roadways.
Similarity Graphs which comes from measures of similarity distance between nodes. For example a blob of metadata then shares the blob structure via graph representation.
Depending on the characteristics of the graphs, we can classify each graph as
Simple homogeneous with one type of node and edge
Complex heterogeneous with multiple types of nodes, multiple types of edges. These can be directed or undirected.
Graphs are multipurpose. You can build supervised models by classifying surrounding neighbors, semi-supervised models by propagating existing labels to missing labels in the neighborhood, and unsupervised models by training node-level embeddings to describe structural role of the data
There are a wide variety of tasks you can complete with graphs. For example, you can classify nodes, graphs, and links depending on your use case.
These include multiple breakthroughs such as: Google DeepMind’s Super Segments Graph to predict Time of Arrival (ETA) and PinSage from Pinterest.
Graphs abstract local information and extract useful global information from data. Graph structure/topology can tell us a lot about our data such as uncovering clusters of data points, or providing distance measures for otherwise intangible concepts.
Graphs work flexibly by embedding and combining multiple types of features such as: textual (e.g: Jaccard similarity ), visual (e.g: image similarities), and other semantic attributes. For example, when analysts work on campaign rules detections, they would use several features such as similarity among regex setups and deploy the regex to capture these sites.
Graph Sampling is used to seek subgraphs on receptive fields. These subgraphs can be formulated on top of async distributions of workers: dedicated servers to fetch model parameters.
This scalability also gives ways to use federated learning in graphs to preserve the privacy of users (such as Android based ML training)
In this case study, we are going to use Cora data, which provides a citation network benchmark with 2708 nodes, 5429 edges, 7 topic bags of words, 140 training, 500 validation, and 1000 test observations.
Please feel free to use the following colab for your tutorial.
colab.sandbox.google.com
Spektral is used as the open source Python library for graph deep learning, based on the Keras and Tensorflow2. The main goal of this project is to provide a simple but flexible framework for creating graph neural networks (GNNs).
Spektral has a convenience function that will allow us to quickly load and preprocess standard graph representation learnings. It also allows functions to access feature matrix, adjacency, matrix, and mask arrays to understand which node belongs to the train, validation, and test set.
TF GNN library is Agnostic to Model API and integrates with DeepMind graphNet, Google Neural Structured Learning, TF GNN API based on MPNN paper. The graph can also be passed around Keras layers with batching/serialization supported with TPUs.
To install and import these libraries in colab is very simple
!pip install numpy!pip install tensorflow!pip install spektral==0.6.1import numpy as npimport tensorflow as tfimport spektral
adj refers to adjacency matrix, features to feature_matrix, labels to topics of paper, and mask sets to indicate which node belongs to which data sets.
adj, features, labels, train_mask, val_mask, test_mask = spektral.datasets.citation.load_data(dataset_name=’cora’)
We then replace the dense features to convert features to adjacency matrices while setting them up in float32 as a standard machine learning output format.
features = features.todense()adj = adj.todense() + np.eye(adj.shape[0])features = features.astype(‘float32’)adj = adj.astype(‘float32’)
We follow the following steps to train our GNN on Cora datasets:
Define 2 GNN layers (Input — units, output — 7 topics, with sumpooling)Implement GNN with the defined layers with Relu activation function.Use tf.GradientTape() to record operations for auto differentiation. This helps us watch variables and gradients to catch back propagation errorsApply optimizer to gradients (Adam opt is the standard)Specify logits and accuracy calculations based on features and adjacency matrices
Define 2 GNN layers (Input — units, output — 7 topics, with sumpooling)
Implement GNN with the defined layers with Relu activation function.
Use tf.GradientTape() to record operations for auto differentiation. This helps us watch variables and gradients to catch back propagation errors
Apply optimizer to gradients (Adam opt is the standard)
Specify logits and accuracy calculations based on features and adjacency matrices
You can experiment with parameters (units, epochs and learning rate) to define the validation accuracy and training/val loss.
train_cora(features,adj,gnn,32,200,0.01)## Results ##Epoch 0 | training loss: 1.9685615301132202 | val_accuracy: 0.20399999618530273 | test_accuracy:0.20799998939037323Epoch 1 | training loss: 2.1238698959350586 | val_accuracy: 0.30399999022483826 | test_accuracy:0.3100000023841858Epoch 2 | training loss: 1.6506766080856323 | val_accuracy: 0.6060000061988831 | test_accuracy:0.6150000095367432Epoch 3 | training loss: 1.504560112953186 | val_accuracy: 0.628000020980835 | test_accuracy:0.6359999775886536...Epoch 129 | training loss: 0.004622798413038254 | val_accuracy: 0.7520000338554382 | test_accuracy:0.7450000047683716
As you can see, it seems the more epochs and training step runs, the more accuracy we can obtain from it.
Done! Congrats for your very first Graph Network!
Vincent fights internet abuse with ML @ Google. Vincent uses advanced data analytics, machine learning, and software engineering to protect Chrome and Gmail users.
Apart from his stint at Google, Vincent is also Georgia Tech CS MSc Alumni, a triathlete, and a featured writer for Towards Data Science Medium to guide aspiring ML and data practitioners with 1M+ viewers globally.
Lastly, please reach out to Vincent via LinkedIn, Medium or Youtube Channel
Soli deo gloria
Google Graph Mining and Learning
Graph Neural Networks in TF and Keras with Spektral
|
[
{
"code": null,
"e": 240,
"s": 171,
"text": "Imagine Facebook: How do you get connected within layers of friends?"
},
{
"code": null,
"e": 345,
"s": 240,
"text": "Imagine Recommendation System: How do you know a person’s preference is closely related to its clusters?"
},
{
"code": null,
"e": 369,
"s": 345,
"text": "Welcome to Graph Mining"
},
{
"code": null,
"e": 564,
"s": 369,
"text": "Graph classification generates graphs among a vast amount of connected data (e.g: Social, Biological, and Payment) and uses the graphs to identify labels (supervised) or clusters (unsupervised)."
},
{
"code": null,
"e": 707,
"s": 564,
"text": "If this sounds tough to you, you can look no further than your brain because it is the master at inferencing connections among graphs quickly."
},
{
"code": null,
"e": 1027,
"s": 707,
"text": "For example, your brain knows how to get from point A to point B without even thinking. Imagine your last grocery trip after being on shopping duty for a long time. You can skim through the catalogues and make multiple beelines of different categories of aisles to compare products while bringing your children to shop."
},
{
"code": null,
"e": 1201,
"s": 1027,
"text": "All these actions require consolidations to infer the best action based on series of sub actions to reach your end goal. All done in the most effortless methods as possible."
},
{
"code": null,
"e": 1311,
"s": 1201,
"text": "Graph mining uses features to see how a set of observations are related from a user facing similarity signal."
},
{
"code": null,
"e": 1415,
"s": 1311,
"text": "Graphs represent relationships (edges) between entities (nodes) which are formulated based on distance."
},
{
"code": null,
"e": 1461,
"s": 1415,
"text": "There are two characteristics commonly found:"
},
{
"code": null,
"e": 1570,
"s": 1461,
"text": "Natural graphs which come from an external source. For example payment networks, social media, and roadways."
},
{
"code": null,
"e": 1740,
"s": 1570,
"text": "Similarity Graphs which comes from measures of similarity distance between nodes. For example a blob of metadata then shares the blob structure via graph representation."
},
{
"code": null,
"e": 1818,
"s": 1740,
"text": "Depending on the characteristics of the graphs, we can classify each graph as"
},
{
"code": null,
"e": 1868,
"s": 1818,
"text": "Simple homogeneous with one type of node and edge"
},
{
"code": null,
"e": 1982,
"s": 1868,
"text": "Complex heterogeneous with multiple types of nodes, multiple types of edges. These can be directed or undirected."
},
{
"code": null,
"e": 2268,
"s": 1982,
"text": "Graphs are multipurpose. You can build supervised models by classifying surrounding neighbors, semi-supervised models by propagating existing labels to missing labels in the neighborhood, and unsupervised models by training node-level embeddings to describe structural role of the data"
},
{
"code": null,
"e": 2415,
"s": 2268,
"text": "There are a wide variety of tasks you can complete with graphs. For example, you can classify nodes, graphs, and links depending on your use case."
},
{
"code": null,
"e": 2561,
"s": 2415,
"text": "These include multiple breakthroughs such as: Google DeepMind’s Super Segments Graph to predict Time of Arrival (ETA) and PinSage from Pinterest."
},
{
"code": null,
"e": 2812,
"s": 2561,
"text": "Graphs abstract local information and extract useful global information from data. Graph structure/topology can tell us a lot about our data such as uncovering clusters of data points, or providing distance measures for otherwise intangible concepts."
},
{
"code": null,
"e": 3174,
"s": 2812,
"text": "Graphs work flexibly by embedding and combining multiple types of features such as: textual (e.g: Jaccard similarity ), visual (e.g: image similarities), and other semantic attributes. For example, when analysts work on campaign rules detections, they would use several features such as similarity among regex setups and deploy the regex to capture these sites."
},
{
"code": null,
"e": 3357,
"s": 3174,
"text": "Graph Sampling is used to seek subgraphs on receptive fields. These subgraphs can be formulated on top of async distributions of workers: dedicated servers to fetch model parameters."
},
{
"code": null,
"e": 3495,
"s": 3357,
"text": "This scalability also gives ways to use federated learning in graphs to preserve the privacy of users (such as Android based ML training)"
},
{
"code": null,
"e": 3700,
"s": 3495,
"text": "In this case study, we are going to use Cora data, which provides a citation network benchmark with 2708 nodes, 5429 edges, 7 topic bags of words, 140 training, 500 validation, and 1000 test observations."
},
{
"code": null,
"e": 3763,
"s": 3700,
"text": "Please feel free to use the following colab for your tutorial."
},
{
"code": null,
"e": 3788,
"s": 3763,
"text": "colab.sandbox.google.com"
},
{
"code": null,
"e": 4019,
"s": 3788,
"text": "Spektral is used as the open source Python library for graph deep learning, based on the Keras and Tensorflow2. The main goal of this project is to provide a simple but flexible framework for creating graph neural networks (GNNs)."
},
{
"code": null,
"e": 4305,
"s": 4019,
"text": "Spektral has a convenience function that will allow us to quickly load and preprocess standard graph representation learnings. It also allows functions to access feature matrix, adjacency, matrix, and mask arrays to understand which node belongs to the train, validation, and test set."
},
{
"code": null,
"e": 4549,
"s": 4305,
"text": "TF GNN library is Agnostic to Model API and integrates with DeepMind graphNet, Google Neural Structured Learning, TF GNN API based on MPNN paper. The graph can also be passed around Keras layers with batching/serialization supported with TPUs."
},
{
"code": null,
"e": 4611,
"s": 4549,
"text": "To install and import these libraries in colab is very simple"
},
{
"code": null,
"e": 4737,
"s": 4611,
"text": "!pip install numpy!pip install tensorflow!pip install spektral==0.6.1import numpy as npimport tensorflow as tfimport spektral"
},
{
"code": null,
"e": 4889,
"s": 4737,
"text": "adj refers to adjacency matrix, features to feature_matrix, labels to topics of paper, and mask sets to indicate which node belongs to which data sets."
},
{
"code": null,
"e": 5004,
"s": 4889,
"text": "adj, features, labels, train_mask, val_mask, test_mask = spektral.datasets.citation.load_data(dataset_name=’cora’)"
},
{
"code": null,
"e": 5160,
"s": 5004,
"text": "We then replace the dense features to convert features to adjacency matrices while setting them up in float32 as a standard machine learning output format."
},
{
"code": null,
"e": 5296,
"s": 5160,
"text": "features = features.todense()adj = adj.todense() + np.eye(adj.shape[0])features = features.astype(‘float32’)adj = adj.astype(‘float32’)"
},
{
"code": null,
"e": 5361,
"s": 5296,
"text": "We follow the following steps to train our GNN on Cora datasets:"
},
{
"code": null,
"e": 5782,
"s": 5361,
"text": "Define 2 GNN layers (Input — units, output — 7 topics, with sumpooling)Implement GNN with the defined layers with Relu activation function.Use tf.GradientTape() to record operations for auto differentiation. This helps us watch variables and gradients to catch back propagation errorsApply optimizer to gradients (Adam opt is the standard)Specify logits and accuracy calculations based on features and adjacency matrices"
},
{
"code": null,
"e": 5854,
"s": 5782,
"text": "Define 2 GNN layers (Input — units, output — 7 topics, with sumpooling)"
},
{
"code": null,
"e": 5923,
"s": 5854,
"text": "Implement GNN with the defined layers with Relu activation function."
},
{
"code": null,
"e": 6069,
"s": 5923,
"text": "Use tf.GradientTape() to record operations for auto differentiation. This helps us watch variables and gradients to catch back propagation errors"
},
{
"code": null,
"e": 6125,
"s": 6069,
"text": "Apply optimizer to gradients (Adam opt is the standard)"
},
{
"code": null,
"e": 6207,
"s": 6125,
"text": "Specify logits and accuracy calculations based on features and adjacency matrices"
},
{
"code": null,
"e": 6333,
"s": 6207,
"text": "You can experiment with parameters (units, epochs and learning rate) to define the validation accuracy and training/val loss."
},
{
"code": null,
"e": 6960,
"s": 6333,
"text": "train_cora(features,adj,gnn,32,200,0.01)## Results ##Epoch 0 | training loss: 1.9685615301132202 | val_accuracy: 0.20399999618530273 | test_accuracy:0.20799998939037323Epoch 1 | training loss: 2.1238698959350586 | val_accuracy: 0.30399999022483826 | test_accuracy:0.3100000023841858Epoch 2 | training loss: 1.6506766080856323 | val_accuracy: 0.6060000061988831 | test_accuracy:0.6150000095367432Epoch 3 | training loss: 1.504560112953186 | val_accuracy: 0.628000020980835 | test_accuracy:0.6359999775886536...Epoch 129 | training loss: 0.004622798413038254 | val_accuracy: 0.7520000338554382 | test_accuracy:0.7450000047683716"
},
{
"code": null,
"e": 7066,
"s": 6960,
"text": "As you can see, it seems the more epochs and training step runs, the more accuracy we can obtain from it."
},
{
"code": null,
"e": 7116,
"s": 7066,
"text": "Done! Congrats for your very first Graph Network!"
},
{
"code": null,
"e": 7280,
"s": 7116,
"text": "Vincent fights internet abuse with ML @ Google. Vincent uses advanced data analytics, machine learning, and software engineering to protect Chrome and Gmail users."
},
{
"code": null,
"e": 7495,
"s": 7280,
"text": "Apart from his stint at Google, Vincent is also Georgia Tech CS MSc Alumni, a triathlete, and a featured writer for Towards Data Science Medium to guide aspiring ML and data practitioners with 1M+ viewers globally."
},
{
"code": null,
"e": 7571,
"s": 7495,
"text": "Lastly, please reach out to Vincent via LinkedIn, Medium or Youtube Channel"
},
{
"code": null,
"e": 7587,
"s": 7571,
"text": "Soli deo gloria"
},
{
"code": null,
"e": 7620,
"s": 7587,
"text": "Google Graph Mining and Learning"
}
] |
DayOfWeek of() method in Java with Examples - GeeksforGeeks
|
19 Mar, 2019
The of() method of java.time.DayOfWeek is an in-built function in Java which returns an instance of DayOfWeek from an int value. The int value ranges between 1 (Monday) to 7 (Sunday).
Method Declaration:
public static DayOfWeek of(int dayOfWeek)
Syntax:
DayOfWeek dayOfWeekObject = DayOfWeek.of(int dayOfWeek)
Parameters: This method takes dayOfWeek as parameter where:
dayOfWeek – is the int value from 1 (Monday) to 7 (Sunday).
dayOfWeekObject – is an instance of the DayOfWeek object.
Return Value: The function returns an instance of DayOfWeek object.
Below programs illustrate the above method:Program 1:
// Java Program Demonstrate of()// method of DayOfWeekimport java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Getting an instance of DayOfWeek from int value DayOfWeek dayOfWeek = DayOfWeek.of(4); // Printing the day of the week // and its Int value System.out.println("Day of the Week - " + dayOfWeek.name()); System.out.println("Int Value of " + dayOfWeek.name() + " - " + dayOfWeek.getValue()); }}
Day of the Week - THURSDAY
Int Value of THURSDAY - 4
Program 2:
// Java Program Demonstrate of()// method of DayOfWeekimport java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Getting an instance of DayOfWeek from int value DayOfWeek dayOfWeek = DayOfWeek.of(7); // Printing the day of the week // and its Int value System.out.println("Day of the Week - " + dayOfWeek.name()); System.out.println("Int Value of " + dayOfWeek.name() + " - " + dayOfWeek.getValue()); }}
Day of the Week - SUNDAY
Int Value of SUNDAY - 7
Reference: https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html#of-int-
Java - util package
Java-DayOfWeek
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stream In Java
Stack Class in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 24530,
"s": 24502,
"text": "\n19 Mar, 2019"
},
{
"code": null,
"e": 24714,
"s": 24530,
"text": "The of() method of java.time.DayOfWeek is an in-built function in Java which returns an instance of DayOfWeek from an int value. The int value ranges between 1 (Monday) to 7 (Sunday)."
},
{
"code": null,
"e": 24734,
"s": 24714,
"text": "Method Declaration:"
},
{
"code": null,
"e": 24777,
"s": 24734,
"text": "public static DayOfWeek of(int dayOfWeek)\n"
},
{
"code": null,
"e": 24785,
"s": 24777,
"text": "Syntax:"
},
{
"code": null,
"e": 24842,
"s": 24785,
"text": "DayOfWeek dayOfWeekObject = DayOfWeek.of(int dayOfWeek)\n"
},
{
"code": null,
"e": 24902,
"s": 24842,
"text": "Parameters: This method takes dayOfWeek as parameter where:"
},
{
"code": null,
"e": 24962,
"s": 24902,
"text": "dayOfWeek – is the int value from 1 (Monday) to 7 (Sunday)."
},
{
"code": null,
"e": 25020,
"s": 24962,
"text": "dayOfWeekObject – is an instance of the DayOfWeek object."
},
{
"code": null,
"e": 25088,
"s": 25020,
"text": "Return Value: The function returns an instance of DayOfWeek object."
},
{
"code": null,
"e": 25142,
"s": 25088,
"text": "Below programs illustrate the above method:Program 1:"
},
{
"code": "// Java Program Demonstrate of()// method of DayOfWeekimport java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Getting an instance of DayOfWeek from int value DayOfWeek dayOfWeek = DayOfWeek.of(4); // Printing the day of the week // and its Int value System.out.println(\"Day of the Week - \" + dayOfWeek.name()); System.out.println(\"Int Value of \" + dayOfWeek.name() + \" - \" + dayOfWeek.getValue()); }}",
"e": 25716,
"s": 25142,
"text": null
},
{
"code": null,
"e": 25770,
"s": 25716,
"text": "Day of the Week - THURSDAY\nInt Value of THURSDAY - 4\n"
},
{
"code": null,
"e": 25781,
"s": 25770,
"text": "Program 2:"
},
{
"code": "// Java Program Demonstrate of()// method of DayOfWeekimport java.time.DayOfWeek; class DayOfWeekExample { public static void main(String[] args) { // Getting an instance of DayOfWeek from int value DayOfWeek dayOfWeek = DayOfWeek.of(7); // Printing the day of the week // and its Int value System.out.println(\"Day of the Week - \" + dayOfWeek.name()); System.out.println(\"Int Value of \" + dayOfWeek.name() + \" - \" + dayOfWeek.getValue()); }}",
"e": 26355,
"s": 25781,
"text": null
},
{
"code": null,
"e": 26405,
"s": 26355,
"text": "Day of the Week - SUNDAY\nInt Value of SUNDAY - 7\n"
},
{
"code": null,
"e": 26491,
"s": 26405,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html#of-int-"
},
{
"code": null,
"e": 26511,
"s": 26491,
"text": "Java - util package"
},
{
"code": null,
"e": 26526,
"s": 26511,
"text": "Java-DayOfWeek"
},
{
"code": null,
"e": 26541,
"s": 26526,
"text": "Java-Functions"
},
{
"code": null,
"e": 26546,
"s": 26541,
"text": "Java"
},
{
"code": null,
"e": 26551,
"s": 26546,
"text": "Java"
},
{
"code": null,
"e": 26649,
"s": 26551,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26681,
"s": 26649,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26732,
"s": 26681,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26762,
"s": 26732,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26781,
"s": 26762,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26812,
"s": 26781,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26830,
"s": 26812,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26862,
"s": 26830,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 26877,
"s": 26862,
"text": "Stream In Java"
},
{
"code": null,
"e": 26897,
"s": 26877,
"text": "Stack Class in Java"
}
] |
Allow wrapping of flex items in Bootstrap on different screens
|
To allow wrapping of flex items on different screens, use the flex-*-wrap class. The flex-wrap for varied screen sizes work for small, medium, large and extra large screens.
For example, use the flex-lg-wrap class to wrap flex items on large screen −
<div class="d-flex flex-lg-wrap bg-primary">
For small screen −
<div class="d-flex flex-sm-wrap bg-primary">
You can try to run the following code to implement the flex-*-wrap class to wrap flex items on small and large screen size −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-3">
<h3>Flex Examples</h3>
<p>Wrap - Yes</p>
<div class="d-flex flex-wrap bg-primary">
<div class="p-2 border">Poland</div>
<div class="p-2 border">Netherlands</div>
<div class="p-2 border">Ireland</div>
<div class="p-2 border">Brazil</div>
<div class="p-2 border">India</div>
<div class="p-2 border">US</div>
<div class="p-2 border">Bangladesh</div>
<div class="p-2 border">Russia</div>
<div class="p-2 border">Morocco</div>
<div class="p-2 border">UK</div>
<div class="p-2 border">Australia</div>
<div class="p-2 border">Denmark</div>
</div>
<br>
<p>Will wrap on Small Screen</p>
<div class="d-flex flex-sm-wrap bg-primary">
<div class="p-2 border">Poland</div>
<div class="p-2 border">Netherlands</div>
<div class="p-2 border">Ireland</div>
<div class="p-2 border">Brazil</div>
<div class="p-2 border">India</div>
<div class="p-2 border">US</div>
<div class="p-2 border">Bangladesh</div>
<div class="p-2 border">Russia</div>
<div class="p-2 border">Morocco</div>
<div class="p-2 border">UK</div>
<div class="p-2 border">Australia</div>
<div class="p-2 border">Denmark</div>
</div><br>
<p>Will Wrap on Large Screen</p>
<div class="d-flex flex-lg-wrap bg-primary">
<div class="p-2 border">Poland</div>
<div class="p-2 border">Netherlands</div>
<div class="p-2 border">Ireland</div>
<div class="p-2 border">Brazil</div>
<div class="p-2 border">India</div>
<div class="p-2 border">US</div>
<div class="p-2 border">Bangladesh</div>
<div class="p-2 border">Russia</div>
<div class="p-2 border">Morocco</div>
<div class="p-2 border">UK</div>
<div class="p-2 border">Australia</div>
<div class="p-2 border">Denmark</div>
</div><br>
</div>
</body>
</html>
|
[
{
"code": null,
"e": 1236,
"s": 1062,
"text": "To allow wrapping of flex items on different screens, use the flex-*-wrap class. The flex-wrap for varied screen sizes work for small, medium, large and extra large screens."
},
{
"code": null,
"e": 1313,
"s": 1236,
"text": "For example, use the flex-lg-wrap class to wrap flex items on large screen −"
},
{
"code": null,
"e": 1358,
"s": 1313,
"text": "<div class=\"d-flex flex-lg-wrap bg-primary\">"
},
{
"code": null,
"e": 1377,
"s": 1358,
"text": "For small screen −"
},
{
"code": null,
"e": 1422,
"s": 1377,
"text": "<div class=\"d-flex flex-sm-wrap bg-primary\">"
},
{
"code": null,
"e": 1547,
"s": 1422,
"text": "You can try to run the following code to implement the flex-*-wrap class to wrap flex items on small and large screen size −"
},
{
"code": null,
"e": 1557,
"s": 1547,
"text": "Live Demo"
},
{
"code": null,
"e": 4139,
"s": 1557,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n <body>\n <div class=\"container mt-3\">\n <h3>Flex Examples</h3>\n <p>Wrap - Yes</p>\n <div class=\"d-flex flex-wrap bg-primary\">\n <div class=\"p-2 border\">Poland</div>\n <div class=\"p-2 border\">Netherlands</div>\n <div class=\"p-2 border\">Ireland</div>\n <div class=\"p-2 border\">Brazil</div>\n <div class=\"p-2 border\">India</div>\n <div class=\"p-2 border\">US</div>\n <div class=\"p-2 border\">Bangladesh</div>\n <div class=\"p-2 border\">Russia</div>\n <div class=\"p-2 border\">Morocco</div>\n <div class=\"p-2 border\">UK</div>\n <div class=\"p-2 border\">Australia</div>\n <div class=\"p-2 border\">Denmark</div>\n </div>\n <br>\n <p>Will wrap on Small Screen</p>\n <div class=\"d-flex flex-sm-wrap bg-primary\">\n <div class=\"p-2 border\">Poland</div>\n <div class=\"p-2 border\">Netherlands</div>\n <div class=\"p-2 border\">Ireland</div>\n <div class=\"p-2 border\">Brazil</div>\n <div class=\"p-2 border\">India</div>\n <div class=\"p-2 border\">US</div>\n <div class=\"p-2 border\">Bangladesh</div>\n <div class=\"p-2 border\">Russia</div>\n <div class=\"p-2 border\">Morocco</div>\n <div class=\"p-2 border\">UK</div>\n <div class=\"p-2 border\">Australia</div>\n <div class=\"p-2 border\">Denmark</div>\n </div><br>\n <p>Will Wrap on Large Screen</p>\n <div class=\"d-flex flex-lg-wrap bg-primary\">\n <div class=\"p-2 border\">Poland</div>\n <div class=\"p-2 border\">Netherlands</div>\n <div class=\"p-2 border\">Ireland</div>\n <div class=\"p-2 border\">Brazil</div>\n <div class=\"p-2 border\">India</div>\n <div class=\"p-2 border\">US</div>\n <div class=\"p-2 border\">Bangladesh</div>\n <div class=\"p-2 border\">Russia</div>\n <div class=\"p-2 border\">Morocco</div>\n <div class=\"p-2 border\">UK</div>\n <div class=\"p-2 border\">Australia</div>\n <div class=\"p-2 border\">Denmark</div>\n </div><br>\n </div>\n\n </body>\n</html>"
}
] |
PyQt5 - QSpinBox Widget
|
A QSpinBox object presents the user with a textbox which displays an integer with up/down button on its right. The value in the textbox increases/decreases if the up/down button is pressed.
By default, the integer number in the box starts with 0, goes upto 99 and changes by step 1. Use QDoubleSpinBox for float values.
Important methods of QSpinBox class are listed in the following table −
setMinimum()
Sets the lower bound of counter
setMaximum()
Sets the upper bound of counter
setRange()
Sets the minimum, maximum and step value
setValue()
Sets the value of spin box programmatically
Value()
Returns the current value
singleStep()
Sets the step value of counter
QSpinBox object emits valueChanged() signal every time when up/own button is pressed. The associated slot function can retrieve current value of the widget by value() method.
Following example has a label (l1) and spinbox (sp) put in vertical layout of a top window. The valueChanged() signal is connected to valuechange() method.
self.sp.valueChanged.connect(self.valuechange)
The valueChange() function displays the current value as caption of the label.
self.l1.setText("current value:"+str(self.sp.value()))
The complete code is as follows −
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class spindemo(QWidget):
def __init__(self, parent = None):
super(spindemo, self).__init__(parent)
layout = QVBoxLayout()
self.l1 = QLabel("current value:")
self.l1.setAlignment(Qt.AlignCenter)
layout.addWidget(self.l1)
self.sp = QSpinBox()
layout.addWidget(self.sp)
self.sp.valueChanged.connect(self.valuechange)
self.setLayout(layout)
self.setWindowTitle("SpinBox demo")
def valuechange(self):
self.l1.setText("current value:"+str(self.sp.value()))
def main():
app = QApplication(sys.argv)
ex = spindemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The above code produces the following output −
146 Lectures
22.5 hours
ALAA EID
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2153,
"s": 1963,
"text": "A QSpinBox object presents the user with a textbox which displays an integer with up/down button on its right. The value in the textbox increases/decreases if the up/down button is pressed."
},
{
"code": null,
"e": 2283,
"s": 2153,
"text": "By default, the integer number in the box starts with 0, goes upto 99 and changes by step 1. Use QDoubleSpinBox for float values."
},
{
"code": null,
"e": 2355,
"s": 2283,
"text": "Important methods of QSpinBox class are listed in the following table −"
},
{
"code": null,
"e": 2368,
"s": 2355,
"text": "setMinimum()"
},
{
"code": null,
"e": 2400,
"s": 2368,
"text": "Sets the lower bound of counter"
},
{
"code": null,
"e": 2413,
"s": 2400,
"text": "setMaximum()"
},
{
"code": null,
"e": 2445,
"s": 2413,
"text": "Sets the upper bound of counter"
},
{
"code": null,
"e": 2456,
"s": 2445,
"text": "setRange()"
},
{
"code": null,
"e": 2497,
"s": 2456,
"text": "Sets the minimum, maximum and step value"
},
{
"code": null,
"e": 2508,
"s": 2497,
"text": "setValue()"
},
{
"code": null,
"e": 2552,
"s": 2508,
"text": "Sets the value of spin box programmatically"
},
{
"code": null,
"e": 2560,
"s": 2552,
"text": "Value()"
},
{
"code": null,
"e": 2586,
"s": 2560,
"text": "Returns the current value"
},
{
"code": null,
"e": 2599,
"s": 2586,
"text": "singleStep()"
},
{
"code": null,
"e": 2630,
"s": 2599,
"text": "Sets the step value of counter"
},
{
"code": null,
"e": 2805,
"s": 2630,
"text": "QSpinBox object emits valueChanged() signal every time when up/own button is pressed. The associated slot function can retrieve current value of the widget by value() method."
},
{
"code": null,
"e": 2961,
"s": 2805,
"text": "Following example has a label (l1) and spinbox (sp) put in vertical layout of a top window. The valueChanged() signal is connected to valuechange() method."
},
{
"code": null,
"e": 3009,
"s": 2961,
"text": "self.sp.valueChanged.connect(self.valuechange)\n"
},
{
"code": null,
"e": 3088,
"s": 3009,
"text": "The valueChange() function displays the current value as caption of the label."
},
{
"code": null,
"e": 3144,
"s": 3088,
"text": "self.l1.setText(\"current value:\"+str(self.sp.value()))\n"
},
{
"code": null,
"e": 3178,
"s": 3144,
"text": "The complete code is as follows −"
},
{
"code": null,
"e": 3950,
"s": 3178,
"text": "import sys\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nclass spindemo(QWidget):\n def __init__(self, parent = None):\n super(spindemo, self).__init__(parent)\n \n layout = QVBoxLayout()\n self.l1 = QLabel(\"current value:\")\n self.l1.setAlignment(Qt.AlignCenter)\n layout.addWidget(self.l1)\n self.sp = QSpinBox()\n\t\t\n layout.addWidget(self.sp)\n self.sp.valueChanged.connect(self.valuechange)\n self.setLayout(layout)\n self.setWindowTitle(\"SpinBox demo\")\n\t\t\n def valuechange(self):\n self.l1.setText(\"current value:\"+str(self.sp.value()))\n\ndef main():\n app = QApplication(sys.argv)\n ex = spindemo()\n ex.show()\n sys.exit(app.exec_())\n\t\nif __name__ == '__main__':\n main()"
},
{
"code": null,
"e": 3997,
"s": 3950,
"text": "The above code produces the following output −"
},
{
"code": null,
"e": 4034,
"s": 3997,
"text": "\n 146 Lectures \n 22.5 hours \n"
},
{
"code": null,
"e": 4044,
"s": 4034,
"text": " ALAA EID"
},
{
"code": null,
"e": 4051,
"s": 4044,
"text": " Print"
},
{
"code": null,
"e": 4062,
"s": 4051,
"text": " Add Notes"
}
] |
Updating a MySQL column that contains dot (.) in its name?
|
If the MySQL column contains dot (.) in its name, then you need to use backticks around the column name.
To understand the above concept, let us create a table. The query to create a table is as follows
mysql> create table UpdateDemo
-> (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> `User.FirstName.LastName` varchar(60)
-> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into UpdateDemo(`User.FirstName.LastName`) values('John Smith');
Query OK, 1 row affected (0.14 sec)
mysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Adam Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Carol Taylor');
Query OK, 1 row affected (0.25 sec)
mysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Mitchell Johnson');
Query OK, 1 row affected (0.19 sec)
mysql> insert into UpdateDemo(`User.FirstName.LastName`) values('David Brown');
Query OK, 1 row affected (0.16 sec)
mysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Larry Miller');
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from UpdateDemo;
The following is the output
+--------+-------------------------+
| UserId | User.FirstName.LastName |
+--------+-------------------------+
| 1 | John Smith |
| 2 | Adam Smith |
| 3 | Carol Taylor |
| 4 | Mitchell Johnson |
| 5 | David Brown |
| 6 | Larry Miller |
+--------+-------------------------+
6 rows in set (0.00 sec)
Use backticks around the column name User.FirstName.LastName which contains (.).
The query is as follows
mysql> update UpdateDemo set `User.FirstName.LastName`='David Miller' where UserId=5;
Query OK, 1 row affected (0.19 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table record once again. The row with UserId=5 is successfully updated.
The query is as follows
mysql> select *from UpdateDemo;
The following is the output
+--------+-------------------------+
| UserId | User.FirstName.LastName |
+--------+-------------------------+
| 1 | John Smith |
| 2 | Adam Smith |
| 3 | Carol Taylor |
| 4 | Mitchell Johnson |
| 5 | David Miller |
| 6 | Larry Miller |
+--------+-------------------------+
6 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1265,
"s": 1062,
"text": "If the MySQL column contains dot (.) in its name, then you need to use backticks around the column name.\nTo understand the above concept, let us create a table. The query to create a table is as follows"
},
{
"code": null,
"e": 1448,
"s": 1265,
"text": "mysql> create table UpdateDemo\n -> (\n -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> `User.FirstName.LastName` varchar(60)\n -> );\nQuery OK, 0 rows affected (0.54 sec)"
},
{
"code": null,
"e": 1503,
"s": 1448,
"text": "Insert some records in the table using insert command."
},
{
"code": null,
"e": 1527,
"s": 1503,
"text": "The query is as follows"
},
{
"code": null,
"e": 2228,
"s": 1527,
"text": "mysql> insert into UpdateDemo(`User.FirstName.LastName`) values('John Smith');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Adam Smith');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Carol Taylor');\nQuery OK, 1 row affected (0.25 sec)\nmysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Mitchell Johnson');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into UpdateDemo(`User.FirstName.LastName`) values('David Brown');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into UpdateDemo(`User.FirstName.LastName`) values('Larry Miller');\nQuery OK, 1 row affected (0.22 sec)"
},
{
"code": null,
"e": 2287,
"s": 2228,
"text": "Display all records from the table using select statement."
},
{
"code": null,
"e": 2311,
"s": 2287,
"text": "The query is as follows"
},
{
"code": null,
"e": 2343,
"s": 2311,
"text": "mysql> select *from UpdateDemo;"
},
{
"code": null,
"e": 2371,
"s": 2343,
"text": "The following is the output"
},
{
"code": null,
"e": 2767,
"s": 2371,
"text": "+--------+-------------------------+\n| UserId | User.FirstName.LastName |\n+--------+-------------------------+\n| 1 | John Smith |\n| 2 | Adam Smith | \n| 3 | Carol Taylor |\n| 4 | Mitchell Johnson |\n| 5 | David Brown |\n| 6 | Larry Miller |\n+--------+-------------------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2848,
"s": 2767,
"text": "Use backticks around the column name User.FirstName.LastName which contains (.)."
},
{
"code": null,
"e": 2872,
"s": 2848,
"text": "The query is as follows"
},
{
"code": null,
"e": 3033,
"s": 2872,
"text": "mysql> update UpdateDemo set `User.FirstName.LastName`='David Miller' where UserId=5;\nQuery OK, 1 row affected (0.19 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 3122,
"s": 3033,
"text": "Let us check the table record once again. The row with UserId=5 is successfully updated."
},
{
"code": null,
"e": 3146,
"s": 3122,
"text": "The query is as follows"
},
{
"code": null,
"e": 3178,
"s": 3146,
"text": "mysql> select *from UpdateDemo;"
},
{
"code": null,
"e": 3206,
"s": 3178,
"text": "The following is the output"
},
{
"code": null,
"e": 3601,
"s": 3206,
"text": "+--------+-------------------------+\n| UserId | User.FirstName.LastName |\n+--------+-------------------------+\n| 1 | John Smith |\n| 2 | Adam Smith |\n| 3 | Carol Taylor |\n| 4 | Mitchell Johnson |\n| 5 | David Miller |\n| 6 | Larry Miller |\n+--------+-------------------------+\n6 rows in set (0.00 sec)"
}
] |
Insert Operation in B-Tree - GeeksforGeeks
|
11 Aug, 2021
In the previous post, we introduced B-Tree. We also discussed search() and traverse() functions. In this post, insert() operation is discussed. A new key is always inserted at the leaf node. Let the key to be inserted be k. Like BST, we start from the root and traverse down till we reach a leaf node. Once we reach a leaf node, we insert the key in that leaf node. Unlike BSTs, we have a predefined range on the number of keys that a node can contain. So before inserting a key to the node, we make sure that the node has extra space.
How to make sure that a node has space available for a key before the key is inserted? We use an operation called splitChild() that is used to split a child of a node. See the following diagram to understand split. In the following diagram, child y of x is being split into two nodes y and z. Note that the splitChild operation moves a key up and this is the reason B-Trees grow up, unlike BSTs which grow down.
As discussed above, to insert a new key, we go down from root to leaf. Before traversing down to a node, we first check if the node is full. If the node is full, we split it to create space. Following is the complete algorithm.
Insertion 1) Initialize x as root. 2) While x is not leaf, do following ..a) Find the child of x that is going to be traversed next. Let the child be y. ..b) If y is not full, change x to point to y. ..c) If y is full, split it and change x to point to one of the two parts of y. If k is smaller than mid key in y, then set x as the first part of y. Else second part of y. When we split y, we move a key from y to its parent x. 3) The loop in step 2 stops when x is leaf. x must have space for 1 extra key as we have been splitting all nodes in advance. So simply insert k to x.
Note that the algorithm follows the Cormen book. It is actually a proactive insertion algorithm where before going down to a node, we split it if it is full. The advantage of splitting before is, we never traverse a node twice. If we don’t split a node before going down to it and split it only if a new key is inserted (reactive), we may end up traversing all nodes again from leaf to root. This happens in cases when all nodes on the path from the root to leaf are full. So when we come to the leaf node, we split it and move a key up. Moving a key up will cause a split in parent node (because the parent was already full). This cascading effect never happens in this proactive insertion algorithm. There is a disadvantage of this proactive insertion though, we may do unnecessary splits.
Let us understand the algorithm with an example tree of minimum degree ‘t’ as 3 and a sequence of integers 10, 20, 30, 40, 50, 60, 70, 80 and 90 in an initially empty B-Tree.Initially root is NULL. Let us first insert 10.
Let us now insert 20, 30, 40 and 50. They all will be inserted in root because the maximum number of keys a node can accommodate is 2*t – 1 which is 5.
Let us now insert 60. Since root node is full, it will first split into two, then 60 will be inserted into the appropriate child.
Let us now insert 70 and 80. These new keys will be inserted into the appropriate leaf without any split.
Let us now insert 90. This insertion will cause a split. The middle key will go up to the parent.
Following is C++ implementation of the above proactive algorithm.
C++
// C++ program for B-Tree insertion#include<iostream>using namespace std; // A BTree nodeclass BTreeNode{ int *keys; // An array of keys int t; // Minimum degree (defines the range for number of keys) BTreeNode **C; // An array of child pointers int n; // Current number of keys bool leaf; // Is true when node is leaf. Otherwise falsepublic: BTreeNode(int _t, bool _leaf); // Constructor // A utility function to insert a new key in the subtree rooted with // this node. The assumption is, the node must be non-full when this // function is called void insertNonFull(int k); // A utility function to split the child y of this node. i is index of y in // child array C[]. The Child y must be full when this function is called void splitChild(int i, BTreeNode *y); // A function to traverse all nodes in a subtree rooted with this node void traverse(); // A function to search a key in the subtree rooted with this node. BTreeNode *search(int k); // returns NULL if k is not present. // Make BTree friend of this so that we can access private members of this// class in BTree functionsfriend class BTree;}; // A BTreeclass BTree{ BTreeNode *root; // Pointer to root node int t; // Minimum degreepublic: // Constructor (Initializes tree as empty) BTree(int _t) { root = NULL; t = _t; } // function to traverse the tree void traverse() { if (root != NULL) root->traverse(); } // function to search a key in this tree BTreeNode* search(int k) { return (root == NULL)? NULL : root->search(k); } // The main function that inserts a new key in this B-Tree void insert(int k);}; // Constructor for BTreeNode classBTreeNode::BTreeNode(int t1, bool leaf1){ // Copy the given minimum degree and leaf property t = t1; leaf = leaf1; // Allocate memory for maximum number of possible keys // and child pointers keys = new int[2*t-1]; C = new BTreeNode *[2*t]; // Initialize the number of keys as 0 n = 0;} // Function to traverse all nodes in a subtree rooted with this nodevoid BTreeNode::traverse(){ // There are n keys and n+1 children, traverse through n keys // and first n children int i; for (i = 0; i < n; i++) { // If this is not leaf, then before printing key[i], // traverse the subtree rooted with child C[i]. if (leaf == false) C[i]->traverse(); cout << " " << keys[i]; } // Print the subtree rooted with last child if (leaf == false) C[i]->traverse();} // Function to search key k in subtree rooted with this nodeBTreeNode *BTreeNode::search(int k){ // Find the first key greater than or equal to k int i = 0; while (i < n && k > keys[i]) i++; // If the found key is equal to k, return this node if (keys[i] == k) return this; // If key is not found here and this is a leaf node if (leaf == true) return NULL; // Go to the appropriate child return C[i]->search(k);} // The main function that inserts a new key in this B-Treevoid BTree::insert(int k){ // If tree is empty if (root == NULL) { // Allocate memory for root root = new BTreeNode(t, true); root->keys[0] = k; // Insert key root->n = 1; // Update number of keys in root } else // If tree is not empty { // If root is full, then tree grows in height if (root->n == 2*t-1) { // Allocate memory for new root BTreeNode *s = new BTreeNode(t, false); // Make old root as child of new root s->C[0] = root; // Split the old root and move 1 key to the new root s->splitChild(0, root); // New root has two children now. Decide which of the // two children is going to have new key int i = 0; if (s->keys[0] < k) i++; s->C[i]->insertNonFull(k); // Change root root = s; } else // If root is not full, call insertNonFull for root root->insertNonFull(k); }} // A utility function to insert a new key in this node// The assumption is, the node must be non-full when this// function is calledvoid BTreeNode::insertNonFull(int k){ // Initialize index as index of rightmost element int i = n-1; // If this is a leaf node if (leaf == true) { // The following loop does two things // a) Finds the location of new key to be inserted // b) Moves all greater keys to one place ahead while (i >= 0 && keys[i] > k) { keys[i+1] = keys[i]; i--; } // Insert the new key at found location keys[i+1] = k; n = n+1; } else // If this node is not leaf { // Find the child which is going to have the new key while (i >= 0 && keys[i] > k) i--; // See if the found child is full if (C[i+1]->n == 2*t-1) { // If the child is full, then split it splitChild(i+1, C[i+1]); // After split, the middle key of C[i] goes up and // C[i] is splitted into two. See which of the two // is going to have the new key if (keys[i+1] < k) i++; } C[i+1]->insertNonFull(k); }} // A utility function to split the child y of this node// Note that y must be full when this function is calledvoid BTreeNode::splitChild(int i, BTreeNode *y){ // Create a new node which is going to store (t-1) keys // of y BTreeNode *z = new BTreeNode(y->t, y->leaf); z->n = t - 1; // Copy the last (t-1) keys of y to z for (int j = 0; j < t-1; j++) z->keys[j] = y->keys[j+t]; // Copy the last t children of y to z if (y->leaf == false) { for (int j = 0; j < t; j++) z->C[j] = y->C[j+t]; } // Reduce the number of keys in y y->n = t - 1; // Since this node is going to have a new child, // create space of new child for (int j = n; j >= i+1; j--) C[j+1] = C[j]; // Link the new child to this node C[i+1] = z; // A key of y will move to this node. Find the location of // new key and move all greater keys one space ahead for (int j = n-1; j >= i; j--) keys[j+1] = keys[j]; // Copy the middle key of y to this node keys[i] = y->keys[t-1]; // Increment count of keys in this node n = n + 1;} // Driver program to test above functionsint main(){ BTree t(3); // A B-Tree with minimum degree 3 t.insert(10); t.insert(20); t.insert(5); t.insert(6); t.insert(12); t.insert(30); t.insert(7); t.insert(17); cout << "Traversal of the constructed tree is "; t.traverse(); int k = 6; (t.search(k) != NULL)? cout << "\nPresent" : cout << "\nNot Present"; k = 15; (t.search(k) != NULL)? cout << "\nPresent" : cout << "\nNot Present"; return 0;}
Output:
Traversal of the constructed tree is 5 6 7 10 12 17 20 30
Present
Not Present
References: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest http://www.cs.utexas.edu/users/djimenez/utsa/cs3343/lecture17.htmlPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
shubham_singh
surindertarika1234
clintra
B-Tree
DBMS Indexing
Advanced Data Structure
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
AVL Tree | Set 1 (Insertion)
Trie | (Insert and Search)
LRU Cache Implementation
Red-Black Tree | Set 1 (Introduction)
Agents in Artificial Intelligence
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
SQL Trigger | Student Database
Difference between Clustered and Non-clustered index
|
[
{
"code": null,
"e": 29622,
"s": 29594,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 30159,
"s": 29622,
"text": "In the previous post, we introduced B-Tree. We also discussed search() and traverse() functions. In this post, insert() operation is discussed. A new key is always inserted at the leaf node. Let the key to be inserted be k. Like BST, we start from the root and traverse down till we reach a leaf node. Once we reach a leaf node, we insert the key in that leaf node. Unlike BSTs, we have a predefined range on the number of keys that a node can contain. So before inserting a key to the node, we make sure that the node has extra space. "
},
{
"code": null,
"e": 30572,
"s": 30159,
"text": "How to make sure that a node has space available for a key before the key is inserted? We use an operation called splitChild() that is used to split a child of a node. See the following diagram to understand split. In the following diagram, child y of x is being split into two nodes y and z. Note that the splitChild operation moves a key up and this is the reason B-Trees grow up, unlike BSTs which grow down. "
},
{
"code": null,
"e": 30800,
"s": 30572,
"text": "As discussed above, to insert a new key, we go down from root to leaf. Before traversing down to a node, we first check if the node is full. If the node is full, we split it to create space. Following is the complete algorithm."
},
{
"code": null,
"e": 31380,
"s": 30800,
"text": "Insertion 1) Initialize x as root. 2) While x is not leaf, do following ..a) Find the child of x that is going to be traversed next. Let the child be y. ..b) If y is not full, change x to point to y. ..c) If y is full, split it and change x to point to one of the two parts of y. If k is smaller than mid key in y, then set x as the first part of y. Else second part of y. When we split y, we move a key from y to its parent x. 3) The loop in step 2 stops when x is leaf. x must have space for 1 extra key as we have been splitting all nodes in advance. So simply insert k to x. "
},
{
"code": null,
"e": 32173,
"s": 31380,
"text": "Note that the algorithm follows the Cormen book. It is actually a proactive insertion algorithm where before going down to a node, we split it if it is full. The advantage of splitting before is, we never traverse a node twice. If we don’t split a node before going down to it and split it only if a new key is inserted (reactive), we may end up traversing all nodes again from leaf to root. This happens in cases when all nodes on the path from the root to leaf are full. So when we come to the leaf node, we split it and move a key up. Moving a key up will cause a split in parent node (because the parent was already full). This cascading effect never happens in this proactive insertion algorithm. There is a disadvantage of this proactive insertion though, we may do unnecessary splits. "
},
{
"code": null,
"e": 32396,
"s": 32173,
"text": "Let us understand the algorithm with an example tree of minimum degree ‘t’ as 3 and a sequence of integers 10, 20, 30, 40, 50, 60, 70, 80 and 90 in an initially empty B-Tree.Initially root is NULL. Let us first insert 10. "
},
{
"code": null,
"e": 32549,
"s": 32396,
"text": "Let us now insert 20, 30, 40 and 50. They all will be inserted in root because the maximum number of keys a node can accommodate is 2*t – 1 which is 5. "
},
{
"code": null,
"e": 32681,
"s": 32549,
"text": "Let us now insert 60. Since root node is full, it will first split into two, then 60 will be inserted into the appropriate child. "
},
{
"code": null,
"e": 32788,
"s": 32681,
"text": "Let us now insert 70 and 80. These new keys will be inserted into the appropriate leaf without any split. "
},
{
"code": null,
"e": 32887,
"s": 32788,
"text": "Let us now insert 90. This insertion will cause a split. The middle key will go up to the parent. "
},
{
"code": null,
"e": 32953,
"s": 32887,
"text": "Following is C++ implementation of the above proactive algorithm."
},
{
"code": null,
"e": 32957,
"s": 32953,
"text": "C++"
},
{
"code": "// C++ program for B-Tree insertion#include<iostream>using namespace std; // A BTree nodeclass BTreeNode{ int *keys; // An array of keys int t; // Minimum degree (defines the range for number of keys) BTreeNode **C; // An array of child pointers int n; // Current number of keys bool leaf; // Is true when node is leaf. Otherwise falsepublic: BTreeNode(int _t, bool _leaf); // Constructor // A utility function to insert a new key in the subtree rooted with // this node. The assumption is, the node must be non-full when this // function is called void insertNonFull(int k); // A utility function to split the child y of this node. i is index of y in // child array C[]. The Child y must be full when this function is called void splitChild(int i, BTreeNode *y); // A function to traverse all nodes in a subtree rooted with this node void traverse(); // A function to search a key in the subtree rooted with this node. BTreeNode *search(int k); // returns NULL if k is not present. // Make BTree friend of this so that we can access private members of this// class in BTree functionsfriend class BTree;}; // A BTreeclass BTree{ BTreeNode *root; // Pointer to root node int t; // Minimum degreepublic: // Constructor (Initializes tree as empty) BTree(int _t) { root = NULL; t = _t; } // function to traverse the tree void traverse() { if (root != NULL) root->traverse(); } // function to search a key in this tree BTreeNode* search(int k) { return (root == NULL)? NULL : root->search(k); } // The main function that inserts a new key in this B-Tree void insert(int k);}; // Constructor for BTreeNode classBTreeNode::BTreeNode(int t1, bool leaf1){ // Copy the given minimum degree and leaf property t = t1; leaf = leaf1; // Allocate memory for maximum number of possible keys // and child pointers keys = new int[2*t-1]; C = new BTreeNode *[2*t]; // Initialize the number of keys as 0 n = 0;} // Function to traverse all nodes in a subtree rooted with this nodevoid BTreeNode::traverse(){ // There are n keys and n+1 children, traverse through n keys // and first n children int i; for (i = 0; i < n; i++) { // If this is not leaf, then before printing key[i], // traverse the subtree rooted with child C[i]. if (leaf == false) C[i]->traverse(); cout << \" \" << keys[i]; } // Print the subtree rooted with last child if (leaf == false) C[i]->traverse();} // Function to search key k in subtree rooted with this nodeBTreeNode *BTreeNode::search(int k){ // Find the first key greater than or equal to k int i = 0; while (i < n && k > keys[i]) i++; // If the found key is equal to k, return this node if (keys[i] == k) return this; // If key is not found here and this is a leaf node if (leaf == true) return NULL; // Go to the appropriate child return C[i]->search(k);} // The main function that inserts a new key in this B-Treevoid BTree::insert(int k){ // If tree is empty if (root == NULL) { // Allocate memory for root root = new BTreeNode(t, true); root->keys[0] = k; // Insert key root->n = 1; // Update number of keys in root } else // If tree is not empty { // If root is full, then tree grows in height if (root->n == 2*t-1) { // Allocate memory for new root BTreeNode *s = new BTreeNode(t, false); // Make old root as child of new root s->C[0] = root; // Split the old root and move 1 key to the new root s->splitChild(0, root); // New root has two children now. Decide which of the // two children is going to have new key int i = 0; if (s->keys[0] < k) i++; s->C[i]->insertNonFull(k); // Change root root = s; } else // If root is not full, call insertNonFull for root root->insertNonFull(k); }} // A utility function to insert a new key in this node// The assumption is, the node must be non-full when this// function is calledvoid BTreeNode::insertNonFull(int k){ // Initialize index as index of rightmost element int i = n-1; // If this is a leaf node if (leaf == true) { // The following loop does two things // a) Finds the location of new key to be inserted // b) Moves all greater keys to one place ahead while (i >= 0 && keys[i] > k) { keys[i+1] = keys[i]; i--; } // Insert the new key at found location keys[i+1] = k; n = n+1; } else // If this node is not leaf { // Find the child which is going to have the new key while (i >= 0 && keys[i] > k) i--; // See if the found child is full if (C[i+1]->n == 2*t-1) { // If the child is full, then split it splitChild(i+1, C[i+1]); // After split, the middle key of C[i] goes up and // C[i] is splitted into two. See which of the two // is going to have the new key if (keys[i+1] < k) i++; } C[i+1]->insertNonFull(k); }} // A utility function to split the child y of this node// Note that y must be full when this function is calledvoid BTreeNode::splitChild(int i, BTreeNode *y){ // Create a new node which is going to store (t-1) keys // of y BTreeNode *z = new BTreeNode(y->t, y->leaf); z->n = t - 1; // Copy the last (t-1) keys of y to z for (int j = 0; j < t-1; j++) z->keys[j] = y->keys[j+t]; // Copy the last t children of y to z if (y->leaf == false) { for (int j = 0; j < t; j++) z->C[j] = y->C[j+t]; } // Reduce the number of keys in y y->n = t - 1; // Since this node is going to have a new child, // create space of new child for (int j = n; j >= i+1; j--) C[j+1] = C[j]; // Link the new child to this node C[i+1] = z; // A key of y will move to this node. Find the location of // new key and move all greater keys one space ahead for (int j = n-1; j >= i; j--) keys[j+1] = keys[j]; // Copy the middle key of y to this node keys[i] = y->keys[t-1]; // Increment count of keys in this node n = n + 1;} // Driver program to test above functionsint main(){ BTree t(3); // A B-Tree with minimum degree 3 t.insert(10); t.insert(20); t.insert(5); t.insert(6); t.insert(12); t.insert(30); t.insert(7); t.insert(17); cout << \"Traversal of the constructed tree is \"; t.traverse(); int k = 6; (t.search(k) != NULL)? cout << \"\\nPresent\" : cout << \"\\nNot Present\"; k = 15; (t.search(k) != NULL)? cout << \"\\nPresent\" : cout << \"\\nNot Present\"; return 0;}",
"e": 39929,
"s": 32957,
"text": null
},
{
"code": null,
"e": 39938,
"s": 39929,
"text": "Output: "
},
{
"code": null,
"e": 40017,
"s": 39938,
"text": "Traversal of the constructed tree is 5 6 7 10 12 17 20 30\nPresent\nNot Present"
},
{
"code": null,
"e": 40336,
"s": 40017,
"text": "References: Introduction to Algorithms 3rd Edition by Clifford Stein, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest http://www.cs.utexas.edu/users/djimenez/utsa/cs3343/lecture17.htmlPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 40349,
"s": 40336,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 40363,
"s": 40349,
"text": "shubham_singh"
},
{
"code": null,
"e": 40382,
"s": 40363,
"text": "surindertarika1234"
},
{
"code": null,
"e": 40390,
"s": 40382,
"text": "clintra"
},
{
"code": null,
"e": 40397,
"s": 40390,
"text": "B-Tree"
},
{
"code": null,
"e": 40411,
"s": 40397,
"text": "DBMS Indexing"
},
{
"code": null,
"e": 40435,
"s": 40411,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 40440,
"s": 40435,
"text": "DBMS"
},
{
"code": null,
"e": 40445,
"s": 40440,
"text": "DBMS"
},
{
"code": null,
"e": 40543,
"s": 40445,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40552,
"s": 40543,
"text": "Comments"
},
{
"code": null,
"e": 40565,
"s": 40552,
"text": "Old Comments"
},
{
"code": null,
"e": 40594,
"s": 40565,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 40621,
"s": 40594,
"text": "Trie | (Insert and Search)"
},
{
"code": null,
"e": 40646,
"s": 40621,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 40684,
"s": 40646,
"text": "Red-Black Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 40718,
"s": 40684,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 40765,
"s": 40718,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 40783,
"s": 40765,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 40824,
"s": 40783,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 40855,
"s": 40824,
"text": "SQL Trigger | Student Database"
}
] |
Cordova - Storage
|
We can use storage API available for storing data on the client apps. This will help the usage of the app when the user is offline and it can also improve performance. Since this tutorial is for beginners, we will show you how to use local storage. In one of our later tutorials, we will show you the other plugins that can be used.
We will create four buttons in the index.html file. The buttons will be located inside the div class = "app" element.
<button id = "setLocalStorage">SET LOCAL STORAGE</button>
<button id = "showLocalStorage">SHOW LOCAL STORAGE</button>
<button id = "removeProjectFromLocalStorage">REMOVE PROJECT</button>
<button id = "getLocalStorageByKey">GET BY KEY</button>
It will produce the following screen −
Cordova security policy doesn't allow inline events so we will add event listeners inside index.js files. We will also assign window.localStorage to a localStorage variable that we will use later.
document.getElementById("setLocalStorage").addEventListener("click", setLocalStorage);
document.getElementById("showLocalStorage").addEventListener("click", showLocalStorage);
document.getElementById("removeProjectFromLocalStorage").addEventListener
("click", removeProjectFromLocalStorage);
document.getElementById("getLocalStorageByKey").addEventListener
("click", getLocalStorageByKey);
var localStorage = window.localStorage;
Now we need to create functions that will be called when the buttons are tapped. First function is used for adding data to local storage.
function setLocalStorage() {
localStorage.setItem("Name", "John");
localStorage.setItem("Job", "Developer");
localStorage.setItem("Project", "Cordova Project");
}
The next one will log the data we added to console.
function showLocalStorage() {
console.log(localStorage.getItem("Name"));
console.log(localStorage.getItem("Job"));
console.log(localStorage.getItem("Project"));
}
If we tap SET LOCAL STORAGE button, we will set three items to local storage. If we tap SHOW LOCAL STORAGE afterwards, the console will log items that we want.
Let us now create function that will delete the project from local storage.
function removeProjectFromLocalStorage() {
localStorage.removeItem("Project");
}
If we click the SHOW LOCAL STORAGE button after we deleted the project, the output will show null value for the project field.
We can also get the local storage elements by using the key() method which will take the index as an argument and return the element with corresponding index value.
function getLocalStorageByKey() {
console.log(localStorage.key(0));
}
Now when we tap the GET BY KEY button, the following output will be displayed.
When we use the key() method, the console will log the job instead of the name even though we passed argument 0 to retrieve the first object. This is because the local storage is storing data in alphabetical order.
The following table shows all the available local storage methods.
setItem(key, value)
Used for setting the item to local storage.
getItem(key)
Used for getting the item from local storage.
removeItem(key)
Used for removing the item from local storage.
key(index)
Used for getting the item by using the index of the item in local storage. This helps sort the items alphabetically.
length()
Used for retrieving the number of items that exists in local storage.
clear()
Used for removing all the key/value pairs from local storage.
45 Lectures
2 hours
Skillbakerystudios
16 Lectures
1 hours
Nilay Mehta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2513,
"s": 2180,
"text": "We can use storage API available for storing data on the client apps. This will help the usage of the app when the user is offline and it can also improve performance. Since this tutorial is for beginners, we will show you how to use local storage. In one of our later tutorials, we will show you the other plugins that can be used."
},
{
"code": null,
"e": 2631,
"s": 2513,
"text": "We will create four buttons in the index.html file. The buttons will be located inside the div class = \"app\" element."
},
{
"code": null,
"e": 2874,
"s": 2631,
"text": "<button id = \"setLocalStorage\">SET LOCAL STORAGE</button>\n<button id = \"showLocalStorage\">SHOW LOCAL STORAGE</button>\n<button id = \"removeProjectFromLocalStorage\">REMOVE PROJECT</button>\n<button id = \"getLocalStorageByKey\">GET BY KEY</button>"
},
{
"code": null,
"e": 2913,
"s": 2874,
"text": "It will produce the following screen −"
},
{
"code": null,
"e": 3110,
"s": 2913,
"text": "Cordova security policy doesn't allow inline events so we will add event listeners inside index.js files. We will also assign window.localStorage to a localStorage variable that we will use later."
},
{
"code": null,
"e": 3555,
"s": 3110,
"text": "document.getElementById(\"setLocalStorage\").addEventListener(\"click\", setLocalStorage); \ndocument.getElementById(\"showLocalStorage\").addEventListener(\"click\", showLocalStorage); \ndocument.getElementById(\"removeProjectFromLocalStorage\").addEventListener \n (\"click\", removeProjectFromLocalStorage); \ndocument.getElementById(\"getLocalStorageByKey\").addEventListener \n (\"click\", getLocalStorageByKey); \nvar localStorage = window.localStorage; \t"
},
{
"code": null,
"e": 3693,
"s": 3555,
"text": "Now we need to create functions that will be called when the buttons are tapped. First function is used for adding data to local storage."
},
{
"code": null,
"e": 3870,
"s": 3693,
"text": "function setLocalStorage() { \n localStorage.setItem(\"Name\", \"John\"); \n localStorage.setItem(\"Job\", \"Developer\"); \n localStorage.setItem(\"Project\", \"Cordova Project\"); \n} "
},
{
"code": null,
"e": 3922,
"s": 3870,
"text": "The next one will log the data we added to console."
},
{
"code": null,
"e": 4100,
"s": 3922,
"text": "function showLocalStorage() { \n console.log(localStorage.getItem(\"Name\")); \n console.log(localStorage.getItem(\"Job\")); \n console.log(localStorage.getItem(\"Project\")); \n} \t"
},
{
"code": null,
"e": 4260,
"s": 4100,
"text": "If we tap SET LOCAL STORAGE button, we will set three items to local storage. If we tap SHOW LOCAL STORAGE afterwards, the console will log items that we want."
},
{
"code": null,
"e": 4336,
"s": 4260,
"text": "Let us now create function that will delete the project from local storage."
},
{
"code": null,
"e": 4420,
"s": 4336,
"text": "function removeProjectFromLocalStorage() {\n localStorage.removeItem(\"Project\");\n}"
},
{
"code": null,
"e": 4547,
"s": 4420,
"text": "If we click the SHOW LOCAL STORAGE button after we deleted the project, the output will show null value for the project field."
},
{
"code": null,
"e": 4712,
"s": 4547,
"text": "We can also get the local storage elements by using the key() method which will take the index as an argument and return the element with corresponding index value."
},
{
"code": null,
"e": 4785,
"s": 4712,
"text": "function getLocalStorageByKey() {\n console.log(localStorage.key(0));\n}"
},
{
"code": null,
"e": 4864,
"s": 4785,
"text": "Now when we tap the GET BY KEY button, the following output will be displayed."
},
{
"code": null,
"e": 5080,
"s": 4864,
"text": "When we use the key() method, the console will log the job instead of the name even though we passed argument 0 to retrieve the first object. This is because the local storage is storing data in alphabetical order."
},
{
"code": null,
"e": 5147,
"s": 5080,
"text": "The following table shows all the available local storage methods."
},
{
"code": null,
"e": 5167,
"s": 5147,
"text": "setItem(key, value)"
},
{
"code": null,
"e": 5211,
"s": 5167,
"text": "Used for setting the item to local storage."
},
{
"code": null,
"e": 5224,
"s": 5211,
"text": "getItem(key)"
},
{
"code": null,
"e": 5270,
"s": 5224,
"text": "Used for getting the item from local storage."
},
{
"code": null,
"e": 5286,
"s": 5270,
"text": "removeItem(key)"
},
{
"code": null,
"e": 5333,
"s": 5286,
"text": "Used for removing the item from local storage."
},
{
"code": null,
"e": 5344,
"s": 5333,
"text": "key(index)"
},
{
"code": null,
"e": 5461,
"s": 5344,
"text": "Used for getting the item by using the index of the item in local storage. This helps sort the items alphabetically."
},
{
"code": null,
"e": 5470,
"s": 5461,
"text": "length()"
},
{
"code": null,
"e": 5540,
"s": 5470,
"text": "Used for retrieving the number of items that exists in local storage."
},
{
"code": null,
"e": 5548,
"s": 5540,
"text": "clear()"
},
{
"code": null,
"e": 5610,
"s": 5548,
"text": "Used for removing all the key/value pairs from local storage."
},
{
"code": null,
"e": 5643,
"s": 5610,
"text": "\n 45 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5663,
"s": 5643,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5696,
"s": 5663,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5709,
"s": 5696,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5716,
"s": 5709,
"text": " Print"
},
{
"code": null,
"e": 5727,
"s": 5716,
"text": " Add Notes"
}
] |
C++ Program Structure
|
The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called "Hello World", which simply prints "Hello World" to your computer screen. Although it is very simple, it contains all the fundamental components C++ programs have. Let's look at the code for this program −
#include<iostream>
int main() {
std::cout << "Hello World\n";
}
Let's dissect this program.
Line 1 − We start with the #include<iostream> line which essentially tells the compiler to copy the code from the iostream file(used for managing input and output streams) and paste it in our source file. Header iostream, that allows performing standard input and output operations, such as writing the output of this program (Hello World) to the screen. Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor.
Line 2 − A blank line: Blank lines have no effect on a program.
Line 3 − We then declare a function called main with the return type of int. main() is the entry point of our program. Whenever we run a C++ program, we start with the main function and begin execution from the first line within this function and keep executing each line till we reach the end. We start a block using the curly brace({) here. This marks the beginning of main's function definition, and the closing brace (}) at line 5, marks its end. All statements between these braces are the function's body that defines what happens when main is called.
Line 4 −
std::cout << "Hello World\n";
This line is a C++ statement. This statement has three parts: First, std::cout, which identifies the standard console output device. Second the insertion operator << which indicates that what follows is inserted into std::cout. Last, we have a sentence within quotes that we'd like printed on the screen. This will become more clear to you as we proceed in learning C++.
In short, we provide cout object with a string "Hello world\n" to be printed to the standard output device.
Note that the statement ends with a semicolon (;). This character marks the end of the statement.
|
[
{
"code": null,
"e": 1402,
"s": 1062,
"text": "The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called \"Hello World\", which simply prints \"Hello World\" to your computer screen. Although it is very simple, it contains all the fundamental components C++ programs have. Let's look at the code for this program −"
},
{
"code": null,
"e": 1469,
"s": 1402,
"text": "#include<iostream>\nint main() {\n std::cout << \"Hello World\\n\";\n}"
},
{
"code": null,
"e": 1497,
"s": 1469,
"text": "Let's dissect this program."
},
{
"code": null,
"e": 1964,
"s": 1497,
"text": "Line 1 − We start with the #include<iostream> line which essentially tells the compiler to copy the code from the iostream file(used for managing input and output streams) and paste it in our source file. Header iostream, that allows performing standard input and output operations, such as writing the output of this program (Hello World) to the screen. Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor."
},
{
"code": null,
"e": 2028,
"s": 1964,
"text": "Line 2 − A blank line: Blank lines have no effect on a program."
},
{
"code": null,
"e": 2586,
"s": 2028,
"text": "Line 3 − We then declare a function called main with the return type of int. main() is the entry point of our program. Whenever we run a C++ program, we start with the main function and begin execution from the first line within this function and keep executing each line till we reach the end. We start a block using the curly brace({) here. This marks the beginning of main's function definition, and the closing brace (}) at line 5, marks its end. All statements between these braces are the function's body that defines what happens when main is called."
},
{
"code": null,
"e": 2596,
"s": 2586,
"text": "Line 4 − "
},
{
"code": null,
"e": 2626,
"s": 2596,
"text": "std::cout << \"Hello World\\n\";"
},
{
"code": null,
"e": 2997,
"s": 2626,
"text": "This line is a C++ statement. This statement has three parts: First, std::cout, which identifies the standard console output device. Second the insertion operator << which indicates that what follows is inserted into std::cout. Last, we have a sentence within quotes that we'd like printed on the screen. This will become more clear to you as we proceed in learning C++."
},
{
"code": null,
"e": 3105,
"s": 2997,
"text": "In short, we provide cout object with a string \"Hello world\\n\" to be printed to the standard output device."
},
{
"code": null,
"e": 3203,
"s": 3105,
"text": "Note that the statement ends with a semicolon (;). This character marks the end of the statement."
}
] |
Absolute sum of array elements - JavaScript
|
We are required to write a JavaScript function that takes in an array with both positive and negative numbers and returns the absolute sum of all the elements of the array.
We are required to do this without taking help of any inbuilt library function.
For example: If the array is −
const arr = [1, -5, -34, -5, 2, 5, 6];
Then the output should be −
58
Following is the code −
const arr = [1, -5, -34, -5, 2, 5, 6];
const absoluteSum = arr => {
let res = 0;
for(let i = 0; i < arr.length; i++){
if(arr[i] < 0){
res += (arr[i] * -1);
continue;
};
res += arr[i];
};
return res;
};
console.log(absoluteSum(arr));
Following is the output in the console −
58
|
[
{
"code": null,
"e": 1235,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array with both positive and negative numbers and returns the absolute sum of all the elements of the array."
},
{
"code": null,
"e": 1315,
"s": 1235,
"text": "We are required to do this without taking help of any inbuilt library function."
},
{
"code": null,
"e": 1346,
"s": 1315,
"text": "For example: If the array is −"
},
{
"code": null,
"e": 1385,
"s": 1346,
"text": "const arr = [1, -5, -34, -5, 2, 5, 6];"
},
{
"code": null,
"e": 1413,
"s": 1385,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1416,
"s": 1413,
"text": "58"
},
{
"code": null,
"e": 1440,
"s": 1416,
"text": "Following is the code −"
},
{
"code": null,
"e": 1721,
"s": 1440,
"text": "const arr = [1, -5, -34, -5, 2, 5, 6];\nconst absoluteSum = arr => {\n let res = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n res += (arr[i] * -1);\n continue;\n };\n res += arr[i];\n };\n return res;\n};\nconsole.log(absoluteSum(arr));"
},
{
"code": null,
"e": 1762,
"s": 1721,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1765,
"s": 1762,
"text": "58"
}
] |
Get today's date in (YYYY-MM-DD) format in MySQL?
|
To get today’s date in (YYYY-MM-DD) format in MySQL, you can use CURDATE().
Following is the query to get the current date:
mysql> SELECT CURDATE();
This will produce the following output:
+------------+
| CURDATE() |
+------------+
| 2019-04-09 |
+------------+
1 row in set (0.00 sec)
You can also use NOW() for this. Following is the query:
mysql> SELECT DATE(NOW());
This will produce the following output
+-------------+
| DATE(NOW()) |
+-------------+
| 2019-04-09 |
+-------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To get today’s date in (YYYY-MM-DD) format in MySQL, you can use CURDATE()."
},
{
"code": null,
"e": 1186,
"s": 1138,
"text": "Following is the query to get the current date:"
},
{
"code": null,
"e": 1211,
"s": 1186,
"text": "mysql> SELECT CURDATE();"
},
{
"code": null,
"e": 1251,
"s": 1211,
"text": "This will produce the following output:"
},
{
"code": null,
"e": 1350,
"s": 1251,
"text": "+------------+\n| CURDATE() |\n+------------+\n| 2019-04-09 |\n+------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 1407,
"s": 1350,
"text": "You can also use NOW() for this. Following is the query:"
},
{
"code": null,
"e": 1434,
"s": 1407,
"text": "mysql> SELECT DATE(NOW());"
},
{
"code": null,
"e": 1473,
"s": 1434,
"text": "This will produce the following output"
},
{
"code": null,
"e": 1577,
"s": 1473,
"text": "+-------------+\n| DATE(NOW()) |\n+-------------+\n| 2019-04-09 |\n+-------------+\n1 row in set (0.00 sec)"
}
] |
Python Program to Implement a Stack
|
When it is required to implement a stack using Python, a stack class is created, and an instance of this class is created. Methods to push, pop elements are defined and the instance is used to call these methods.
Below is a demonstration of the same −
Live Demo
class Stack_struct:
def __init__(self):
self.items = []
def check_empty(self):
return self.items == []
def add_elements(self, my_data):
self.items.append(my_data)
def delete_elements(self):
return self.items.pop()
my_instance = Stack_struct()
while True:
print('Push <value>')
print('Pop')
print('Quit')
my_input = input('What operation would you like to perform ? ').split()
my_op = my_input[0].strip().lower()
if my_op == 'push':
my_instance.add_elements(int(my_input[1]))
elif my_op == 'pop':
if my_instance.check_empty():
print('The stack is empty')
else:
print('The deleted value is : ', my_instance.delete_elements())
elif my_op == 'Quit':
break
Push <value>
Pop
Quit
What operation would you like to perform ? Push 6
Push <value>
Pop
Quit
What operation would you like to perform ? Psuh 8
Push <value>
Pop
Quit
What operation would you like to perform ? Psuh 34
Push <value>
Pop
Quit
What operation would you like to perform ? Pop
The deleted value is : 6
Push <value>
Pop
Quit
The ‘Stack_struct’ class with required attributes is created.
The ‘Stack_struct’ class with required attributes is created.
It has an ‘init’ function that is used to create an empty list.
It has an ‘init’ function that is used to create an empty list.
Another method named ‘check_empty’ that checks to see if a list is empty.
Another method named ‘check_empty’ that checks to see if a list is empty.
Another method named ‘add_elements’ is defined that adds elements to the empty list.
Another method named ‘add_elements’ is defined that adds elements to the empty list.
A method named ‘delete_elements’ is defined, that deletes elements from the list.
A method named ‘delete_elements’ is defined, that deletes elements from the list.
An object of the ‘Stack_struct’ class is created.
An object of the ‘Stack_struct’ class is created.
The user input is taken for the operation that needs to be performed.
The user input is taken for the operation that needs to be performed.
Depending on the user’ choice, the operation is performed.
Depending on the user’ choice, the operation is performed.
Relevant output is displayed on the console.
Relevant output is displayed on the console.
|
[
{
"code": null,
"e": 1275,
"s": 1062,
"text": "When it is required to implement a stack using Python, a stack class is created, and an instance of this class is created. Methods to push, pop elements are defined and the instance is used to call these methods."
},
{
"code": null,
"e": 1314,
"s": 1275,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1325,
"s": 1314,
"text": " Live Demo"
},
{
"code": null,
"e": 2084,
"s": 1325,
"text": "class Stack_struct:\n def __init__(self):\n self.items = []\n\n def check_empty(self):\n return self.items == []\n\n def add_elements(self, my_data):\n self.items.append(my_data)\n\n def delete_elements(self):\n return self.items.pop()\n\nmy_instance = Stack_struct()\nwhile True:\n print('Push <value>')\n print('Pop')\n print('Quit')\n my_input = input('What operation would you like to perform ? ').split()\n\n my_op = my_input[0].strip().lower()\n if my_op == 'push':\n my_instance.add_elements(int(my_input[1]))\n elif my_op == 'pop':\n if my_instance.check_empty():\n print('The stack is empty')\n else:\n print('The deleted value is : ', my_instance.delete_elements())\n elif my_op == 'Quit':\n break"
},
{
"code": null,
"e": 2417,
"s": 2084,
"text": "Push <value>\nPop\nQuit\nWhat operation would you like to perform ? Push 6\nPush <value>\nPop\nQuit\nWhat operation would you like to perform ? Psuh 8\nPush <value>\nPop\nQuit\nWhat operation would you like to perform ? Psuh 34\nPush <value>\nPop\nQuit\nWhat operation would you like to perform ? Pop\nThe deleted value is : 6\nPush <value>\nPop\nQuit"
},
{
"code": null,
"e": 2479,
"s": 2417,
"text": "The ‘Stack_struct’ class with required attributes is created."
},
{
"code": null,
"e": 2541,
"s": 2479,
"text": "The ‘Stack_struct’ class with required attributes is created."
},
{
"code": null,
"e": 2605,
"s": 2541,
"text": "It has an ‘init’ function that is used to create an empty list."
},
{
"code": null,
"e": 2669,
"s": 2605,
"text": "It has an ‘init’ function that is used to create an empty list."
},
{
"code": null,
"e": 2743,
"s": 2669,
"text": "Another method named ‘check_empty’ that checks to see if a list is empty."
},
{
"code": null,
"e": 2817,
"s": 2743,
"text": "Another method named ‘check_empty’ that checks to see if a list is empty."
},
{
"code": null,
"e": 2902,
"s": 2817,
"text": "Another method named ‘add_elements’ is defined that adds elements to the empty list."
},
{
"code": null,
"e": 2987,
"s": 2902,
"text": "Another method named ‘add_elements’ is defined that adds elements to the empty list."
},
{
"code": null,
"e": 3069,
"s": 2987,
"text": "A method named ‘delete_elements’ is defined, that deletes elements from the list."
},
{
"code": null,
"e": 3151,
"s": 3069,
"text": "A method named ‘delete_elements’ is defined, that deletes elements from the list."
},
{
"code": null,
"e": 3201,
"s": 3151,
"text": "An object of the ‘Stack_struct’ class is created."
},
{
"code": null,
"e": 3251,
"s": 3201,
"text": "An object of the ‘Stack_struct’ class is created."
},
{
"code": null,
"e": 3321,
"s": 3251,
"text": "The user input is taken for the operation that needs to be performed."
},
{
"code": null,
"e": 3391,
"s": 3321,
"text": "The user input is taken for the operation that needs to be performed."
},
{
"code": null,
"e": 3450,
"s": 3391,
"text": "Depending on the user’ choice, the operation is performed."
},
{
"code": null,
"e": 3509,
"s": 3450,
"text": "Depending on the user’ choice, the operation is performed."
},
{
"code": null,
"e": 3554,
"s": 3509,
"text": "Relevant output is displayed on the console."
},
{
"code": null,
"e": 3599,
"s": 3554,
"text": "Relevant output is displayed on the console."
}
] |
NATURALLEFTOUTERJOIN function
|
Performs an outer join of a table with another table. The tables are joined on common columns (by name) in the two tables. The two tables should be related.
If the two tables have no common column names, or if there is no relationship between the two tables, an error is returned.
DAX NATURALLEFTOUTERJOIN function is new in Excel 2016.
NATURALLEFTOUTERJOIN (<leftJoinTable>, <rightJoinTable>)
leftJoinTable
A table expression defining the table on the left side of the join.
rightJoinTable
A table expression defining the table on the right side of the join.
table which includes only rows from rightJoinTable for which the values in the common columns specified are also present in leftJoinTable. The table returned will have the common columns from the left table and the other columns from both the tables.
There is no sort order guarantee for the results.
There is no sort order guarantee for the results.
Columns being joined on must have the same data type in both tables.
Columns being joined on must have the same data type in both tables.
Only columns from the same source table (have the same lineage) are joined on. For example, Products[ProductID], WebSales[ProductdID], StoreSales[ProductdID] with many-to-one relationships between WebSales and StoreSales and the Products table based on the ProductID column, WebSales and StoreSales tables are joined on [ProductID].
Only columns from the same source table (have the same lineage) are joined on. For example, Products[ProductID], WebSales[ProductdID], StoreSales[ProductdID] with many-to-one relationships between WebSales and StoreSales and the Products table based on the ProductID column, WebSales and StoreSales tables are joined on [ProductID].
Strict comparison semantics are used during join. There is no type coercion; for example, 1 does not equal 1.0.
Strict comparison semantics are used during join. There is no type coercion; for example, 1 does not equal 1.0.
= SUMX (NATURALLEFTOUTERJOIN (Salesperson,Sales),[Sales Amount])
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2158,
"s": 2001,
"text": "Performs an outer join of a table with another table. The tables are joined on common columns (by name) in the two tables. The two tables should be related."
},
{
"code": null,
"e": 2282,
"s": 2158,
"text": "If the two tables have no common column names, or if there is no relationship between the two tables, an error is returned."
},
{
"code": null,
"e": 2338,
"s": 2282,
"text": "DAX NATURALLEFTOUTERJOIN function is new in Excel 2016."
},
{
"code": null,
"e": 2397,
"s": 2338,
"text": "NATURALLEFTOUTERJOIN (<leftJoinTable>, <rightJoinTable>) \n"
},
{
"code": null,
"e": 2411,
"s": 2397,
"text": "leftJoinTable"
},
{
"code": null,
"e": 2479,
"s": 2411,
"text": "A table expression defining the table on the left side of the join."
},
{
"code": null,
"e": 2494,
"s": 2479,
"text": "rightJoinTable"
},
{
"code": null,
"e": 2563,
"s": 2494,
"text": "A table expression defining the table on the right side of the join."
},
{
"code": null,
"e": 2814,
"s": 2563,
"text": "table which includes only rows from rightJoinTable for which the values in the common columns specified are also present in leftJoinTable. The table returned will have the common columns from the left table and the other columns from both the tables."
},
{
"code": null,
"e": 2864,
"s": 2814,
"text": "There is no sort order guarantee for the results."
},
{
"code": null,
"e": 2914,
"s": 2864,
"text": "There is no sort order guarantee for the results."
},
{
"code": null,
"e": 2983,
"s": 2914,
"text": "Columns being joined on must have the same data type in both tables."
},
{
"code": null,
"e": 3052,
"s": 2983,
"text": "Columns being joined on must have the same data type in both tables."
},
{
"code": null,
"e": 3385,
"s": 3052,
"text": "Only columns from the same source table (have the same lineage) are joined on. For example, Products[ProductID], WebSales[ProductdID], StoreSales[ProductdID] with many-to-one relationships between WebSales and StoreSales and the Products table based on the ProductID column, WebSales and StoreSales tables are joined on [ProductID]."
},
{
"code": null,
"e": 3718,
"s": 3385,
"text": "Only columns from the same source table (have the same lineage) are joined on. For example, Products[ProductID], WebSales[ProductdID], StoreSales[ProductdID] with many-to-one relationships between WebSales and StoreSales and the Products table based on the ProductID column, WebSales and StoreSales tables are joined on [ProductID]."
},
{
"code": null,
"e": 3830,
"s": 3718,
"text": "Strict comparison semantics are used during join. There is no type coercion; for example, 1 does not equal 1.0."
},
{
"code": null,
"e": 3942,
"s": 3830,
"text": "Strict comparison semantics are used during join. There is no type coercion; for example, 1 does not equal 1.0."
},
{
"code": null,
"e": 4008,
"s": 3942,
"text": "= SUMX (NATURALLEFTOUTERJOIN (Salesperson,Sales),[Sales Amount]) "
},
{
"code": null,
"e": 4043,
"s": 4008,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4057,
"s": 4043,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 4090,
"s": 4057,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4104,
"s": 4090,
"text": " Randy Minder"
},
{
"code": null,
"e": 4139,
"s": 4104,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4153,
"s": 4139,
"text": " Randy Minder"
},
{
"code": null,
"e": 4160,
"s": 4153,
"text": " Print"
},
{
"code": null,
"e": 4171,
"s": 4160,
"text": " Add Notes"
}
] |
How To Generate SSH Key With ssh-keygen In Linux? - GeeksforGeeks
|
30 Jun, 2021
Secure Shell(SSH) is a cryptographic network protocol used for operating remote services securely. It is used for remote operation of devices on secure channels using a client-server architecture that generally operates on Port 22. SSH is the successor of Telnet. SSH uses public and private keys to validate and authenticate users. ssh-keygen is used to generate these key pairs.
You can learn more about SSH and Telnet here
SSH protocol needs to have 2 pairs. A Public Key and a Private Key
The Public Key is added to the remote server (or) device into a special folder $HOME/.ssh/authorized_keys.
When the server sends any response encrypted using the public key, as only the client has the private key, it can only decrypt the response.
After successful authentication, a shell session is created or the requested command is executed on the remote server.
How SSH works
ssh-keygen is the utility used to generate, manage, and convert authentication keys for SSH. ssh-keygen comes installed with SSH in most of the operating systems. ssh-keygen is able to generate a key using one of three different digital signature algorithms.
RSA
DSA
ECDSA
Files generated by ssh-keygen
$HOME/.ssh/identity: File containing the RSA private key when using SSH protocol version 1.
$HOME/.ssh/identity.pub: File containing the RSA public key for authentication when you are using the SSH protocol version
$HOME/.ssh/id_dsa: File containing the protocol version 2 DSA authentication identity of the user.
$HOME/.ssh/id_dsa.pub: File containing the DSA public key for authentication when you are using the SSH protocol version.
$HOME/.ssh/id_rsa: File containing the protocol version 2 RSA authentication identity of the user. This file should not be readable by anyone but the user.
$HOME/.ssh/id_rsa.pub: File containing the protocol version 2 RSA public key for authentication.
“.pub” files should be copied to the $HOME/.ssh/authorized_keys file of the remote system where a user wants to log in using SSH authentication.
Almost all Unix and Linux Distro’s come pre-installed with SSH and ssh-keygen, so we will have no need to install. We will get started directly. This process is almost similar to almost all Linux Distros’s
Open your terminal and type ssh-keygen
ssh-keygen
It asks for the names of the ssh key pairs. If you wish to enter the passphrase, go on and ssh-keygen will automatically create your keys.
//Output
Generating public/private rsa key pair.
// enter the name for ssh key pairs
Enter file in which to save the key (/home/kushwanth/.ssh/id_rsa): gfg
// enter passpharse for security
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
// ssh keys generated
Your identification has been saved in gfg
Your public key has been saved in gfg.pub
ssh key gen created
A public key looks like the one below.
Sample public key
This is the key you need to copy into your remote device to get successful SSH authentication.
After the key pair is created, now we need to copy the public key into the server. There are 2 ways to do this, using ssh-copy-id (or) manually copying it into the server.
Using ssh-copy-id
Use the ssh-copy-id command to copy your public key file (e.g., $HOME/.ssh/id_rsa.pub) to your user account on the remote server.
ssh-copy-id -i $HOME/.ssh/id_rsa.pub <user>@<your-remote-host>
Manually copying the public key
Login to your remote server using the password and create a directory at $HOME/.ssh. You can use the command below.
ssh <user>@<your-remote-host> “umask 077; test -d .ssh || mkdir .ssh”
ssh <user>@<host> allows you to login into your remote host server
If the .ssh directory is already present, it will set the permissions of the directory to 077 so that it allows read, write, and execute permission for the file’s owner, but prohibits reading, writing, and execute permission for everyone else.
If the directory is not present, then it will create a new one.
Now send your public key to the remote server,
cat $HOME/.ssh/id_rsa.pub | ssh <user>@<your-remote-host> “cat >> .ssh/authorized_keys”
cat allows you to print the contents of the file in the terminal.
The output from the cat is piped into SSH to append the public key to a remote server.
Now you can logout and test whether you can connect to the remote server using the SSH protocol.
Picked
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Set Git Username and Password in GitBash?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Install Jupyter Notebook on MacOS?
How to Check the OS Version in Linux?
AWK command in Unix/Linux with examples
Sed Command in Linux/Unix with examples
grep command in Unix/Linux
cut command in Linux with examples
TCP Server-Client implementation in C
|
[
{
"code": null,
"e": 24944,
"s": 24913,
"text": " \n30 Jun, 2021\n"
},
{
"code": null,
"e": 25325,
"s": 24944,
"text": "Secure Shell(SSH) is a cryptographic network protocol used for operating remote services securely. It is used for remote operation of devices on secure channels using a client-server architecture that generally operates on Port 22. SSH is the successor of Telnet. SSH uses public and private keys to validate and authenticate users. ssh-keygen is used to generate these key pairs."
},
{
"code": null,
"e": 25370,
"s": 25325,
"text": "You can learn more about SSH and Telnet here"
},
{
"code": null,
"e": 25437,
"s": 25370,
"text": "SSH protocol needs to have 2 pairs. A Public Key and a Private Key"
},
{
"code": null,
"e": 25544,
"s": 25437,
"text": "The Public Key is added to the remote server (or) device into a special folder $HOME/.ssh/authorized_keys."
},
{
"code": null,
"e": 25685,
"s": 25544,
"text": "When the server sends any response encrypted using the public key, as only the client has the private key, it can only decrypt the response."
},
{
"code": null,
"e": 25804,
"s": 25685,
"text": "After successful authentication, a shell session is created or the requested command is executed on the remote server."
},
{
"code": null,
"e": 25818,
"s": 25804,
"text": "How SSH works"
},
{
"code": null,
"e": 26077,
"s": 25818,
"text": "ssh-keygen is the utility used to generate, manage, and convert authentication keys for SSH. ssh-keygen comes installed with SSH in most of the operating systems. ssh-keygen is able to generate a key using one of three different digital signature algorithms."
},
{
"code": null,
"e": 26081,
"s": 26077,
"text": "RSA"
},
{
"code": null,
"e": 26085,
"s": 26081,
"text": "DSA"
},
{
"code": null,
"e": 26091,
"s": 26085,
"text": "ECDSA"
},
{
"code": null,
"e": 26121,
"s": 26091,
"text": "Files generated by ssh-keygen"
},
{
"code": null,
"e": 26213,
"s": 26121,
"text": "$HOME/.ssh/identity: File containing the RSA private key when using SSH protocol version 1."
},
{
"code": null,
"e": 26336,
"s": 26213,
"text": "$HOME/.ssh/identity.pub: File containing the RSA public key for authentication when you are using the SSH protocol version"
},
{
"code": null,
"e": 26435,
"s": 26336,
"text": "$HOME/.ssh/id_dsa: File containing the protocol version 2 DSA authentication identity of the user."
},
{
"code": null,
"e": 26557,
"s": 26435,
"text": "$HOME/.ssh/id_dsa.pub: File containing the DSA public key for authentication when you are using the SSH protocol version."
},
{
"code": null,
"e": 26713,
"s": 26557,
"text": "$HOME/.ssh/id_rsa: File containing the protocol version 2 RSA authentication identity of the user. This file should not be readable by anyone but the user."
},
{
"code": null,
"e": 26810,
"s": 26713,
"text": "$HOME/.ssh/id_rsa.pub: File containing the protocol version 2 RSA public key for authentication."
},
{
"code": null,
"e": 26955,
"s": 26810,
"text": "“.pub” files should be copied to the $HOME/.ssh/authorized_keys file of the remote system where a user wants to log in using SSH authentication."
},
{
"code": null,
"e": 27161,
"s": 26955,
"text": "Almost all Unix and Linux Distro’s come pre-installed with SSH and ssh-keygen, so we will have no need to install. We will get started directly. This process is almost similar to almost all Linux Distros’s"
},
{
"code": null,
"e": 27200,
"s": 27161,
"text": "Open your terminal and type ssh-keygen"
},
{
"code": null,
"e": 27211,
"s": 27200,
"text": "ssh-keygen"
},
{
"code": null,
"e": 27350,
"s": 27211,
"text": "It asks for the names of the ssh key pairs. If you wish to enter the passphrase, go on and ssh-keygen will automatically create your keys."
},
{
"code": null,
"e": 27724,
"s": 27350,
"text": "//Output\n\nGenerating public/private rsa key pair.\n\n// enter the name for ssh key pairs\nEnter file in which to save the key (/home/kushwanth/.ssh/id_rsa): gfg\n\n// enter passpharse for security\nEnter passphrase (empty for no passphrase): \nEnter same passphrase again: \n\n// ssh keys generated\nYour identification has been saved in gfg\nYour public key has been saved in gfg.pub"
},
{
"code": null,
"e": 27744,
"s": 27724,
"text": "ssh key gen created"
},
{
"code": null,
"e": 27783,
"s": 27744,
"text": "A public key looks like the one below."
},
{
"code": null,
"e": 27801,
"s": 27783,
"text": "Sample public key"
},
{
"code": null,
"e": 27896,
"s": 27801,
"text": "This is the key you need to copy into your remote device to get successful SSH authentication."
},
{
"code": null,
"e": 28068,
"s": 27896,
"text": "After the key pair is created, now we need to copy the public key into the server. There are 2 ways to do this, using ssh-copy-id (or) manually copying it into the server."
},
{
"code": null,
"e": 28086,
"s": 28068,
"text": "Using ssh-copy-id"
},
{
"code": null,
"e": 28216,
"s": 28086,
"text": "Use the ssh-copy-id command to copy your public key file (e.g., $HOME/.ssh/id_rsa.pub) to your user account on the remote server."
},
{
"code": null,
"e": 28279,
"s": 28216,
"text": "ssh-copy-id -i $HOME/.ssh/id_rsa.pub <user>@<your-remote-host>"
},
{
"code": null,
"e": 28311,
"s": 28279,
"text": "Manually copying the public key"
},
{
"code": null,
"e": 28427,
"s": 28311,
"text": "Login to your remote server using the password and create a directory at $HOME/.ssh. You can use the command below."
},
{
"code": null,
"e": 28497,
"s": 28427,
"text": "ssh <user>@<your-remote-host> “umask 077; test -d .ssh || mkdir .ssh”"
},
{
"code": null,
"e": 28564,
"s": 28497,
"text": "ssh <user>@<host> allows you to login into your remote host server"
},
{
"code": null,
"e": 28808,
"s": 28564,
"text": "If the .ssh directory is already present, it will set the permissions of the directory to 077 so that it allows read, write, and execute permission for the file’s owner, but prohibits reading, writing, and execute permission for everyone else."
},
{
"code": null,
"e": 28872,
"s": 28808,
"text": "If the directory is not present, then it will create a new one."
},
{
"code": null,
"e": 28919,
"s": 28872,
"text": "Now send your public key to the remote server,"
},
{
"code": null,
"e": 29007,
"s": 28919,
"text": "cat $HOME/.ssh/id_rsa.pub | ssh <user>@<your-remote-host> “cat >> .ssh/authorized_keys”"
},
{
"code": null,
"e": 29073,
"s": 29007,
"text": "cat allows you to print the contents of the file in the terminal."
},
{
"code": null,
"e": 29161,
"s": 29073,
"text": "The output from the cat is piped into SSH to append the public key to a remote server."
},
{
"code": null,
"e": 29258,
"s": 29161,
"text": "Now you can logout and test whether you can connect to the remote server using the SSH protocol."
},
{
"code": null,
"e": 29267,
"s": 29258,
"text": "\nPicked\n"
},
{
"code": null,
"e": 29276,
"s": 29267,
"text": "\nHow To\n"
},
{
"code": null,
"e": 29289,
"s": 29276,
"text": "\nLinux-Unix\n"
},
{
"code": null,
"e": 29494,
"s": 29289,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 29528,
"s": 29494,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 29577,
"s": 29528,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 29635,
"s": 29577,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 29677,
"s": 29635,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 29715,
"s": 29677,
"text": "How to Check the OS Version in Linux?"
},
{
"code": null,
"e": 29755,
"s": 29715,
"text": "AWK command in Unix/Linux with examples"
},
{
"code": null,
"e": 29795,
"s": 29755,
"text": "Sed Command in Linux/Unix with examples"
},
{
"code": null,
"e": 29822,
"s": 29795,
"text": "grep command in Unix/Linux"
},
{
"code": null,
"e": 29857,
"s": 29822,
"text": "cut command in Linux with examples"
}
] |
fmt.Scanln() Function in Golang With Examples - GeeksforGeeks
|
05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scanln() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments. This function stops scanning at a newline and after the final item, there must be a newline or EOF. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Scanln(a ...interface{}) (n int, err error)
Here, “a ...interface{}” receives each given texts.
Returns: It returns the number of items successfully scanned.
Example 1:
// Golang program to illustrate the usage of// fmt.Scanln() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int // Calling Scanln() function for // scanning and reading the input // texts given in standard input fmt.Scanln(&name) fmt.Scanln(&alphabet_count) // Printing the given texts fmt.Printf("%s %d", name, alphabet_count) }
Input:
GFG 3
Output:
GFG 0
Example 2:
// Golang program to illustrate the usage of// fmt.Scanln() function // Including the main packagepackage main // Importing fmtimport ( "fmt") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int // Calling Scanln() function for // scanning and reading the input // texts given in standard input fmt.Scanln(&name) fmt.Scanln(&alphabet_count) // Printing the given texts fmt.Printf("%s %d", name, alphabet_count) }
Input:
GeeksforGeeks \n 13
Output:
GeeksforGeeks 0
In the above example, it can be seen that standard input takes the value of “GeeksforGeeks \n 13” but it returns output as “GeeksforGeeks 0” this is because of this function stop scannning at new line (\n).
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
fmt.Sprintf() Function in Golang With Examples
strings.Replace() Function in Golang With Examples
How to Split a String in Golang?
Golang Maps
Slices in Golang
Arrays in Go
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
How to compare times in Golang?
Different Ways to Find the Type of Variable in Golang
|
[
{
"code": null,
"e": 24404,
"s": 24376,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 24948,
"s": 24404,
"text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scanln() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments. This function stops scanning at a newline and after the final item, there must be a newline or EOF. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions."
},
{
"code": null,
"e": 24956,
"s": 24948,
"text": "Syntax:"
},
{
"code": null,
"e": 25006,
"s": 24956,
"text": "func Scanln(a ...interface{}) (n int, err error)\n"
},
{
"code": null,
"e": 25058,
"s": 25006,
"text": "Here, “a ...interface{}” receives each given texts."
},
{
"code": null,
"e": 25120,
"s": 25058,
"text": "Returns: It returns the number of items successfully scanned."
},
{
"code": null,
"e": 25131,
"s": 25120,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Scanln() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int // Calling Scanln() function for // scanning and reading the input // texts given in standard input fmt.Scanln(&name) fmt.Scanln(&alphabet_count) // Printing the given texts fmt.Printf(\"%s %d\", name, alphabet_count) }",
"e": 25646,
"s": 25131,
"text": null
},
{
"code": null,
"e": 25653,
"s": 25646,
"text": "Input:"
},
{
"code": null,
"e": 25660,
"s": 25653,
"text": "GFG 3\n"
},
{
"code": null,
"e": 25668,
"s": 25660,
"text": "Output:"
},
{
"code": null,
"e": 25675,
"s": 25668,
"text": "GFG 0\n"
},
{
"code": null,
"e": 25686,
"s": 25675,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// fmt.Scanln() function // Including the main packagepackage main // Importing fmtimport ( \"fmt\") // Calling mainfunc main() { // Declaring some variables var name string var alphabet_count int // Calling Scanln() function for // scanning and reading the input // texts given in standard input fmt.Scanln(&name) fmt.Scanln(&alphabet_count) // Printing the given texts fmt.Printf(\"%s %d\", name, alphabet_count) }",
"e": 26201,
"s": 25686,
"text": null
},
{
"code": null,
"e": 26208,
"s": 26201,
"text": "Input:"
},
{
"code": null,
"e": 26229,
"s": 26208,
"text": "GeeksforGeeks \\n 13\n"
},
{
"code": null,
"e": 26237,
"s": 26229,
"text": "Output:"
},
{
"code": null,
"e": 26254,
"s": 26237,
"text": "GeeksforGeeks 0\n"
},
{
"code": null,
"e": 26461,
"s": 26254,
"text": "In the above example, it can be seen that standard input takes the value of “GeeksforGeeks \\n 13” but it returns output as “GeeksforGeeks 0” this is because of this function stop scannning at new line (\\n)."
},
{
"code": null,
"e": 26472,
"s": 26461,
"text": "Golang-fmt"
},
{
"code": null,
"e": 26484,
"s": 26472,
"text": "Go Language"
},
{
"code": null,
"e": 26582,
"s": 26484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26591,
"s": 26582,
"text": "Comments"
},
{
"code": null,
"e": 26604,
"s": 26591,
"text": "Old Comments"
},
{
"code": null,
"e": 26651,
"s": 26604,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 26702,
"s": 26651,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 26735,
"s": 26702,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 26747,
"s": 26735,
"text": "Golang Maps"
},
{
"code": null,
"e": 26764,
"s": 26747,
"text": "Slices in Golang"
},
{
"code": null,
"e": 26777,
"s": 26764,
"text": "Arrays in Go"
},
{
"code": null,
"e": 26809,
"s": 26777,
"text": "How to Trim a String in Golang?"
},
{
"code": null,
"e": 26858,
"s": 26809,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 26890,
"s": 26858,
"text": "How to compare times in Golang?"
}
] |
VBA - Nested If Statement
|
An If or ElseIf statement inside another If or ElseIf statement(s). The inner If statements are executed based on the outermost If statements. This enables VBScript to handle complex conditions with ease.
Following is the syntax of an Nested If statement in VBScript.
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
If(boolean_expression) Then
Statement 1
.....
.....
Statement n
ElseIf (boolean_expression) Then
Statement 1
.....
....
Statement n
Else
Statement 1
.....
....
Statement n
End If
Else
Statement 1
.....
....
Statement n
End If
For demo purpose, let us find the type of a positive number with the help of a function.
Private Sub nested_if_demo_Click()
Dim a As Integer
a = 23
If a > 0 Then
MsgBox "The Number is a POSITIVE Number"
If a = 1 Then
MsgBox "The Number is Neither Prime NOR Composite"
ElseIf a = 2 Then
MsgBox "The Number is the Only Even Prime Number"
ElseIf a = 3 Then
MsgBox "The Number is the Least Odd Prime Number"
Else
MsgBox "The Number is NOT 0,1,2 or 3"
End If
ElseIf a < 0 Then
MsgBox "The Number is a NEGATIVE Number"
Else
MsgBox "The Number is ZERO"
End If
End Sub
When the above code is executed, it produces the following result.
The Number is a POSITIVE Number
The Number is NOT 0,1,2 or 3
101 Lectures
6 hours
Pavan Lalwani
41 Lectures
3 hours
Arnold Higuit
80 Lectures
5.5 hours
Prashant Panchal
25 Lectures
2 hours
Prashant Panchal
26 Lectures
2 hours
Arnold Higuit
92 Lectures
10.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2140,
"s": 1935,
"text": "An If or ElseIf statement inside another If or ElseIf statement(s). The inner If statements are executed based on the outermost If statements. This enables VBScript to handle complex conditions with ease."
},
{
"code": null,
"e": 2203,
"s": 2140,
"text": "Following is the syntax of an Nested If statement in VBScript."
},
{
"code": null,
"e": 2602,
"s": 2203,
"text": "If(boolean_expression) Then\n Statement 1\n .....\n .....\n Statement n\n \n If(boolean_expression) Then\n Statement 1\n .....\n .....\n Statement n\n ElseIf (boolean_expression) Then\n Statement 1\n .....\n ....\n Statement n\n Else\n Statement 1\n .....\n ....\n Statement n\n End If\nElse\n Statement 1\n\t.....\n\t....\n Statement n\nEnd If\n"
},
{
"code": null,
"e": 2691,
"s": 2602,
"text": "For demo purpose, let us find the type of a positive number with the help of a function."
},
{
"code": null,
"e": 3275,
"s": 2691,
"text": "Private Sub nested_if_demo_Click()\n Dim a As Integer\n a = 23\n \n If a > 0 Then\n MsgBox \"The Number is a POSITIVE Number\"\n \n If a = 1 Then\n MsgBox \"The Number is Neither Prime NOR Composite\"\n ElseIf a = 2 Then\n MsgBox \"The Number is the Only Even Prime Number\"\n ElseIf a = 3 Then\n MsgBox \"The Number is the Least Odd Prime Number\"\n Else\n MsgBox \"The Number is NOT 0,1,2 or 3\"\n End If\n ElseIf a < 0 Then\n MsgBox \"The Number is a NEGATIVE Number\"\n Else\n MsgBox \"The Number is ZERO\"\n End If\nEnd Sub"
},
{
"code": null,
"e": 3342,
"s": 3275,
"text": "When the above code is executed, it produces the following result."
},
{
"code": null,
"e": 3404,
"s": 3342,
"text": "The Number is a POSITIVE Number\nThe Number is NOT 0,1,2 or 3\n"
},
{
"code": null,
"e": 3438,
"s": 3404,
"text": "\n 101 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3453,
"s": 3438,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 3486,
"s": 3453,
"text": "\n 41 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 3501,
"s": 3486,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3536,
"s": 3501,
"text": "\n 80 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3554,
"s": 3536,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3587,
"s": 3554,
"text": "\n 25 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3605,
"s": 3587,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 3638,
"s": 3605,
"text": "\n 26 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3653,
"s": 3638,
"text": " Arnold Higuit"
},
{
"code": null,
"e": 3689,
"s": 3653,
"text": "\n 92 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 3717,
"s": 3689,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 3724,
"s": 3717,
"text": " Print"
},
{
"code": null,
"e": 3735,
"s": 3724,
"text": " Add Notes"
}
] |
Quant’s Guide: Finding Key Metrics & Ratios Using Python | by Posey | Towards Data Science
|
We’ll use Yahoo Finance for this example. You can use your data source of choice. First, let’s import the libraries and grab the data used in this article...
The Efficient Frontier is a common subject of portfolio theory. It involves finding the portfolio(s) with the highest expected return with fixed risk OR the lowest risk for a fixed expected return.
Let’s walk through the above code piece by piece...
data = f.get(stocks, start='2019-01-01', end='2019-09-01') mu = expected_returns.mean_historical_return(data) S = risk_models.sample_cov(data) ef = EfficientFrontier(mu, S) raw_weights = ef.max_sharpe() cleaned_weights = ef.clean_weights() perf = ef.portfolio_performance(verbose=True) ef.__dict__
First, we gather our data passing a list of stocks and a timeframe to ffn.
Next, we calculate mu and S. mu is calculated from the mean of historical returns for stocks from the set timeframe. S is the covariance matrix.
Using mu and S we can find the efficient frontier. From here, we can plot risk vs return and begin to curve fit the optimal portfolios.
From there, we can do some fun things like maximize for various ratios like Sharpe, Calmar, Sortino, or whatever we desire and get the weights of individual equities. It will only find the efficient frontier and distribute weights from the list of stocks we pass and get returns from Yahoo Finance.
The stats and metrics the following script explores include:
Returns
CAGR
Max Drawdown
Sharpe Ratio
Calmar Ratio
Keep in mind that calc_stats() gives us a lot more data, but we’re cherrypicking some relevant metrics.
Immediately you see us calculate cumulative returns using ffn. We round and find the mean of the cumulative returns in an effort to clean up our data a bit. From there, I found that the function for calculating the Sharpe Ratio directly doesn’t work for me so I grab it from calc_stats. To do this, I iterate over every stock in my desired list of stocks and add their Sharpe Ratios to a list. I can then take the mean of that list of ratios to find the mean Sharpe Ratio or do whatever else I desire...
Now in the above section, I gather Sharpe, max drawdown, CAGR, and Calmar for each individual equity. In the end, you might append it to a list, JSON to send someplace else, maybe a dataframe. That’s totally up to you!
At Spawner we’re tackling these problems and our API can solve most of the herein discussed problems.
I hope this made it clear to you that some powerful libraries are out there to be explored. I’ve received a lot of emails asking for resources. Here’s a list of resources directly mentioned or tangential to this article:
ffn
pyportfolioopt
Quantopian
IEX Cloud
pynance
Zipline
TA-Lib
bt
pyfolio
Github link
Let’s continue the convo on Twitter.
To support my writing and get full access to all articles on Medium, visit https://posey.medium.com/membership
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
|
[
{
"code": null,
"e": 330,
"s": 172,
"text": "We’ll use Yahoo Finance for this example. You can use your data source of choice. First, let’s import the libraries and grab the data used in this article..."
},
{
"code": null,
"e": 528,
"s": 330,
"text": "The Efficient Frontier is a common subject of portfolio theory. It involves finding the portfolio(s) with the highest expected return with fixed risk OR the lowest risk for a fixed expected return."
},
{
"code": null,
"e": 580,
"s": 528,
"text": "Let’s walk through the above code piece by piece..."
},
{
"code": null,
"e": 928,
"s": 580,
"text": "data = f.get(stocks, start='2019-01-01', end='2019-09-01') mu = expected_returns.mean_historical_return(data) S = risk_models.sample_cov(data) ef = EfficientFrontier(mu, S) raw_weights = ef.max_sharpe() cleaned_weights = ef.clean_weights() perf = ef.portfolio_performance(verbose=True) ef.__dict__"
},
{
"code": null,
"e": 1003,
"s": 928,
"text": "First, we gather our data passing a list of stocks and a timeframe to ffn."
},
{
"code": null,
"e": 1148,
"s": 1003,
"text": "Next, we calculate mu and S. mu is calculated from the mean of historical returns for stocks from the set timeframe. S is the covariance matrix."
},
{
"code": null,
"e": 1284,
"s": 1148,
"text": "Using mu and S we can find the efficient frontier. From here, we can plot risk vs return and begin to curve fit the optimal portfolios."
},
{
"code": null,
"e": 1583,
"s": 1284,
"text": "From there, we can do some fun things like maximize for various ratios like Sharpe, Calmar, Sortino, or whatever we desire and get the weights of individual equities. It will only find the efficient frontier and distribute weights from the list of stocks we pass and get returns from Yahoo Finance."
},
{
"code": null,
"e": 1644,
"s": 1583,
"text": "The stats and metrics the following script explores include:"
},
{
"code": null,
"e": 1652,
"s": 1644,
"text": "Returns"
},
{
"code": null,
"e": 1657,
"s": 1652,
"text": "CAGR"
},
{
"code": null,
"e": 1670,
"s": 1657,
"text": "Max Drawdown"
},
{
"code": null,
"e": 1683,
"s": 1670,
"text": "Sharpe Ratio"
},
{
"code": null,
"e": 1696,
"s": 1683,
"text": "Calmar Ratio"
},
{
"code": null,
"e": 1800,
"s": 1696,
"text": "Keep in mind that calc_stats() gives us a lot more data, but we’re cherrypicking some relevant metrics."
},
{
"code": null,
"e": 2304,
"s": 1800,
"text": "Immediately you see us calculate cumulative returns using ffn. We round and find the mean of the cumulative returns in an effort to clean up our data a bit. From there, I found that the function for calculating the Sharpe Ratio directly doesn’t work for me so I grab it from calc_stats. To do this, I iterate over every stock in my desired list of stocks and add their Sharpe Ratios to a list. I can then take the mean of that list of ratios to find the mean Sharpe Ratio or do whatever else I desire..."
},
{
"code": null,
"e": 2523,
"s": 2304,
"text": "Now in the above section, I gather Sharpe, max drawdown, CAGR, and Calmar for each individual equity. In the end, you might append it to a list, JSON to send someplace else, maybe a dataframe. That’s totally up to you!"
},
{
"code": null,
"e": 2625,
"s": 2523,
"text": "At Spawner we’re tackling these problems and our API can solve most of the herein discussed problems."
},
{
"code": null,
"e": 2846,
"s": 2625,
"text": "I hope this made it clear to you that some powerful libraries are out there to be explored. I’ve received a lot of emails asking for resources. Here’s a list of resources directly mentioned or tangential to this article:"
},
{
"code": null,
"e": 2850,
"s": 2846,
"text": "ffn"
},
{
"code": null,
"e": 2865,
"s": 2850,
"text": "pyportfolioopt"
},
{
"code": null,
"e": 2876,
"s": 2865,
"text": "Quantopian"
},
{
"code": null,
"e": 2886,
"s": 2876,
"text": "IEX Cloud"
},
{
"code": null,
"e": 2894,
"s": 2886,
"text": "pynance"
},
{
"code": null,
"e": 2902,
"s": 2894,
"text": "Zipline"
},
{
"code": null,
"e": 2909,
"s": 2902,
"text": "TA-Lib"
},
{
"code": null,
"e": 2912,
"s": 2909,
"text": "bt"
},
{
"code": null,
"e": 2920,
"s": 2912,
"text": "pyfolio"
},
{
"code": null,
"e": 2932,
"s": 2920,
"text": "Github link"
},
{
"code": null,
"e": 2969,
"s": 2932,
"text": "Let’s continue the convo on Twitter."
},
{
"code": null,
"e": 3080,
"s": 2969,
"text": "To support my writing and get full access to all articles on Medium, visit https://posey.medium.com/membership"
}
] |
How to set action to a RadioButton in JavaFX?
|
A radio button is a type of button, which is circular in shape. It has two states, selected and deselected. Generally, radio buttons are grouped using toggle groups, where you can only select one of them.
You can create a radio button in JavaFX by instantiating the javafx.scene.control.RadioButton class, which is the subclass of the ToggleButton class. Action is generated whenever a radio button is pressed or released. You can set a radio button to a group using the setToggleGroup() method.
The property named selected of the RadioButton class specifies whether the current checkbox is selected. Its value will be true if checked and false if unchecked.
The selectedProperty() method returns a boolean property indicating whether the current checkbox is checked. If you want to perform a certain actions in case a checkbox is selected. You can add a listener to this property as −
checkBox2.selectedProperty().addListener(
//. . . . .
);
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Slider;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class RadioButton_Action extends Application {
public void start(Stage stage) {
//Creating a button
Button button = new Button("Hi");
button.setPrefSize(40, 40);
//Creating a slider to resize the button
Slider slider = new Slider(40, 200, 40);
//Setting its orientation to Horizontal
slider.setPrefHeight(180);
slider.setOrientation(Orientation.VERTICAL);
slider.setShowTickLabels(true);
slider.setShowTickMarks(true);
slider.setMajorTickUnit(40);
slider.setBlockIncrement(20);
slider.valueProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue <?extends Number>observable, Number
oldValue, Number newValue){
button.setPrefSize((double)newValue, (double)newValue);
}
});
RadioButton prevent = new RadioButton();
RadioButton reset = new RadioButton();
ToggleGroup group = new ToggleGroup();
prevent.setToggleGroup(group);
reset.setToggleGroup(group);
prevent.selectedProperty().addListener(
(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) ->{
button.setMinWidth(40);
button.setPrefWidth(40);
button.setMaxWidth(40);
button.setMinHeight(40);
button.setMaxHeight(40);
button.setPrefHeight(40);
});
reset.selectedProperty().addListener(
ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {
button.setPrefHeight(40);
button.setPrefWidth(40);
button.setMinWidth(Button.USE_PREF_SIZE);
button.setMaxWidth(Button.USE_PREF_SIZE);
button.setMinHeight(Button.USE_PREF_SIZE);
button.setMaxHeight(Button.USE_PREF_SIZE);
});
//Creating the pane
BorderPane pane = new BorderPane();
pane.setCenter(button);
pane.setRight(new HBox(new Label("Prevent Reize"), prevent, new Label("Allow Resize"), reset));
pane.setLeft(new VBox(new Label("Button Reize"), slider));
pane.setPadding(new Insets(10, 10, 10, 10));
//Preparing the scene
Scene scene = new Scene(pane, 595, 250);
stage.setTitle("JavaFX Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
|
[
{
"code": null,
"e": 1267,
"s": 1062,
"text": "A radio button is a type of button, which is circular in shape. It has two states, selected and deselected. Generally, radio buttons are grouped using toggle groups, where you can only select one of them."
},
{
"code": null,
"e": 1558,
"s": 1267,
"text": "You can create a radio button in JavaFX by instantiating the javafx.scene.control.RadioButton class, which is the subclass of the ToggleButton class. Action is generated whenever a radio button is pressed or released. You can set a radio button to a group using the setToggleGroup() method."
},
{
"code": null,
"e": 1721,
"s": 1558,
"text": "The property named selected of the RadioButton class specifies whether the current checkbox is selected. Its value will be true if checked and false if unchecked."
},
{
"code": null,
"e": 1948,
"s": 1721,
"text": "The selectedProperty() method returns a boolean property indicating whether the current checkbox is checked. If you want to perform a certain actions in case a checkbox is selected. You can add a listener to this property as −"
},
{
"code": null,
"e": 2008,
"s": 1948,
"text": "checkBox2.selectedProperty().addListener(\n //. . . . .\n);"
},
{
"code": null,
"e": 4906,
"s": 2008,
"text": "import javafx.application.Application;\nimport javafx.beans.value.ChangeListener;\nimport javafx.beans.value.ObservableValue;\nimport javafx.geometry.Insets;\nimport javafx.geometry.Orientation;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Button;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.RadioButton;\nimport javafx.scene.control.Slider;\nimport javafx.scene.control.ToggleGroup;\nimport javafx.scene.layout.BorderPane;\nimport javafx.scene.layout.HBox;\nimport javafx.scene.layout.VBox;\nimport javafx.stage.Stage;\npublic class RadioButton_Action extends Application {\n public void start(Stage stage) {\n //Creating a button\n Button button = new Button(\"Hi\");\n button.setPrefSize(40, 40);\n //Creating a slider to resize the button\n Slider slider = new Slider(40, 200, 40);\n //Setting its orientation to Horizontal\n slider.setPrefHeight(180);\n slider.setOrientation(Orientation.VERTICAL);\n slider.setShowTickLabels(true);\n slider.setShowTickMarks(true);\n slider.setMajorTickUnit(40);\n slider.setBlockIncrement(20);\n slider.valueProperty().addListener(new ChangeListener<Number>() {\n public void changed(ObservableValue <?extends Number>observable, Number\n oldValue, Number newValue){\n button.setPrefSize((double)newValue, (double)newValue);\n }\n });\n RadioButton prevent = new RadioButton();\n RadioButton reset = new RadioButton();\n ToggleGroup group = new ToggleGroup();\n prevent.setToggleGroup(group);\n reset.setToggleGroup(group);\n prevent.selectedProperty().addListener(\n (ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) ->{\n button.setMinWidth(40);\n button.setPrefWidth(40);\n button.setMaxWidth(40);\n button.setMinHeight(40);\n button.setMaxHeight(40);\n button.setPrefHeight(40);\n });\n reset.selectedProperty().addListener(\n ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) -> {\n button.setPrefHeight(40);\n button.setPrefWidth(40);\n button.setMinWidth(Button.USE_PREF_SIZE);\n button.setMaxWidth(Button.USE_PREF_SIZE);\n button.setMinHeight(Button.USE_PREF_SIZE);\n button.setMaxHeight(Button.USE_PREF_SIZE);\n });\n //Creating the pane\n BorderPane pane = new BorderPane();\n pane.setCenter(button);\n pane.setRight(new HBox(new Label(\"Prevent Reize\"), prevent, new Label(\"Allow Resize\"), reset));\n pane.setLeft(new VBox(new Label(\"Button Reize\"), slider));\n pane.setPadding(new Insets(10, 10, 10, 10));\n //Preparing the scene\n Scene scene = new Scene(pane, 595, 250);\n stage.setTitle(\"JavaFX Example\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}"
}
] |
Statistical Functions in Python | Set 2 ( Measure of Spread) - GeeksforGeeks
|
10 Feb, 2020
Statistical Functions in Python | Set 1(Averages and Measure of Central Location)
Measure of spread functions of statistics are discussed in this article.
1. variance() :- This function calculates the variance i.e measure of deviation of data, more the value of variance, more the data values are spread. Sample variance is computed in this function, assuming data is of a part of population. If passed argument is empty, StatisticsError is raised.
2. pvariance() :- This function computes the variance of the entire population. The data is interpreted as it is of the whole population. If passed argument is empty, StatisticsError is raised.
# Python code to demonstrate the working of # variance() and pvariance() # importing statistics to handle statistical operationsimport statistics # initializing listli = [1.5, 2.5, 2.5, 3.5, 3.5, 3.5] # using variance to calculate variance of dataprint ("The variance of data is : ",end="")print (statistics.variance(li)) # using pvariance to calculate population variance of dataprint ("The population variance of data is : ",end="")print (statistics.pvariance(li))
Output:
The variance of data is : 0.6666666666666667
The population variance of data is : 0.5555555555555556
3. stdev() :- This function returns the standard deviation ( square root of sample variance ) of the data. If passed argument is empty, StatisticsError is raised.
4. pstdev() :- This function returns the population standard deviation ( square root of population variance ) of the data. If passed argument is empty, StatisticsError is raised.
# Python code to demonstrate the working of # stdev() and pstdev() # importing statistics to handle statistical operationsimport statistics # initializing listli = [1.5, 2.5, 2.5, 3.5, 3.5, 3.5] # using stdev to calculate standard deviation of dataprint ("The standard deviation of data is : ",end="")print (statistics.stdev(li)) # using pstdev to calculate population standard deviation of dataprint ("The population standard deviation of data is : ",end="")print (statistics.pstdev(li))
Output:
The standard deviation of data is : 0.816496580927726
The population standard deviation of data is : 0.7453559924999299
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=hxkBmeFTGzA" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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 String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 24286,
"s": 24258,
"text": "\n10 Feb, 2020"
},
{
"code": null,
"e": 24368,
"s": 24286,
"text": "Statistical Functions in Python | Set 1(Averages and Measure of Central Location)"
},
{
"code": null,
"e": 24441,
"s": 24368,
"text": "Measure of spread functions of statistics are discussed in this article."
},
{
"code": null,
"e": 24735,
"s": 24441,
"text": "1. variance() :- This function calculates the variance i.e measure of deviation of data, more the value of variance, more the data values are spread. Sample variance is computed in this function, assuming data is of a part of population. If passed argument is empty, StatisticsError is raised."
},
{
"code": null,
"e": 24929,
"s": 24735,
"text": "2. pvariance() :- This function computes the variance of the entire population. The data is interpreted as it is of the whole population. If passed argument is empty, StatisticsError is raised."
},
{
"code": "# Python code to demonstrate the working of # variance() and pvariance() # importing statistics to handle statistical operationsimport statistics # initializing listli = [1.5, 2.5, 2.5, 3.5, 3.5, 3.5] # using variance to calculate variance of dataprint (\"The variance of data is : \",end=\"\")print (statistics.variance(li)) # using pvariance to calculate population variance of dataprint (\"The population variance of data is : \",end=\"\")print (statistics.pvariance(li))",
"e": 25400,
"s": 24929,
"text": null
},
{
"code": null,
"e": 25408,
"s": 25400,
"text": "Output:"
},
{
"code": null,
"e": 25510,
"s": 25408,
"text": "The variance of data is : 0.6666666666666667\nThe population variance of data is : 0.5555555555555556\n"
},
{
"code": null,
"e": 25673,
"s": 25510,
"text": "3. stdev() :- This function returns the standard deviation ( square root of sample variance ) of the data. If passed argument is empty, StatisticsError is raised."
},
{
"code": null,
"e": 25852,
"s": 25673,
"text": "4. pstdev() :- This function returns the population standard deviation ( square root of population variance ) of the data. If passed argument is empty, StatisticsError is raised."
},
{
"code": "# Python code to demonstrate the working of # stdev() and pstdev() # importing statistics to handle statistical operationsimport statistics # initializing listli = [1.5, 2.5, 2.5, 3.5, 3.5, 3.5] # using stdev to calculate standard deviation of dataprint (\"The standard deviation of data is : \",end=\"\")print (statistics.stdev(li)) # using pstdev to calculate population standard deviation of dataprint (\"The population standard deviation of data is : \",end=\"\")print (statistics.pstdev(li))",
"e": 26345,
"s": 25852,
"text": null
},
{
"code": null,
"e": 26353,
"s": 26345,
"text": "Output:"
},
{
"code": null,
"e": 26474,
"s": 26353,
"text": "The standard deviation of data is : 0.816496580927726\nThe population standard deviation of data is : 0.7453559924999299\n"
},
{
"code": null,
"e": 26766,
"s": 26474,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=hxkBmeFTGzA\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 27067,
"s": 26766,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27192,
"s": 27067,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27199,
"s": 27192,
"text": "Python"
},
{
"code": null,
"e": 27297,
"s": 27199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27306,
"s": 27297,
"text": "Comments"
},
{
"code": null,
"e": 27319,
"s": 27306,
"text": "Old Comments"
},
{
"code": null,
"e": 27337,
"s": 27319,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27372,
"s": 27337,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27394,
"s": 27372,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27426,
"s": 27394,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27456,
"s": 27426,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27498,
"s": 27456,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27524,
"s": 27498,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27567,
"s": 27524,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27611,
"s": 27567,
"text": "Reading and Writing to text files in Python"
}
] |
Deep Reinforcement Learning for Video Games Made Easy | by Andreas Holm Nielsen | Towards Data Science
|
In this post, we will investigate how easily we can train a Deep Q-Network (DQN) agent (Mnih et al., 2015) for Atari 2600 games using the Google reinforcement learning library Dopamine. While many RL libraries exist, this library is specifically designed with four essential features in mind:
Easy experimentation
Flexible development
Compact and reliable
Reproducible
We believe these principles makes Dopamine one of the best RL learning environment available today. Additionally, we even got the library to work on Windows, which we think is quite a feat!
In my view, the visualization of any trained RL agent is an absolute must in reinforcement learning! Therefore, we will (of course) include this for our own trained agent at the very end!
We will go through all the pieces of code required (which is minimal compared to other libraries), but you can also find all scripts needed in the following Github repo.
The general premise of deep reinforcement learning is to
“derive efficient representations of the environment from high-dimensional sensory inputs, and use these to generalize past experience to new situations.”
- Mnih et al. (2015)
As stated earlier, we will implement the DQN model by Deepmind, which only uses raw pixels and game score as input. The raw pixels are processed using convolutional neural networks similar to image classification. The primary difference lies in the objective function, which for the DQN agent is called the optimal action-value function
where rt is the maximum sum of rewards at time t discounted by γ, obtained using a behavior policy π = P(a∣s) for each observation-action pair.
There are relatively many details to Deep Q-Learning, such as Experience Replay (Lin, 1993) and an iterative update rule. Thus, we refer the reader to the original paper for an excellent walk-through of the mathematical details.
One key benefit of DQN compared to previous approaches at the time (2015) was the ability to outperform existing methods for Atari 2600 games using the same set of hyperparameters and only pixel values and game score as input, clearly a tremendous achievement.
This post does not include instructions for installing Tensorflow, but we do want to stress that you can use both the CPU and GPU versions.
Nevertheless, assuming you are using Python 3.7.x, these are the libraries you need to install (which can all be installed via pip):
tensorflow-gpu=1.15 (or tensorflow==1.15 for CPU version)cmakedopamine-rlatari-pymatplotlibpygameseabornpandas
Hyperparameter tuning for Deep Reinforcement Learning requires a significant amount of compute resources and therefore considered out of scope for this guide. Luckily, the authors of Dopamine have provided the specific hyperparameters used in Bellemare et al. (2017), which can be found in the following file. We use the contents of this “config file” as a string that we parse using the gin configuration framework. It contains all relevant training, environment, and hyperparameters needed, meaning we only need to update which game we want to run (although the hyperparameters might not work out equally well for all games).
We start by importing the required libraries
import osimport gin.tffrom dopamine.discrete_domains import run_experiment
Next, we define the root path to save our experiments
DQN_PATH = '/tmp/path/to/save/experiments/dqn'
Then, we define the game we want to run (in this instance we run the game “Pong”),
GAME = 'Pong'
And finally, we define the DQN config string:
dqn_config = """# Hyperparameters used for reporting DQN results in Bellemare et al. (2017).import dopamine.discrete_domains.atari_libimport dopamine.discrete_domains.run_experimentimport dopamine.agents.dqn.dqn_agentimport dopamine.replay_memory.circular_replay_bufferimport gin.tf.external_configurablesDQNAgent.gamma = 0.99DQNAgent.update_horizon = 1DQNAgent.min_replay_history = 50000 # agent stepsDQNAgent.update_period = 4DQNAgent.target_update_period = 10000 # agent stepsDQNAgent.epsilon_train = 0.01DQNAgent.epsilon_eval = 0.001DQNAgent.epsilon_decay_period = 1000000 # agent stepsDQNAgent.tf_device = '/gpu:0' # use '/cpu:*' for non-GPU versionDQNAgent.optimizer = @tf.train.RMSPropOptimizer()tf.train.RMSPropOptimizer.learning_rate = 0.00025tf.train.RMSPropOptimizer.decay = 0.95tf.train.RMSPropOptimizer.momentum = 0.0tf.train.RMSPropOptimizer.epsilon = 0.00001tf.train.RMSPropOptimizer.centered = Trueatari_lib.create_atari_environment.game_name = "{}"# Deterministic ALE version used in the DQN Nature paper (Mnih et al., 2015).atari_lib.create_atari_environment.sticky_actions = Falsecreate_agent.agent_name = 'dqn'Runner.num_iterations = 200 # 200Runner.training_steps = 250000 # 250000 # agent stepsRunner.evaluation_steps = 125000 # 125000 # agent stepsRunner.max_steps_per_episode = 27000 # 27000 # agent stepsAtariPreprocessing.terminal_on_life_loss = TrueWrappedReplayBuffer.replay_capacity = 1000000WrappedReplayBuffer.batch_size = 32""".format(GAME)
And that is basically it!
Now, we just write the final code for training our agent,
Run the above (which will take a long time!), and you should see the DQN model crushing the Pong game!
We ran the experiment for roughly 22 hours on a GTX 1070 GPU. We include a visualization of the optimization results and the “live” performance of our Pong agent. We divide this into two sections:
Navigate to the tensorboard logs folder, which can be found inside the DQN_PATH that you defined earlier, and run the following:
tensorboard --logdir .
This should give you a visualization similar to this
You can see performance only gradually increases after 12 runs.
Now for the fun part!
We will use the example_vis_lib script located in the utils folder of the Dopamine library. Hence, our script for running the live demonstration looks as follows:
Run the above, and you should see the script starting to generate images for 1000 steps and then save the images into a video.mp4 file.
Here is a gif of our model:
Clearly, the agent is not perfect and does lose quite a few games. Still, it does a relatively good job!
We could probably get a close-to-perfect agent if we trained it for a few more days (or use a bigger GPU).
And there you have it!
That is essentially how little code we actually need to implement a state-of-the-art DQN model for running Atari 2600 games with a live demonstration!
Feel free to experiment with the significantly better Rainbow model (Hessel et al., 2018), which is also included in the Dopamine library, as well as other non-Atari games!
As a final demonstration, we include a small gif of an agent trained for two days for Atari Breakout using the Rainbow model:
You can see the Rainbow model is performing extremely well!
[1] Long-Ji Lin, Reinforcement learning for robots using neural networks (1993), No. CMU-CS-93–103.
[2] M. Hessel, et al., Rainbow: Combining improvements in deep reinforcement learning (2018), Thirty-Second AAAI Conference on Artificial Intelligence.
[3] P. S. Castro, S. Moitra, C. Gelada, S. Kumar, and M. G. Bellemare, Dopamine: A research framework for deep reinforcement learning (2018), arXiv preprint arXiv:1812.06110.
[4] V. Mnih, et al., (2015), Human-level control through deep reinforcement learning, Nature 518.7540 (529–533).
Originally published at https://holmdk.github.io on July 22, 2020.
|
[
{
"code": null,
"e": 465,
"s": 172,
"text": "In this post, we will investigate how easily we can train a Deep Q-Network (DQN) agent (Mnih et al., 2015) for Atari 2600 games using the Google reinforcement learning library Dopamine. While many RL libraries exist, this library is specifically designed with four essential features in mind:"
},
{
"code": null,
"e": 486,
"s": 465,
"text": "Easy experimentation"
},
{
"code": null,
"e": 507,
"s": 486,
"text": "Flexible development"
},
{
"code": null,
"e": 528,
"s": 507,
"text": "Compact and reliable"
},
{
"code": null,
"e": 541,
"s": 528,
"text": "Reproducible"
},
{
"code": null,
"e": 731,
"s": 541,
"text": "We believe these principles makes Dopamine one of the best RL learning environment available today. Additionally, we even got the library to work on Windows, which we think is quite a feat!"
},
{
"code": null,
"e": 919,
"s": 731,
"text": "In my view, the visualization of any trained RL agent is an absolute must in reinforcement learning! Therefore, we will (of course) include this for our own trained agent at the very end!"
},
{
"code": null,
"e": 1089,
"s": 919,
"text": "We will go through all the pieces of code required (which is minimal compared to other libraries), but you can also find all scripts needed in the following Github repo."
},
{
"code": null,
"e": 1146,
"s": 1089,
"text": "The general premise of deep reinforcement learning is to"
},
{
"code": null,
"e": 1301,
"s": 1146,
"text": "“derive efficient representations of the environment from high-dimensional sensory inputs, and use these to generalize past experience to new situations.”"
},
{
"code": null,
"e": 1322,
"s": 1301,
"text": "- Mnih et al. (2015)"
},
{
"code": null,
"e": 1659,
"s": 1322,
"text": "As stated earlier, we will implement the DQN model by Deepmind, which only uses raw pixels and game score as input. The raw pixels are processed using convolutional neural networks similar to image classification. The primary difference lies in the objective function, which for the DQN agent is called the optimal action-value function"
},
{
"code": null,
"e": 1803,
"s": 1659,
"text": "where rt is the maximum sum of rewards at time t discounted by γ, obtained using a behavior policy π = P(a∣s) for each observation-action pair."
},
{
"code": null,
"e": 2032,
"s": 1803,
"text": "There are relatively many details to Deep Q-Learning, such as Experience Replay (Lin, 1993) and an iterative update rule. Thus, we refer the reader to the original paper for an excellent walk-through of the mathematical details."
},
{
"code": null,
"e": 2293,
"s": 2032,
"text": "One key benefit of DQN compared to previous approaches at the time (2015) was the ability to outperform existing methods for Atari 2600 games using the same set of hyperparameters and only pixel values and game score as input, clearly a tremendous achievement."
},
{
"code": null,
"e": 2433,
"s": 2293,
"text": "This post does not include instructions for installing Tensorflow, but we do want to stress that you can use both the CPU and GPU versions."
},
{
"code": null,
"e": 2566,
"s": 2433,
"text": "Nevertheless, assuming you are using Python 3.7.x, these are the libraries you need to install (which can all be installed via pip):"
},
{
"code": null,
"e": 2680,
"s": 2566,
"text": "tensorflow-gpu=1.15 (or tensorflow==1.15 for CPU version)cmakedopamine-rlatari-pymatplotlibpygameseabornpandas"
},
{
"code": null,
"e": 3308,
"s": 2680,
"text": "Hyperparameter tuning for Deep Reinforcement Learning requires a significant amount of compute resources and therefore considered out of scope for this guide. Luckily, the authors of Dopamine have provided the specific hyperparameters used in Bellemare et al. (2017), which can be found in the following file. We use the contents of this “config file” as a string that we parse using the gin configuration framework. It contains all relevant training, environment, and hyperparameters needed, meaning we only need to update which game we want to run (although the hyperparameters might not work out equally well for all games)."
},
{
"code": null,
"e": 3353,
"s": 3308,
"text": "We start by importing the required libraries"
},
{
"code": null,
"e": 3428,
"s": 3353,
"text": "import osimport gin.tffrom dopamine.discrete_domains import run_experiment"
},
{
"code": null,
"e": 3482,
"s": 3428,
"text": "Next, we define the root path to save our experiments"
},
{
"code": null,
"e": 3529,
"s": 3482,
"text": "DQN_PATH = '/tmp/path/to/save/experiments/dqn'"
},
{
"code": null,
"e": 3612,
"s": 3529,
"text": "Then, we define the game we want to run (in this instance we run the game “Pong”),"
},
{
"code": null,
"e": 3626,
"s": 3612,
"text": "GAME = 'Pong'"
},
{
"code": null,
"e": 3672,
"s": 3626,
"text": "And finally, we define the DQN config string:"
},
{
"code": null,
"e": 5154,
"s": 3672,
"text": "dqn_config = \"\"\"# Hyperparameters used for reporting DQN results in Bellemare et al. (2017).import dopamine.discrete_domains.atari_libimport dopamine.discrete_domains.run_experimentimport dopamine.agents.dqn.dqn_agentimport dopamine.replay_memory.circular_replay_bufferimport gin.tf.external_configurablesDQNAgent.gamma = 0.99DQNAgent.update_horizon = 1DQNAgent.min_replay_history = 50000 # agent stepsDQNAgent.update_period = 4DQNAgent.target_update_period = 10000 # agent stepsDQNAgent.epsilon_train = 0.01DQNAgent.epsilon_eval = 0.001DQNAgent.epsilon_decay_period = 1000000 # agent stepsDQNAgent.tf_device = '/gpu:0' # use '/cpu:*' for non-GPU versionDQNAgent.optimizer = @tf.train.RMSPropOptimizer()tf.train.RMSPropOptimizer.learning_rate = 0.00025tf.train.RMSPropOptimizer.decay = 0.95tf.train.RMSPropOptimizer.momentum = 0.0tf.train.RMSPropOptimizer.epsilon = 0.00001tf.train.RMSPropOptimizer.centered = Trueatari_lib.create_atari_environment.game_name = \"{}\"# Deterministic ALE version used in the DQN Nature paper (Mnih et al., 2015).atari_lib.create_atari_environment.sticky_actions = Falsecreate_agent.agent_name = 'dqn'Runner.num_iterations = 200 # 200Runner.training_steps = 250000 # 250000 # agent stepsRunner.evaluation_steps = 125000 # 125000 # agent stepsRunner.max_steps_per_episode = 27000 # 27000 # agent stepsAtariPreprocessing.terminal_on_life_loss = TrueWrappedReplayBuffer.replay_capacity = 1000000WrappedReplayBuffer.batch_size = 32\"\"\".format(GAME)"
},
{
"code": null,
"e": 5180,
"s": 5154,
"text": "And that is basically it!"
},
{
"code": null,
"e": 5238,
"s": 5180,
"text": "Now, we just write the final code for training our agent,"
},
{
"code": null,
"e": 5341,
"s": 5238,
"text": "Run the above (which will take a long time!), and you should see the DQN model crushing the Pong game!"
},
{
"code": null,
"e": 5538,
"s": 5341,
"text": "We ran the experiment for roughly 22 hours on a GTX 1070 GPU. We include a visualization of the optimization results and the “live” performance of our Pong agent. We divide this into two sections:"
},
{
"code": null,
"e": 5667,
"s": 5538,
"text": "Navigate to the tensorboard logs folder, which can be found inside the DQN_PATH that you defined earlier, and run the following:"
},
{
"code": null,
"e": 5690,
"s": 5667,
"text": "tensorboard --logdir ."
},
{
"code": null,
"e": 5743,
"s": 5690,
"text": "This should give you a visualization similar to this"
},
{
"code": null,
"e": 5807,
"s": 5743,
"text": "You can see performance only gradually increases after 12 runs."
},
{
"code": null,
"e": 5829,
"s": 5807,
"text": "Now for the fun part!"
},
{
"code": null,
"e": 5992,
"s": 5829,
"text": "We will use the example_vis_lib script located in the utils folder of the Dopamine library. Hence, our script for running the live demonstration looks as follows:"
},
{
"code": null,
"e": 6128,
"s": 5992,
"text": "Run the above, and you should see the script starting to generate images for 1000 steps and then save the images into a video.mp4 file."
},
{
"code": null,
"e": 6156,
"s": 6128,
"text": "Here is a gif of our model:"
},
{
"code": null,
"e": 6261,
"s": 6156,
"text": "Clearly, the agent is not perfect and does lose quite a few games. Still, it does a relatively good job!"
},
{
"code": null,
"e": 6368,
"s": 6261,
"text": "We could probably get a close-to-perfect agent if we trained it for a few more days (or use a bigger GPU)."
},
{
"code": null,
"e": 6391,
"s": 6368,
"text": "And there you have it!"
},
{
"code": null,
"e": 6542,
"s": 6391,
"text": "That is essentially how little code we actually need to implement a state-of-the-art DQN model for running Atari 2600 games with a live demonstration!"
},
{
"code": null,
"e": 6715,
"s": 6542,
"text": "Feel free to experiment with the significantly better Rainbow model (Hessel et al., 2018), which is also included in the Dopamine library, as well as other non-Atari games!"
},
{
"code": null,
"e": 6841,
"s": 6715,
"text": "As a final demonstration, we include a small gif of an agent trained for two days for Atari Breakout using the Rainbow model:"
},
{
"code": null,
"e": 6901,
"s": 6841,
"text": "You can see the Rainbow model is performing extremely well!"
},
{
"code": null,
"e": 7001,
"s": 6901,
"text": "[1] Long-Ji Lin, Reinforcement learning for robots using neural networks (1993), No. CMU-CS-93–103."
},
{
"code": null,
"e": 7153,
"s": 7001,
"text": "[2] M. Hessel, et al., Rainbow: Combining improvements in deep reinforcement learning (2018), Thirty-Second AAAI Conference on Artificial Intelligence."
},
{
"code": null,
"e": 7328,
"s": 7153,
"text": "[3] P. S. Castro, S. Moitra, C. Gelada, S. Kumar, and M. G. Bellemare, Dopamine: A research framework for deep reinforcement learning (2018), arXiv preprint arXiv:1812.06110."
},
{
"code": null,
"e": 7441,
"s": 7328,
"text": "[4] V. Mnih, et al., (2015), Human-level control through deep reinforcement learning, Nature 518.7540 (529–533)."
}
] |
Select and add result of multiplying two columns from a table in MySQL?
|
You can use aggregate function SUM() for this. Let us first create a table −
mysql> create table DemoTable
(
CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
CustomerProductName varchar(100),
CustomerProductQuantity int,
CustomerPrice int
);
Query OK, 0 rows affected (0.17 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,400);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',3,100);
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',2,300);
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,50);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-3',6,10);
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',10,20);
Query OK, 1 row affected (0.03 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------+---------------------+-------------------------+---------------+
| CustomerId | CustomerProductName | CustomerProductQuantity | CustomerPrice |
+------------+---------------------+-------------------------+---------------+
| 1 | Product-1 | 5 | 400 |
| 2 | Product-2 | 3 | 100 |
| 3 | Product-1 | 2 | 300 |
| 4 | Product-1 | 5 | 50 |
| 5 | Product-3 | 6 | 10 |
| 6 | Product-2 | 10 | 20 |
+------------+---------------------+-------------------------+---------------+
6 rows in set (0.00 sec)
Following is the query to select and add result of multiplying two columns (CustomerProductQuantity*CustomerPrice) from a table in MySQL.
mysql> select CustomerProductName,
SUM(CustomerProductQuantity*CustomerPrice) AS TOTAL_PRICE
from DemoTable
group by CustomerProductName;
This will produce the following output −
+---------------------+-------------+
| CustomerProductName | TOTAL_PRICE |
+---------------------+-------------+
| Product-1 | 2850 |
| Product-2 | 500 |
| Product-3 | 60 |
+---------------------+-------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "You can use aggregate function SUM() for this. Let us first create a table −"
},
{
"code": null,
"e": 1362,
"s": 1139,
"text": "mysql> create table DemoTable\n (\n CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n CustomerProductName varchar(100),\n CustomerProductQuantity int,\n CustomerPrice int\n );\nQuery OK, 0 rows affected (0.17 sec)"
},
{
"code": null,
"e": 1418,
"s": 1362,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2327,
"s": 1418,
"text": "mysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,400);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',3,100);\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',2,300);\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-1',5,50);\nQuery OK, 1 row affected (0.08 sec)\n\nmysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-3',6,10);\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(CustomerProductName,CustomerProductQuantity,CustomerPrice) values('Product-2',10,20);\nQuery OK, 1 row affected (0.03 sec)"
},
{
"code": null,
"e": 2387,
"s": 2327,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2418,
"s": 2387,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2459,
"s": 2418,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3274,
"s": 2459,
"text": "+------------+---------------------+-------------------------+---------------+\n| CustomerId | CustomerProductName | CustomerProductQuantity | CustomerPrice |\n+------------+---------------------+-------------------------+---------------+\n| 1 | Product-1 | 5 | 400 |\n| 2 | Product-2 | 3 | 100 |\n| 3 | Product-1 | 2 | 300 |\n| 4 | Product-1 | 5 | 50 |\n| 5 | Product-3 | 6 | 10 |\n| 6 | Product-2 | 10 | 20 |\n+------------+---------------------+-------------------------+---------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3412,
"s": 3274,
"text": "Following is the query to select and add result of multiplying two columns (CustomerProductQuantity*CustomerPrice) from a table in MySQL."
},
{
"code": null,
"e": 3550,
"s": 3412,
"text": "mysql> select CustomerProductName,\nSUM(CustomerProductQuantity*CustomerPrice) AS TOTAL_PRICE\nfrom DemoTable\ngroup by CustomerProductName;"
},
{
"code": null,
"e": 3591,
"s": 3550,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3882,
"s": 3591,
"text": "+---------------------+-------------+\n| CustomerProductName | TOTAL_PRICE |\n+---------------------+-------------+\n| Product-1 | 2850 |\n| Product-2 | 500 |\n| Product-3 | 60 |\n+---------------------+-------------+\n3 rows in set (0.00 sec)"
}
] |
Ext.js - Yes NO Cancel Box
|
This is like a confirm box which asks the user for some confirmation, such as whether the user wants to do the task or decline or cancel the task. Based on the user selection different methods get called.
Following is a simple syntax.
Ext.MessageBox.show ({
title: 'Details',
msg: 'Please enter your details:',
width:300,
buttons: Ext.MessageBox.YESNOCANCEL
// this button property for all three options YES, NO, Cancel.
});
Following is a simple example showing the usage.
<!DOCTYPE html>
<html>
<head>
<link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css"
rel = "stylesheet" />
<script type = "text/javascript"
src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
<script type = "text/javascript">
Ext.onReady(function() {
Ext.create('Ext.Button', {
renderTo: Ext.getElementById('msgBox'),
text: 'Click Me',
listeners: {
click: function() {
Ext.MessageBox.show ({
title: 'Details',
msg: 'Please enter your details:',
width:300,
buttons: Ext.MessageBox.YESNOCANCEL,
multiline: true,
fn: callbackFunction
});
function callbackFunction() {
Ext.Msg.alert('status', 'Details entered succesfully');
}
}
}
});
});
</script>
</head>
<body>
<p> Click the button for alert box </p>
<div id = "msgBox" ></div>
</body>
</html>
The above program will produce the following result −
Click the button for alert box
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2228,
"s": 2023,
"text": "This is like a confirm box which asks the user for some confirmation, such as whether the user wants to do the task or decline or cancel the task. Based on the user selection different methods get called."
},
{
"code": null,
"e": 2258,
"s": 2228,
"text": "Following is a simple syntax."
},
{
"code": null,
"e": 2467,
"s": 2258,
"text": "Ext.MessageBox.show ({\n title: 'Details',\n msg: 'Please enter your details:',\n width:300,\n buttons: Ext.MessageBox.YESNOCANCEL \n // this button property for all three options YES, NO, Cancel.\n});\n"
},
{
"code": null,
"e": 2516,
"s": 2467,
"text": "Following is a simple example showing the usage."
},
{
"code": null,
"e": 3837,
"s": 2516,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <link href = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css\" \n rel = \"stylesheet\" />\n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js\"></script>\n \n <script type = \"text/javascript\">\n Ext.onReady(function() {\n Ext.create('Ext.Button', {\n renderTo: Ext.getElementById('msgBox'),\n text: 'Click Me',\n \n listeners: {\n click: function() {\n Ext.MessageBox.show ({\n title: 'Details',\n msg: 'Please enter your details:',\n width:300,\n buttons: Ext.MessageBox.YESNOCANCEL,\n multiline: true,\n fn: callbackFunction\n });\n function callbackFunction() {\n Ext.Msg.alert('status', 'Details entered succesfully');\n }\n }\n }\n });\n });\n </script>\n </head>\n \n <body>\n <p> Click the button for alert box </p>\n <div id = \"msgBox\" ></div>\n </body>\n</html>"
},
{
"code": null,
"e": 3891,
"s": 3837,
"text": "The above program will produce the following result −"
},
{
"code": null,
"e": 3924,
"s": 3891,
"text": " Click the button for alert box "
},
{
"code": null,
"e": 3931,
"s": 3924,
"text": " Print"
},
{
"code": null,
"e": 3942,
"s": 3931,
"text": " Add Notes"
}
] |
How to Scrape Tweets From Twitter | by Martin Beck | Towards Data Science
|
Social media can be a gold mine of data in regards to consumer sentiment. Platforms such as Twitter lend themselves to holding useful information since users may post unfiltered opinions that are able to be retrieved with ease. Combining this with other internal company information can help with providing insight into the general sentiment people may have in regards to companies, products, etc.
This tutorial is meant to be a quick straightforward introduction to scraping tweets from Twitter in Python using Tweepy’s Twitter API or Dmitry Mottl’s GetOldTweets3. To provide direction for this tutorial I decided to focus on scraping through two avenues: scraping a specific user’s tweets and scraping tweets from a general text search.
Due to the interest in a non-coding solution for scraping tweets, my team is creating an application to fulfill that need. Yes, that means you don’t have to code to scrape data! We are currently in Alpha testing for our app Socialscrapr. If you want to participate or be contacted when the next testing phase is open please sign up for our mailing list below!
Thank you for signing up! Look out for future emails for updates!
Before we get to the actual scraping it is important to understand what both of these libraries offer, so let’s breakdown the differences between the two to help you decide which one to use.
Tweepy is a Python library for accessing the Twitter API. There are several different types and levels of API access that Tweepy offers as shown here, but those are for very specific use cases. Tweepy is able to accomplish various tasks beyond just querying tweets as shown in the following picture. For the sake of relevancy, we will only focus on using this API to scrape tweets.
There are limitations in using Tweepy for scraping tweets. The standard API only allows you to retrieve tweets up to 7 days ago and is limited to scraping 18,000 tweets per a 15 minute window. However, it is possible to increase this limit as shown here. Also, using Tweepy you’re only able to return up to 3,200 of a user’s most recent tweets. Using Tweepy is great for someone who is trying to make use of Twitter’s other functionality, making complex queries, or wants the most extensive information provided for each tweet.
UPDATE: DUE TO CHANGES IN TWITTER’S API GETOLDTWEETS3 IS NO LONGER FUNCTIONING. SNSCRAPE HAS BECOME A SUBSTITUTE AS A FREE LIBRARY YOU CAN USE TO SCRAPE BEYOND TWEEPY’S FREE LIMITATIONS. MY ARTICLE IS AVAILABLE HERE FOR SNSCRAPE.
GetOldTweets3 was created by Dmitry Mottl and is an improvement fork of Jefferson Henrqiue’s GetOldTweets-python. It does not offer any of the other functionality that Tweepy has, but instead only focuses on querying tweets and does not have the same search limitations of Tweepy. This package allows you to retrieve a larger amount of tweets and tweets older than a week. However, it does not provide the extent of information that Tweepy has. The picture below shows all the information that is retrievable from tweets using this package. It is also worth noting that as of now, there is an open issue with accessing the geo data from a tweet using GetOldTweets3.
Using GetOldTweets3 is a great option for someone who’s looking for a quick no-frills way of scraping, or wants to work around the standard Tweepy API search limitations to scrape larger amount of tweets or tweets older than a week.
While they focus on very different things, both options are most likely sufficient for the bulk of what most people normally scrape for. It’s not until one is scraping with specific purposes in mind should one really have to choose between using either option.
Alright, enough with the explanations. This is a scraping tutorial so let’s jump into the coding.
UPDATE: I’ve written a follow-up article that does a deeper dive into how to pull more information from tweets like user information and refining queries for tweets such as searching for tweets by location. If you read this section and decide you need more, my follow-up article is available here.
The Jupyter Notebooks for the following section are available on my GitHub here. I created functions around exporting CSV files from these example queries.
There are two parts to scraping with Tweepy because it requires Twitter developer credentials. If you already have credentials from a previous project then you can ignore this section.
In order to receive credentials, you must apply to become a Twitter developer here. This does require that you have a Twitter account. The application will ask various questions about what sort of work you want to do. Don’t fret, these details don’t have to be extensive, and the process is relatively easy.
After finishing the application, the approval process is relatively quick and shouldn’t take longer than a couple of days. Upon being approved you will need to log in and set up a dev environment in the developer dashboard and view that app’s details to retrieve your developer credentials as shown in the below picture. Unless you specifically have requested access to the other API’s offered, you will now be able to use the standard Tweepy API.
Great, you have your Twitter Developer credentials and can finally get started scraping some tweets.
Setting up Tweepy authorization:
Before getting started you Tweepy will have to authorize that you have the credentials to utilize its API. The following code snippet is how one authorizes themself.
consumer_key = "XXXXXXXXX"consumer_secret = "XXXXXXXXX"access_token = "XXXXXXXXX"access_token_secret = "XXXXXXXXX"auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth,wait_on_rate_limit=True)
Scraping a specific Twitter user’s Tweets:
The search parameters I focused on are id and count. Id is the specific Twitter user’s @ username, and count is the max amount of most recent tweets you want to scrape from the specific user’s timeline. In this example, I use the Twitter CEO's @jack username and chose to scrape 100 of his most recent tweets. Most of the scraping code is relatively quick and straight forward.
username = 'jack'count = 150try: # Creation of query method using parameters tweets = tweepy.Cursor(api.user_timeline,id=username).items(count) # Pulling information from tweets iterable object tweets_list = [[tweet.created_at, tweet.id, tweet.text] for tweet in tweets] # Creation of dataframe from tweets list # Add or remove columns as you remove tweet information tweets_df = pd.DataFrame(tweets_list)except BaseException as e: print('failed on_status,',str(e)) time.sleep(3)
If you want to further customize your search you can view the rest of the search parameters available in the api.user_timeline method here.
Scraping tweets from a text search query:
The search parameters I focused on are q and count. q is supposed to be the text search query you want to search with, and count is again the max amount of most recent tweets you want to scrape from this specific search query. In this example, I scrape the 100 of the most recent tweets that were relevant to the 2020 US Election.
text_query = '2020 US Election'count = 150try: # Creation of query method using parameters tweets = tweepy.Cursor(api.search,q=text_query).items(count) # Pulling information from tweets iterable object tweets_list = [[tweet.created_at, tweet.id, tweet.text] for tweet in tweets] # Creation of dataframe from tweets list # Add or remove columns as you remove tweet information tweets_df = pd.DataFrame(tweets_list) except BaseException as e: print('failed on_status,',str(e)) time.sleep(3)
If you want to further customize your search you can view the rest of the search parameters available in the api.search method here.
What other information from the tweet is accessible?
One of the advantages of querying with Tweepy is the amount of information contained in the tweet object. If you’re interested in grabbing other information than what I chose in this tutorial you can view the full list of information available in Tweepy’s tweet object here. To show how easy it is to grab more information, in the following example I created a list of tweets with the following information: when it was created, the tweet id, the tweet text, the user the tweet is associated with, and how many favorites the tweet had at the time it was retrieved.
tweets = tweepy.Cursor(api.search, q=text_query).items(count)# Pulling information from tweets iterable tweets_list = [[tweet.created_at, tweet.id, tweet.text, tweet.user, tweet.favorite_count] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(tweets_list)
UPDATE: DUE TO CHANGES IN TWITTER’S API GETOLDTWEETS3 IS NO LONGER FUNCTIONING. SNSCRAPE HAS BECOME A SUBSTITUTE AS A FREE LIBRARY YOU CAN USE TO SCRAPE BEYOND TWEEPY’S FREE LIMITATIONS. MY ARTICLE IS AVAILABLE HERE FOR SNSCRAPE.
Using GetOldTweets3 does not require any authorization like Tweepy does, you just need to pip install the library and can get started right away.
Scraping a specific Twitter user’s Tweets:
The two variables I focused on are username and count. In this example, we scrape tweets from a specific user using the setUsername method and setting the amount of most recent tweets to view using setMaxTweets.
username = 'jack'count = 2000# Creation of query objecttweetCriteria = got.manager.TweetCriteria().setUsername(username)\ .setMaxTweets(count)# Creation of list that contains all tweetstweets = got.manager.TweetManager.getTweets(tweetCriteria)# Creating list of chosen tweet datauser_tweets = [[tweet.date, tweet.text] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(user_tweets)
Scraping tweets from a text search query:
The two variables I focused on are text_query and count. In this example, we scrape tweets found from a text query by using the setQuerySearch method.
text_query = 'USA Election 2020'count = 2000# Creation of query objecttweetCriteria = got.manager.TweetCriteria().setQuerySearch(text_query)\ .setMaxTweets(count)# Creation of list that contains all tweetstweets = got.manager.TweetManager.getTweets(tweetCriteria)# Creating list of chosen tweet datatext_tweets = [[tweet.date, tweet.text] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(text_tweets)
Queries can be further customized by combining TweetCriteria search parameters. All the current search parameters available are shown below.
Example of a query using several search parameters:
The following stacked query will return 2,000 tweets relevant to USA Election 2020 that were tweeted between January 1st 2019 and October 31st 2019.
text_query = 'USA Election 2020'since_date = '2019-01-01'until_date = '2019-10-31'count = 2000# Creation of query objecttweetCriteria = got.manager.TweetCriteria().setQuerySearch(text_query).setSince(since_date).setUntil(until_date).setMaxTweets(count)# Creation of list that contains all tweetstweets = got.manager.TweetManager.getTweets(tweetCriteria)# Creating list of chosen tweet datatext_tweets = [[tweet.date, tweet.text] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(text_tweets)
If you want to reach out don’t be afraid to connect with me on LinkedIn
If you’re interested, sign up for our Socialscrapr mailing list: https://upscri.be/3kcmqx
My follow up article that does a deeper dive into both packages: https://towardsdatascience.com/how-to-scrape-more-information-from-tweets-on-twitter-44fd540b8a1f
snscrape article that helps setup and provides a couple of example queries: https://medium.com/better-programming/how-to-scrape-tweets-with-snscrape-90124ed006af
GitHub containing this tutorial’s Twitter scraper’s: https://github.com/MartinBeckUT/TwitterScraper/tree/master/BasicScraper
Increasing Tweepy’s standard API search limit: https://bhaskarvk.github.io/2015/01/how-to-use-twitters-search-rest-api-most-effectively./
Tweepy GitHub: https://github.com/tweepy/tweepy
GetOldTweets3 GitHub: https://github.com/Mottl/GetOldTweets3
|
[
{
"code": null,
"e": 570,
"s": 172,
"text": "Social media can be a gold mine of data in regards to consumer sentiment. Platforms such as Twitter lend themselves to holding useful information since users may post unfiltered opinions that are able to be retrieved with ease. Combining this with other internal company information can help with providing insight into the general sentiment people may have in regards to companies, products, etc."
},
{
"code": null,
"e": 911,
"s": 570,
"text": "This tutorial is meant to be a quick straightforward introduction to scraping tweets from Twitter in Python using Tweepy’s Twitter API or Dmitry Mottl’s GetOldTweets3. To provide direction for this tutorial I decided to focus on scraping through two avenues: scraping a specific user’s tweets and scraping tweets from a general text search."
},
{
"code": null,
"e": 1271,
"s": 911,
"text": "Due to the interest in a non-coding solution for scraping tweets, my team is creating an application to fulfill that need. Yes, that means you don’t have to code to scrape data! We are currently in Alpha testing for our app Socialscrapr. If you want to participate or be contacted when the next testing phase is open please sign up for our mailing list below!"
},
{
"code": null,
"e": 1337,
"s": 1271,
"text": "Thank you for signing up! Look out for future emails for updates!"
},
{
"code": null,
"e": 1528,
"s": 1337,
"text": "Before we get to the actual scraping it is important to understand what both of these libraries offer, so let’s breakdown the differences between the two to help you decide which one to use."
},
{
"code": null,
"e": 1910,
"s": 1528,
"text": "Tweepy is a Python library for accessing the Twitter API. There are several different types and levels of API access that Tweepy offers as shown here, but those are for very specific use cases. Tweepy is able to accomplish various tasks beyond just querying tweets as shown in the following picture. For the sake of relevancy, we will only focus on using this API to scrape tweets."
},
{
"code": null,
"e": 2438,
"s": 1910,
"text": "There are limitations in using Tweepy for scraping tweets. The standard API only allows you to retrieve tweets up to 7 days ago and is limited to scraping 18,000 tweets per a 15 minute window. However, it is possible to increase this limit as shown here. Also, using Tweepy you’re only able to return up to 3,200 of a user’s most recent tweets. Using Tweepy is great for someone who is trying to make use of Twitter’s other functionality, making complex queries, or wants the most extensive information provided for each tweet."
},
{
"code": null,
"e": 2668,
"s": 2438,
"text": "UPDATE: DUE TO CHANGES IN TWITTER’S API GETOLDTWEETS3 IS NO LONGER FUNCTIONING. SNSCRAPE HAS BECOME A SUBSTITUTE AS A FREE LIBRARY YOU CAN USE TO SCRAPE BEYOND TWEEPY’S FREE LIMITATIONS. MY ARTICLE IS AVAILABLE HERE FOR SNSCRAPE."
},
{
"code": null,
"e": 3334,
"s": 2668,
"text": "GetOldTweets3 was created by Dmitry Mottl and is an improvement fork of Jefferson Henrqiue’s GetOldTweets-python. It does not offer any of the other functionality that Tweepy has, but instead only focuses on querying tweets and does not have the same search limitations of Tweepy. This package allows you to retrieve a larger amount of tweets and tweets older than a week. However, it does not provide the extent of information that Tweepy has. The picture below shows all the information that is retrievable from tweets using this package. It is also worth noting that as of now, there is an open issue with accessing the geo data from a tweet using GetOldTweets3."
},
{
"code": null,
"e": 3567,
"s": 3334,
"text": "Using GetOldTweets3 is a great option for someone who’s looking for a quick no-frills way of scraping, or wants to work around the standard Tweepy API search limitations to scrape larger amount of tweets or tweets older than a week."
},
{
"code": null,
"e": 3828,
"s": 3567,
"text": "While they focus on very different things, both options are most likely sufficient for the bulk of what most people normally scrape for. It’s not until one is scraping with specific purposes in mind should one really have to choose between using either option."
},
{
"code": null,
"e": 3926,
"s": 3828,
"text": "Alright, enough with the explanations. This is a scraping tutorial so let’s jump into the coding."
},
{
"code": null,
"e": 4224,
"s": 3926,
"text": "UPDATE: I’ve written a follow-up article that does a deeper dive into how to pull more information from tweets like user information and refining queries for tweets such as searching for tweets by location. If you read this section and decide you need more, my follow-up article is available here."
},
{
"code": null,
"e": 4380,
"s": 4224,
"text": "The Jupyter Notebooks for the following section are available on my GitHub here. I created functions around exporting CSV files from these example queries."
},
{
"code": null,
"e": 4565,
"s": 4380,
"text": "There are two parts to scraping with Tweepy because it requires Twitter developer credentials. If you already have credentials from a previous project then you can ignore this section."
},
{
"code": null,
"e": 4873,
"s": 4565,
"text": "In order to receive credentials, you must apply to become a Twitter developer here. This does require that you have a Twitter account. The application will ask various questions about what sort of work you want to do. Don’t fret, these details don’t have to be extensive, and the process is relatively easy."
},
{
"code": null,
"e": 5321,
"s": 4873,
"text": "After finishing the application, the approval process is relatively quick and shouldn’t take longer than a couple of days. Upon being approved you will need to log in and set up a dev environment in the developer dashboard and view that app’s details to retrieve your developer credentials as shown in the below picture. Unless you specifically have requested access to the other API’s offered, you will now be able to use the standard Tweepy API."
},
{
"code": null,
"e": 5422,
"s": 5321,
"text": "Great, you have your Twitter Developer credentials and can finally get started scraping some tweets."
},
{
"code": null,
"e": 5455,
"s": 5422,
"text": "Setting up Tweepy authorization:"
},
{
"code": null,
"e": 5621,
"s": 5455,
"text": "Before getting started you Tweepy will have to authorize that you have the credentials to utilize its API. The following code snippet is how one authorizes themself."
},
{
"code": null,
"e": 5895,
"s": 5621,
"text": "consumer_key = \"XXXXXXXXX\"consumer_secret = \"XXXXXXXXX\"access_token = \"XXXXXXXXX\"access_token_secret = \"XXXXXXXXX\"auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth,wait_on_rate_limit=True)"
},
{
"code": null,
"e": 5938,
"s": 5895,
"text": "Scraping a specific Twitter user’s Tweets:"
},
{
"code": null,
"e": 6316,
"s": 5938,
"text": "The search parameters I focused on are id and count. Id is the specific Twitter user’s @ username, and count is the max amount of most recent tweets you want to scrape from the specific user’s timeline. In this example, I use the Twitter CEO's @jack username and chose to scrape 100 of his most recent tweets. Most of the scraping code is relatively quick and straight forward."
},
{
"code": null,
"e": 6813,
"s": 6316,
"text": "username = 'jack'count = 150try: # Creation of query method using parameters tweets = tweepy.Cursor(api.user_timeline,id=username).items(count) # Pulling information from tweets iterable object tweets_list = [[tweet.created_at, tweet.id, tweet.text] for tweet in tweets] # Creation of dataframe from tweets list # Add or remove columns as you remove tweet information tweets_df = pd.DataFrame(tweets_list)except BaseException as e: print('failed on_status,',str(e)) time.sleep(3)"
},
{
"code": null,
"e": 6953,
"s": 6813,
"text": "If you want to further customize your search you can view the rest of the search parameters available in the api.user_timeline method here."
},
{
"code": null,
"e": 6995,
"s": 6953,
"text": "Scraping tweets from a text search query:"
},
{
"code": null,
"e": 7326,
"s": 6995,
"text": "The search parameters I focused on are q and count. q is supposed to be the text search query you want to search with, and count is again the max amount of most recent tweets you want to scrape from this specific search query. In this example, I scrape the 100 of the most recent tweets that were relevant to the 2020 US Election."
},
{
"code": null,
"e": 7823,
"s": 7326,
"text": "text_query = '2020 US Election'count = 150try: # Creation of query method using parameters tweets = tweepy.Cursor(api.search,q=text_query).items(count) # Pulling information from tweets iterable object tweets_list = [[tweet.created_at, tweet.id, tweet.text] for tweet in tweets] # Creation of dataframe from tweets list # Add or remove columns as you remove tweet information tweets_df = pd.DataFrame(tweets_list) except BaseException as e: print('failed on_status,',str(e)) time.sleep(3)"
},
{
"code": null,
"e": 7956,
"s": 7823,
"text": "If you want to further customize your search you can view the rest of the search parameters available in the api.search method here."
},
{
"code": null,
"e": 8009,
"s": 7956,
"text": "What other information from the tweet is accessible?"
},
{
"code": null,
"e": 8574,
"s": 8009,
"text": "One of the advantages of querying with Tweepy is the amount of information contained in the tweet object. If you’re interested in grabbing other information than what I chose in this tutorial you can view the full list of information available in Tweepy’s tweet object here. To show how easy it is to grab more information, in the following example I created a list of tweets with the following information: when it was created, the tweet id, the tweet text, the user the tweet is associated with, and how many favorites the tweet had at the time it was retrieved."
},
{
"code": null,
"e": 8866,
"s": 8574,
"text": "tweets = tweepy.Cursor(api.search, q=text_query).items(count)# Pulling information from tweets iterable tweets_list = [[tweet.created_at, tweet.id, tweet.text, tweet.user, tweet.favorite_count] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(tweets_list)"
},
{
"code": null,
"e": 9096,
"s": 8866,
"text": "UPDATE: DUE TO CHANGES IN TWITTER’S API GETOLDTWEETS3 IS NO LONGER FUNCTIONING. SNSCRAPE HAS BECOME A SUBSTITUTE AS A FREE LIBRARY YOU CAN USE TO SCRAPE BEYOND TWEEPY’S FREE LIMITATIONS. MY ARTICLE IS AVAILABLE HERE FOR SNSCRAPE."
},
{
"code": null,
"e": 9242,
"s": 9096,
"text": "Using GetOldTweets3 does not require any authorization like Tweepy does, you just need to pip install the library and can get started right away."
},
{
"code": null,
"e": 9285,
"s": 9242,
"text": "Scraping a specific Twitter user’s Tweets:"
},
{
"code": null,
"e": 9497,
"s": 9285,
"text": "The two variables I focused on are username and count. In this example, we scrape tweets from a specific user using the setUsername method and setting the amount of most recent tweets to view using setMaxTweets."
},
{
"code": null,
"e": 9953,
"s": 9497,
"text": "username = 'jack'count = 2000# Creation of query objecttweetCriteria = got.manager.TweetCriteria().setUsername(username)\\ .setMaxTweets(count)# Creation of list that contains all tweetstweets = got.manager.TweetManager.getTweets(tweetCriteria)# Creating list of chosen tweet datauser_tweets = [[tweet.date, tweet.text] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(user_tweets)"
},
{
"code": null,
"e": 9995,
"s": 9953,
"text": "Scraping tweets from a text search query:"
},
{
"code": null,
"e": 10146,
"s": 9995,
"text": "The two variables I focused on are text_query and count. In this example, we scrape tweets found from a text query by using the setQuerySearch method."
},
{
"code": null,
"e": 10626,
"s": 10146,
"text": "text_query = 'USA Election 2020'count = 2000# Creation of query objecttweetCriteria = got.manager.TweetCriteria().setQuerySearch(text_query)\\ .setMaxTweets(count)# Creation of list that contains all tweetstweets = got.manager.TweetManager.getTweets(tweetCriteria)# Creating list of chosen tweet datatext_tweets = [[tweet.date, tweet.text] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(text_tweets)"
},
{
"code": null,
"e": 10767,
"s": 10626,
"text": "Queries can be further customized by combining TweetCriteria search parameters. All the current search parameters available are shown below."
},
{
"code": null,
"e": 10819,
"s": 10767,
"text": "Example of a query using several search parameters:"
},
{
"code": null,
"e": 10968,
"s": 10819,
"text": "The following stacked query will return 2,000 tweets relevant to USA Election 2020 that were tweeted between January 1st 2019 and October 31st 2019."
},
{
"code": null,
"e": 11495,
"s": 10968,
"text": "text_query = 'USA Election 2020'since_date = '2019-01-01'until_date = '2019-10-31'count = 2000# Creation of query objecttweetCriteria = got.manager.TweetCriteria().setQuerySearch(text_query).setSince(since_date).setUntil(until_date).setMaxTweets(count)# Creation of list that contains all tweetstweets = got.manager.TweetManager.getTweets(tweetCriteria)# Creating list of chosen tweet datatext_tweets = [[tweet.date, tweet.text] for tweet in tweets]# Creation of dataframe from tweets listtweets_df = pd.DataFrame(text_tweets)"
},
{
"code": null,
"e": 11567,
"s": 11495,
"text": "If you want to reach out don’t be afraid to connect with me on LinkedIn"
},
{
"code": null,
"e": 11657,
"s": 11567,
"text": "If you’re interested, sign up for our Socialscrapr mailing list: https://upscri.be/3kcmqx"
},
{
"code": null,
"e": 11820,
"s": 11657,
"text": "My follow up article that does a deeper dive into both packages: https://towardsdatascience.com/how-to-scrape-more-information-from-tweets-on-twitter-44fd540b8a1f"
},
{
"code": null,
"e": 11982,
"s": 11820,
"text": "snscrape article that helps setup and provides a couple of example queries: https://medium.com/better-programming/how-to-scrape-tweets-with-snscrape-90124ed006af"
},
{
"code": null,
"e": 12107,
"s": 11982,
"text": "GitHub containing this tutorial’s Twitter scraper’s: https://github.com/MartinBeckUT/TwitterScraper/tree/master/BasicScraper"
},
{
"code": null,
"e": 12245,
"s": 12107,
"text": "Increasing Tweepy’s standard API search limit: https://bhaskarvk.github.io/2015/01/how-to-use-twitters-search-rest-api-most-effectively./"
},
{
"code": null,
"e": 12293,
"s": 12245,
"text": "Tweepy GitHub: https://github.com/tweepy/tweepy"
}
] |
How to show node name in Matplotlib graphs using networkx?
|
To show node name in graphs using networkx, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a graph with edges, name, or graph attributes.
Add multiple nodes using add_nodes_from() method.
Add all the edges using add_edge_from() method.
Draw the graph G with Matplotlib using draw() method. Set with_labels to True.
To display the graph, we can use show() method.
import matplotlib.pylab as plt
import networkx as nx
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 1), (2, 3), (1,4), (3,4)])
nx.draw(G, with_labels=True)
plt.show()
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To show node name in graphs using networkx, we can take the following steps −"
},
{
"code": null,
"e": 1216,
"s": 1140,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1274,
"s": 1216,
"text": "Initialize a graph with edges, name, or graph attributes."
},
{
"code": null,
"e": 1324,
"s": 1274,
"text": "Add multiple nodes using add_nodes_from() method."
},
{
"code": null,
"e": 1372,
"s": 1324,
"text": "Add all the edges using add_edge_from() method."
},
{
"code": null,
"e": 1451,
"s": 1372,
"text": "Draw the graph G with Matplotlib using draw() method. Set with_labels to True."
},
{
"code": null,
"e": 1499,
"s": 1451,
"text": "To display the graph, we can use show() method."
},
{
"code": null,
"e": 1787,
"s": 1499,
"text": "import matplotlib.pylab as plt\nimport networkx as nx\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nG = nx.DiGraph()\nG.add_nodes_from([1, 2, 3, 4])\nG.add_edges_from([(1, 2), (2, 1), (2, 3), (1,4), (3,4)])\nnx.draw(G, with_labels=True)\n\nplt.show()"
}
] |
How to create a transparent polygon using ggplot2 in R?
|
A transparent polygon just represents the border lines and a hollow area; thus, we can only understand the area covered but it becomes a little difficult to understand the scales. Hence, this visualisation technique is not as useful as others that fills the area with a different color. But it could be used if the range of the data is not large.
Consider the below data frame −
Live Demo
set.seed(123)
x<-sample(1:5,10,replace=TRUE)
y<-sample(3:8,10,replace=TRUE)
df<-data.frame(x,y)
df
x y
1 2 8
2 4 5
3 3 7
4 5 6
5 5 3
6 1 8
7 3 4
8 5 3
9 3 4
10 3 8
Loading ggplot2 package and creating a polygon using x and y −
library(ggplot2) ggplot(df,aes(x,y))+geom_polygon()
Creating a polygon using x and y with transparency −
ggplot(df,aes(x,y))+geom_polygon(fill=NA,color="red")
|
[
{
"code": null,
"e": 1409,
"s": 1062,
"text": "A transparent polygon just represents the border lines and a hollow area; thus, we can only understand the area covered but it becomes a little difficult to understand the scales. Hence, this visualisation technique is not as useful as others that fills the area with a different color. But it could be used if the range of the data is not large."
},
{
"code": null,
"e": 1441,
"s": 1409,
"text": "Consider the below data frame −"
},
{
"code": null,
"e": 1452,
"s": 1441,
"text": " Live Demo"
},
{
"code": null,
"e": 1551,
"s": 1452,
"text": "set.seed(123)\nx<-sample(1:5,10,replace=TRUE)\ny<-sample(3:8,10,replace=TRUE)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1628,
"s": 1551,
"text": " x y\n1 2 8\n2 4 5\n3 3 7\n4 5 6\n5 5 3\n6 1 8\n7 3 4\n8 5 3\n9 3 4\n10 3 8"
},
{
"code": null,
"e": 1691,
"s": 1628,
"text": "Loading ggplot2 package and creating a polygon using x and y −"
},
{
"code": null,
"e": 1743,
"s": 1691,
"text": "library(ggplot2) ggplot(df,aes(x,y))+geom_polygon()"
},
{
"code": null,
"e": 1796,
"s": 1743,
"text": "Creating a polygon using x and y with transparency −"
},
{
"code": null,
"e": 1850,
"s": 1796,
"text": "ggplot(df,aes(x,y))+geom_polygon(fill=NA,color=\"red\")"
}
] |
13 Key Code Blocks for EDA-Classification Task | by Susan Maina | Towards Data Science
|
Following my previous article on the 11 code blocks for EDA which covered a regression task (predicting a continuous variable), here are the 13 code blocks for performing EDA on a classification task (predicting a categorical or binary feature).
EDA or Exploratory Data Analysis is an important machine learning step that involves learning about the data without spending too much time or getting lost in it. Here, you get familiar with the structure and general characteristics of the dataset, and the independent and dependent features, and their interactions. You will also get an idea of the data cleaning processes to employ, and the possible modeling techniques.
In this article, we will explore a dataset from Kaggle for a company running training courses on prospective employees. The task is to predict whether the trainees taking their courses are looking to change jobs and will leave their current position and join the company, or will stay at their current job even after completing the courses. The task is therefore a binary task and the target is 0 -stays (not looking for a job change), and 1 -leaves (looking for a job change)
The data can be downloaded from the Kaggle page here, and the feature definitions are also available on the same page. The full workflow code is here on my GitHub page so you can follow along.
The first step is to import the libraries we will use throughout the EDA project. We then read in the train.csv which I downloaded and saved in the same folder as my Jupyter notebook. I will perform EDA on the train set because it contains the target variable, and we are interested in understanding the individual features as well as their relationship with the target feature.
Shape (dimension of the DataFrame)
Shape (dimension of the DataFrame)
A DataFrame has rows and columns, and the Pandas .shape attribute returns a tuple of length 2, each value showing the length of each dimension, or (rows, columns).
(19158, 14)
We can see that the dataset has 19,158 rows and 14 columns. One of those columns in the target feature.
2. Data types of the various columns
We will now display all the columns’ data types. This helps us understand the kind of data we are dealing with, in terms of the numerical and categorical distributions. This will also shed light on some of the exploratory plots and graphs to use.
What to look out for;
Categorical features that should be numeric, and vice versa.
We see several categorical (object) features. We also see the target is a float, represented as 1.0 for those who left their job and 0.0 for those that stayed after training. This makes target a binary feature.
3. Display a few rows
We will now display a small section of our data. We use df.head() to display the first 5 rows, df.tail() to display the last 5, or df.sample() to pick 1 random row from the dataset. df.sample(5) displays 5 randomly selected rows.
What to look out for:
Do the column names make sense? You can check the column definitions again.
What values are in the columns? Do they make sense?
Can you see a significant number of missing values (NaNs)
What are some of the unique classes for the categorical features?
The table gives us an idea of the values present in the different features, and the column names are self-explanatory. We can see some significant missing values in columns such as gender and company_size.
The distribution of a feature refers to how often the values in that feature occur. For numeric (continuous) features, the values are grouped in ranges, also known as bins. We will use graphs to plot the distributions and get an intuitive idea of the values in each column. We will also display actual summary statistics that contain actual numbers of the distributions. It is important to use both graphs and statistics as they complement each other.
4. Plot a histogram grid of the numeric features
A histogram is a form of a bar chart that groups numbers into ranges and the height of the bars show how many values fall into that range. We will use Panda’s df.hist() function to plot a histogram of each numeric feature in the dataset. We will also pass to the function figsize=(8,8) and xrot=45 to increase the grid size and rotate the x-axis for readability.
What to look out for;
Potential outliers
Numeric features that should be categorical (indicator) features. For example, if there are only two possible values like 0 and 1.
Boundaries that do not make sense, such as a percentage value greater than 100.
As expected, we see that target, our dependent feature, is actually an indicator variable with only two possible values; 0 and 1. enrollee_id is an ID column, meaning that each value occurs only once hence the equal distribution among all bins.
5. Display the numeric features’ summary statistics
We will use Panda’s df.describe() function that returns an analysis of each numeric feature.
What to look out for;
The count, or the number of non-NaN values in the column. If the count is less than the overall rows in the data frame, that column contains missing (NaN) values.
The average value, or mean.
The std, or standard deviation of the values in the column
The minimum value
The 25th percentile value
The median, or 50th percentile
The 75th percentile
The maximum value. This could also indicate extreme (outlier) values.
We see that there are no missing values or significant outliers in any column.
Categorical features are columns that contain only a handful of unique values, and therefore each value belongs to a particular class or group. As with the numeric features, we will use both graphs and summary statistics to view the distributions of the different classes in each column.
6. Summary statistics of the Categorical features
We will use the Panda’s df.describe(include=’object’) that only displays the analysis of the features that have the datatype ‘object’.
What to look out for;
The count, or number of non-NaN values. Missing values are present if the count is less than the total rows of the DataFrame.
The number of unique classes.
The top most common value or class. If multiple values have the highest occurrence, an arbitrary top (and freq) value will be displayed.
The frequency (freq), or the number of occurrences of the top class.
We can see that many features have missing values.
7. Plot categorical distributions
We will now plot the categorical features to see how the classes are distributed for each feature. We will use Seaborn’s countplot which is like a bar graph where each bar represents a class and the height is the number of values in that class. Using the summary statistics above, we see that some features such as city have many unique classes and may not be readable when plotted. I decided to plot those with 22 or fewer unique classes.
What to look out for;
Sparse classes — those with very few values. These can affect a model’s performance.
Inconsistent names or typos eg labeling 2 similar classes differently.
We can now see the distributions of classes in the various categorical features.
We can segment our data into groups and observe the relationships between categorical and numeric features, particularly concerning the target.
8. Segment the target by numeric features
Here, we will separate the data by the target feature and observe how the numeric features are distributed among those who left (target = 1) and those who stayed (target = 0).
We will use Seaborn’s boxplot which displays the five-number summary of a numeric feature. The five numbers are minimum, first quartile (Q1 or 25% mark), median (Q2), third quartile (Q3 or 75% mark), and maximum. Check out this article for more on the box plot.
What to look out for:
Which target class is most affected by the numeric features
First, let us do some cleaning and convert 2 categorical columns into numeric.
On-the-fly data cleaning/feature engineering
We will convert experience and last_new_job into numeric features because they both represent the years of experience of the trainees. This will enable us to see how experience influenced a trainee’s decision to leave or stay at current employment. The code below replaces some values in a column then converts the entire column into a float datatype(int did not work because the columns have NaNs)
Now we get to creating box plots. We will first save the four numeric columns-of-interest in a list called num_cols. We will then loop through these columns as we create box plots of each feature against the target.
We can see that training_hours are equally distributed among those who stayed(target 0) and those who left (target 1). This means that training_hours might not be a good predictor for the target. However, we see that when it comes to experience and last_new_job, a bigger proportion of those who stayed are tending towards more years of experience and these could be good predictors.
Now that we have seen how the target changes with numeric features, we will do the same for categorical features.
9. Tabulate target across various categorical features using cross tab
The Panda’s .crosstab(col1, col2) function builds a cross-tabulation table that shows the relationship between two categorical features. The table shows the frequency by which groups of data from the two features appear. You can include the parameter normalize=’index’ to show the percentages across the rows instead of the real numbers. More on cross tabs here. Let us see this in action.
I will loop through 3 categorical columns (those with less than 4 unique classes) and display a cross tab of their relationships with the target. display() function is used because it shows a cleaner table than print()when running a loop.
These tables show how the categorical features’ classes are split among the target’s classes. Let us visualize these results below.
10. Count plot of target across various categorical features
We can plot the categorical relationships above to get a better feel of the interactions. We will create count plots of the data using Seaborn’s catplot() function and provide kind=’count’ as a parameter, which selects a count plot as the underlying axes-level function to use. Other plots you can create using catplot include box plots, bar plots, and violin plots.
What to look out for;
Categorical features that change significantly with the target classes.
In the code, we use the loop to plot only 3 categorical features against the target. Remember that target 0 left while target 1 stayed at their jobs. Notice the parameter sharey=False in catplot which disassociates the y-scales for each target class so that we can better view and compare the relationships.
We can see that the gender classes do not change much depending on the target, but there is a significant difference in how the target feature is distributed among relevant_experience and enrolled_university . We see a bigger proportion of those without relevant experience leaving their jobs. We also see more of those enrolled in a full-time course leaving. This shows that these two features are good predictors of the target.
11. Group numeric features by categorical features.
Now that we have observed how our target is distributed across the other input features, let us check how the categories are related to the numeric features.
We will use the DataFrame’s .groupby() function to group our data into categories and observe how the numeric features are distributed by calculating a metric such as mean, median, and standard deviation across the classes. The metric we will use is mean. We will also provide the columns for which to calculate the means.
Here, we get to compare various feature’s classes against the numeric features.
12. Correlation matrix for the various numeric features
A correlation matrix is a table used to summarize the associations between numeric features. The same features are shown in the rows and columns, and each cell holds the correlation coefficient of two features. The correlation coefficient is a measure of the strength of the relationship between the two variables and can take any value between -1 and 1. The correlation of a feature with itself is 1. Refer to the image below.
In python, calculating the correlations is as easy as calling the DataFrame’s .corr() function to return the pairwise correlation coefficients of all the numeric variables in the data frame.
Take a moment to scan through the numbers and then move on down to see them visualized in a heat map.
13. Heat map of the correlations
A heat map refers to a color-coded representation of data where the values are portrayed by color. We will use the Seaborn heatmap to visualize our grid above.
The code is sns.heatmap(corr, cmap=’RdBu_r’, annot=True, vmax=1, vmin=-1) We pass our correlation matrix corr, along with four other parameters which are optional. cmap=’RdBu_r’ specifies what color palette the heat map should use with dark-red cells showing a strong positive correlation and dark-blue showing a strong negative one. More on Seaborn’s color palettes here. annot=True includes the coefficient values in each cell while vmax=1 and vmin=-1 set the boundaries for the color bar, as our correlation values also fall in the same range.
What to look out for;
Strongly correlated features. These are either dark-red (strong positive) or dark-blue (strong negative).
Target feature’s strong correlations. If any features have a strong positive or negative correlation with the target.
We see that experience and last_new_job have a somewhat strong positive correlation. We also see a slightly weak negative relationship between the target and city_development_index.
That concludes our Exploratory Data Analysis for a classification task. We looked at the 13 code blocks for an EDA project for the HR classification dataset on Kaggle. These blocks of code are important to give you a top-level understanding of the dataset and its features. Find the complete code here. You can also check out the article 11 code blocks for EDA for a regression task.
|
[
{
"code": null,
"e": 418,
"s": 172,
"text": "Following my previous article on the 11 code blocks for EDA which covered a regression task (predicting a continuous variable), here are the 13 code blocks for performing EDA on a classification task (predicting a categorical or binary feature)."
},
{
"code": null,
"e": 841,
"s": 418,
"text": "EDA or Exploratory Data Analysis is an important machine learning step that involves learning about the data without spending too much time or getting lost in it. Here, you get familiar with the structure and general characteristics of the dataset, and the independent and dependent features, and their interactions. You will also get an idea of the data cleaning processes to employ, and the possible modeling techniques."
},
{
"code": null,
"e": 1318,
"s": 841,
"text": "In this article, we will explore a dataset from Kaggle for a company running training courses on prospective employees. The task is to predict whether the trainees taking their courses are looking to change jobs and will leave their current position and join the company, or will stay at their current job even after completing the courses. The task is therefore a binary task and the target is 0 -stays (not looking for a job change), and 1 -leaves (looking for a job change)"
},
{
"code": null,
"e": 1511,
"s": 1318,
"text": "The data can be downloaded from the Kaggle page here, and the feature definitions are also available on the same page. The full workflow code is here on my GitHub page so you can follow along."
},
{
"code": null,
"e": 1890,
"s": 1511,
"text": "The first step is to import the libraries we will use throughout the EDA project. We then read in the train.csv which I downloaded and saved in the same folder as my Jupyter notebook. I will perform EDA on the train set because it contains the target variable, and we are interested in understanding the individual features as well as their relationship with the target feature."
},
{
"code": null,
"e": 1925,
"s": 1890,
"text": "Shape (dimension of the DataFrame)"
},
{
"code": null,
"e": 1960,
"s": 1925,
"text": "Shape (dimension of the DataFrame)"
},
{
"code": null,
"e": 2124,
"s": 1960,
"text": "A DataFrame has rows and columns, and the Pandas .shape attribute returns a tuple of length 2, each value showing the length of each dimension, or (rows, columns)."
},
{
"code": null,
"e": 2136,
"s": 2124,
"text": "(19158, 14)"
},
{
"code": null,
"e": 2240,
"s": 2136,
"text": "We can see that the dataset has 19,158 rows and 14 columns. One of those columns in the target feature."
},
{
"code": null,
"e": 2277,
"s": 2240,
"text": "2. Data types of the various columns"
},
{
"code": null,
"e": 2524,
"s": 2277,
"text": "We will now display all the columns’ data types. This helps us understand the kind of data we are dealing with, in terms of the numerical and categorical distributions. This will also shed light on some of the exploratory plots and graphs to use."
},
{
"code": null,
"e": 2546,
"s": 2524,
"text": "What to look out for;"
},
{
"code": null,
"e": 2607,
"s": 2546,
"text": "Categorical features that should be numeric, and vice versa."
},
{
"code": null,
"e": 2818,
"s": 2607,
"text": "We see several categorical (object) features. We also see the target is a float, represented as 1.0 for those who left their job and 0.0 for those that stayed after training. This makes target a binary feature."
},
{
"code": null,
"e": 2840,
"s": 2818,
"text": "3. Display a few rows"
},
{
"code": null,
"e": 3070,
"s": 2840,
"text": "We will now display a small section of our data. We use df.head() to display the first 5 rows, df.tail() to display the last 5, or df.sample() to pick 1 random row from the dataset. df.sample(5) displays 5 randomly selected rows."
},
{
"code": null,
"e": 3092,
"s": 3070,
"text": "What to look out for:"
},
{
"code": null,
"e": 3168,
"s": 3092,
"text": "Do the column names make sense? You can check the column definitions again."
},
{
"code": null,
"e": 3220,
"s": 3168,
"text": "What values are in the columns? Do they make sense?"
},
{
"code": null,
"e": 3278,
"s": 3220,
"text": "Can you see a significant number of missing values (NaNs)"
},
{
"code": null,
"e": 3344,
"s": 3278,
"text": "What are some of the unique classes for the categorical features?"
},
{
"code": null,
"e": 3550,
"s": 3344,
"text": "The table gives us an idea of the values present in the different features, and the column names are self-explanatory. We can see some significant missing values in columns such as gender and company_size."
},
{
"code": null,
"e": 4002,
"s": 3550,
"text": "The distribution of a feature refers to how often the values in that feature occur. For numeric (continuous) features, the values are grouped in ranges, also known as bins. We will use graphs to plot the distributions and get an intuitive idea of the values in each column. We will also display actual summary statistics that contain actual numbers of the distributions. It is important to use both graphs and statistics as they complement each other."
},
{
"code": null,
"e": 4051,
"s": 4002,
"text": "4. Plot a histogram grid of the numeric features"
},
{
"code": null,
"e": 4414,
"s": 4051,
"text": "A histogram is a form of a bar chart that groups numbers into ranges and the height of the bars show how many values fall into that range. We will use Panda’s df.hist() function to plot a histogram of each numeric feature in the dataset. We will also pass to the function figsize=(8,8) and xrot=45 to increase the grid size and rotate the x-axis for readability."
},
{
"code": null,
"e": 4436,
"s": 4414,
"text": "What to look out for;"
},
{
"code": null,
"e": 4455,
"s": 4436,
"text": "Potential outliers"
},
{
"code": null,
"e": 4586,
"s": 4455,
"text": "Numeric features that should be categorical (indicator) features. For example, if there are only two possible values like 0 and 1."
},
{
"code": null,
"e": 4666,
"s": 4586,
"text": "Boundaries that do not make sense, such as a percentage value greater than 100."
},
{
"code": null,
"e": 4911,
"s": 4666,
"text": "As expected, we see that target, our dependent feature, is actually an indicator variable with only two possible values; 0 and 1. enrollee_id is an ID column, meaning that each value occurs only once hence the equal distribution among all bins."
},
{
"code": null,
"e": 4963,
"s": 4911,
"text": "5. Display the numeric features’ summary statistics"
},
{
"code": null,
"e": 5056,
"s": 4963,
"text": "We will use Panda’s df.describe() function that returns an analysis of each numeric feature."
},
{
"code": null,
"e": 5078,
"s": 5056,
"text": "What to look out for;"
},
{
"code": null,
"e": 5241,
"s": 5078,
"text": "The count, or the number of non-NaN values in the column. If the count is less than the overall rows in the data frame, that column contains missing (NaN) values."
},
{
"code": null,
"e": 5269,
"s": 5241,
"text": "The average value, or mean."
},
{
"code": null,
"e": 5328,
"s": 5269,
"text": "The std, or standard deviation of the values in the column"
},
{
"code": null,
"e": 5346,
"s": 5328,
"text": "The minimum value"
},
{
"code": null,
"e": 5372,
"s": 5346,
"text": "The 25th percentile value"
},
{
"code": null,
"e": 5403,
"s": 5372,
"text": "The median, or 50th percentile"
},
{
"code": null,
"e": 5423,
"s": 5403,
"text": "The 75th percentile"
},
{
"code": null,
"e": 5493,
"s": 5423,
"text": "The maximum value. This could also indicate extreme (outlier) values."
},
{
"code": null,
"e": 5572,
"s": 5493,
"text": "We see that there are no missing values or significant outliers in any column."
},
{
"code": null,
"e": 5860,
"s": 5572,
"text": "Categorical features are columns that contain only a handful of unique values, and therefore each value belongs to a particular class or group. As with the numeric features, we will use both graphs and summary statistics to view the distributions of the different classes in each column."
},
{
"code": null,
"e": 5910,
"s": 5860,
"text": "6. Summary statistics of the Categorical features"
},
{
"code": null,
"e": 6045,
"s": 5910,
"text": "We will use the Panda’s df.describe(include=’object’) that only displays the analysis of the features that have the datatype ‘object’."
},
{
"code": null,
"e": 6067,
"s": 6045,
"text": "What to look out for;"
},
{
"code": null,
"e": 6193,
"s": 6067,
"text": "The count, or number of non-NaN values. Missing values are present if the count is less than the total rows of the DataFrame."
},
{
"code": null,
"e": 6223,
"s": 6193,
"text": "The number of unique classes."
},
{
"code": null,
"e": 6360,
"s": 6223,
"text": "The top most common value or class. If multiple values have the highest occurrence, an arbitrary top (and freq) value will be displayed."
},
{
"code": null,
"e": 6429,
"s": 6360,
"text": "The frequency (freq), or the number of occurrences of the top class."
},
{
"code": null,
"e": 6480,
"s": 6429,
"text": "We can see that many features have missing values."
},
{
"code": null,
"e": 6514,
"s": 6480,
"text": "7. Plot categorical distributions"
},
{
"code": null,
"e": 6954,
"s": 6514,
"text": "We will now plot the categorical features to see how the classes are distributed for each feature. We will use Seaborn’s countplot which is like a bar graph where each bar represents a class and the height is the number of values in that class. Using the summary statistics above, we see that some features such as city have many unique classes and may not be readable when plotted. I decided to plot those with 22 or fewer unique classes."
},
{
"code": null,
"e": 6976,
"s": 6954,
"text": "What to look out for;"
},
{
"code": null,
"e": 7061,
"s": 6976,
"text": "Sparse classes — those with very few values. These can affect a model’s performance."
},
{
"code": null,
"e": 7132,
"s": 7061,
"text": "Inconsistent names or typos eg labeling 2 similar classes differently."
},
{
"code": null,
"e": 7213,
"s": 7132,
"text": "We can now see the distributions of classes in the various categorical features."
},
{
"code": null,
"e": 7357,
"s": 7213,
"text": "We can segment our data into groups and observe the relationships between categorical and numeric features, particularly concerning the target."
},
{
"code": null,
"e": 7399,
"s": 7357,
"text": "8. Segment the target by numeric features"
},
{
"code": null,
"e": 7575,
"s": 7399,
"text": "Here, we will separate the data by the target feature and observe how the numeric features are distributed among those who left (target = 1) and those who stayed (target = 0)."
},
{
"code": null,
"e": 7837,
"s": 7575,
"text": "We will use Seaborn’s boxplot which displays the five-number summary of a numeric feature. The five numbers are minimum, first quartile (Q1 or 25% mark), median (Q2), third quartile (Q3 or 75% mark), and maximum. Check out this article for more on the box plot."
},
{
"code": null,
"e": 7859,
"s": 7837,
"text": "What to look out for:"
},
{
"code": null,
"e": 7919,
"s": 7859,
"text": "Which target class is most affected by the numeric features"
},
{
"code": null,
"e": 7998,
"s": 7919,
"text": "First, let us do some cleaning and convert 2 categorical columns into numeric."
},
{
"code": null,
"e": 8043,
"s": 7998,
"text": "On-the-fly data cleaning/feature engineering"
},
{
"code": null,
"e": 8442,
"s": 8043,
"text": "We will convert experience and last_new_job into numeric features because they both represent the years of experience of the trainees. This will enable us to see how experience influenced a trainee’s decision to leave or stay at current employment. The code below replaces some values in a column then converts the entire column into a float datatype(int did not work because the columns have NaNs)"
},
{
"code": null,
"e": 8658,
"s": 8442,
"text": "Now we get to creating box plots. We will first save the four numeric columns-of-interest in a list called num_cols. We will then loop through these columns as we create box plots of each feature against the target."
},
{
"code": null,
"e": 9042,
"s": 8658,
"text": "We can see that training_hours are equally distributed among those who stayed(target 0) and those who left (target 1). This means that training_hours might not be a good predictor for the target. However, we see that when it comes to experience and last_new_job, a bigger proportion of those who stayed are tending towards more years of experience and these could be good predictors."
},
{
"code": null,
"e": 9156,
"s": 9042,
"text": "Now that we have seen how the target changes with numeric features, we will do the same for categorical features."
},
{
"code": null,
"e": 9227,
"s": 9156,
"text": "9. Tabulate target across various categorical features using cross tab"
},
{
"code": null,
"e": 9617,
"s": 9227,
"text": "The Panda’s .crosstab(col1, col2) function builds a cross-tabulation table that shows the relationship between two categorical features. The table shows the frequency by which groups of data from the two features appear. You can include the parameter normalize=’index’ to show the percentages across the rows instead of the real numbers. More on cross tabs here. Let us see this in action."
},
{
"code": null,
"e": 9856,
"s": 9617,
"text": "I will loop through 3 categorical columns (those with less than 4 unique classes) and display a cross tab of their relationships with the target. display() function is used because it shows a cleaner table than print()when running a loop."
},
{
"code": null,
"e": 9988,
"s": 9856,
"text": "These tables show how the categorical features’ classes are split among the target’s classes. Let us visualize these results below."
},
{
"code": null,
"e": 10049,
"s": 9988,
"text": "10. Count plot of target across various categorical features"
},
{
"code": null,
"e": 10416,
"s": 10049,
"text": "We can plot the categorical relationships above to get a better feel of the interactions. We will create count plots of the data using Seaborn’s catplot() function and provide kind=’count’ as a parameter, which selects a count plot as the underlying axes-level function to use. Other plots you can create using catplot include box plots, bar plots, and violin plots."
},
{
"code": null,
"e": 10438,
"s": 10416,
"text": "What to look out for;"
},
{
"code": null,
"e": 10510,
"s": 10438,
"text": "Categorical features that change significantly with the target classes."
},
{
"code": null,
"e": 10818,
"s": 10510,
"text": "In the code, we use the loop to plot only 3 categorical features against the target. Remember that target 0 left while target 1 stayed at their jobs. Notice the parameter sharey=False in catplot which disassociates the y-scales for each target class so that we can better view and compare the relationships."
},
{
"code": null,
"e": 11248,
"s": 10818,
"text": "We can see that the gender classes do not change much depending on the target, but there is a significant difference in how the target feature is distributed among relevant_experience and enrolled_university . We see a bigger proportion of those without relevant experience leaving their jobs. We also see more of those enrolled in a full-time course leaving. This shows that these two features are good predictors of the target."
},
{
"code": null,
"e": 11300,
"s": 11248,
"text": "11. Group numeric features by categorical features."
},
{
"code": null,
"e": 11458,
"s": 11300,
"text": "Now that we have observed how our target is distributed across the other input features, let us check how the categories are related to the numeric features."
},
{
"code": null,
"e": 11781,
"s": 11458,
"text": "We will use the DataFrame’s .groupby() function to group our data into categories and observe how the numeric features are distributed by calculating a metric such as mean, median, and standard deviation across the classes. The metric we will use is mean. We will also provide the columns for which to calculate the means."
},
{
"code": null,
"e": 11861,
"s": 11781,
"text": "Here, we get to compare various feature’s classes against the numeric features."
},
{
"code": null,
"e": 11917,
"s": 11861,
"text": "12. Correlation matrix for the various numeric features"
},
{
"code": null,
"e": 12345,
"s": 11917,
"text": "A correlation matrix is a table used to summarize the associations between numeric features. The same features are shown in the rows and columns, and each cell holds the correlation coefficient of two features. The correlation coefficient is a measure of the strength of the relationship between the two variables and can take any value between -1 and 1. The correlation of a feature with itself is 1. Refer to the image below."
},
{
"code": null,
"e": 12536,
"s": 12345,
"text": "In python, calculating the correlations is as easy as calling the DataFrame’s .corr() function to return the pairwise correlation coefficients of all the numeric variables in the data frame."
},
{
"code": null,
"e": 12638,
"s": 12536,
"text": "Take a moment to scan through the numbers and then move on down to see them visualized in a heat map."
},
{
"code": null,
"e": 12671,
"s": 12638,
"text": "13. Heat map of the correlations"
},
{
"code": null,
"e": 12831,
"s": 12671,
"text": "A heat map refers to a color-coded representation of data where the values are portrayed by color. We will use the Seaborn heatmap to visualize our grid above."
},
{
"code": null,
"e": 13378,
"s": 12831,
"text": "The code is sns.heatmap(corr, cmap=’RdBu_r’, annot=True, vmax=1, vmin=-1) We pass our correlation matrix corr, along with four other parameters which are optional. cmap=’RdBu_r’ specifies what color palette the heat map should use with dark-red cells showing a strong positive correlation and dark-blue showing a strong negative one. More on Seaborn’s color palettes here. annot=True includes the coefficient values in each cell while vmax=1 and vmin=-1 set the boundaries for the color bar, as our correlation values also fall in the same range."
},
{
"code": null,
"e": 13400,
"s": 13378,
"text": "What to look out for;"
},
{
"code": null,
"e": 13506,
"s": 13400,
"text": "Strongly correlated features. These are either dark-red (strong positive) or dark-blue (strong negative)."
},
{
"code": null,
"e": 13624,
"s": 13506,
"text": "Target feature’s strong correlations. If any features have a strong positive or negative correlation with the target."
},
{
"code": null,
"e": 13806,
"s": 13624,
"text": "We see that experience and last_new_job have a somewhat strong positive correlation. We also see a slightly weak negative relationship between the target and city_development_index."
}
] |
How to skip first 10 results in MySQL?
|
To skip first 10 results, use “limit offset”. The syntax is as follows −
select *from yourTableName limit 10 offset lastValue;
Let us create a table to understand the above syntax. The following is the query to create a table −
mysql> create table SkipFirstTenRecords
−> (
−> StudentId int,
−> StudentName varchar(200)
−> );
Query OK, 0 rows affected (0.53 sec)
Now you can insert some records in the table with the help of insert command. The query is as follows −
mysql> insert into SkipFirstTenRecords values(100,'John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into SkipFirstTenRecords values(101,'Johnson');
Query OK, 1 row affected (0.14 sec)
mysql> insert into SkipFirstTenRecords values(102,'Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into SkipFirstTenRecords values(103,'Smith');
Query OK, 1 row affected (0.32 sec)
mysql> insert into SkipFirstTenRecords values(104,'Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into SkipFirstTenRecords values(105,'David');
Query OK, 1 row affected (0.18 sec)
mysql> insert into SkipFirstTenRecords values(106,'Sam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into SkipFirstTenRecords values(107,'Taylor');
Query OK, 1 row affected (0.23 sec)
mysql> insert into SkipFirstTenRecords values(108,'Ramit');
Query OK, 1 row affected (0.16 sec)
mysql> insert into SkipFirstTenRecords values(109,'Belly');
Query OK, 1 row affected (0.18 sec)
mysql> insert into SkipFirstTenRecords values(110,'Aaron ');
Query OK, 1 row affected (0.16 sec)
mysql> insert into SkipFirstTenRecords values(111,'Peter');
Query OK, 1 row affected (0.10 sec)
mysql> insert into SkipFirstTenRecords values(112,'Travis');
Query OK, 1 row affected (0.14 sec)
mysql> insert into SkipFirstTenRecords values(113,'Alex');
Query OK, 1 row affected (0.18 sec)
mysql> insert into SkipFirstTenRecords values(114,'Pat ');
Query OK, 1 row affected (0.11 sec)
Display all records which I have inserted in the table. The query is as follows:
mysql> select *from SkipFirstTenRecords;
The following is the output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 100 | John |
| 101 | Johnson |
| 102 | Carol |
| 103 | Smith |
| 104 | Bob |
| 105 | David |
| 106 | Sam |
| 107 | Taylor |
| 108 | Ramit |
| 109 | Belly |
| 110 | Aaron |
| 111 | Peter |
| 112 | Travis |
| 113 | Alex |
| 114 | Pat |
+-----------+-------------+
15 rows in set (0.00 sec)
The query to skip first 10 records from the above table is all follows −
mysql> select *from SkipFirstTenRecords limit 10 offset 10;
The following is the output displays only the last 5 records since we skipped the first 10 records −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 110 | Aaron |
| 111 | Peter |
| 112 | Travis |
| 113 | Alex |
| 114 | Pat |
+-----------+-------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To skip first 10 results, use “limit offset”. The syntax is as follows −"
},
{
"code": null,
"e": 1189,
"s": 1135,
"text": "select *from yourTableName limit 10 offset lastValue;"
},
{
"code": null,
"e": 1290,
"s": 1189,
"text": "Let us create a table to understand the above syntax. The following is the query to create a table −"
},
{
"code": null,
"e": 1442,
"s": 1290,
"text": "mysql> create table SkipFirstTenRecords\n −> (\n −> StudentId int,\n −> StudentName varchar(200)\n −> );\nQuery OK, 0 rows affected (0.53 sec)"
},
{
"code": null,
"e": 1546,
"s": 1442,
"text": "Now you can insert some records in the table with the help of insert command. The query is as follows −"
},
{
"code": null,
"e": 3122,
"s": 1546,
"text": "mysql> insert into SkipFirstTenRecords values(100,'John');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into SkipFirstTenRecords values(101,'Johnson');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into SkipFirstTenRecords values(102,'Carol');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into SkipFirstTenRecords values(103,'Smith');\nQuery OK, 1 row affected (0.32 sec)\n\nmysql> insert into SkipFirstTenRecords values(104,'Bob');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into SkipFirstTenRecords values(105,'David');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into SkipFirstTenRecords values(106,'Sam');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into SkipFirstTenRecords values(107,'Taylor');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into SkipFirstTenRecords values(108,'Ramit');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into SkipFirstTenRecords values(109,'Belly');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into SkipFirstTenRecords values(110,'Aaron ');\nQuery OK, 1 row affected (0.16 sec)\n\nmysql> insert into SkipFirstTenRecords values(111,'Peter');\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into SkipFirstTenRecords values(112,'Travis');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into SkipFirstTenRecords values(113,'Alex');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into SkipFirstTenRecords values(114,'Pat ');\nQuery OK, 1 row affected (0.11 sec)\n\nDisplay all records which I have inserted in the table. The query is as follows:\n\nmysql> select *from SkipFirstTenRecords;"
},
{
"code": null,
"e": 3152,
"s": 3122,
"text": "The following is the output −"
},
{
"code": null,
"e": 3710,
"s": 3152,
"text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 100 | John |\n| 101 | Johnson |\n| 102 | Carol |\n| 103 | Smith |\n| 104 | Bob |\n| 105 | David |\n| 106 | Sam |\n| 107 | Taylor |\n| 108 | Ramit |\n| 109 | Belly |\n| 110 | Aaron |\n| 111 | Peter |\n| 112 | Travis |\n| 113 | Alex |\n| 114 | Pat |\n+-----------+-------------+\n15 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3783,
"s": 3710,
"text": "The query to skip first 10 records from the above table is all follows −"
},
{
"code": null,
"e": 3843,
"s": 3783,
"text": "mysql> select *from SkipFirstTenRecords limit 10 offset 10;"
},
{
"code": null,
"e": 3944,
"s": 3843,
"text": "The following is the output displays only the last 5 records since we skipped the first 10 records −"
},
{
"code": null,
"e": 4221,
"s": 3944,
"text": "+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 110 | Aaron |\n| 111 | Peter |\n| 112 | Travis |\n| 113 | Alex |\n| 114 | Pat |\n+-----------+-------------+\n5 rows in set (0.00 sec)"
}
] |
Travelling Salesman Problem
|
A traveler needs to visit all the cities from a list, where distances between all the cities are known and each city should be visited just once. What is the shortest possible route that he visits each city exactly once and returns to the origin city?
Travelling salesman problem is the most notorious computational problem. We can use brute-force approach to evaluate every possible tour and select the best one. For n number of vertices in a graph, there are (n - 1)! number of possibilities.
Instead of brute-force using dynamic programming approach, the solution can be obtained in lesser time, though there is no polynomial time algorithm.
Let us consider a graph G = (V, E), where V is a set of cities and E is a set of weighted edges. An edge e(u, v) represents that vertices u and v are connected. Distance between vertex u and v is d(u, v), which should be non-negative.
Suppose we have started at city 1 and after visiting some cities now we are in city j. Hence, this is a partial tour. We certainly need to know j, since this will determine which cities are most convenient to visit next. We also need to know all the cities visited so far, so that we don't repeat any of them. Hence, this is an appropriate sub-problem.
For a subset of cities S Є {1, 2, 3, ... , n} that includes 1, and j Є S, let C(S, j) be the length of the shortest path visiting each node in S exactly once, starting at 1 and ending at j.
When |S| > 1, we define C(S, 1) = ∝ since the path cannot start and end at 1.
Now, let express C(S, j) in terms of smaller sub-problems. We need to start at 1 and end at j. We should select the next city in such a way that
C(S,j)=minC(S−{j},i)+d(i,j)wherei∈Sandi≠jc(S,j)=minC(s−{j},i)+d(i,j)wherei∈Sandi≠j
Algorithm: Traveling-Salesman-Problem
C ({1}, 1) = 0
for s = 2 to n do
for all subsets S Є {1, 2, 3, ... , n} of size s and containing 1
C (S, 1) = ∞
for all j Є S and j ≠ 1
C (S, j) = min {C (S – {j}, i) + d(i, j) for i Є S and i ≠ j}
Return minj C ({1, 2, 3, ..., n}, j) + d(j, i)
There are at the most 2n.n sub-problems and each one takes linear time to solve. Therefore, the total running time is O(2n.n2).
In the following example, we will illustrate the steps to solve the travelling salesman problem.
From the above graph, the following table is prepared.
Cost(2,Φ,1)=d(2,1)=5Cost(2,Φ,1)=d(2,1)=5
Cost(3,Φ,1)=d(3,1)=6Cost(3,Φ,1)=d(3,1)=6
Cost(4,Φ,1)=d(4,1)=8Cost(4,Φ,1)=d(4,1)=8
Cost(i,s)=min{Cost(j,s–(j))+d[i,j]}Cost(i,s)=min{Cost(j,s)−(j))+d[i,j]}
Cost(2,{3},1)=d[2,3]+Cost(3,Φ,1)=9+6=15cost(2,{3},1)=d[2,3]+cost(3,Φ,1)=9+6=15
Cost(2,{4},1)=d[2,4]+Cost(4,Φ,1)=10+8=18cost(2,{4},1)=d[2,4]+cost(4,Φ,1)=10+8=18
Cost(3,{2},1)=d[3,2]+Cost(2,Φ,1)=13+5=18cost(3,{2},1)=d[3,2]+cost(2,Φ,1)=13+5=18
Cost(3,{4},1)=d[3,4]+Cost(4,Φ,1)=12+8=20cost(3,{4},1)=d[3,4]+cost(4,Φ,1)=12+8=20
Cost(4,{3},1)=d[4,3]+Cost(3,Φ,1)=9+6=15cost(4,{3},1)=d[4,3]+cost(3,Φ,1)=9+6=15
Cost(4,{2},1)=d[4,2]+Cost(2,Φ,1)=8+5=13cost(4,{2},1)=d[4,2]+cost(2,Φ,1)=8+5=13
Cost(2,{3,4},1)={d[2,3]+Cost(3,{4},1)=9+20=29d[2,4]+Cost(4,{3},1)=10+15=25=25Cost(2,{3,4},1){d[2,3]+cost(3,{4},1)=9+20=29d[2,4]+Cost(4,{3},1)=10+15=25=25
Cost(3,{2,4},1)={d[3,2]+Cost(2,{4},1)=13+18=31d[3,4]+Cost(4,{2},1)=12+13=25=25Cost(3,{2,4},1){d[3,2]+cost(2,{4},1)=13+18=31d[3,4]+Cost(4,{2},1)=12+13=25=25
Cost(4,{2,3},1)={d[4,2]+Cost(2,{3},1)=8+15=23d[4,3]+Cost(3,{2},1)=9+18=27=23Cost(4,{2,3},1){d[4,2]+cost(2,{3},1)=8+15=23d[4,3]+Cost(3,{2},1)=9+18=27=23
Cost(1,{2,3,4},1)={d[1,2]+Cost(2,{3,4},1)=10+25=35d[1,3]+Cost(3,{2,4},1)=15+25=40d[1,4]+Cost(4,{2,3},1)=20+23=43=35cost(1,{2,3,4}),1)d[1,2]+cost(2,{3,4},1)=10+25=35d[1,3]+cost(3,{2,4},1)=15+25=40d[1,4]+cost(4,{2,3},1)=20+23=43=35
The minimum cost path is 35.
Start from cost {1, {2, 3, 4}, 1}, we get the minimum value for d [1, 2]. When s = 3, select the path from 1 to 2 (cost is 10) then go backwards. When s = 2, we get the minimum value for d [4, 2]. Select the path from 2 to 4 (cost is 10) then go backwards.
When s = 1, we get the minimum value for d [4, 3]. Selecting path 4 to 3 (cost is 9), then we shall go to then go to s = Φ step. We get the minimum value for d [3, 1] (cost is 6).
102 Lectures
10 hours
Arnab Chakraborty
30 Lectures
3 hours
Arnab Chakraborty
31 Lectures
4 hours
Arnab Chakraborty
43 Lectures
1.5 hours
Manoj Kumar
7 Lectures
1 hours
Zach Miller
54 Lectures
4 hours
Sasha Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2851,
"s": 2599,
"text": "A traveler needs to visit all the cities from a list, where distances between all the cities are known and each city should be visited just once. What is the shortest possible route that he visits each city exactly once and returns to the origin city?"
},
{
"code": null,
"e": 3094,
"s": 2851,
"text": "Travelling salesman problem is the most notorious computational problem. We can use brute-force approach to evaluate every possible tour and select the best one. For n number of vertices in a graph, there are (n - 1)! number of possibilities."
},
{
"code": null,
"e": 3244,
"s": 3094,
"text": "Instead of brute-force using dynamic programming approach, the solution can be obtained in lesser time, though there is no polynomial time algorithm."
},
{
"code": null,
"e": 3479,
"s": 3244,
"text": "Let us consider a graph G = (V, E), where V is a set of cities and E is a set of weighted edges. An edge e(u, v) represents that vertices u and v are connected. Distance between vertex u and v is d(u, v), which should be non-negative."
},
{
"code": null,
"e": 3832,
"s": 3479,
"text": "Suppose we have started at city 1 and after visiting some cities now we are in city j. Hence, this is a partial tour. We certainly need to know j, since this will determine which cities are most convenient to visit next. We also need to know all the cities visited so far, so that we don't repeat any of them. Hence, this is an appropriate sub-problem."
},
{
"code": null,
"e": 4022,
"s": 3832,
"text": "For a subset of cities S Є {1, 2, 3, ... , n} that includes 1, and j Є S, let C(S, j) be the length of the shortest path visiting each node in S exactly once, starting at 1 and ending at j."
},
{
"code": null,
"e": 4100,
"s": 4022,
"text": "When |S| > 1, we define C(S, 1) = ∝ since the path cannot start and end at 1."
},
{
"code": null,
"e": 4245,
"s": 4100,
"text": "Now, let express C(S, j) in terms of smaller sub-problems. We need to start at 1 and end at j. We should select the next city in such a way that"
},
{
"code": null,
"e": 4330,
"s": 4245,
"text": "C(S,j)=minC(S−{j},i)+d(i,j)wherei∈Sandi≠jc(S,j)=minC(s−{j},i)+d(i,j)wherei∈Sandi≠j"
},
{
"code": null,
"e": 4642,
"s": 4330,
"text": "Algorithm: Traveling-Salesman-Problem \nC ({1}, 1) = 0 \nfor s = 2 to n do \n for all subsets S Є {1, 2, 3, ... , n} of size s and containing 1 \n C (S, 1) = ∞ \n for all j Є S and j ≠ 1 \n C (S, j) = min {C (S – {j}, i) + d(i, j) for i Є S and i ≠ j} \nReturn minj C ({1, 2, 3, ..., n}, j) + d(j, i) \n"
},
{
"code": null,
"e": 4770,
"s": 4642,
"text": "There are at the most 2n.n sub-problems and each one takes linear time to solve. Therefore, the total running time is O(2n.n2)."
},
{
"code": null,
"e": 4867,
"s": 4770,
"text": "In the following example, we will illustrate the steps to solve the travelling salesman problem."
},
{
"code": null,
"e": 4922,
"s": 4867,
"text": "From the above graph, the following table is prepared."
},
{
"code": null,
"e": 4963,
"s": 4922,
"text": "Cost(2,Φ,1)=d(2,1)=5Cost(2,Φ,1)=d(2,1)=5"
},
{
"code": null,
"e": 5004,
"s": 4963,
"text": "Cost(3,Φ,1)=d(3,1)=6Cost(3,Φ,1)=d(3,1)=6"
},
{
"code": null,
"e": 5045,
"s": 5004,
"text": "Cost(4,Φ,1)=d(4,1)=8Cost(4,Φ,1)=d(4,1)=8"
},
{
"code": null,
"e": 5117,
"s": 5045,
"text": "Cost(i,s)=min{Cost(j,s–(j))+d[i,j]}Cost(i,s)=min{Cost(j,s)−(j))+d[i,j]}"
},
{
"code": null,
"e": 5196,
"s": 5117,
"text": "Cost(2,{3},1)=d[2,3]+Cost(3,Φ,1)=9+6=15cost(2,{3},1)=d[2,3]+cost(3,Φ,1)=9+6=15"
},
{
"code": null,
"e": 5277,
"s": 5196,
"text": "Cost(2,{4},1)=d[2,4]+Cost(4,Φ,1)=10+8=18cost(2,{4},1)=d[2,4]+cost(4,Φ,1)=10+8=18"
},
{
"code": null,
"e": 5358,
"s": 5277,
"text": "Cost(3,{2},1)=d[3,2]+Cost(2,Φ,1)=13+5=18cost(3,{2},1)=d[3,2]+cost(2,Φ,1)=13+5=18"
},
{
"code": null,
"e": 5439,
"s": 5358,
"text": "Cost(3,{4},1)=d[3,4]+Cost(4,Φ,1)=12+8=20cost(3,{4},1)=d[3,4]+cost(4,Φ,1)=12+8=20"
},
{
"code": null,
"e": 5518,
"s": 5439,
"text": "Cost(4,{3},1)=d[4,3]+Cost(3,Φ,1)=9+6=15cost(4,{3},1)=d[4,3]+cost(3,Φ,1)=9+6=15"
},
{
"code": null,
"e": 5597,
"s": 5518,
"text": "Cost(4,{2},1)=d[4,2]+Cost(2,Φ,1)=8+5=13cost(4,{2},1)=d[4,2]+cost(2,Φ,1)=8+5=13"
},
{
"code": null,
"e": 5751,
"s": 5597,
"text": "Cost(2,{3,4},1)={d[2,3]+Cost(3,{4},1)=9+20=29d[2,4]+Cost(4,{3},1)=10+15=25=25Cost(2,{3,4},1){d[2,3]+cost(3,{4},1)=9+20=29d[2,4]+Cost(4,{3},1)=10+15=25=25"
},
{
"code": null,
"e": 5907,
"s": 5751,
"text": "Cost(3,{2,4},1)={d[3,2]+Cost(2,{4},1)=13+18=31d[3,4]+Cost(4,{2},1)=12+13=25=25Cost(3,{2,4},1){d[3,2]+cost(2,{4},1)=13+18=31d[3,4]+Cost(4,{2},1)=12+13=25=25"
},
{
"code": null,
"e": 6059,
"s": 5907,
"text": "Cost(4,{2,3},1)={d[4,2]+Cost(2,{3},1)=8+15=23d[4,3]+Cost(3,{2},1)=9+18=27=23Cost(4,{2,3},1){d[4,2]+cost(2,{3},1)=8+15=23d[4,3]+Cost(3,{2},1)=9+18=27=23"
},
{
"code": null,
"e": 6289,
"s": 6059,
"text": "Cost(1,{2,3,4},1)={d[1,2]+Cost(2,{3,4},1)=10+25=35d[1,3]+Cost(3,{2,4},1)=15+25=40d[1,4]+Cost(4,{2,3},1)=20+23=43=35cost(1,{2,3,4}),1)d[1,2]+cost(2,{3,4},1)=10+25=35d[1,3]+cost(3,{2,4},1)=15+25=40d[1,4]+cost(4,{2,3},1)=20+23=43=35"
},
{
"code": null,
"e": 6318,
"s": 6289,
"text": "The minimum cost path is 35."
},
{
"code": null,
"e": 6575,
"s": 6318,
"text": "Start from cost {1, {2, 3, 4}, 1}, we get the minimum value for d [1, 2]. When s = 3, select the path from 1 to 2 (cost is 10) then go backwards. When s = 2, we get the minimum value for d [4, 2]. Select the path from 2 to 4 (cost is 10) then go backwards."
},
{
"code": null,
"e": 6755,
"s": 6575,
"text": "When s = 1, we get the minimum value for d [4, 3]. Selecting path 4 to 3 (cost is 9), then we shall go to then go to s = Φ step. We get the minimum value for d [3, 1] (cost is 6)."
},
{
"code": null,
"e": 6790,
"s": 6755,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 6809,
"s": 6790,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6842,
"s": 6809,
"text": "\n 30 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6861,
"s": 6842,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6894,
"s": 6861,
"text": "\n 31 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6913,
"s": 6894,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6948,
"s": 6913,
"text": "\n 43 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6961,
"s": 6948,
"text": " Manoj Kumar"
},
{
"code": null,
"e": 6993,
"s": 6961,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7006,
"s": 6993,
"text": " Zach Miller"
},
{
"code": null,
"e": 7039,
"s": 7006,
"text": "\n 54 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 7053,
"s": 7039,
"text": " Sasha Miller"
},
{
"code": null,
"e": 7060,
"s": 7053,
"text": " Print"
},
{
"code": null,
"e": 7071,
"s": 7060,
"text": " Add Notes"
}
] |
How to Paraphrase Text using Python | by Chanin Nantasenamat | Towards Data Science
|
As writers, we often seek out tools to help us become more efficient or productive. Tools such as Grammarly can help with language editing. Text generation tools can help to rapidly generate original contents by just giving the AI a few keyword ideas to work with.
Perhaps this could help end writer’s block? This is a debatable question that is best saved for a later time.
Paraphrasing content is also another great way to take existing content (either from your own or from others) and add your own spin to it. Wouldn’t it be great if we could paraphrase text automatically?
In this article, you will learn how to paraphrase text for FREE in Python using the PARROT library. Particularly, under the hood PARROT’s paraphrasing technology is based on the T5 algorithm (an acronym for Text-To-Text Transfer Transformer) that was originally developed by Google (for more information refer to the T5 resource at Papers with Code). At a high-level, text generation is niche area of the exciting area of natural language processing (NLP), which is generally referred to as artificial intelligence or AI when explained to the general audience.
It should be noted that an accompanying YouTube video (How to paraphrase text in Python using the PARROT library (Ft. Ken Jee)) to this article is shown below.
We’re going to perform the text paraphrasing on the cloud using Google Colab, which is an online version of the Jupyter notebook that allows you to run Python code on the cloud. If you’re new to Google Colab, you will want to brush up on the basics in the Introductory notebook.
Log into your Gmail account, then go to Google Colab.Launch the tutorial notebook by first heading over to File > Open Notebook and then click on the Upload tab (far right).Type dataprofessor/parrot into the search boxClick on the parrot.ipynb file
Log into your Gmail account, then go to Google Colab.
Launch the tutorial notebook by first heading over to File > Open Notebook and then click on the Upload tab (far right).
Type dataprofessor/parrot into the search box
Click on the parrot.ipynb file
The PARROT library can be installed via pip by typing the following into the code cell:
! pip install git+https://github.com/PrithivirajDamodaran/Parrot.git
Library installation should take a short moment.
Here, we’re going to import 3 Python libraries consisting of parrot, torch and warnings. You can go ahead and type the following (or copy and paste) into a code cell then run it either by pressing the CTRL + Enter buttons (Windows and Linux) or the CMD + Enter buttons (Mac OSX). Alternatively, the code cell can also be run by clicking on the play button found to the left of the code cell.
from parrot import Parrotimport torchimport warningswarnings.filterwarnings("ignore")
The parrot library contains the pre-trained text paraphrasing model that we will use to perform the paraphrasing task.
Under the hood, the pre-trained text paraphrasing model was created using PyTorch (torch) and thus we’re importing it here in order to run the model. This model is called parrot_paraphraser_on_T5 and is listed on the Hugging Face website. It should be noted that Hugging Face is the company that develops the transformer library which hosts the parrot_paraphraser_on_T5 model.
As the code implies, warnings that appears will be ignored via the warnings library.
In order to allow reproducibility of the text paraphrasing, the random seed number will be set. What this does is produce the same results for the same seed number (even if it is re-run multiple times).
To set the random seed number for reproducibility, enter the following code block into the code cell:
def random_state(seed): torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)random_state(1234)
We will now load and initialize the PARROT model by entering the following into a code cell and run the cell.
parrot = Parrot(model_tag="prithivida/parrot_paraphraser_on_T5", use_gpu=False)
The models will be loaded as shown below:
The input text for this example, which is What’s the most delicious papayas?, will be assigned to the phrases variable, which we will be using in just a moment.
To find out the answer to that make sure to watch the accompanying YouTube video (How to paraphrase text in Python using the PARROT library (Ft. Ken Jee)).
phrases = ["What's the most delicious papayas?"]
Now, to the fun part of generating the paraphrased text using the PARROT T5 model.
Enter the following code block into the code cell and run the cell.
for phrase in phrases: print("-"*100) print("Input_phrase: ", phrase) print("-"*100) para_phrases = parrot.augment(input_phrase=phrase) for para_phrase in para_phrases: print(para_phrase)
Here, we’ll be using a for loop to iterate through all the sentences in the phrases variable (in the example above we assigned only a single sentence or a single phrase to this variable).
For each phrase in the phrases variable:
Print out the - character for 100 times.
Print "Input phrase: " followed by the returned output of the phrase that is being iterated.
Print out the - character for 100 times.
Perform the paraphrasing using the parrot.augment() function that takes in as input argument the phrase being iterated. Generated paraphrases are assigned to the para_phrases variable.
Perform a nested for loop on the para_phrases variable: — Print the returned output of the paraphrases from the para_phrases variable that have been generated iteratively (the 4 paraphrased text that we will soon see in the next section).
This code block generates the following output:
Here, we can see that PARROT produces 4 paraphrased text and you can choose any of these for further usage.
Congratulations, you can successfully produced paraphrased text using AI!
In case you’re interested in taking this a step or two further.
Here are some project ideas that you can try out and build to expand your own portfolio of projects. Speaking of portfolios, you can learn how to build a portfolio website for free from this recent article that I wrote:
towardsdatascience.com
Create a Colab/Jupyter notebook that expands on this example (which generates paraphrased text for a single input phrase) by making a version that can take in multiple phrases as input. For example, we can assign a paragraph consisting of a couple of phrases to an input variable, which is then used by the code to generate paraphrased text. Then for the returned outputs of each phrase, randomly select a single output to represent each of the phrase (i.e. each input phrase will correspondingly have 1 paraphrased text). Combine the paraphrased phrases together into a new paragraph. Compare the original paragraph and the new paraphrased paragraph.
Expand on Project Idea 1 by making it into a web app using Streamlit (Also check out the Streamlit Tutorial Playlist) or PyWebIO. Particularly, the web app would take as input a paragraph of phrases and applies the code to generate paraphrased text and return them as output in the main panel of the web app.
I’d love to see some of your creations and so please feel free to post them in the comment section. Happy creation!
Code used in this article was adapted from the example provided by Parrot creator Prithiviraj Damodaran.
I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page).
www.youtube.com
✅ YouTube: http://youtube.com/dataprofessor/✅ Website: http://dataprofessor.org/ (Under construction)✅ LinkedIn: https://www.linkedin.com/company/dataprofessor/✅ Twitter: https://twitter.com/thedataprof✅ FaceBook: http://facebook.com/dataprofessor/✅ GitHub: https://github.com/dataprofessor/✅ Instagram: https://www.instagram.com/data.professor/
|
[
{
"code": null,
"e": 436,
"s": 171,
"text": "As writers, we often seek out tools to help us become more efficient or productive. Tools such as Grammarly can help with language editing. Text generation tools can help to rapidly generate original contents by just giving the AI a few keyword ideas to work with."
},
{
"code": null,
"e": 546,
"s": 436,
"text": "Perhaps this could help end writer’s block? This is a debatable question that is best saved for a later time."
},
{
"code": null,
"e": 749,
"s": 546,
"text": "Paraphrasing content is also another great way to take existing content (either from your own or from others) and add your own spin to it. Wouldn’t it be great if we could paraphrase text automatically?"
},
{
"code": null,
"e": 1310,
"s": 749,
"text": "In this article, you will learn how to paraphrase text for FREE in Python using the PARROT library. Particularly, under the hood PARROT’s paraphrasing technology is based on the T5 algorithm (an acronym for Text-To-Text Transfer Transformer) that was originally developed by Google (for more information refer to the T5 resource at Papers with Code). At a high-level, text generation is niche area of the exciting area of natural language processing (NLP), which is generally referred to as artificial intelligence or AI when explained to the general audience."
},
{
"code": null,
"e": 1470,
"s": 1310,
"text": "It should be noted that an accompanying YouTube video (How to paraphrase text in Python using the PARROT library (Ft. Ken Jee)) to this article is shown below."
},
{
"code": null,
"e": 1749,
"s": 1470,
"text": "We’re going to perform the text paraphrasing on the cloud using Google Colab, which is an online version of the Jupyter notebook that allows you to run Python code on the cloud. If you’re new to Google Colab, you will want to brush up on the basics in the Introductory notebook."
},
{
"code": null,
"e": 1998,
"s": 1749,
"text": "Log into your Gmail account, then go to Google Colab.Launch the tutorial notebook by first heading over to File > Open Notebook and then click on the Upload tab (far right).Type dataprofessor/parrot into the search boxClick on the parrot.ipynb file"
},
{
"code": null,
"e": 2052,
"s": 1998,
"text": "Log into your Gmail account, then go to Google Colab."
},
{
"code": null,
"e": 2173,
"s": 2052,
"text": "Launch the tutorial notebook by first heading over to File > Open Notebook and then click on the Upload tab (far right)."
},
{
"code": null,
"e": 2219,
"s": 2173,
"text": "Type dataprofessor/parrot into the search box"
},
{
"code": null,
"e": 2250,
"s": 2219,
"text": "Click on the parrot.ipynb file"
},
{
"code": null,
"e": 2338,
"s": 2250,
"text": "The PARROT library can be installed via pip by typing the following into the code cell:"
},
{
"code": null,
"e": 2407,
"s": 2338,
"text": "! pip install git+https://github.com/PrithivirajDamodaran/Parrot.git"
},
{
"code": null,
"e": 2456,
"s": 2407,
"text": "Library installation should take a short moment."
},
{
"code": null,
"e": 2848,
"s": 2456,
"text": "Here, we’re going to import 3 Python libraries consisting of parrot, torch and warnings. You can go ahead and type the following (or copy and paste) into a code cell then run it either by pressing the CTRL + Enter buttons (Windows and Linux) or the CMD + Enter buttons (Mac OSX). Alternatively, the code cell can also be run by clicking on the play button found to the left of the code cell."
},
{
"code": null,
"e": 2934,
"s": 2848,
"text": "from parrot import Parrotimport torchimport warningswarnings.filterwarnings(\"ignore\")"
},
{
"code": null,
"e": 3053,
"s": 2934,
"text": "The parrot library contains the pre-trained text paraphrasing model that we will use to perform the paraphrasing task."
},
{
"code": null,
"e": 3430,
"s": 3053,
"text": "Under the hood, the pre-trained text paraphrasing model was created using PyTorch (torch) and thus we’re importing it here in order to run the model. This model is called parrot_paraphraser_on_T5 and is listed on the Hugging Face website. It should be noted that Hugging Face is the company that develops the transformer library which hosts the parrot_paraphraser_on_T5 model."
},
{
"code": null,
"e": 3515,
"s": 3430,
"text": "As the code implies, warnings that appears will be ignored via the warnings library."
},
{
"code": null,
"e": 3718,
"s": 3515,
"text": "In order to allow reproducibility of the text paraphrasing, the random seed number will be set. What this does is produce the same results for the same seed number (even if it is re-run multiple times)."
},
{
"code": null,
"e": 3820,
"s": 3718,
"text": "To set the random seed number for reproducibility, enter the following code block into the code cell:"
},
{
"code": null,
"e": 3954,
"s": 3820,
"text": "def random_state(seed): torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)random_state(1234)"
},
{
"code": null,
"e": 4064,
"s": 3954,
"text": "We will now load and initialize the PARROT model by entering the following into a code cell and run the cell."
},
{
"code": null,
"e": 4144,
"s": 4064,
"text": "parrot = Parrot(model_tag=\"prithivida/parrot_paraphraser_on_T5\", use_gpu=False)"
},
{
"code": null,
"e": 4186,
"s": 4144,
"text": "The models will be loaded as shown below:"
},
{
"code": null,
"e": 4347,
"s": 4186,
"text": "The input text for this example, which is What’s the most delicious papayas?, will be assigned to the phrases variable, which we will be using in just a moment."
},
{
"code": null,
"e": 4503,
"s": 4347,
"text": "To find out the answer to that make sure to watch the accompanying YouTube video (How to paraphrase text in Python using the PARROT library (Ft. Ken Jee))."
},
{
"code": null,
"e": 4552,
"s": 4503,
"text": "phrases = [\"What's the most delicious papayas?\"]"
},
{
"code": null,
"e": 4635,
"s": 4552,
"text": "Now, to the fun part of generating the paraphrased text using the PARROT T5 model."
},
{
"code": null,
"e": 4703,
"s": 4635,
"text": "Enter the following code block into the code cell and run the cell."
},
{
"code": null,
"e": 4898,
"s": 4703,
"text": "for phrase in phrases: print(\"-\"*100) print(\"Input_phrase: \", phrase) print(\"-\"*100) para_phrases = parrot.augment(input_phrase=phrase) for para_phrase in para_phrases: print(para_phrase)"
},
{
"code": null,
"e": 5086,
"s": 4898,
"text": "Here, we’ll be using a for loop to iterate through all the sentences in the phrases variable (in the example above we assigned only a single sentence or a single phrase to this variable)."
},
{
"code": null,
"e": 5127,
"s": 5086,
"text": "For each phrase in the phrases variable:"
},
{
"code": null,
"e": 5168,
"s": 5127,
"text": "Print out the - character for 100 times."
},
{
"code": null,
"e": 5261,
"s": 5168,
"text": "Print \"Input phrase: \" followed by the returned output of the phrase that is being iterated."
},
{
"code": null,
"e": 5302,
"s": 5261,
"text": "Print out the - character for 100 times."
},
{
"code": null,
"e": 5487,
"s": 5302,
"text": "Perform the paraphrasing using the parrot.augment() function that takes in as input argument the phrase being iterated. Generated paraphrases are assigned to the para_phrases variable."
},
{
"code": null,
"e": 5726,
"s": 5487,
"text": "Perform a nested for loop on the para_phrases variable: — Print the returned output of the paraphrases from the para_phrases variable that have been generated iteratively (the 4 paraphrased text that we will soon see in the next section)."
},
{
"code": null,
"e": 5774,
"s": 5726,
"text": "This code block generates the following output:"
},
{
"code": null,
"e": 5882,
"s": 5774,
"text": "Here, we can see that PARROT produces 4 paraphrased text and you can choose any of these for further usage."
},
{
"code": null,
"e": 5956,
"s": 5882,
"text": "Congratulations, you can successfully produced paraphrased text using AI!"
},
{
"code": null,
"e": 6020,
"s": 5956,
"text": "In case you’re interested in taking this a step or two further."
},
{
"code": null,
"e": 6240,
"s": 6020,
"text": "Here are some project ideas that you can try out and build to expand your own portfolio of projects. Speaking of portfolios, you can learn how to build a portfolio website for free from this recent article that I wrote:"
},
{
"code": null,
"e": 6263,
"s": 6240,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6915,
"s": 6263,
"text": "Create a Colab/Jupyter notebook that expands on this example (which generates paraphrased text for a single input phrase) by making a version that can take in multiple phrases as input. For example, we can assign a paragraph consisting of a couple of phrases to an input variable, which is then used by the code to generate paraphrased text. Then for the returned outputs of each phrase, randomly select a single output to represent each of the phrase (i.e. each input phrase will correspondingly have 1 paraphrased text). Combine the paraphrased phrases together into a new paragraph. Compare the original paragraph and the new paraphrased paragraph."
},
{
"code": null,
"e": 7224,
"s": 6915,
"text": "Expand on Project Idea 1 by making it into a web app using Streamlit (Also check out the Streamlit Tutorial Playlist) or PyWebIO. Particularly, the web app would take as input a paragraph of phrases and applies the code to generate paraphrased text and return them as output in the main panel of the web app."
},
{
"code": null,
"e": 7340,
"s": 7224,
"text": "I’d love to see some of your creations and so please feel free to post them in the comment section. Happy creation!"
},
{
"code": null,
"e": 7445,
"s": 7340,
"text": "Code used in this article was adapted from the example provided by Parrot creator Prithiviraj Damodaran."
},
{
"code": null,
"e": 7807,
"s": 7445,
"text": "I work full-time as an Associate Professor of Bioinformatics and Head of Data Mining and Biomedical Informatics at a Research University in Thailand. In my after work hours, I’m a YouTuber (AKA the Data Professor) making online videos about data science. In all tutorial videos that I make, I also share Jupyter notebooks on GitHub (Data Professor GitHub page)."
},
{
"code": null,
"e": 7823,
"s": 7807,
"text": "www.youtube.com"
}
] |
Python - Order Tuples by List - GeeksforGeeks
|
10 Jul, 2020
Sometimes, while working with Python tuples, we can have a problem in which we need to perform ordering of all the tuples keys using external list. This problem can have application in data domains such as Data Science. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(‘Gfg’, 10), (‘best’, 3), (‘CS’, 8), (‘Geeks’, 7)], ord_list = [‘Geeks’, ‘best’, ‘CS’, ‘Gfg’]Output : [(‘Geeks’, 7), (‘best’, 3), (‘CS’, 8), (‘Gfg’, 10)]
Input : test_list = [(‘best’, 3), (‘CS’, 8), (‘Geeks’, 7)], ord_list = [‘Geeks’, ‘best’, ‘CS’]Output : [(‘Geeks’, 7), (‘best’, 3), (‘CS’, 8)]
Method #1 : Using dict() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform this task by converting tuple list to dictionaries, and as a second step use list comprehension to iterate through list and map the dictionary keys with values.
# Python3 code to demonstrate working of # Order Tuples by List# Using dict() + list comprehension # initializing listtest_list = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] # printing original listprint("The original list is : " + str(test_list)) # initializing order list ord_list = ['Geeks', 'best', 'CS', 'Gfg'] # Order Tuples by List# Using dict() + list comprehensiontemp = dict(test_list)res = [(key, temp[key]) for key in ord_list] # printing result print("The ordered tuple list : " + str(res))
The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
The ordered tuple list : [('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]
Method #2 : Using setdefault() + sorted() + lambdaThe combination of above functions can be used to solve this problem. In this, we perform task of mapping elements to indices and creating a lookup using setdefault. And, as a second step, using sorted to sort list using lookup dictionary value list.
# Python3 code to demonstrate working of # Order Tuples by List# Using setdefault() + sorted() + lambda # initializing listtest_list = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] # printing original listprint("The original list is : " + str(test_list)) # initializing order list ord_list = ['Geeks', 'best', 'CS', 'Gfg'] # Order Tuples by List# Using setdefault() + sorted() + lambdatemp = dict()for key, ele in enumerate(ord_list): temp.setdefault(ele, []).append(key) res = sorted(test_list, key = lambda ele: temp[ele[0]].pop()) # printing result print("The ordered tuple list : " + str(res))
The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]
The ordered tuple list : [('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]
Python List-of-Tuples
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 24211,
"s": 23927,
"text": "Sometimes, while working with Python tuples, we can have a problem in which we need to perform ordering of all the tuples keys using external list. This problem can have application in data domains such as Data Science. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 24386,
"s": 24211,
"text": "Input : test_list = [(‘Gfg’, 10), (‘best’, 3), (‘CS’, 8), (‘Geeks’, 7)], ord_list = [‘Geeks’, ‘best’, ‘CS’, ‘Gfg’]Output : [(‘Geeks’, 7), (‘best’, 3), (‘CS’, 8), (‘Gfg’, 10)]"
},
{
"code": null,
"e": 24528,
"s": 24386,
"text": "Input : test_list = [(‘best’, 3), (‘CS’, 8), (‘Geeks’, 7)], ord_list = [‘Geeks’, ‘best’, ‘CS’]Output : [(‘Geeks’, 7), (‘best’, 3), (‘CS’, 8)]"
},
{
"code": null,
"e": 24824,
"s": 24528,
"text": "Method #1 : Using dict() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform this task by converting tuple list to dictionaries, and as a second step use list comprehension to iterate through list and map the dictionary keys with values."
},
{
"code": "# Python3 code to demonstrate working of # Order Tuples by List# Using dict() + list comprehension # initializing listtest_list = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing order list ord_list = ['Geeks', 'best', 'CS', 'Gfg'] # Order Tuples by List# Using dict() + list comprehensiontemp = dict(test_list)res = [(key, temp[key]) for key in ord_list] # printing result print(\"The ordered tuple list : \" + str(res)) ",
"e": 25342,
"s": 24824,
"text": null
},
{
"code": null,
"e": 25495,
"s": 25342,
"text": "The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]\nThe ordered tuple list : [('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]\n"
},
{
"code": null,
"e": 25798,
"s": 25497,
"text": "Method #2 : Using setdefault() + sorted() + lambdaThe combination of above functions can be used to solve this problem. In this, we perform task of mapping elements to indices and creating a lookup using setdefault. And, as a second step, using sorted to sort list using lookup dictionary value list."
},
{
"code": "# Python3 code to demonstrate working of # Order Tuples by List# Using setdefault() + sorted() + lambda # initializing listtest_list = [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing order list ord_list = ['Geeks', 'best', 'CS', 'Gfg'] # Order Tuples by List# Using setdefault() + sorted() + lambdatemp = dict()for key, ele in enumerate(ord_list): temp.setdefault(ele, []).append(key) res = sorted(test_list, key = lambda ele: temp[ele[0]].pop()) # printing result print(\"The ordered tuple list : \" + str(res)) ",
"e": 26419,
"s": 25798,
"text": null
},
{
"code": null,
"e": 26572,
"s": 26419,
"text": "The original list is : [('Gfg', 3), ('best', 9), ('CS', 10), ('Geeks', 2)]\nThe ordered tuple list : [('Geeks', 2), ('best', 9), ('CS', 10), ('Gfg', 3)]\n"
},
{
"code": null,
"e": 26594,
"s": 26572,
"text": "Python List-of-Tuples"
},
{
"code": null,
"e": 26616,
"s": 26594,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 26623,
"s": 26616,
"text": "Python"
},
{
"code": null,
"e": 26639,
"s": 26623,
"text": "Python Programs"
},
{
"code": null,
"e": 26737,
"s": 26639,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26746,
"s": 26737,
"text": "Comments"
},
{
"code": null,
"e": 26759,
"s": 26746,
"text": "Old Comments"
},
{
"code": null,
"e": 26791,
"s": 26759,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26847,
"s": 26791,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26889,
"s": 26847,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26931,
"s": 26889,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26967,
"s": 26931,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 26989,
"s": 26967,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27028,
"s": 26989,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27074,
"s": 27028,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27112,
"s": 27074,
"text": "Python | Convert a list to dictionary"
}
] |
Problems on min-max normalization - GeeksforGeeks
|
16 Jul, 2021
Overview :The measurement unit used can affect the data analysis. For instance, changing the measurement unit from kg to pounds. Expressing an attribute in smaller units will lead to a larger range for that attribute and thus give inefficient results. To avoid the dependence on the choice of measurement units, the data should be normalized. Normalization is used for scaling the data of attributes so that it falls in a smaller range, such as -2.0 to 2.0. It is usually used in classification algorithms.
Use of normalization :Normalization is required when we deal with attributes having a different scale, and it may lead to less effectiveness of an important attribute(having a lower scale) because of other attributes having values on a larger scale. It also decreases the training time needed for the machine to learn the data. Thus, the efficiency of the machine learning model increases after the dataset is normalized.
Min-Max Normalization :In this technique of knowledge normalization, a linear transformation is performed on the first data. Minimum and maximum value from data is fetched and each value is replaced according to the following formula. Min-Max Normalization preserves the relationships among the original data values. It will encounter an out-of-bounds error if a future input case for normalization falls outside the first data range for A. The formula is given below-
Where A is the attribute data represent as follows.
Min(A) - It is the minimum absolute value A.
Max(A) - It is maximum absolute value of A.
v’ - It is the new value of each attribute data.
v - It is the old value of each attribute data.
new_max(A), new_min(A) is the max and min value within the range
(i.e boundary value of range required) respectively.
Min-Max Normalization maps a value v of A to v' in the range
[new_min(A),new_max(A)] by computing.
Example :Here, we will discuss an example as follows.Normalize the following group of data –
1000,2000,3000,9000
using min-max normalization by setting min:0 and max:1
Solution –
here,new_max(A)=1 , as given in question- max=1
new_min(A)=0,as given in question- min=0
max(A)=9000,as the maximum data among 1000,2000,3000,9000 is 9000
min(A)=1000,as the minimum data among 1000,2000,3000,9000 is 1000
Case-1: normalizing 1000 –
v = 1000 , putting all values in the formula,we get
v' = (1000-1000) X (1-0)
----------------- + 0 =0
9000-1000
Case-2: normalizing 2000 –
v = 2000, putting all values in the formula,we get
v '= (2000-1000) X (1-0)
----------------- + 0 =0 .125
9000-1000
Case-3: normalizing 3000 –
v=3000, putting all values in the formula,we get
v'=(3000-1000) X (1-0)
----------------- + 0 =0 .25
9000-1000
Case-4: normalizing 9000 –
v=9000, putting all values in the formula, we get
v'=(9000-1000) X (1-0)
----------------- + 0 =1
9000-1000
Outcome :Hence, the normalized values of 1000,2000,3000,9000 are 0, 0.125, .25, 1.
abhijithoyur
data mining
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Introduction to Parallel Computing
|
[
{
"code": null,
"e": 25893,
"s": 25865,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 26400,
"s": 25893,
"text": "Overview :The measurement unit used can affect the data analysis. For instance, changing the measurement unit from kg to pounds. Expressing an attribute in smaller units will lead to a larger range for that attribute and thus give inefficient results. To avoid the dependence on the choice of measurement units, the data should be normalized. Normalization is used for scaling the data of attributes so that it falls in a smaller range, such as -2.0 to 2.0. It is usually used in classification algorithms."
},
{
"code": null,
"e": 26822,
"s": 26400,
"text": "Use of normalization :Normalization is required when we deal with attributes having a different scale, and it may lead to less effectiveness of an important attribute(having a lower scale) because of other attributes having values on a larger scale. It also decreases the training time needed for the machine to learn the data. Thus, the efficiency of the machine learning model increases after the dataset is normalized."
},
{
"code": null,
"e": 27291,
"s": 26822,
"text": "Min-Max Normalization :In this technique of knowledge normalization, a linear transformation is performed on the first data. Minimum and maximum value from data is fetched and each value is replaced according to the following formula. Min-Max Normalization preserves the relationships among the original data values. It will encounter an out-of-bounds error if a future input case for normalization falls outside the first data range for A. The formula is given below-"
},
{
"code": null,
"e": 27343,
"s": 27291,
"text": "Where A is the attribute data represent as follows."
},
{
"code": null,
"e": 27763,
"s": 27343,
"text": "Min(A) - It is the minimum absolute value A.\nMax(A) - It is maximum absolute value of A.\nv’ - It is the new value of each attribute data.\nv - It is the old value of each attribute data.\n\nnew_max(A), new_min(A) is the max and min value within the range\n(i.e boundary value of range required) respectively.\n\nMin-Max Normalization maps a value v of A to v' in the range \n[new_min(A),new_max(A)] by computing."
},
{
"code": null,
"e": 27856,
"s": 27763,
"text": "Example :Here, we will discuss an example as follows.Normalize the following group of data –"
},
{
"code": null,
"e": 27931,
"s": 27856,
"text": "1000,2000,3000,9000\nusing min-max normalization by setting min:0 and max:1"
},
{
"code": null,
"e": 27942,
"s": 27931,
"text": "Solution –"
},
{
"code": null,
"e": 28163,
"s": 27942,
"text": "here,new_max(A)=1 , as given in question- max=1\nnew_min(A)=0,as given in question- min=0\nmax(A)=9000,as the maximum data among 1000,2000,3000,9000 is 9000\nmin(A)=1000,as the minimum data among 1000,2000,3000,9000 is 1000"
},
{
"code": null,
"e": 28190,
"s": 28163,
"text": "Case-1: normalizing 1000 –"
},
{
"code": null,
"e": 28320,
"s": 28190,
"text": "v = 1000 , putting all values in the formula,we get\nv' = (1000-1000) X (1-0)\n ----------------- + 0 =0\n 9000-1000"
},
{
"code": null,
"e": 28347,
"s": 28320,
"text": "Case-2: normalizing 2000 –"
},
{
"code": null,
"e": 28496,
"s": 28347,
"text": "v = 2000, putting all values in the formula,we get\nv '= (2000-1000) X (1-0) \n ----------------- + 0 =0 .125 \n 9000-1000"
},
{
"code": null,
"e": 28523,
"s": 28496,
"text": "Case-3: normalizing 3000 –"
},
{
"code": null,
"e": 28665,
"s": 28523,
"text": "v=3000, putting all values in the formula,we get\nv'=(3000-1000) X (1-0) \n ----------------- + 0 =0 .25 \n 9000-1000"
},
{
"code": null,
"e": 28692,
"s": 28665,
"text": "Case-4: normalizing 9000 –"
},
{
"code": null,
"e": 28815,
"s": 28692,
"text": "v=9000, putting all values in the formula, we get\nv'=(9000-1000) X (1-0) \n ----------------- + 0 =1\n 9000-1000"
},
{
"code": null,
"e": 28898,
"s": 28815,
"text": "Outcome :Hence, the normalized values of 1000,2000,3000,9000 are 0, 0.125, .25, 1."
},
{
"code": null,
"e": 28911,
"s": 28898,
"text": "abhijithoyur"
},
{
"code": null,
"e": 28923,
"s": 28911,
"text": "data mining"
},
{
"code": null,
"e": 28928,
"s": 28923,
"text": "Misc"
},
{
"code": null,
"e": 28933,
"s": 28928,
"text": "Misc"
},
{
"code": null,
"e": 28938,
"s": 28933,
"text": "Misc"
},
{
"code": null,
"e": 29036,
"s": 28938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29057,
"s": 29036,
"text": "Activation Functions"
},
{
"code": null,
"e": 29095,
"s": 29057,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 29131,
"s": 29095,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 29166,
"s": 29131,
"text": "Sensors in Internet of Things(IoT)"
},
{
"code": null,
"e": 29205,
"s": 29166,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 29251,
"s": 29205,
"text": "Election algorithm and distributed processing"
},
{
"code": null,
"e": 29300,
"s": 29251,
"text": "Introduction to Internet of Things (IoT) | Set 1"
},
{
"code": null,
"e": 29332,
"s": 29300,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 29382,
"s": 29332,
"text": "Communication Models in IoT (Internet of Things )"
}
] |
Best First Search (Informed Search) - GeeksforGeeks
|
12 Apr, 2022
Prerequisites : BFS, DFS In BFS and DFS, when we are at a node, we can consider any of the adjacent as next node. So both BFS and DFS blindly explore paths without considering any cost function. The idea of Best First Search is to use an evaluation function to decide which adjacent is most promising and then explore. Best First Search falls under the category of Heuristic Search or Informed Search.
We use a priority queue or heap to store costs of nodes which have lowest evaluation function value. So the implementation is a variation of BFS, we just need to change Queue to PriorityQueue.
// This pseudocode is adapted from below
// source:
// https://courses.cs.washington.edu/
Best-First-Search(Graph g, Node start)
1) Create an empty PriorityQueue
PriorityQueue pq;
2) Insert "start" in pq.
pq.insert(start)
3) Until PriorityQueue is empty
u = PriorityQueue.DeleteMin
If u is the goal
Exit
Else
Foreach neighbor v of u
If v "Unvisited"
Mark v "Visited"
pq.insert(v)
Mark u "Examined"
End procedure
Let us consider the below example.
We start from source "S" and search for
goal "I" using given costs and Best
First search.
pq initially contains S
We remove s from and process unvisited
neighbors of S to pq.
pq now contains {A, C, B} (C is put
before B because C has lesser cost)
We remove A from pq and process unvisited
neighbors of A to pq.
pq now contains {C, B, E, D}
We remove C from pq and process unvisited
neighbors of C to pq.
pq now contains {B, H, E, D}
We remove B from pq and process unvisited
neighbors of B to pq.
pq now contains {H, E, D, F, G}
We remove H from pq. Since our goal
"I" is a neighbor of H, we return.
Below is the implementation of the above idea:
C++
Python3
// C++ program to implement Best First Search using priority// queue#include <bits/stdc++.h>using namespace std;typedef pair<int, int> pi; vector<vector<pi> > graph; // Function for adding edges to graphvoid addedge(int x, int y, int cost){ graph[x].push_back(make_pair(cost, y)); graph[y].push_back(make_pair(cost, x));} // Function For Implementing Best First Search// Gives output path having lowest costvoid best_first_search(int source, int target, int n){ vector<bool> visited(n, false); // MIN HEAP priority queue priority_queue<pi, vector<pi>, greater<pi> > pq; // sorting in pq gets done by first value of pair pq.push(make_pair(0, source)); int s = source; visited[s] = true; while (!pq.empty()) { int x = pq.top().second; // Displaying the path having lowest cost cout << x << " "; pq.pop(); if (x == target) break; for (int i = 0; i < graph[x].size(); i++) { if (!visited[graph[x][i].second]) { visited[graph[x][i].second] = true; pq.push(make_pair(graph[x][i].first,graph[x][i].second)); } } }} // Driver code to test above methodsint main(){ // No. of Nodes int v = 14; graph.resize(v); // The nodes shown in above example(by alphabets) are // implemented using integers addedge(x,y,cost); addedge(0, 1, 3); addedge(0, 2, 6); addedge(0, 3, 5); addedge(1, 4, 9); addedge(1, 5, 8); addedge(2, 6, 12); addedge(2, 7, 14); addedge(3, 8, 7); addedge(8, 9, 5); addedge(8, 10, 6); addedge(9, 11, 1); addedge(9, 12, 10); addedge(9, 13, 2); int source = 0; int target = 9; // Function call best_first_search(source, target, v); return 0;}
from queue import PriorityQueuev = 14graph = [[] for i in range(v)] # Function For Implementing Best First Search# Gives output path having lowest cost def best_first_search(source, target, n): visited = [False] * n visited = True pq = PriorityQueue() pq.put((0, source)) while pq.empty() == False: u = pq.get()[1] # Displaying the path having lowest cost print(u, end=" ") if u == target: break for v, c in graph[u]: if visited[v] == False: visited[v] = True pq.put((c, v)) print() # Function for adding edges to graph def addedge(x, y, cost): graph[x].append((y, cost)) graph[y].append((x, cost)) # The nodes shown in above example(by alphabets) are# implemented using integers addedge(x,y,cost);addedge(0, 1, 3)addedge(0, 2, 6)addedge(0, 3, 5)addedge(1, 4, 9)addedge(1, 5, 8)addedge(2, 6, 12)addedge(2, 7, 14)addedge(3, 8, 7)addedge(8, 9, 5)addedge(8, 10, 6)addedge(9, 11, 1)addedge(9, 12, 10)addedge(9, 13, 2) source = 0target = 9best_first_search(source, target, v) # This code is contributed by Jyotheeswar Ganne
0 1 3 2 8 9
Analysis :
worst case time complexity for Best First Search is O(n * Log n) where n is number of nodes. In worst case, we may have to visit all nodes before we reach goal. Note that priority queue is implemented using Min(or Max) Heap, and insert and remove operations take O(log n) time.
Performance of the algorithm depends on how well the cost or evaluation function is designed.
Special case of Best first search :
1. Greedy Best first search algorithm
2. A* search algorithm
Related Article: A* Search Algorithm This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManuelRaimann
tech_shot
jyotheeswarganne60
iamwiz
sumitgumber28
amartyaghoshgfg
akmore90
surbhikumaridav
BFS
Graph
Searching
Searching
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Strongly Connected Components
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number
|
[
{
"code": null,
"e": 26263,
"s": 26235,
"text": "\n12 Apr, 2022"
},
{
"code": null,
"e": 26665,
"s": 26263,
"text": "Prerequisites : BFS, DFS In BFS and DFS, when we are at a node, we can consider any of the adjacent as next node. So both BFS and DFS blindly explore paths without considering any cost function. The idea of Best First Search is to use an evaluation function to decide which adjacent is most promising and then explore. Best First Search falls under the category of Heuristic Search or Informed Search."
},
{
"code": null,
"e": 26859,
"s": 26665,
"text": "We use a priority queue or heap to store costs of nodes which have lowest evaluation function value. So the implementation is a variation of BFS, we just need to change Queue to PriorityQueue. "
},
{
"code": null,
"e": 27463,
"s": 26859,
"text": "// This pseudocode is adapted from below \n// source:\n// https://courses.cs.washington.edu/\nBest-First-Search(Graph g, Node start)\n 1) Create an empty PriorityQueue\n PriorityQueue pq;\n 2) Insert \"start\" in pq.\n pq.insert(start)\n 3) Until PriorityQueue is empty\n u = PriorityQueue.DeleteMin\n If u is the goal\n Exit\n Else\n Foreach neighbor v of u\n If v \"Unvisited\"\n Mark v \"Visited\" \n pq.insert(v)\n Mark u \"Examined\" \nEnd procedure"
},
{
"code": null,
"e": 27500,
"s": 27463,
"text": "Let us consider the below example. "
},
{
"code": null,
"e": 28106,
"s": 27500,
"text": "We start from source \"S\" and search for\ngoal \"I\" using given costs and Best\nFirst search.\n\npq initially contains S\nWe remove s from and process unvisited\nneighbors of S to pq.\npq now contains {A, C, B} (C is put\nbefore B because C has lesser cost)\n\nWe remove A from pq and process unvisited\nneighbors of A to pq.\npq now contains {C, B, E, D}\n\nWe remove C from pq and process unvisited\nneighbors of C to pq.\npq now contains {B, H, E, D}\n\nWe remove B from pq and process unvisited\nneighbors of B to pq.\npq now contains {H, E, D, F, G}\n\nWe remove H from pq. Since our goal\n\"I\" is a neighbor of H, we return."
},
{
"code": null,
"e": 28153,
"s": 28106,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 28157,
"s": 28153,
"text": "C++"
},
{
"code": null,
"e": 28165,
"s": 28157,
"text": "Python3"
},
{
"code": "// C++ program to implement Best First Search using priority// queue#include <bits/stdc++.h>using namespace std;typedef pair<int, int> pi; vector<vector<pi> > graph; // Function for adding edges to graphvoid addedge(int x, int y, int cost){ graph[x].push_back(make_pair(cost, y)); graph[y].push_back(make_pair(cost, x));} // Function For Implementing Best First Search// Gives output path having lowest costvoid best_first_search(int source, int target, int n){ vector<bool> visited(n, false); // MIN HEAP priority queue priority_queue<pi, vector<pi>, greater<pi> > pq; // sorting in pq gets done by first value of pair pq.push(make_pair(0, source)); int s = source; visited[s] = true; while (!pq.empty()) { int x = pq.top().second; // Displaying the path having lowest cost cout << x << \" \"; pq.pop(); if (x == target) break; for (int i = 0; i < graph[x].size(); i++) { if (!visited[graph[x][i].second]) { visited[graph[x][i].second] = true; pq.push(make_pair(graph[x][i].first,graph[x][i].second)); } } }} // Driver code to test above methodsint main(){ // No. of Nodes int v = 14; graph.resize(v); // The nodes shown in above example(by alphabets) are // implemented using integers addedge(x,y,cost); addedge(0, 1, 3); addedge(0, 2, 6); addedge(0, 3, 5); addedge(1, 4, 9); addedge(1, 5, 8); addedge(2, 6, 12); addedge(2, 7, 14); addedge(3, 8, 7); addedge(8, 9, 5); addedge(8, 10, 6); addedge(9, 11, 1); addedge(9, 12, 10); addedge(9, 13, 2); int source = 0; int target = 9; // Function call best_first_search(source, target, v); return 0;}",
"e": 29927,
"s": 28165,
"text": null
},
{
"code": "from queue import PriorityQueuev = 14graph = [[] for i in range(v)] # Function For Implementing Best First Search# Gives output path having lowest cost def best_first_search(source, target, n): visited = [False] * n visited = True pq = PriorityQueue() pq.put((0, source)) while pq.empty() == False: u = pq.get()[1] # Displaying the path having lowest cost print(u, end=\" \") if u == target: break for v, c in graph[u]: if visited[v] == False: visited[v] = True pq.put((c, v)) print() # Function for adding edges to graph def addedge(x, y, cost): graph[x].append((y, cost)) graph[y].append((x, cost)) # The nodes shown in above example(by alphabets) are# implemented using integers addedge(x,y,cost);addedge(0, 1, 3)addedge(0, 2, 6)addedge(0, 3, 5)addedge(1, 4, 9)addedge(1, 5, 8)addedge(2, 6, 12)addedge(2, 7, 14)addedge(3, 8, 7)addedge(8, 9, 5)addedge(8, 10, 6)addedge(9, 11, 1)addedge(9, 12, 10)addedge(9, 13, 2) source = 0target = 9best_first_search(source, target, v) # This code is contributed by Jyotheeswar Ganne",
"e": 31061,
"s": 29927,
"text": null
},
{
"code": null,
"e": 31074,
"s": 31061,
"text": "0 1 3 2 8 9 "
},
{
"code": null,
"e": 31086,
"s": 31074,
"text": "Analysis : "
},
{
"code": null,
"e": 31364,
"s": 31086,
"text": "worst case time complexity for Best First Search is O(n * Log n) where n is number of nodes. In worst case, we may have to visit all nodes before we reach goal. Note that priority queue is implemented using Min(or Max) Heap, and insert and remove operations take O(log n) time."
},
{
"code": null,
"e": 31458,
"s": 31364,
"text": "Performance of the algorithm depends on how well the cost or evaluation function is designed."
},
{
"code": null,
"e": 31561,
"s": 31458,
"text": "Special case of Best first search :\n 1. Greedy Best first search algorithm\n 2. A* search algorithm"
},
{
"code": null,
"e": 31898,
"s": 31561,
"text": "Related Article: A* Search Algorithm This article is contributed by Shambhavi Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 32023,
"s": 31898,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32037,
"s": 32023,
"text": "ManuelRaimann"
},
{
"code": null,
"e": 32047,
"s": 32037,
"text": "tech_shot"
},
{
"code": null,
"e": 32066,
"s": 32047,
"text": "jyotheeswarganne60"
},
{
"code": null,
"e": 32073,
"s": 32066,
"text": "iamwiz"
},
{
"code": null,
"e": 32087,
"s": 32073,
"text": "sumitgumber28"
},
{
"code": null,
"e": 32103,
"s": 32087,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 32112,
"s": 32103,
"text": "akmore90"
},
{
"code": null,
"e": 32128,
"s": 32112,
"text": "surbhikumaridav"
},
{
"code": null,
"e": 32132,
"s": 32128,
"text": "BFS"
},
{
"code": null,
"e": 32138,
"s": 32132,
"text": "Graph"
},
{
"code": null,
"e": 32148,
"s": 32138,
"text": "Searching"
},
{
"code": null,
"e": 32158,
"s": 32148,
"text": "Searching"
},
{
"code": null,
"e": 32164,
"s": 32158,
"text": "Graph"
},
{
"code": null,
"e": 32168,
"s": 32164,
"text": "BFS"
},
{
"code": null,
"e": 32266,
"s": 32168,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32299,
"s": 32266,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 32367,
"s": 32299,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 32417,
"s": 32367,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 32492,
"s": 32417,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 32522,
"s": 32492,
"text": "Strongly Connected Components"
},
{
"code": null,
"e": 32536,
"s": 32522,
"text": "Binary Search"
},
{
"code": null,
"e": 32604,
"s": 32536,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 32618,
"s": 32604,
"text": "Linear Search"
},
{
"code": null,
"e": 32666,
"s": 32618,
"text": "Search an element in a sorted and rotated array"
}
] |
Corona Fighter Game using JavaScript - GeeksforGeeks
|
14 Dec, 2020
In this article, we will create a covid fighter game using HTML, CSS, and JavaScript. In this game, we will create three objects the first object will represent the user which have to cross several hurdles to reach the final object.
Approach: We will create the HTML layout first, style it using CSS, and then write the logic in JavaScript. In our game, the first object represents the earth, the second represents the coronavirus, and the third represents the vaccine.
HTML code: We will use HTML to design the web page structure or layout. Create HTML canvas with id “mycanvas”. Include the JavaScript file “covid.js” in the HTML code.
HTML
<!DOCTYPE html><html> <body> <h1>COVID-19 Fighter Game</h1> <canvas id="mycanvas"></canvas> <script src="covid.js"></script></body> </html>
CSS code: CSS is used to give general styling and make it more visually appealing. Give general styling to the whole page like color, alignment, and background color. We use flex to center canvas and set the background image to the background of our game. Include the following in the above HTML code in the style section of head part of the code.
body {
text-align: center;
color: #ffff;
background: #000;
}
#mycanvas{
display: flex;
align-items: center;
justify-content: center;
background-image: url(Assets/bg.gif)
background-size: cover;
}
Output: The result of the HTML layout and CSS styling looks like the following.
The resultant output does not look like the desired output but we will adjust canvas height and width using JavaScript.
Logic: The main logic part is implemented using JavaScript.
According to our logic when the earth object collides with the coronavirus (the second object ) we will decrease the health of the player by 50 points.
The initial health of the player will be 100.
When the health of the player will be <= 0 our game will get over.
When the player will reach the third object player wins.
Our game is basically divided into basic six functions.
function load_assets(){
}
function init(){
}
function isOverlap(rect1, rect2){
}
function draw(){
}
function update(){
}
function gameloop(){
}
Step 1:
Initially, we will load all the required assets. We will require one enemy, one player, winning sound, losing sound and a third object which is vaccine.
We will create the function load_assets() which will load all the required assets.
JavaScript
function load_assets(){ // Enemy object enemy_img = new Image(); enemy_img.src = "Assets/enemy.png"; // Main user player_img = new Image(); player_img.src = "Assets/fighter.png"; // Vaccine gem_img = new Image; gem_img.src = "Assets/vac.gif"; // Winning sound win = new Audio(); win.src = "Audio/won.wav"; // Losing sound lose = new Audio(); lose.src = "Audio/dead.mp3";}
Step 2:
In this step, we will initialize our state of the game. We will set the height and width of the canvas.
We will also set the number of second objects. We will create five enemies by setting their general position, speed,height and width.
We will also create the player object with properties like position, height, width, speed health, and moving state.
Create a gem object which will represent the final state of our game with properties like height, width and positions.
At the end, add the event listener with mousedown and mouseup events to move the player and stop the player.
We are ready with the initial setup. Let us look at the output below.
JavaScript
function init(){ cvs = document.getElementById('mycanvas'); // Setting the height and width of canvas W = cvs.width = 1252; H = cvs.height = 516; // Getting the context the of canvas pen = cvs.getContext('2d'); // Initially setting the variable to false game_over = false; // Creating the enemies object with // coordinates x y width(w) height(h) // and speed e1 = { x:200, y:50, w:80, h:80, speed:20, }; e2 = { x:450, y:150, w:80, h:80, speed:35, }; e3 = { x:700, y:300, w:80, h:80, speed:40, }; e4 = { x:900, y:100, w:80, h:80, speed:30, }; // Array of enemies enemy = [e1, e2, e3, e4]; // Creating the player object player = { x:20, y:H/2, w:110, h:110, speed:30, health:100, moving: "false" } // Creating the vaccine gem gem = { x:W-150, y:H/2, w:150, h:150, } // The main part lets move the player // using event mouse down and stop //using mouse up cvs.addEventListener('mousedown', function(){ console.log("Mouse Pressed"); player.moving = true; }); cvs.addEventListener('mouseup', function(){ console.log("Mouse Released"); player.moving = false; });}
Output:
Step 3:
In this step, we will see the overlap function which we will use to check if our player is colliding with some other object may be an enemy or a gem(vaccine).
JavaScript
function isOverlap(rect1, rect2) { if (rect1.x < rect2.x + rect2.w && rect1.x + rect1.w > rect2.x && rect1.y < rect2.y + rect2.h && rect1.y + rect1.h > rect2.y) { return true; } return false;}
Step 4:
We will see the draw() function which will help in drawing graphical images of the enemy player and gem in their respective position.
JavaScript
function draw() { // Drawing the images for(let i = 0; i < enemy.length; i++) { pen.drawImage(enemy_img, enemy[i].x, enemy[i].y, enemy[i].w, enemy[i].h); } // Draw the player pen.drawImage(player_img, player.x, player.y, player.w, player.h); // Draw the vaccine pen.drawImage(gem_img, gem.x, gem.y, gem.w, gem.h); // Displaying score pen.fillStyle = "white"; pen.font = "30px Roboto"; pen.fillText("Score " + player.health, 30, 30);}
Step 5:
The following implements the update() function.
It returns when the game is over.
If the player is still moving, it will increase the player’s speed and health.
If our player is colliding with any of the enemies, it will play the losing sound and decrease the health by 50 points.
If health goes negative or 0, the game is over and it returns.
If the game is still not over we will see if our player is colliding with the vaccine(gem). In this case the game is over which plays the winning sound, and alert the score.
If the game is still not over, it will adjust the speed and positions of the enemy.
JavaScript
function update() { // If player is moving if(game_over){ return; } if(player.moving == true){ player.x += player.speed; player.health += 20; } // Checking collision of player // with all enemies for(let i = 0; i < enemy.length; i++){ if(isOverlap(enemy[i], player)){ lose.play(); player.health -= 50; if(player.health < 0){ draw(); lose.play(); alert("You Lose "); game_over = true; return; } } } // checking the player and vaccine // collision for the win. if(isOverlap(player, gem)){ win.play(); alert("You Won " + player.health); game_over = true; return; } // Adjusting the speed and positions // of enemy for(let i = 0; i<enemy.length; i++){ enemy[i].y += enemy[i].speed; if(enemy[i].y > H-enemy[i].h || enemy[i].y <= 0){ enemy[i].speed *= -1; } }}
Step 6:
Let us complete the gameloop() function which we will use to run the game.
If the state of the game is over, it will clear the whole interval which we are calling in the end.
We will draw the object and update the things according to the user’s action.
JavaScript
function gameloop(){ if(game_over){ clearInterval(f); } draw(); update();}
Step 7:
Note: We call all the functions together in the JavaScript file “covid.js”.
First, we will call the load_assets() and init() function.
We will call the gameloop() function in an interval of every 100ms.
JavaScript
load_assets();init();var f = setInterval(gameloop, 100);
Output:
Source Code:
https://github.com/Nandini-72/Covid_Fighter_Game
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26243,
"s": 26215,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 26476,
"s": 26243,
"text": "In this article, we will create a covid fighter game using HTML, CSS, and JavaScript. In this game, we will create three objects the first object will represent the user which have to cross several hurdles to reach the final object."
},
{
"code": null,
"e": 26713,
"s": 26476,
"text": "Approach: We will create the HTML layout first, style it using CSS, and then write the logic in JavaScript. In our game, the first object represents the earth, the second represents the coronavirus, and the third represents the vaccine."
},
{
"code": null,
"e": 26881,
"s": 26713,
"text": "HTML code: We will use HTML to design the web page structure or layout. Create HTML canvas with id “mycanvas”. Include the JavaScript file “covid.js” in the HTML code."
},
{
"code": null,
"e": 26886,
"s": 26881,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h1>COVID-19 Fighter Game</h1> <canvas id=\"mycanvas\"></canvas> <script src=\"covid.js\"></script></body> </html>",
"e": 27043,
"s": 26886,
"text": null
},
{
"code": null,
"e": 27391,
"s": 27043,
"text": "CSS code: CSS is used to give general styling and make it more visually appealing. Give general styling to the whole page like color, alignment, and background color. We use flex to center canvas and set the background image to the background of our game. Include the following in the above HTML code in the style section of head part of the code."
},
{
"code": null,
"e": 27620,
"s": 27391,
"text": "body {\n text-align: center;\n color: #ffff;\n background: #000;\n}\n#mycanvas{\n display: flex;\n align-items: center;\n justify-content: center;\n background-image: url(Assets/bg.gif)\n background-size: cover;\n}\n"
},
{
"code": null,
"e": 27700,
"s": 27620,
"text": "Output: The result of the HTML layout and CSS styling looks like the following."
},
{
"code": null,
"e": 27820,
"s": 27700,
"text": "The resultant output does not look like the desired output but we will adjust canvas height and width using JavaScript."
},
{
"code": null,
"e": 27880,
"s": 27820,
"text": "Logic: The main logic part is implemented using JavaScript."
},
{
"code": null,
"e": 28032,
"s": 27880,
"text": "According to our logic when the earth object collides with the coronavirus (the second object ) we will decrease the health of the player by 50 points."
},
{
"code": null,
"e": 28078,
"s": 28032,
"text": "The initial health of the player will be 100."
},
{
"code": null,
"e": 28145,
"s": 28078,
"text": "When the health of the player will be <= 0 our game will get over."
},
{
"code": null,
"e": 28202,
"s": 28145,
"text": "When the player will reach the third object player wins."
},
{
"code": null,
"e": 28258,
"s": 28202,
"text": "Our game is basically divided into basic six functions."
},
{
"code": null,
"e": 28403,
"s": 28258,
"text": "function load_assets(){\n}\nfunction init(){\n}\nfunction isOverlap(rect1, rect2){\n}\nfunction draw(){\n}\nfunction update(){\n}\nfunction gameloop(){\n}\n"
},
{
"code": null,
"e": 28411,
"s": 28403,
"text": "Step 1:"
},
{
"code": null,
"e": 28564,
"s": 28411,
"text": "Initially, we will load all the required assets. We will require one enemy, one player, winning sound, losing sound and a third object which is vaccine."
},
{
"code": null,
"e": 28647,
"s": 28564,
"text": "We will create the function load_assets() which will load all the required assets."
},
{
"code": null,
"e": 28658,
"s": 28647,
"text": "JavaScript"
},
{
"code": "function load_assets(){ // Enemy object enemy_img = new Image(); enemy_img.src = \"Assets/enemy.png\"; // Main user player_img = new Image(); player_img.src = \"Assets/fighter.png\"; // Vaccine gem_img = new Image; gem_img.src = \"Assets/vac.gif\"; // Winning sound win = new Audio(); win.src = \"Audio/won.wav\"; // Losing sound lose = new Audio(); lose.src = \"Audio/dead.mp3\";}",
"e": 29101,
"s": 28658,
"text": null
},
{
"code": null,
"e": 29109,
"s": 29101,
"text": "Step 2:"
},
{
"code": null,
"e": 29213,
"s": 29109,
"text": "In this step, we will initialize our state of the game. We will set the height and width of the canvas."
},
{
"code": null,
"e": 29347,
"s": 29213,
"text": "We will also set the number of second objects. We will create five enemies by setting their general position, speed,height and width."
},
{
"code": null,
"e": 29463,
"s": 29347,
"text": "We will also create the player object with properties like position, height, width, speed health, and moving state."
},
{
"code": null,
"e": 29582,
"s": 29463,
"text": "Create a gem object which will represent the final state of our game with properties like height, width and positions."
},
{
"code": null,
"e": 29691,
"s": 29582,
"text": "At the end, add the event listener with mousedown and mouseup events to move the player and stop the player."
},
{
"code": null,
"e": 29761,
"s": 29691,
"text": "We are ready with the initial setup. Let us look at the output below."
},
{
"code": null,
"e": 29772,
"s": 29761,
"text": "JavaScript"
},
{
"code": "function init(){ cvs = document.getElementById('mycanvas'); // Setting the height and width of canvas W = cvs.width = 1252; H = cvs.height = 516; // Getting the context the of canvas pen = cvs.getContext('2d'); // Initially setting the variable to false game_over = false; // Creating the enemies object with // coordinates x y width(w) height(h) // and speed e1 = { x:200, y:50, w:80, h:80, speed:20, }; e2 = { x:450, y:150, w:80, h:80, speed:35, }; e3 = { x:700, y:300, w:80, h:80, speed:40, }; e4 = { x:900, y:100, w:80, h:80, speed:30, }; // Array of enemies enemy = [e1, e2, e3, e4]; // Creating the player object player = { x:20, y:H/2, w:110, h:110, speed:30, health:100, moving: \"false\" } // Creating the vaccine gem gem = { x:W-150, y:H/2, w:150, h:150, } // The main part lets move the player // using event mouse down and stop //using mouse up cvs.addEventListener('mousedown', function(){ console.log(\"Mouse Pressed\"); player.moving = true; }); cvs.addEventListener('mouseup', function(){ console.log(\"Mouse Released\"); player.moving = false; });}",
"e": 31219,
"s": 29772,
"text": null
},
{
"code": null,
"e": 31227,
"s": 31219,
"text": "Output:"
},
{
"code": null,
"e": 31235,
"s": 31227,
"text": "Step 3:"
},
{
"code": null,
"e": 31394,
"s": 31235,
"text": "In this step, we will see the overlap function which we will use to check if our player is colliding with some other object may be an enemy or a gem(vaccine)."
},
{
"code": null,
"e": 31405,
"s": 31394,
"text": "JavaScript"
},
{
"code": "function isOverlap(rect1, rect2) { if (rect1.x < rect2.x + rect2.w && rect1.x + rect1.w > rect2.x && rect1.y < rect2.y + rect2.h && rect1.y + rect1.h > rect2.y) { return true; } return false;}",
"e": 31639,
"s": 31405,
"text": null
},
{
"code": null,
"e": 31647,
"s": 31639,
"text": "Step 4:"
},
{
"code": null,
"e": 31781,
"s": 31647,
"text": "We will see the draw() function which will help in drawing graphical images of the enemy player and gem in their respective position."
},
{
"code": null,
"e": 31792,
"s": 31781,
"text": "JavaScript"
},
{
"code": "function draw() { // Drawing the images for(let i = 0; i < enemy.length; i++) { pen.drawImage(enemy_img, enemy[i].x, enemy[i].y, enemy[i].w, enemy[i].h); } // Draw the player pen.drawImage(player_img, player.x, player.y, player.w, player.h); // Draw the vaccine pen.drawImage(gem_img, gem.x, gem.y, gem.w, gem.h); // Displaying score pen.fillStyle = \"white\"; pen.font = \"30px Roboto\"; pen.fillText(\"Score \" + player.health, 30, 30);}",
"e": 32308,
"s": 31792,
"text": null
},
{
"code": null,
"e": 32317,
"s": 32308,
"text": "Step 5: "
},
{
"code": null,
"e": 32365,
"s": 32317,
"text": "The following implements the update() function."
},
{
"code": null,
"e": 32399,
"s": 32365,
"text": "It returns when the game is over."
},
{
"code": null,
"e": 32478,
"s": 32399,
"text": "If the player is still moving, it will increase the player’s speed and health."
},
{
"code": null,
"e": 32598,
"s": 32478,
"text": "If our player is colliding with any of the enemies, it will play the losing sound and decrease the health by 50 points."
},
{
"code": null,
"e": 32661,
"s": 32598,
"text": "If health goes negative or 0, the game is over and it returns."
},
{
"code": null,
"e": 32835,
"s": 32661,
"text": "If the game is still not over we will see if our player is colliding with the vaccine(gem). In this case the game is over which plays the winning sound, and alert the score."
},
{
"code": null,
"e": 32919,
"s": 32835,
"text": "If the game is still not over, it will adjust the speed and positions of the enemy."
},
{
"code": null,
"e": 32930,
"s": 32919,
"text": "JavaScript"
},
{
"code": "function update() { // If player is moving if(game_over){ return; } if(player.moving == true){ player.x += player.speed; player.health += 20; } // Checking collision of player // with all enemies for(let i = 0; i < enemy.length; i++){ if(isOverlap(enemy[i], player)){ lose.play(); player.health -= 50; if(player.health < 0){ draw(); lose.play(); alert(\"You Lose \"); game_over = true; return; } } } // checking the player and vaccine // collision for the win. if(isOverlap(player, gem)){ win.play(); alert(\"You Won \" + player.health); game_over = true; return; } // Adjusting the speed and positions // of enemy for(let i = 0; i<enemy.length; i++){ enemy[i].y += enemy[i].speed; if(enemy[i].y > H-enemy[i].h || enemy[i].y <= 0){ enemy[i].speed *= -1; } }}",
"e": 33958,
"s": 32930,
"text": null
},
{
"code": null,
"e": 33966,
"s": 33958,
"text": "Step 6:"
},
{
"code": null,
"e": 34041,
"s": 33966,
"text": "Let us complete the gameloop() function which we will use to run the game."
},
{
"code": null,
"e": 34141,
"s": 34041,
"text": "If the state of the game is over, it will clear the whole interval which we are calling in the end."
},
{
"code": null,
"e": 34219,
"s": 34141,
"text": "We will draw the object and update the things according to the user’s action."
},
{
"code": null,
"e": 34230,
"s": 34219,
"text": "JavaScript"
},
{
"code": "function gameloop(){ if(game_over){ clearInterval(f); } draw(); update();}",
"e": 34324,
"s": 34230,
"text": null
},
{
"code": null,
"e": 34332,
"s": 34324,
"text": "Step 7:"
},
{
"code": null,
"e": 34408,
"s": 34332,
"text": "Note: We call all the functions together in the JavaScript file “covid.js”."
},
{
"code": null,
"e": 34467,
"s": 34408,
"text": "First, we will call the load_assets() and init() function."
},
{
"code": null,
"e": 34535,
"s": 34467,
"text": "We will call the gameloop() function in an interval of every 100ms."
},
{
"code": null,
"e": 34546,
"s": 34535,
"text": "JavaScript"
},
{
"code": "load_assets();init();var f = setInterval(gameloop, 100);",
"e": 34603,
"s": 34546,
"text": null
},
{
"code": null,
"e": 34611,
"s": 34603,
"text": "Output:"
},
{
"code": null,
"e": 34624,
"s": 34611,
"text": "Source Code:"
},
{
"code": null,
"e": 34673,
"s": 34624,
"text": "https://github.com/Nandini-72/Covid_Fighter_Game"
},
{
"code": null,
"e": 34682,
"s": 34673,
"text": "CSS-Misc"
},
{
"code": null,
"e": 34692,
"s": 34682,
"text": "HTML-Misc"
},
{
"code": null,
"e": 34708,
"s": 34692,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 34732,
"s": 34708,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 34736,
"s": 34732,
"text": "CSS"
},
{
"code": null,
"e": 34741,
"s": 34736,
"text": "HTML"
},
{
"code": null,
"e": 34752,
"s": 34741,
"text": "JavaScript"
},
{
"code": null,
"e": 34771,
"s": 34752,
"text": "Technical Scripter"
},
{
"code": null,
"e": 34788,
"s": 34771,
"text": "Web Technologies"
},
{
"code": null,
"e": 34815,
"s": 34788,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 34820,
"s": 34815,
"text": "HTML"
},
{
"code": null,
"e": 34918,
"s": 34820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34973,
"s": 34918,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 35010,
"s": 34973,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 35074,
"s": 35010,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 35113,
"s": 35074,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 35150,
"s": 35113,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 35210,
"s": 35150,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 35263,
"s": 35210,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 35324,
"s": 35263,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 35348,
"s": 35324,
"text": "REST API (Introduction)"
}
] |
Python - Unnest single Key Nested Dictionary List - GeeksforGeeks
|
14 May, 2020
Sometimes, while working with Python data, we can have a problem in which we need to perform unnesting of all the dictionaries which have single nesting of keys, i.e a single key and value and can easily be pointed to outer key directly. This kind of problem is common in domains requiring data optimization. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [{‘gfg’ : {‘data’ : 1}}, {‘is’ : {‘data’ : 5, ‘geeks’ : 7}}]Output : {‘is’: 5, ‘gfg’: 1}
Input : test_list = [{‘gfg’ : {‘data’ : ‘best’}}]Output : {‘gfg’: ‘best’}
Method #1 : Using loop + items()The combination of above methods can be used to solve this problem. In this, we iterate for the values in list, using loop and extract all dictionary items using items() and perform new dictionary creation using brute force method.
# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List# Using loop + items() # initializing listtest_list = [{'gfg' : {'data' : 1}}, {'is' : {'data' : 5}}, {'best' : {'data' : 4}}] # printing original listprint("The original list is : " + str(test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List# Using loop + items()res = dict()for sub in test_list: for key, val in sub.items(): res[key] = sub[key][data_key] # printing result print("The constructed Dictionary list : " + str(res))
The original list is : [{‘gfg’: {‘data’: 1}}, {‘is’: {‘data’: 5}}, {‘best’: {‘data’: 4}}]The constructed Dictionary list : {‘gfg’: 1, ‘best’: 4, ‘is’: 5}
Method #2 : Using list comprehensionThis is yet another way in which this task can be performed. In this, we perform solution in similar approach but in shorthand way using list comprehension.
# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List# Using list comprehension # initializing listtest_list = [{'gfg' : {'data' : 1}}, {'is' : {'data' : 5}}, {'best' : {'data' : 4}}] # printing original listprint("The original list is : " + str(test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List# Using list comprehensionres = {x : y[data_key] for idx in test_list for x, y in idx.items()} # printing result print("The constructed Dictionary list : " + str(res))
The original list is : [{‘gfg’: {‘data’: 1}}, {‘is’: {‘data’: 5}}, {‘best’: {‘data’: 4}}]The constructed Dictionary list : {‘gfg’: 1, ‘best’: 4, ‘is’: 5}
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
|
[
{
"code": null,
"e": 26151,
"s": 26123,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 26524,
"s": 26151,
"text": "Sometimes, while working with Python data, we can have a problem in which we need to perform unnesting of all the dictionaries which have single nesting of keys, i.e a single key and value and can easily be pointed to outer key directly. This kind of problem is common in domains requiring data optimization. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 26633,
"s": 26524,
"text": "Input : test_list = [{‘gfg’ : {‘data’ : 1}}, {‘is’ : {‘data’ : 5, ‘geeks’ : 7}}]Output : {‘is’: 5, ‘gfg’: 1}"
},
{
"code": null,
"e": 26707,
"s": 26633,
"text": "Input : test_list = [{‘gfg’ : {‘data’ : ‘best’}}]Output : {‘gfg’: ‘best’}"
},
{
"code": null,
"e": 26971,
"s": 26707,
"text": "Method #1 : Using loop + items()The combination of above methods can be used to solve this problem. In this, we iterate for the values in list, using loop and extract all dictionary items using items() and perform new dictionary creation using brute force method."
},
{
"code": "# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List# Using loop + items() # initializing listtest_list = [{'gfg' : {'data' : 1}}, {'is' : {'data' : 5}}, {'best' : {'data' : 4}}] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List# Using loop + items()res = dict()for sub in test_list: for key, val in sub.items(): res[key] = sub[key][data_key] # printing result print(\"The constructed Dictionary list : \" + str(res)) ",
"e": 27538,
"s": 26971,
"text": null
},
{
"code": null,
"e": 27692,
"s": 27538,
"text": "The original list is : [{‘gfg’: {‘data’: 1}}, {‘is’: {‘data’: 5}}, {‘best’: {‘data’: 4}}]The constructed Dictionary list : {‘gfg’: 1, ‘best’: 4, ‘is’: 5}"
},
{
"code": null,
"e": 27887,
"s": 27694,
"text": "Method #2 : Using list comprehensionThis is yet another way in which this task can be performed. In this, we perform solution in similar approach but in shorthand way using list comprehension."
},
{
"code": "# Python3 code to demonstrate working of # Unnest single Key Nested Dictionary List# Using list comprehension # initializing listtest_list = [{'gfg' : {'data' : 1}}, {'is' : {'data' : 5}}, {'best' : {'data' : 4}}] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing key data_key = 'data' # Unnest single Key Nested Dictionary List# Using list comprehensionres = {x : y[data_key] for idx in test_list for x, y in idx.items()} # printing result print(\"The constructed Dictionary list : \" + str(res)) ",
"e": 28428,
"s": 27887,
"text": null
},
{
"code": null,
"e": 28582,
"s": 28428,
"text": "The original list is : [{‘gfg’: {‘data’: 1}}, {‘is’: {‘data’: 5}}, {‘best’: {‘data’: 4}}]The constructed Dictionary list : {‘gfg’: 1, ‘best’: 4, ‘is’: 5}"
},
{
"code": null,
"e": 28609,
"s": 28582,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 28634,
"s": 28609,
"text": "Python-nested-dictionary"
},
{
"code": null,
"e": 28641,
"s": 28634,
"text": "Python"
},
{
"code": null,
"e": 28657,
"s": 28641,
"text": "Python Programs"
},
{
"code": null,
"e": 28755,
"s": 28657,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28773,
"s": 28755,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28808,
"s": 28773,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28840,
"s": 28808,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28862,
"s": 28840,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28904,
"s": 28862,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28947,
"s": 28904,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28969,
"s": 28947,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29008,
"s": 28969,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 29054,
"s": 29008,
"text": "Python | Split string into list of characters"
}
] |
CSS | Number Data Type - GeeksforGeeks
|
11 Jun, 2020
CSS Value is represented by <number> which takes an integer as a parameter or a number with a fractional component. They can be used by the symbol (+) or (-). The number can be positive or negative. All the digits of the number are 0 to 9 and all are of numeric types.
Syntax:
<number>
Note: No unit associated with numbers.
Examples for valid numbers
23, +90, -76, 0.56, 34.67, 10e4, -4.6e-2
Examples for invalid numbers
23., -+45, 45.7.6
Example 1: The following example demonstrates applying opacity to any element.
<!DOCTYPE html><html> <head> <style> img { opacity: 0.5; } </style></head> <body> <h1>GeeksforGeeks Logo</h1> <p> The opacity property specifies the transparency of an element. It takes a number as parameter. The lower the value, the image is more transparent </p> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GFG" width="170" height="100"></body> </html>
Output:
Example 2: The following example shows the opacity property with some changed value.
<!DOCTYPE html><html> <head> <style> img { opacity: .11; } </style></head> <body> <h1>GeeksforGeeks Logo</h1>] <p> The opacity property specifies the transparency of an element. It takes a number as parameter. The lower the value, the image is more transparent: </p> <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" alt="GFG" width="170" height="100"></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.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n11 Jun, 2020"
},
{
"code": null,
"e": 26890,
"s": 26621,
"text": "CSS Value is represented by <number> which takes an integer as a parameter or a number with a fractional component. They can be used by the symbol (+) or (-). The number can be positive or negative. All the digits of the number are 0 to 9 and all are of numeric types."
},
{
"code": null,
"e": 26898,
"s": 26890,
"text": "Syntax:"
},
{
"code": null,
"e": 26907,
"s": 26898,
"text": "<number>"
},
{
"code": null,
"e": 26946,
"s": 26907,
"text": "Note: No unit associated with numbers."
},
{
"code": null,
"e": 26973,
"s": 26946,
"text": "Examples for valid numbers"
},
{
"code": null,
"e": 27014,
"s": 26973,
"text": "23, +90, -76, 0.56, 34.67, 10e4, -4.6e-2"
},
{
"code": null,
"e": 27043,
"s": 27014,
"text": "Examples for invalid numbers"
},
{
"code": null,
"e": 27061,
"s": 27043,
"text": "23., -+45, 45.7.6"
},
{
"code": null,
"e": 27140,
"s": 27061,
"text": "Example 1: The following example demonstrates applying opacity to any element."
},
{
"code": "<!DOCTYPE html><html> <head> <style> img { opacity: 0.5; } </style></head> <body> <h1>GeeksforGeeks Logo</h1> <p> The opacity property specifies the transparency of an element. It takes a number as parameter. The lower the value, the image is more transparent </p> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GFG\" width=\"170\" height=\"100\"></body> </html>",
"e": 27650,
"s": 27140,
"text": null
},
{
"code": null,
"e": 27658,
"s": 27650,
"text": "Output:"
},
{
"code": null,
"e": 27743,
"s": 27658,
"text": "Example 2: The following example shows the opacity property with some changed value."
},
{
"code": "<!DOCTYPE html><html> <head> <style> img { opacity: .11; } </style></head> <body> <h1>GeeksforGeeks Logo</h1>] <p> The opacity property specifies the transparency of an element. It takes a number as parameter. The lower the value, the image is more transparent: </p> <img src=\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png\" alt=\"GFG\" width=\"170\" height=\"100\"></body> </html>",
"e": 28256,
"s": 27743,
"text": null
},
{
"code": null,
"e": 28264,
"s": 28256,
"text": "Output:"
},
{
"code": null,
"e": 28401,
"s": 28264,
"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": 28410,
"s": 28401,
"text": "CSS-Misc"
},
{
"code": null,
"e": 28420,
"s": 28410,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28427,
"s": 28420,
"text": "Picked"
},
{
"code": null,
"e": 28431,
"s": 28427,
"text": "CSS"
},
{
"code": null,
"e": 28436,
"s": 28431,
"text": "HTML"
},
{
"code": null,
"e": 28453,
"s": 28436,
"text": "Web Technologies"
},
{
"code": null,
"e": 28480,
"s": 28453,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28485,
"s": 28480,
"text": "HTML"
},
{
"code": null,
"e": 28583,
"s": 28485,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28620,
"s": 28583,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28659,
"s": 28620,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28688,
"s": 28659,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28730,
"s": 28688,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28765,
"s": 28730,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28825,
"s": 28765,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 28878,
"s": 28825,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 28939,
"s": 28878,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 28963,
"s": 28939,
"text": "REST API (Introduction)"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.