Trending March 2024 # How To Use Logstash Aws With Examples? # Suggested April 2024 # Top 12 Popular

You are reading the article How To Use Logstash Aws With Examples? updated in March 2024 on the website Cattuongwedding.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 How To Use Logstash Aws With Examples?

Introduction to Logstash AWS

Logstash AWS is a data processing pipeline that collects data from several sources, transforms it on the fly, and sends it to our preferred destination. Elasticsearch, an open-source analytics and search engine, is frequently used as a data pipeline. AWS offers Amazon OpenSearch Service (successor to Amazon Elasticsearch Service), a fully managed service that provides Elasticsearch with an easy connection with Logstash to make it easy for clients.

Start Your Free Data Science Course

What is Logstash AWS?

Create an Amazon OpenSearch Service domain and start loading data from our Logstash server. The Amazon Web Services Free Tier allows us to try Logstash and Amazon OpenSearch Service for free.

To make it easier to import data into Elasticsearch, Amazon OpenSearch Service has built-in connections with Amazon Kinesis Data Firehose, Amazon CloudWatch Logs, and AWS IoT.

We can also create our data pipeline using open-source tools like Apache Kafka and Fluentd.

All common Logstash input plugins, including the Amazon S3 input plugin, are supported. In addition, depending on our Logstash version, login method, and whether our domain uses Elasticsearch or OpenSearch, OpenSearch Service now supports the following Logstash output plugins.

Logstash output amazon es, signs, and exports Logstash events to OpenSearch Service using IAM credentials.

Logstash output OpenSearch, which only supports basic authentication at the moment. When building or upgrading to an OpenSearch version, select Enable compatibility mode in the console to allow OpenSearch domains.

We can also use the OpenSearch cluster settings API to enable or disable the compatibility of logstash.

Depending on our authentication strategy, we can use either the normal Elasticsearch plugin or the logstash output amazon es plugin for an Elasticsearch OSS domain.

Step-By-Step Guide logstash AWS

Configuration is comparable to any other OpenSearch cluster if our OpenSearch Service domain supports fine-grained access control and HTTP basic authentication.

The input for this sample configuration file comes from Filebeat’s open-source version.

Below is the configuration of the available search service domain as follows.

Code –

}

The configuration differs depending on the Beats app and the use situation.

All requests to OpenSearch Service must be signed using IAM credentials if our domain has an IAM-based domain access policy or fine-grained access control with an IAM master user.

In this scenario, the logstash output amazon es plugin is the simplest way to sign requests from Logstash OSS.

After configuring the available search service domain, we are installing the plugin name as logstash-output-amazon_es.

After exporting the plugin, we are exporting the IAM credential. And finally, we are changing the configuration files to use the plugin.

How to Use Logstash AWS?

Logstash provides several outputs that allow us to route data wherever we want, opening up a downstream application.

Over 200 plugins are available in Logstash’s pluggable structure. To work in pipeline harmony, mix, match, and orchestrate various inputs, filters, and outputs.

While Elasticsearch is our preferred output for searching and analyzing data, it is far from the only option.

We provide a great API for plugin development and a plugin generator to assist us in getting started and sharing our work.

The below step shows how to use logstash in AWS as follows.

The first step is to forward logs to OpenSearch Service using our security ports as 443.

The second step is to update the configurations for Logstash, filebeat, and OpenSearch Services.

The third step is to set up filebeat on the Amazon Elastic Compute Cloud instance we want to use as a source. Then, finally, check that our YAML config file is correctly installed and set up.

The fourth step is to set up Logstash on a separate Amazon EC2 instance to send logs.

Install logstash AWS

The below step shows install logstash on AWS as follows.

Create a new Ec2 instance –

In this step, we are creating a new instance of EC2 to install the logstash. In the below example, we have created the t2.micro instance.

Create a yum repository for installing the logstash –

In this step, we create the yum repository for installing the logstash in the Amazon EC2 instance.

[logstash-7.x] Type = rpm-md

Install the logstash on the newly created EC2 instance –

In this step, we install the logstash on a newly created instance using the yum command.

Start the logstash and check the status –

In this step, we are starting the logstash and checking the status of the logstash as follows.

# service logstash start

# service logstash status

Setup a Logstash Server for AWS

The below step shows the setup logstash for AWS as follows.

Create IAM policy –

Create a logstash configuration file –

}

Start the logstash and check the logs –

# service logstash start

Conclusion

Logstash AWS is a data processing pipeline that collects data from several sources, transforms it on the fly, and sends it to our preferred destination. Depending on our authentication strategy, we can use either the normal Elasticsearch plugin or the logstash-output-amazon_es plugin for an Elasticsearch OSS domain.

Recommended Articles

This is a guide to Logstash AWS. Here we discuss how to use logstash AWS, its installation and setup process, and a detailed explanation. You may also have a look at the following articles to learn more –

You're reading How To Use Logstash Aws With Examples?

How To Use Pytorch Amd With Examples?

Introduction to PyTorch AMD

Web development, programming languages, Software testing & others

In this article, we will try to dive into the topic of PyTorch AMD and will try to understand What is PyTorch AMD, how to use PyTorch AMD, image classification models in AMD, its associated examples, and finally give our concluding statement on it.

What is PyTorch AMD?

PyTorch AMD is the container of the framework, allowing us to run the container of AMD’s machine learning framework. For doing so, it is necessary that the docker environment of your system should support the AMD GPU.

The minimum requirements of the single node server are that it should have X86-64 CPU or CPUs along with GPU(s) of AMD instinct MI100 and GPU of Radeon instinct MI50 (S). The operating system used for this should be Centos 8.3 or higher OR Ubuntu 18.04 or higher version. The driver for ROCm should be compatible with the 4.2 version, and the Docker Engine Singularity container is used at runtime.

By default, the considerations and suppositions made by PyTorch AMD container of frameworks are that the server should contain x-86-64 single or multiple CPUs and should have a minimum of one listing AMD GPU. Furthermore, to run the docker container, the server should have the listed ROCm driver with a specified or higher version installed on it and the required operating system. Finally, the server should contain the docker engine in it to run the container.

If you want to go for installing the Docker engine, kindly visit this link. In order to install singularity in its latest version, if the use of singularity is already planned, then visit this link. For installation of procedures of ROCm as well as validity checks, kindly go through this link.

How to Use PyTorch AMD?

AMD is an open-source platform and has high performance and flexibility. It comes along with various libraries, compilers, and languages that can be used by developers and communities working in Machine Learning, Artificial Intelligence, and HPC technology to make their task of coding easy, fast, and implementing complex logic and functionalities in it. The biggest task is that PyTorch AMD provides you with containers.

Docker pull “name of the container”

For example, for AMDih container of PyTorch, the command would be –

docker pull AMDih / PyTorch : rocm4.2_ubuntu18.04_py3.6_PyTorch_1.9.0 Image classification models in AMD

Broadly, image classification can be done by using either of the two technologies of PyTorch or tensorflow in AMD. Some of the products include AMD Radeon instinct MI50, AMD Instinct MI100, while for tensorflow same products can be used.

There are various models that can be used in AMD for image classifications. Some of them are as listed below –

Efficent b0 and b7

Resnet 101 and 50

Inceptive v3

For running a particular image container in PyTorch AMD, you will have to give a check on the operating system on which you have installed and the software and its version that you have installed in the process of running the containers of AMD. Some of the steps that need to be followed for running the containers are as given below –

A search of the tab named Tags and then hit into the container image release that is located inside it, which you are about to run.

You will have to paste the command you have copied by opening a command prompt in your system. At this step, the beginning of pulling the image of the container happens. Before you go for the next step, make sure that the pulling of the docker completes.

Now, the container image that is pulled should be run. For running the container, you will have to choose the mode of interactive or non-interactive as per necessity and scenario.

While running the command, the “-it” parameter stands for the interactive mode running.

The option “–rm” specifies that the container should be deleted after finishing.

The parameter “-v” is used for specifying the directory for mounting.

The absolute path to the file or directory of the host system, which we will need to access in the container, is specified by using the parameter local_dir.

The target directory’s absolute path is specified by using the container_dir parameter when you are present in the container.

xx is the version of the container.

When you want to run particular command inside the image, the command parameter should be specified.

Examples of PyTorch AMD def sampleEducbaExample(args, educbaModel, sampleEducbaExample_loader): educbaModel.eval() corectionPrecision = 0 cumulativeCount = 0 with torch.no_grad(): for data, target in sampleEducbaExample_loader: achievedOutput = educbaModel(data) predictedValue = achievedOutput.argmax(dim=1) corectionPrecision += predictedValue.eq(target.view_as(predictedValue)).sum() cumulativeCount += args.sampleEducbaExample_batch_size cumulativeCorrections = corectionPrecision.copy().get().float_precision().long().item() print('Test set: Accuracy: {}/{} ({:.0f}%)'.format( cumulativeCorrections, cumulativeCount, 100. * cumulativeCorrections / cumulativeCount))

The output of the execution of the above program gives the following result on the console panel –

Here, we have carried out the predictions in a secure manner from end to end. Both server and client are completely unaware. The server has no idea about the output of classification and input of data, and the client is not aware of the server’s model weights.

Conclusion

We can use PyTorch AMD to improve the user’s data protection and secure machine learning. The docker container of PyTorch 3.6 internally provides AMD support.

Recommended Articles

This is a guide to PyTorch AMD. Here we discuss What is PyTorch AMD, how to use PyTorch AMD, image classification models in AMD. You may also have a look at the following articles to learn more –

How To Use Excel Vba Or Function With Examples?

Excel VBA OR Function

Like a worksheet function excel VBA also has a logical function which is OR function. In any programming language OR function is defined as follows:

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Condition 1 OR Condition 2. If any of the given conditions happens to be true the value returned by the function is true while if both of the condition happens to be false the value returned by the function is false. OR Function can be termed as that it is opposite to AND function because in AND function both of the condition needs to be true in order to get a true value. Even if a single condition is termed as false then the whole value returned by the AND function is false. While in OR Function only one condition needs to be true in order to get TRUE as an output.

Syntax of OR Function in Excel VBA

VBA OR function has the following syntax:

{Condition 1} OR {Condition 2}

Let us use this function in VBA to have a clear mindset of how to use this function in general terms.

Note: In order to use VBA we need to have developer access enabled from the file tab.

How to Use Excel VBA OR Function?

We will learn how to use VBA OR Function with few examples in excel.

You can download this VBA OR Excel Template here – VBA OR Excel Template

Example #1 – VBA OR

Follow the below steps to use VBA Union function in Excel:

Step 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.

Code:

Sub

Sample()

End Sub

Step 3: Define the four variables A B C and D as integers.

Code:

Sub

Sample()

Dim

A

As

Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

End Sub

Step 4: Define a variable X to store the value of OR Function, define it as a string.

Code:

Sub

Sample()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

End Sub

Step 5: Assign Random Values to A B C and D.

Code:

Sub

Sample()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

A = 10 B = 15 C = 20 D = 25

End Sub

Step 6: Define X’s Values as conditions for A B C and D.

Code:

Sub

Sample()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

A = 10 B = 15 C = 20 D = 25

End Sub

Step 7: Now we will display the value of X stored in it.

Code:

Sub

Sample()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

A = 10 B = 15 C = 20 D = 25 MsgBox X

End Sub

Step 8: Run the code from the run button provided in the screenshot below and then we see the following result when we run the above code.

Why we get the value as false because A is not greater than B and C is not greater than D. Both of the values of the condition were returned as false so our final output is also returned as false.

Example #2 – VBA OR

Step 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.

Step 2: A code window will appear on the right-hand side of the screen. Define the subfunction as Sample1.

Code:

Sub

Sample1()

End Sub

Step 3: Define the four variables A B C and D as integers.

Code:

Sub

Sample1()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

End Sub

Step 4: Define a variable X to store the value of OR Function, define it as a string.

Code:

Sub

Sample1()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

End Sub

Step 5: Assign Random Values to A B C and D.

Sub

Sample1()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

A = 10 B = 15 C = 20 D = 25

End Sub

Step 6: Define X’s Values as conditions for A B C and D.

Code:

Sub

Sample1()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

A = 10 B = 15 C = 20 D = 25

End Sub

Step 7: Now we will display the value of X stored in it.

Code:

Sub

Sample1()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

Dim

X

As String

A = 10 B = 15 C = 20 D = 25 MsgBox X

End Sub

Step 8: Run the code above from the run button as shown and we will see the following result as we run the above code.

Why we get the value as True because A is less than B and C is not greater than D. One of the values of the condition were returned as true so our final output is also returned as true.

Example #3 – VBA OR

Now let us use OR Function in VBA with the IF function. Earlier we used another variable to store the Boolean value of OR function and display it. This time we will use a personalized message to display using or and if function.

Steps 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.

Step 2: A code window will appear on the right-hand side of the screen. Define the subfunction as Sample2.

Code:

Sub

Sample2()

End Sub

Step 3: Define all the four variables A B C and D as integers and assign them random values.

Code:

Sub

Sample2()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

A = 5 B = 10 C = 15 D = 20

End Sub

Step 4: Now write the if statement for the given variables, for example, like in the code given below,

Code:

Sub

Sample2()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

A = 5 B = 10 C = 15 D = 20

End Sub

Code:

Sub

Sample2()

Dim

A

As Integer

Dim

B

As Integer

Dim

C

As Integer

Dim

D

As Integer

A = 5 B = 10 C = 15 D = 20 MsgBox "One of the conditions is true"

Else

MsgBox "None of the conditions is true"

End If

End Sub

Step 6: Run the above code from the run button and we will get the following result displayed.

As one of the conditions were true we have the above result.

Example #4 – VBA OR

Let use VBA OR function in a real scenario. We have the following data, Name of the employees and sales done by them. If their sales are equals to specific criteria or greater than that then they will receive the incentive or there will be no incentive for those employees. Have a look at the data below,

The incentive criteria are 10000 for this example. If the sales done by the employees is equals to or above 10000 they will receive the incentive.

Steps 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.

Step 2: In the code window, declare the subfunction,

Code:

Sub

Employee()

End Sub

Step 3: Declare a variable X as Long and write the if statement as below,

Code:

Sub

Employee()

Dim

X

As Long

For

X = 2

To

10 Cells(X, 3).Value = "Incentive"

Else

Cells(X, 3).Value = "No Incentive"

End If

End Sub

Step 4: Start the loop for the next cell.

Code:

Sub

Employee()

Dim

X

As Long

For

X = 2

To

10 Cells(X, 3).Value = "Incentive"

Else

Cells(X, 3).Value = "No Incentive"

End If

Next

X

End Sub

Step 5: Run the code to form the run button provided and once we have run the code check the result below,

In the If Statement, we used that if the sales are done is equals to 10000 or sales done greater than 10000 the employee will receive incentive.

Things to Remember

There are a few things we need to remember about VBA OR Function:

It is a logical function in excel or any other programming language.

It returns a logical output true or false.

It is the opposite of AND Function.

Recommended Articles

This is a guide to VBA OR. Here we have discussed how to use Excel VBA OR Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –

How To Install Odoo 13 On Ubuntu 18.04 With Nginx – Aws

Install Odoo 13 on Ubuntu 18.04 with Nginx – AWS. In this tutorial you are going to learn how to install and setup Odoo with Nginx reverse proxy and connect it with PostgreSQL in Amazon RDS.

Odoo is a management self hosted software to run a business with a top notch user experience. The applications within Odoo are perfectly integrated with each other, allowing you to fully automate your business processes easily.

Advanced and easy tutorial to Install Odoo using Docker with Nginx and SSL

Step 2: Install Wkhtmltopdf

Wkhtmltopdf is package that is used to render HTML to PDF and other image formats. If you are using Odoo to print PDF reports you should install wkhtmltopdf tool. The recommended version for Odoo is 0.12.5. This is not included in the default Ubuntu 18.04 repository.

So we shall download the package and install it.

sudo apt install ./wkhtmltox_0.12.5-1.bionic_amd64.deb Step 3: Install Odoo 13

Now you can install Odoo 13 by adding the repository to your Ubuntu server.

Update the apt cache and proceed install Odoo13.

sudo apt update sudo apt install odoo

Once the installation is complete Odoo is started automatically as a service.

To make sure Odoo is running you can check the status using the following command.

sudo service odoo status

Output

● odoo.service - Odoo Open Source ERP and CRM Loaded: loaded (/lib/systemd/system/odoo.service; enabled; vendor preset: enabled) Active:

active (running)

since Wed 2023-02-14 09:29:38 UTC; 10min ago Main PID: 8387 (odoo) Tasks: 6 (limit: 4395) CGroup: /system.slice/odoo.service └─8387 /usr/bin/python3 /usr/bin/odoo --config chúng tôi --logfile /var/log/odoo/odoo-server.log Feb 14 09:29:38 odoo systemd[1]: Started Odoo Open Source ERP and CRM.

This indicates Odoo is started and running successfully.

Now you can enable Odoo service to start on system boot.

sudo systemctl enable --now odoo Step 4: Configure Cloud SQL – PostgreSQL

Now you can configure Odoo to use remote database like Cloud SQL or Amazon RDS.

sudo nano /etc/odoo/odoo.conf

Replace the highlighted values corresponding to your Cloud SQL values.

[options] ; This is the password that allows database operations: ; admin_passwd = admin db_host =

RDS_ENDPOINT

db_port = False db_user =

RDS_user

db_password =

RDS_user_password

;addons_path = /usr/lib/python3/dist-packages/odoo/addons

Restart Odoo.

sudo service odoo restart Step 5: Install Nginx

Install Nginx using the followng command.

sudo apt install nginx

Remove default Nginx configurations.

sudo rm /etc/nginx/sites-enabled/default sudo rm /etc/nginx/sites-available/default Step 6: Configure Nginx Reverse proxy for Odoo

Create a new Nginx configuration for Odoo in the sites-available directory.

sudo nano /etc/nginx/sites-available/

odoo.conf

Copy and paste the following configuration, ensure that you change the server_name directory to match your domain name.

upstream odooserver { server 127.0.0.1:8069; } server { listen 80; access_log /var/log/nginx/odoo_access.log; error_log /var/log/nginx/odoo_error.log; proxy_read_timeout 720s; proxy_connect_timeout 720s; proxy_send_timeout 720s; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; location / { proxy_redirect off; } location ~* /web/static/ { proxy_cache_valid 200 90m; proxy_buffering on; expires 864000; } gzip_types text/css text/less text/plain text/xml application/xml application/json application/javascript; gzip on; }

Hit Ctrl+X followed by Y and Enter to save the file and exit.

To enable this newly created website configuration, symlink the file that you just created into the sites-enabled directory.

sudo ln -s /etc/nginx/sites-available/

odoo.conf

/etc/nginx/sites-enabled/

odoo.conf

Check your configuration and restart Nginx for the changes to take effect.

Step 7: Install and configure SSL for Odoo

Now we have installed Certbot by Let’s Encrypt for Ubuntu 18.04, run this command to receive your certificates.

sudo certbot --nginx certonly

Enter your email and agree to the terms and conditions, then you will receive the list of domains you need to generate SSL certificate.

To select all domains simply hit Enter

The Certbot client will automatically generate the new certificate for your domain. Now we need to update the Nginx config.

Redirect HTTP Traffic to HTTPS

Open your site’s Nginx configuration file add replace everything with the following. Replacing the file path with the one you received when obtaining the SSL certificate. The ssl_certificate directive should point to your fullchain.pem file, and the ssl_certificate_key directive should point to your privkey.pem file.

upstream odooserver { server 127.0.0.1:8069; } server { listen [::]:80; listen 80; } server { listen [::]:443 ssl; listen 443 ssl; } server { access_log /var/log/nginx/odoo_access.log; error_log /var/log/nginx/odoo_error.log; proxy_read_timeout 720s; proxy_connect_timeout 720s; proxy_send_timeout 720s; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Real-IP $remote_addr; location / { proxy_redirect off; } location ~* /web/static/ { proxy_cache_valid 200 90m; proxy_buffering on; expires 864000; } gzip_types text/css text/less text/plain text/xml application/xml application/json application/javascript; gzip on; }

Hit CTRL+X followed by Y to save the changes.

Check your configuration and restart Nginx for the changes to take effect.

sudo nginx -t sudo service nginx restart Renewing SSL Certificate

Certificates provided by Let’s Encrypt are valid for 90 days only, so you need to renew them often. Now you set up a cronjob to check for the certificate which is due to expire in next 30 days and renew it automatically.

sudo crontab -e

Add this line at the end of the file

Hit CTRL+X followed by Y to save the changes.

This cronjob will attempt to check for renewing the certificate twice daily.

Step 8: Setup Odoo

Now you can visit your domain name on your web browser. You will see the page similar to the one below. Here you can create the database and admin user for your Odoo.

Conclusion

Now you have learned how to install Odoo 13 on your Ubuntu server with Nginx on AWS and secure it with Let’s Encrypt.

How To Create Constants In Php With Examples?

Introduction to PHP Constants

PHP Constants are variables whose values, once defined, cannot be changed, and these constants are defined without a $ sign in the beginning. PHP Constants are created using define() function. This function takes two parameters first is the name, and the second is the value of the constant defined.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The name of the constant starts using letters or underscores and not with a number. It can start with a letter or underscore followed by letters, underscores or numbers. The name is case-sensitive and in uppercase. After a constant is defined, it cannot be undefined or redefined again. It remains the same throughout the script and cannot be changed as the variables do.

Syntax with Explanation

A constant is a name for a particular value. To define a constant, we have to use the define() function and to get the value of the constant; we just need to specify the name.

define(name, value, case-insensitive);

where name is the name of the constant,

value is the value of the constant,

case-insensitive is either true or false, by default, it is false.

define('TEXT', 'Hello World!');

A constant can also be defined using const construct.

<?php const MSG = "WELCOME"; echo MSG;

How to Create Constants in PHP using Various Methods?

To create constants, we have to use a simple define function, which takes two parameters, first the name of the constant second the value to be stored. The name is by default in uppercase. It does not start with a $.

Example #1

Code:

<?php define("TEXT", "Hello World!"); echo TEXT;

Output:

In this example, we will be using a const construct to define a constant named TEXT. We have used const followed by the name of the constant and then the value. It can be assigned a value using an assignment operator =.

Once we have defined the constant, to access the defined constant TEXT, we will echo the name with the constant keyword, as shown below.

Example #2

Code:

<?php const TEXT = 'PHP PROGRAMMING!'; echo TEXT; echo constant("TEXT");

Output:

Example #3

In the below example, we are defining a TEXT constant with a value. Also, in the same program, we have defined a function Demo(). We have declared the TEXT constant outside the function Demo. Here we see that we can access the constant TEXT from within the function. This means once you define the constant, it is globally available in the script.

Code:

<?php define("TEXT", "Hello World!"); echo TEXT; function Demo() { echo TEXT; } Demo();

Rules and Regulations for PHP Constants

The following are the rules to define PHP constants.

should not start with a $.

should not start with a number.

should not start with an underscore.

start with a letter and follow by numbers.

start with a letter and follow by an underscore and numbers.

Let us look at the below statements.

<?php define("TEXT","PHP");             //valid define("TEXT1", "PHP");          define("1TEXT", "PHP");         //invalid define("1_TEXT", "PHP");       //invalid define("TEXT_1", "PHP");      define("__TEXT__", "PHP");   // valid but should be avoided

Magic Constants

It starts with a double underscore

__LINE__

__FILE__

__FUNCTION__

__CLASS__

__METHOD__

1. __LINE__

This gives the current line number.

Code:

<?php echo 'I am at Line number '. __LINE__;

Output:

2.__FILE__

This gives the filename along with the file path of the file. It can be used to include a file in a script.

Code:

<?php echo 'FILE NAME '. __FILE__;

3. __FUNCTION__

This gives the name of the function in which it is declared. It is case-sensitive.

Code:

<?php function show() { echo 'In the function '.__FUNCTION__; } show();

Output:

4. __METHOD__ , __CLASS__

This gives the name of the method and the name of the class in which it is declared. In the below example, we have defined the MainClass and two methods within it, the show method and the test method. Inside the show method, we have printed the __CLASS__, which gives the class name and inside the test method, we have printed the __METHOD__, which gives the method name, test.

Code:

<?php class MainClass { function show() { } function test() { } } $obj = new MainClass;

Output:

Conclusion

This article, it is explained about PHP constants and magic constants with examples. These examples help to create their own constants and use them in the script with the help of the given syntax. This article also explains the rules on how to create PHP Constants and then how to use them within the script with different methods.

Recommended Articles

This is a guide to PHP Constants. Here we discuss the introduction, syntax, and examples to create constants in PHP along with magic constants. You may also look at the following articles to learn more –

How Xpath Attribute Works With Examples?

Definition of XPath attribute

For finding an XPath node in an XML document, use the XPath Attribute expression location path. We can use XPath to generate attribute expressions to locate nodes in an XML document. When there are certain uniquely recognized attribute values accessible in the container tag, we employ the XPath functions (contains or starts-with) with the attribute. The “@” symbol is used to access attributes.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

Xpath Syntax is given as:

Within a single node

/path to/element[@attribute_name]

At any point in the document

//*[@attribute_name]

Within a node that has some value

/path to/element[@attribute_name='search value'] /path to/element[@attribute_name="search value"]

//*[@attribute_name='search string'] How XPath attribute works?

Attribute predicates are another approach to indicate the items we want to choose more accurately. They are divided into two types: [@attr=”value”] chooses only elements with the attr attribute set to a value, and [@attr] selects only elements with an attr attribute set to a value (set to any value).

For example, let’s see an XML code like:

/purchase/product[@id=”soap”]/name

The following examples, which deal with qualities, are a little more complicated.

1. Choose objects that begin with the word “imagebox”:

[starts-with(name(),’imagebox’)]

2.Only objects from the “gallery” set should be selected:

/*[@sets=',gallery,']

3.Select the following objects from the set “gallery” that begins with the name albums:

/*[starts-with(name(),'albums')] /*[@sets=',gallery,']

4.Choose between img_1 and img_ 2:

5.Select all objects in the “blue” or “flower” sets:

//*[@sets,',blue,') or contains(@sets,'flower')]

6.Select all objects in the “blue” set but not the “flower” set:

//*[contains(@sets,',blue,') and not(contains(@sets,'flower')]

7.Select all items in sets that start with the letter “pot”:

//*[starts-with(@sets,',pot')]

Following Observations could be taken to see how attribute works with Xpath functions:

– With absolute text or an attribute, we can also utilise the contains () and starts-with() methods.

Let’s take a real-time case:

When using the contains() and starts-with() methods, we need to be very careful about which attribute we utilize. We won’t be able to uniquely identify the element if the property value isn’t unique. The XPath won’t function if we use the “type” attribute to identify the “I’m Feeling Lucky” button.

The presence of two matching nodes indicates that the element has not been appropriately detected. The value of the type attribute is not unique in this case.

For instance

The attribute expression is

//chi/@name

The result would be

In the following section, we shall see how attribute works in java Programming to extract the specific element from the XML document rather than calling all the elements. Let’s get started:

Examples

Let us discuss examples of the XPath attribute.

Example #1: Using Simple Xpath Expression

chúng tôi

/stateinfo/client/@id

Output:

ii) Selecting all attribute value

This selects all attributes of the specified context node.

Output:

iii) Selecting discipline attribute

@discipline

Output:

Example #2

.xml

/Universe/*[@uname]

Explanation

With Xpath expression let’s see how to extract the value of an attribute.

Output:

/Universe/*[@uname='Star']

Output:

Find nodes by substring matching the value of an attribute.

Xpath Expression

/Universe/*[contains(@uname,'Ma')]

Output:

Find nodes using a substring that matches the beginning of an attribute’s value.

/Universe/*[starts-with(lower-case(@uname),'sta')]

Output:

Example #3: Using java

}

chúng tôi

Explanation

Output:

Conclusion

Therefore, this article offers a code example that shows how to implement this requirement by using the contains XML Path Language (XPath) Attribute function. In the following post, we’ll look at how to use XPath Functions to improve the position of elements on the available webpage.

Recommended Articles

This is a guide to XPath attribute. Here we discuss the definition, How XPath attribute works? And examples for better understanding. You may also have a look at the following articles to learn more –

Update the detailed information about How To Use Logstash Aws With Examples? on the Cattuongwedding.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!