title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Floating Action Button using Fab Option Library in Android - GeeksforGeeks
19 Feb, 2021 Floating Action Button using Fab Options is another unique way of displaying various options. With the help of this, we can Navigate to different screens easily. This Floating Action button display various menu with Animation. So it increases user experience. In this article, we are going to learn how to implement Floating Action Button using Fab Option Library in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Floating Action Button using Fab Option provide a good User Experience. Floating Action Button using Fab Option helps to give various menus in Animated form. Floating Action Button using Fab Option makes it easy to navigate to different screens. Attributes Description Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency of Floating Action Button using Fab Option library in build.gradle file Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section. implementation ‘com.github.joaquimley:faboptions:1.2.0’ Now click on Sync now it will sync your all files in build.gradle(). Step 3: Create a new Floating Action Button using Fab Option in your activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--Text View heading--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:text="Geeks for Geeks" android:textColor="@color/purple_200" android:textSize="20dp" android:textStyle="bold" /> <!--Fab Options--> <com.joaquimley.faboptions.FabOptions android:id="@+id/fab_options" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_gravity="bottom" /> </RelativeLayout> Step 4: Create a new menu file in your resource folder Go to the app > res > right-click > New > Android Resource File and choose Resource type as “Menu” and enter the file name as “menu” and click on the OK button. Enter the below code into the menu.xml file. XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <!--Menu items--> <item android:id="@+id/balance" android:icon="@drawable/ic_baseline_account_balance_24" android:title="Bank" /> <item android:id="@+id/download" android:icon="@drawable/ic_baseline_cloud_download_24" android:title="Download" /> <item android:id="@+id/photo" android:icon="@drawable/ic_baseline_add_a_photo_24" android:title="Add Photo" /> <item android:id="@+id/account" android:icon="@drawable/ic_baseline_account_circle_24" android:title="Account" /> </menu> Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.joaquimley.faboptions.FabOptions; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Fab Options Code FabOptions fabOptions = (FabOptions) findViewById(R.id.fab_options); fabOptions.setButtonsMenu(this, R.menu.menu); fabOptions.setOnClickListener(this); } @Override public void onClick(View v) { // Menu given along with toast switch (v.getId()) { case R.id.balance: Toast.makeText(this, "Bank", Toast.LENGTH_SHORT).show(); break; case R.id.download: Toast.makeText(this, "Download", Toast.LENGTH_SHORT).show(); break; case R.id.photo: Toast.makeText(this, "Add Photo", Toast.LENGTH_SHORT).show(); break; case R.id.account: Toast.makeText(this, "Account", Toast.LENGTH_SHORT).show(); break; } }} Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below. Android-Button Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Change the Background Color After Clicking the Button in Android? Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java
[ { "code": null, "e": 25116, "s": 25088, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25657, "s": 25116, "text": "Floating Action Button using Fab Options is another unique way of displaying various options. With the help of this, we can Navigate to different screens easily. This Floating Action button display various menu with Animation. So it increases user experience. In this article, we are going to learn how to implement Floating Action Button using Fab Option Library in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 25729, "s": 25657, "text": "Floating Action Button using Fab Option provide a good User Experience." }, { "code": null, "e": 25815, "s": 25729, "text": "Floating Action Button using Fab Option helps to give various menus in Animated form." }, { "code": null, "e": 25903, "s": 25815, "text": "Floating Action Button using Fab Option makes it easy to navigate to different screens." }, { "code": null, "e": 25914, "s": 25903, "text": "Attributes" }, { "code": null, "e": 25926, "s": 25914, "text": "Description" }, { "code": null, "e": 25955, "s": 25926, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26117, "s": 25955, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 26212, "s": 26117, "text": "Step 2: Add dependency of Floating Action Button using Fab Option library in build.gradle file" }, { "code": null, "e": 26349, "s": 26212, "text": "Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section." }, { "code": null, "e": 26405, "s": 26349, "text": "implementation ‘com.github.joaquimley:faboptions:1.2.0’" }, { "code": null, "e": 26474, "s": 26405, "text": "Now click on Sync now it will sync your all files in build.gradle()." }, { "code": null, "e": 26566, "s": 26474, "text": "Step 3: Create a new Floating Action Button using Fab Option in your activity_main.xml file" }, { "code": null, "e": 26709, "s": 26566, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 26713, "s": 26709, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!--Text View heading--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerHorizontal=\"true\" android:layout_marginTop=\"10dp\" android:text=\"Geeks for Geeks\" android:textColor=\"@color/purple_200\" android:textSize=\"20dp\" android:textStyle=\"bold\" /> <!--Fab Options--> <com.joaquimley.faboptions.FabOptions android:id=\"@+id/fab_options\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:layout_centerHorizontal=\"true\" android:layout_gravity=\"bottom\" /> </RelativeLayout>", "e": 27704, "s": 26713, "text": null }, { "code": null, "e": 27759, "s": 27704, "text": "Step 4: Create a new menu file in your resource folder" }, { "code": null, "e": 27965, "s": 27759, "text": "Go to the app > res > right-click > New > Android Resource File and choose Resource type as “Menu” and enter the file name as “menu” and click on the OK button. Enter the below code into the menu.xml file." }, { "code": null, "e": 27969, "s": 27965, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!--Menu items--> <item android:id=\"@+id/balance\" android:icon=\"@drawable/ic_baseline_account_balance_24\" android:title=\"Bank\" /> <item android:id=\"@+id/download\" android:icon=\"@drawable/ic_baseline_cloud_download_24\" android:title=\"Download\" /> <item android:id=\"@+id/photo\" android:icon=\"@drawable/ic_baseline_add_a_photo_24\" android:title=\"Add Photo\" /> <item android:id=\"@+id/account\" android:icon=\"@drawable/ic_baseline_account_circle_24\" android:title=\"Account\" /> </menu>", "e": 28668, "s": 27969, "text": null }, { "code": null, "e": 28716, "s": 28668, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 28906, "s": 28716, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 28911, "s": 28906, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.joaquimley.faboptions.FabOptions; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Fab Options Code FabOptions fabOptions = (FabOptions) findViewById(R.id.fab_options); fabOptions.setButtonsMenu(this, R.menu.menu); fabOptions.setOnClickListener(this); } @Override public void onClick(View v) { // Menu given along with toast switch (v.getId()) { case R.id.balance: Toast.makeText(this, \"Bank\", Toast.LENGTH_SHORT).show(); break; case R.id.download: Toast.makeText(this, \"Download\", Toast.LENGTH_SHORT).show(); break; case R.id.photo: Toast.makeText(this, \"Add Photo\", Toast.LENGTH_SHORT).show(); break; case R.id.account: Toast.makeText(this, \"Account\", Toast.LENGTH_SHORT).show(); break; } }}", "e": 30177, "s": 28911, "text": null }, { "code": null, "e": 30308, "s": 30177, "text": "Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below." }, { "code": null, "e": 30323, "s": 30308, "text": "Android-Button" }, { "code": null, "e": 30347, "s": 30323, "text": "Technical Scripter 2020" }, { "code": null, "e": 30355, "s": 30347, "text": "Android" }, { "code": null, "e": 30360, "s": 30355, "text": "Java" }, { "code": null, "e": 30379, "s": 30360, "text": "Technical Scripter" }, { "code": null, "e": 30384, "s": 30379, "text": "Java" }, { "code": null, "e": 30392, "s": 30384, "text": "Android" }, { "code": null, "e": 30490, "s": 30392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30529, "s": 30490, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 30579, "s": 30529, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30621, "s": 30579, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30659, "s": 30621, "text": "Android Listview in Java with Example" }, { "code": null, "e": 30732, "s": 30659, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 30747, "s": 30732, "text": "Arrays in Java" }, { "code": null, "e": 30791, "s": 30747, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30813, "s": 30791, "text": "For-each loop in Java" }, { "code": null, "e": 30849, "s": 30813, "text": "Arrays.sort() in Java with examples" } ]
D3.js selection.classed() Function - GeeksforGeeks
06 Sep, 2020 The selection.classed() function is used to set the class to the selected element. This function can also be used to unset the class to a particular element that is selected. Syntax: selection.classed(names[, value]); Parameters: The above-given function takes two parameters which are given above and described below: name: It is the name of the class to be given to the element that is selected. value: It is the boolean value i.e true or false to set or unset the class. Return Values: This function does not return anything. Example 1: Setting the class name. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <div> <a>GeeksforGeeks</a> </div> <script> // Sets the class to the a tag var a = d3.select("a") .classed("className", true); // This will select the anchor tag var divselect = document.querySelector(".className"); console.log(divselect.innerHTML); </script></body> </html> Output: GeeksforGeeks Example 2: Unset the class name. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent="width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script></head> <body> <div> <p class="classGiven classGiven2"> GeeksforGeeks </p> </div> <script> // Unsets the class named classGiven // to the "p" tag var a = d3.select("p") .classed("classGiven2", false); // This will select the "p" tag var divselect = document .querySelector(".classGiven"); console.log(divselect.innerHTML); // This will not select the "p" tag // As the classGiven 2 is unset var divselect = document .querySelector(".classGiven2"); console.log(divselect); </script></body> </html> Output: GeeksforGeeks null D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24598, "s": 24570, "text": "\n06 Sep, 2020" }, { "code": null, "e": 24773, "s": 24598, "text": "The selection.classed() function is used to set the class to the selected element. This function can also be used to unset the class to a particular element that is selected." }, { "code": null, "e": 24781, "s": 24773, "text": "Syntax:" }, { "code": null, "e": 24817, "s": 24781, "text": "selection.classed(names[, value]);\n" }, { "code": null, "e": 24918, "s": 24817, "text": "Parameters: The above-given function takes two parameters which are given above and described below:" }, { "code": null, "e": 24997, "s": 24918, "text": "name: It is the name of the class to be given to the element that is selected." }, { "code": null, "e": 25073, "s": 24997, "text": "value: It is the boolean value i.e true or false to set or unset the class." }, { "code": null, "e": 25128, "s": 25073, "text": "Return Values: This function does not return anything." }, { "code": null, "e": 25163, "s": 25128, "text": "Example 1: Setting the class name." }, { "code": null, "e": 25168, "s": 25163, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <div> <a>GeeksforGeeks</a> </div> <script> // Sets the class to the a tag var a = d3.select(\"a\") .classed(\"className\", true); // This will select the anchor tag var divselect = document.querySelector(\".className\"); console.log(divselect.innerHTML); </script></body> </html>", "e": 25760, "s": 25168, "text": null }, { "code": null, "e": 25768, "s": 25760, "text": "Output:" }, { "code": null, "e": 25782, "s": 25768, "text": "GeeksforGeeks" }, { "code": null, "e": 25815, "s": 25782, "text": "Example 2: Unset the class name." }, { "code": null, "e": 25820, "s": 25815, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent=\"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <div> <p class=\"classGiven classGiven2\"> GeeksforGeeks </p> </div> <script> // Unsets the class named classGiven // to the \"p\" tag var a = d3.select(\"p\") .classed(\"classGiven2\", false); // This will select the \"p\" tag var divselect = document .querySelector(\".classGiven\"); console.log(divselect.innerHTML); // This will not select the \"p\" tag // As the classGiven 2 is unset var divselect = document .querySelector(\".classGiven2\"); console.log(divselect); </script></body> </html>", "e": 26715, "s": 25820, "text": null }, { "code": null, "e": 26723, "s": 26715, "text": "Output:" }, { "code": null, "e": 26742, "s": 26723, "text": "GeeksforGeeks\nnull" }, { "code": null, "e": 26748, "s": 26742, "text": "D3.js" }, { "code": null, "e": 26759, "s": 26748, "text": "JavaScript" }, { "code": null, "e": 26776, "s": 26759, "text": "Web Technologies" }, { "code": null, "e": 26874, "s": 26776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26919, "s": 26874, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26980, "s": 26919, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27052, "s": 26980, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27104, "s": 27052, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 27150, "s": 27104, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27192, "s": 27150, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27225, "s": 27192, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27268, "s": 27225, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27330, "s": 27268, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Building a Question and Answer Chatbot with Amazon Kendra and AWS Fargate | by Yi Ai | Towards Data Science
Amazon announced the general availability of Amazon Kendra a few weeks ago, Kendra is a highly accurate and easy to use enterprise search service powered by machine learning. In this post I will build a question and answer chatbot solution using React with Amplify, WebSocket API in AWS API Gateway, AWS Fargate and Amazon Kendra. The solution provides a conversational interface for Questions and Answers. This chatbot allows users to ask their questions and get relevant answers quickly. Create an Amazon Kendra index, extract questions and answers from semi-structured document to Kendra FAQ. Deploy a WebSocket API in API Gateway to process questions and answer messages. Create a React application and use AWS Amplify to connect & interact with this chatbot through WebSocket. Create a service in AWS Fargate that let our bot call Kendra’s API to provide answer and send it back to user. The following diagram shows the architecture of the above steps: An easier approach to building a chatbot would be to use a lambda function to query Amazon Kendra without using Fargate. However, with AWS Fargate or EC2, we are able to extend the chatbot with custom AI models to make our bot more human, eg. We can build a chatbot based on the Hugging Face State-of-the-Art Conversational AI model and query Kendra only for Specific data. If your program is a long compute job which requires more GBs of memory and higher performance, Fargate is probably the better option. Setup an AWS account Install latest aws-cli Install Amplify cli Basic understanding of React Basic understanding of Docker Basic understanding of CloudFormation Install or update the Serverless Framework to latest version jq installed (optional) Let’s create a Kendra index. Amazon Kendra is a highly accurate and easy to use enterprise search service that’s powered by machine learning. Kendra supports unstructured and semi-structured documents like FAQs stored in S3, we will use FAQS in our case. First, let’s download a QnA dataset and upload it to S3. We can use Microsoft Research WikiQA Corpus for our chatbot. Once downloading the dataset, let’s transform to Kendra supported csv format like below: Use following script to transform the dataset and upload the transformed csv file to existing S3 bucket my-kendra-index: !wget https://download.microsoft.com/download/A/A/9/AA9C9802-B448-4361-89E0-DBF24D5A5C2C/WikiQACodePackage.zip !unzip WikiQACodePackage.zip import json import boto3 import pandas as pd import os def create_faq_format(input_path): faq_list = [] with open(input_path) as f: lines = [line.strip('\n') for line in f] for i in range(2, len(lines)): l = lines[i].split('\t') if l[2]=="1": faq_list.append({"Question":l[0],"Answer":l[1]}) return faq_list qa_list = create_faq_format("WikiQACodePackage/data/wiki/WikiQASent-train.txt") df = pd.DataFrame(qa_list, columns=["Question","Answer"]) df = df.drop_duplicates(subset='Question', keep="first") df.to_csv('faq.csv', index=False) s3 = boto3.resource('s3') s3.meta.client.upload_file("faq.csv", 'my-kendra-index', 'faq/faq.csv') Now, we are now ready to create a Kendra index. To create a Kendra index, complete the following steps: On the Amazon Kendra console, choose Launch Amazon Kendra.Create index and enter an Index name, such as my-aq-index.For IAM role, choose Create a new role to create a role to allow Amazon Kendra to access CloudWatch Logs.Create Index. On the Amazon Kendra console, choose Launch Amazon Kendra. Create index and enter an Index name, such as my-aq-index. For IAM role, choose Create a new role to create a role to allow Amazon Kendra to access CloudWatch Logs. Create Index. After the Kendra index has been created, we can add our FAQ document: Add FAQ from Amazon Kendra console.For S3, browse S3 to find your bucket, and select the FAQ csv file. Here we use s3://my-kendra-index/faq/faq.csv.For IAM role, select Create a new role to allow Amazon Kendra to access FAQ content object in S3 bucket.Add FAQ. Add FAQ from Amazon Kendra console. For S3, browse S3 to find your bucket, and select the FAQ csv file. Here we use s3://my-kendra-index/faq/faq.csv. For IAM role, select Create a new role to allow Amazon Kendra to access FAQ content object in S3 bucket. Add FAQ. Now that we have a working Kendra index, let’s move to the next step. In this section we will build a 1) WebSockets API in AWS API Gateway, 2) create lambda functions to manage WebSockets routes ($connect, $disconnect, sendMessage) and 3) create DynamoDb to store WebSockets connection Ids and user names. We will use Serverless Framework to build and deploy all required resources. let’s create a new Serverless project and add the following config to serverless.yml : Note that the Cognito App Client Id (/chatbot/dev/app_client_id) and Cognito User Pool Id (/chatbot/dev/user_pool_id) in serverless.yml has not been created yet, We only reference Cognito details as SSM Parameters here, in the next step, we will create Cognito User Pool using Amplify Cli and then we can modify related SSM parameters from theSystem Storage Manager console. Once serviceless.yml has been modified, update handler.js to create the lambda functions for WebSockets routes: $connect with custom authorizer, $disconnect, sendMessage: Run the following commands to deploy the WebSocket API: $sls deploy --stage dev --region YOUR_REGION In this section, We will build a web app using React and AWS Amplify with an authentication feature. The complete project is in my Github repo, you can find the following folders in the project directory: amplify/.config/, and amplify/backend/.project-config.json in .config/ folder.backend-config.json in backend/ folder.CloudFormation files in the backend/ folder. amplify/.config/, and amplify/backend/. project-config.json in .config/ folder. backend-config.json in backend/ folder. CloudFormation files in the backend/ folder. Let’s download the source code and re-initialise the existing Amplify project by running: $amplify init then push changes: $amplify push and deploy: $amplify publish We will get the web application URL after the project has been deployed: Now, log in to the AWS Cognito service console and you can now see AWS Cognito User Pool has been created . Copy the User Pool Id and App Client Id and use them as SSM Parameters we already created in previous step. In this section, we will create a bot task to run our chatbot service in AWS Fargate. First, a chatbot task connects to a websocket API, Then, when the user asks a question, the bot can query the Kendra index, and Kendra will surface a relevant answer, and send it back to the user who asked the questions. To deploy the Fargate service, perform the following steps: Download chatbot script and Dockerfile here.Build Docker, tag an Amazon ECR Repository and push the image to ECR. For more details, please refer to AWS official tutorial.Download the CloudFormation templates and bash scripts here.If using the Fargate launch type, the awsvpc network mode is required. We need to deploy VPC and Security Groups: Download chatbot script and Dockerfile here. Build Docker, tag an Amazon ECR Repository and push the image to ECR. For more details, please refer to AWS official tutorial. Download the CloudFormation templates and bash scripts here. If using the Fargate launch type, the awsvpc network mode is required. We need to deploy VPC and Security Groups: $bash create-infra.sh -d dev 5. Create task definition. $bash create-task.sh -d dev 6. Deploy chatbot service in AWS Fargate. $bash deploy-service.sh -d dev The main logic can be found here: To extend the chatbot with ConvAI model, you can try below sample script, note that you will need to put more effort to train the model and put it in the docker or Amazon EFS. Once the service has been deployed, we should be able to ask the bot questions. Let’s visit the React application and try it out live! As evident above, using keywords alone is sufficient for the system to respond with the correct answer. If you would like to learn more about Amazon Kendra, there is an official tutorial on how to build a chatbot using Lex and Kendra here. I hope you have found this article useful, The source code for this post can be found in my GitHub repo.
[ { "code": null, "e": 222, "s": 47, "text": "Amazon announced the general availability of Amazon Kendra a few weeks ago, Kendra is a highly accurate and easy to use enterprise search service powered by machine learning." }, { "code": null, "e": 378, "s": 222, "text": "In this post I will build a question and answer chatbot solution using React with Amplify, WebSocket API in AWS API Gateway, AWS Fargate and Amazon Kendra." }, { "code": null, "e": 537, "s": 378, "text": "The solution provides a conversational interface for Questions and Answers. This chatbot allows users to ask their questions and get relevant answers quickly." }, { "code": null, "e": 643, "s": 537, "text": "Create an Amazon Kendra index, extract questions and answers from semi-structured document to Kendra FAQ." }, { "code": null, "e": 723, "s": 643, "text": "Deploy a WebSocket API in API Gateway to process questions and answer messages." }, { "code": null, "e": 829, "s": 723, "text": "Create a React application and use AWS Amplify to connect & interact with this chatbot through WebSocket." }, { "code": null, "e": 940, "s": 829, "text": "Create a service in AWS Fargate that let our bot call Kendra’s API to provide answer and send it back to user." }, { "code": null, "e": 1005, "s": 940, "text": "The following diagram shows the architecture of the above steps:" }, { "code": null, "e": 1379, "s": 1005, "text": "An easier approach to building a chatbot would be to use a lambda function to query Amazon Kendra without using Fargate. However, with AWS Fargate or EC2, we are able to extend the chatbot with custom AI models to make our bot more human, eg. We can build a chatbot based on the Hugging Face State-of-the-Art Conversational AI model and query Kendra only for Specific data." }, { "code": null, "e": 1514, "s": 1379, "text": "If your program is a long compute job which requires more GBs of memory and higher performance, Fargate is probably the better option." }, { "code": null, "e": 1535, "s": 1514, "text": "Setup an AWS account" }, { "code": null, "e": 1558, "s": 1535, "text": "Install latest aws-cli" }, { "code": null, "e": 1578, "s": 1558, "text": "Install Amplify cli" }, { "code": null, "e": 1607, "s": 1578, "text": "Basic understanding of React" }, { "code": null, "e": 1637, "s": 1607, "text": "Basic understanding of Docker" }, { "code": null, "e": 1675, "s": 1637, "text": "Basic understanding of CloudFormation" }, { "code": null, "e": 1736, "s": 1675, "text": "Install or update the Serverless Framework to latest version" }, { "code": null, "e": 1760, "s": 1736, "text": "jq installed (optional)" }, { "code": null, "e": 2015, "s": 1760, "text": "Let’s create a Kendra index. Amazon Kendra is a highly accurate and easy to use enterprise search service that’s powered by machine learning. Kendra supports unstructured and semi-structured documents like FAQs stored in S3, we will use FAQS in our case." }, { "code": null, "e": 2133, "s": 2015, "text": "First, let’s download a QnA dataset and upload it to S3. We can use Microsoft Research WikiQA Corpus for our chatbot." }, { "code": null, "e": 2222, "s": 2133, "text": "Once downloading the dataset, let’s transform to Kendra supported csv format like below:" }, { "code": null, "e": 2343, "s": 2222, "text": "Use following script to transform the dataset and upload the transformed csv file to existing S3 bucket my-kendra-index:" }, { "code": null, "e": 2484, "s": 2343, "text": "!wget https://download.microsoft.com/download/A/A/9/AA9C9802-B448-4361-89E0-DBF24D5A5C2C/WikiQACodePackage.zip\n!unzip WikiQACodePackage.zip\n" }, { "code": null, "e": 3102, "s": 2484, "text": "import json\nimport boto3\nimport pandas as pd\nimport os\n\ndef create_faq_format(input_path):\n faq_list = []\n \n with open(input_path) as f:\n lines = [line.strip('\\n') for line in f]\n for i in range(2, len(lines)):\n l = lines[i].split('\\t')\n if l[2]==\"1\":\n faq_list.append({\"Question\":l[0],\"Answer\":l[1]})\n \n return faq_list\n \nqa_list = create_faq_format(\"WikiQACodePackage/data/wiki/WikiQASent-train.txt\")\ndf = pd.DataFrame(qa_list, columns=[\"Question\",\"Answer\"])\ndf = df.drop_duplicates(subset='Question', keep=\"first\")\ndf.to_csv('faq.csv', index=False)\n" }, { "code": null, "e": 3201, "s": 3102, "text": "s3 = boto3.resource('s3')\ns3.meta.client.upload_file(\"faq.csv\", 'my-kendra-index', 'faq/faq.csv')\n" }, { "code": null, "e": 3305, "s": 3201, "text": "Now, we are now ready to create a Kendra index. To create a Kendra index, complete the following steps:" }, { "code": null, "e": 3540, "s": 3305, "text": "On the Amazon Kendra console, choose Launch Amazon Kendra.Create index and enter an Index name, such as my-aq-index.For IAM role, choose Create a new role to create a role to allow Amazon Kendra to access CloudWatch Logs.Create Index." }, { "code": null, "e": 3599, "s": 3540, "text": "On the Amazon Kendra console, choose Launch Amazon Kendra." }, { "code": null, "e": 3658, "s": 3599, "text": "Create index and enter an Index name, such as my-aq-index." }, { "code": null, "e": 3764, "s": 3658, "text": "For IAM role, choose Create a new role to create a role to allow Amazon Kendra to access CloudWatch Logs." }, { "code": null, "e": 3778, "s": 3764, "text": "Create Index." }, { "code": null, "e": 3848, "s": 3778, "text": "After the Kendra index has been created, we can add our FAQ document:" }, { "code": null, "e": 4109, "s": 3848, "text": "Add FAQ from Amazon Kendra console.For S3, browse S3 to find your bucket, and select the FAQ csv file. Here we use s3://my-kendra-index/faq/faq.csv.For IAM role, select Create a new role to allow Amazon Kendra to access FAQ content object in S3 bucket.Add FAQ." }, { "code": null, "e": 4145, "s": 4109, "text": "Add FAQ from Amazon Kendra console." }, { "code": null, "e": 4259, "s": 4145, "text": "For S3, browse S3 to find your bucket, and select the FAQ csv file. Here we use s3://my-kendra-index/faq/faq.csv." }, { "code": null, "e": 4364, "s": 4259, "text": "For IAM role, select Create a new role to allow Amazon Kendra to access FAQ content object in S3 bucket." }, { "code": null, "e": 4373, "s": 4364, "text": "Add FAQ." }, { "code": null, "e": 4443, "s": 4373, "text": "Now that we have a working Kendra index, let’s move to the next step." }, { "code": null, "e": 4679, "s": 4443, "text": "In this section we will build a 1) WebSockets API in AWS API Gateway, 2) create lambda functions to manage WebSockets routes ($connect, $disconnect, sendMessage) and 3) create DynamoDb to store WebSockets connection Ids and user names." }, { "code": null, "e": 4843, "s": 4679, "text": "We will use Serverless Framework to build and deploy all required resources. let’s create a new Serverless project and add the following config to serverless.yml :" }, { "code": null, "e": 5218, "s": 4843, "text": "Note that the Cognito App Client Id (/chatbot/dev/app_client_id) and Cognito User Pool Id (/chatbot/dev/user_pool_id) in serverless.yml has not been created yet, We only reference Cognito details as SSM Parameters here, in the next step, we will create Cognito User Pool using Amplify Cli and then we can modify related SSM parameters from theSystem Storage Manager console." }, { "code": null, "e": 5389, "s": 5218, "text": "Once serviceless.yml has been modified, update handler.js to create the lambda functions for WebSockets routes: $connect with custom authorizer, $disconnect, sendMessage:" }, { "code": null, "e": 5445, "s": 5389, "text": "Run the following commands to deploy the WebSocket API:" }, { "code": null, "e": 5490, "s": 5445, "text": "$sls deploy --stage dev --region YOUR_REGION" }, { "code": null, "e": 5591, "s": 5490, "text": "In this section, We will build a web app using React and AWS Amplify with an authentication feature." }, { "code": null, "e": 5695, "s": 5591, "text": "The complete project is in my Github repo, you can find the following folders in the project directory:" }, { "code": null, "e": 5857, "s": 5695, "text": "amplify/.config/, and amplify/backend/.project-config.json in .config/ folder.backend-config.json in backend/ folder.CloudFormation files in the backend/ folder." }, { "code": null, "e": 5897, "s": 5857, "text": "amplify/.config/, and amplify/backend/." }, { "code": null, "e": 5937, "s": 5897, "text": "project-config.json in .config/ folder." }, { "code": null, "e": 5977, "s": 5937, "text": "backend-config.json in backend/ folder." }, { "code": null, "e": 6022, "s": 5977, "text": "CloudFormation files in the backend/ folder." }, { "code": null, "e": 6112, "s": 6022, "text": "Let’s download the source code and re-initialise the existing Amplify project by running:" }, { "code": null, "e": 6126, "s": 6112, "text": "$amplify init" }, { "code": null, "e": 6145, "s": 6126, "text": "then push changes:" }, { "code": null, "e": 6160, "s": 6145, "text": "$amplify push " }, { "code": null, "e": 6172, "s": 6160, "text": "and deploy:" }, { "code": null, "e": 6189, "s": 6172, "text": "$amplify publish" }, { "code": null, "e": 6262, "s": 6189, "text": "We will get the web application URL after the project has been deployed:" }, { "code": null, "e": 6478, "s": 6262, "text": "Now, log in to the AWS Cognito service console and you can now see AWS Cognito User Pool has been created . Copy the User Pool Id and App Client Id and use them as SSM Parameters we already created in previous step." }, { "code": null, "e": 6785, "s": 6478, "text": "In this section, we will create a bot task to run our chatbot service in AWS Fargate. First, a chatbot task connects to a websocket API, Then, when the user asks a question, the bot can query the Kendra index, and Kendra will surface a relevant answer, and send it back to the user who asked the questions." }, { "code": null, "e": 6845, "s": 6785, "text": "To deploy the Fargate service, perform the following steps:" }, { "code": null, "e": 7189, "s": 6845, "text": "Download chatbot script and Dockerfile here.Build Docker, tag an Amazon ECR Repository and push the image to ECR. For more details, please refer to AWS official tutorial.Download the CloudFormation templates and bash scripts here.If using the Fargate launch type, the awsvpc network mode is required. We need to deploy VPC and Security Groups:" }, { "code": null, "e": 7234, "s": 7189, "text": "Download chatbot script and Dockerfile here." }, { "code": null, "e": 7361, "s": 7234, "text": "Build Docker, tag an Amazon ECR Repository and push the image to ECR. For more details, please refer to AWS official tutorial." }, { "code": null, "e": 7422, "s": 7361, "text": "Download the CloudFormation templates and bash scripts here." }, { "code": null, "e": 7536, "s": 7422, "text": "If using the Fargate launch type, the awsvpc network mode is required. We need to deploy VPC and Security Groups:" }, { "code": null, "e": 7565, "s": 7536, "text": "$bash create-infra.sh -d dev" }, { "code": null, "e": 7592, "s": 7565, "text": "5. Create task definition." }, { "code": null, "e": 7620, "s": 7592, "text": "$bash create-task.sh -d dev" }, { "code": null, "e": 7662, "s": 7620, "text": "6. Deploy chatbot service in AWS Fargate." }, { "code": null, "e": 7693, "s": 7662, "text": "$bash deploy-service.sh -d dev" }, { "code": null, "e": 7727, "s": 7693, "text": "The main logic can be found here:" }, { "code": null, "e": 7903, "s": 7727, "text": "To extend the chatbot with ConvAI model, you can try below sample script, note that you will need to put more effort to train the model and put it in the docker or Amazon EFS." }, { "code": null, "e": 8038, "s": 7903, "text": "Once the service has been deployed, we should be able to ask the bot questions. Let’s visit the React application and try it out live!" }, { "code": null, "e": 8142, "s": 8038, "text": "As evident above, using keywords alone is sufficient for the system to respond with the correct answer." }, { "code": null, "e": 8278, "s": 8142, "text": "If you would like to learn more about Amazon Kendra, there is an official tutorial on how to build a chatbot using Lex and Kendra here." } ]
Logical and Cartesian Indexing in Julia
22 Apr, 2020 Julia, like most technical computing languages, provides a first-class array implementation with very important functions that make working with N-Dimensional arrays quite easy. One of the latest features, the dot(.) based broadcasting makes most of the “repetitive” array operations, a one-lined code. Indexing into arrays in Julia is similar to it’s counterparts.Syntax: x = arr[index_1, index_2, ..., index_n] where each index_k may be a scalar integer, an array of integers, or an object that represents an array of scalar indices. Array Indexing in Julia is of two types: Cartesian Indexing Logical Indexing Cartesian Coordinates give the location of a point in 1D, 2D or 3D plane. Cartesian Indices have similar behavior. They give the value of element stored in a 1D, 2D, 3D or n-D array.For scalar indices, CartesianIndex{N}s, behave like an N-tuple of integers spanning multiple dimensions while array of scalar indices include Arrays of CartesianIndex{N}Syntax: CartesianIndex(i, j, k...) -> I CartesianIndex((i, j, k...)) -> I The above syntax creates a multidimensional index I, which can be used for indexing a multidimensional array arr. We can say that, arr[I] is equivalent to arr[i, j, k...]. It is allowed to mix integer and CartesianIndex indices.Example : arr[Ipre, i, Ipost] (where Ipre and Ipost are CartesianIndex indices and i is an Int) can be a useful expression when writing algorithms that work along a single dimension of an array of arbitrary dimensionality. CartesianIndexing for 1D arrays: # Create a 1D array of size 5arr = reshape(Vector(1:2:10), (5)) # Select index number 1arr[CartesianIndex(1)] # Select index number 3arr[CartesianIndex(3)] Output: CartesianIndexing for a 2D array: # Create a 2D array of size 3x2arr = reshape(Vector(1:2:12), (3, 2)) # Select cartesian index 2, 2 arr[CartesianIndex(2, 2)] # Select index number 3, 1arr[CartesianIndex(3, 1)] Output: CartesianIndexing for 3D Array: # Create a 3D array of size 2x1x2arr = reshape(Vector(1:2:8), (2, 1, 2)) # Select cartesian index 1, 1, 1arr[CartesianIndex(1, 1, 1)] # Select index number 1, 1, 2arr[CartesianIndex(1, 1, 2)] Output: CartesianIndexing for nD array: # Create a 5D array of size 2x2x1x2x2arr = reshape(Vector(1:2:32), (2, 2, 1, 2, 2)) # Select cartesian index 1, 2, 1, 2, 2arr[CartesianIndex(2, 2, 1, 2, 2)] Output: From the above examples, it becomes pretty clear that CartesianIndex simply gathers multiple integers together into one object that represents a single multidimensional index.Having discussed scalar representations, let’s talk about arrays of CartesianIndex{N}, which represent a collection of scalar indices each spanning N dimensions, such form of indexing is referred to as “pointwise” indexing. Array based CartesianIndexing for 1D Array: # Create a 1D array of size 5arr = reshape(Vector(2:6), 5) # Select an array of cartesian indices 2, 3, 5arr[[CartesianIndex(2), CartesianIndex(3), CartesianIndex(5)]] Output: Array based CartesianIndexing for 2D Array: # Create a 2D array of size 5x6arr = reshape(Vector(1:30), (5, 6)) # Select an array of cartesian indices (5, 2), (3, 6), (1, 4)arr[[CartesianIndex(5, 2), CartesianIndex(3, 6), CartesianIndex(1, 4)]] Output: Array based CartesianIndexing for 3D array: # Create a 3D array of size 2x3x1arr = reshape(Vector(1:12), (2, 3, 2)) # Select an array of cartesian indices (1, 2, 1), (2, 2, 2), (1, 3, 1)arr[[CartesianIndex(1, 2, 1), CartesianIndex(1, 3, 1), CartesianIndex(2, 2, 2)]] Output: Array based CartesianIndexing for nD array: # Create a 5D array of size 2x2x1x2x2arr = reshape(Vector(1:2:32), (2, 2, 1, 2, 2)) # Select an array of cartesian indices # (1, 2, 1, 1, 1), (1, 2, 1, 2, 2), (2, 1, 1, 2, 1)arr[[CartesianIndex(1, 2, 1, 1, 1), CartesianIndex(1, 2, 1, 2, 2), CartesianIndex(2, 1, 1, 2, 1)]] Output: This is really useful, in case we want to select specific elements of an array if they are not in order. But what if we have an array of 1000 and we need to extract 100 elements, it’ll be quite tedious!This is where dot(.) broadcasting comes into play. # Create a 3D array of size 3x3x3arr = reshape(Vector(1:27), (3, 3, 3)) # Select diagonal elements in all the # 3 planes of cartesian coordinatesarr[[CartesianIndex(1, 1, 1), CartesianIndex(2, 2, 1), CartesianIndex(3, 3, 1), CartesianIndex(1, 1, 2), CartesianIndex(2, 2, 2), CartesianIndex(3, 3, 2), CartesianIndex(1, 1, 3), CartesianIndex(2, 2, 3), CartesianIndex(3, 3, 3)]] # Using dot broadcasting and (:)colon, to reduce codearr[CartesianIndex.(axes(arr, 1), axes(arr, 2), :)] Output:How efficiently we have been able to reduce our code in the third step!! What should we do with Cartesian Indexing ?We observe, CartesianIndices bear close resemblence to Cartesian coordinates and function in a similar way.Example: We have a 3D shape in space, and it is mapped out by storing the coordinates of it's edges in an array and we might want to mask out a region from the shape. It becomes easy to deal with by using CartesianIndices, since they resemble the coordinate system. In computing/electronics, the basis is a logic that is deterministic in nature. It is: true, false one, zero on, off It is basically a selection of elements at the indices where the values of our logical indexing array are true.A logical indexing array is called a “mask” since it masks out the values that are false. A mask is of type bool(boolean). Relation with CartesianIndexing: Indexing by a N-dimensional boolean array is equivalent to indexing by the vector of CartesianIndex{N}s where its values are true. Example : Implementation of a logical mask # Create a 2D array of size 5x5arr = reshape(Vector(1:25), (5, 5)) # Apply a logical mask to the arrayarr[[true, false, true, false, true], :] Output:So we see how only the rows whose index matches with the index of trues in our mask[true, false, true, false, true] are selected. Any condition that yields a boolean value can be used as a mask.Example for 1D array: # Create a 1D array of size 10arr = reshape(Vector(4:2:22), 10) # Create a power of 2 logic mask # and map it with the size of arrmask = map(ispow2, arr) # Apply it to the arrayarr[mask] Output: Example for 2D array: # Create a 2D array of size 10x10arr = reshape(Vector(1:100), (10, 10)) # Create a prime number logic mask and # map it with the size of arr # Julia library for working with prime numbers using Primes mask = map(isprime, arr) # Apply it to the arrayarr[mask] Output: Example for 3D array: # Create a 3D array of size 3x2x3arr = reshape(Vector(2:19), (3, 2, 3)) # Create a prime number logic mask # and map it with the size of arr# Julia library for working with prime numbers using Primesmask = map(isprime, arr) # Apply it to the arrayarr[mask] Output: One of the most used cases of logical indexing is when we want to filter elements out of an array on the basis of multiple conditions.Example: # Create a 3D array of size 3x2x3arr = reshape(Vector(2:19), (3, 2, 3)) # Create a function that checks for # both prime number or power of two# Julia library for working with prime numbers using Primes function prime_and_2pow(arr) if isprime(arr) || ispow2(arr) return true else return false endend # Create a logic mask and map it# with the size of arrmask = map(prime_and_2pow, arr) # Apply it to the arrayarr[mask] Output: Picked Julia Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 331, "s": 28, "text": "Julia, like most technical computing languages, provides a first-class array implementation with very important functions that make working with N-Dimensional arrays quite easy. One of the latest features, the dot(.) based broadcasting makes most of the “repetitive” array operations, a one-lined code." }, { "code": null, "e": 401, "s": 331, "text": "Indexing into arrays in Julia is similar to it’s counterparts.Syntax:" }, { "code": null, "e": 441, "s": 401, "text": "x = arr[index_1, index_2, ..., index_n]" }, { "code": null, "e": 564, "s": 441, "text": "where each index_k may be a scalar integer, an array of integers, or an object that represents an array of scalar indices." }, { "code": null, "e": 605, "s": 564, "text": "Array Indexing in Julia is of two types:" }, { "code": null, "e": 624, "s": 605, "text": "Cartesian Indexing" }, { "code": null, "e": 641, "s": 624, "text": "Logical Indexing" }, { "code": null, "e": 1000, "s": 641, "text": "Cartesian Coordinates give the location of a point in 1D, 2D or 3D plane. Cartesian Indices have similar behavior. They give the value of element stored in a 1D, 2D, 3D or n-D array.For scalar indices, CartesianIndex{N}s, behave like an N-tuple of integers spanning multiple dimensions while array of scalar indices include Arrays of CartesianIndex{N}Syntax:" }, { "code": null, "e": 1069, "s": 1000, "text": "CartesianIndex(i, j, k...) -> I\nCartesianIndex((i, j, k...)) -> I\n" }, { "code": null, "e": 1307, "s": 1069, "text": "The above syntax creates a multidimensional index I, which can be used for indexing a multidimensional array arr. We can say that, arr[I] is equivalent to arr[i, j, k...]. It is allowed to mix integer and CartesianIndex indices.Example :" }, { "code": null, "e": 1522, "s": 1307, "text": "arr[Ipre, i, Ipost] \n(where Ipre and Ipost are CartesianIndex indices and i is an Int) \ncan be a useful expression when writing algorithms that work along a single dimension\nof an array of arbitrary dimensionality." }, { "code": null, "e": 1555, "s": 1522, "text": "CartesianIndexing for 1D arrays:" }, { "code": "# Create a 1D array of size 5arr = reshape(Vector(1:2:10), (5)) # Select index number 1arr[CartesianIndex(1)] # Select index number 3arr[CartesianIndex(3)]", "e": 1713, "s": 1555, "text": null }, { "code": null, "e": 1721, "s": 1713, "text": "Output:" }, { "code": null, "e": 1755, "s": 1721, "text": "CartesianIndexing for a 2D array:" }, { "code": "# Create a 2D array of size 3x2arr = reshape(Vector(1:2:12), (3, 2)) # Select cartesian index 2, 2 arr[CartesianIndex(2, 2)] # Select index number 3, 1arr[CartesianIndex(3, 1)]", "e": 1934, "s": 1755, "text": null }, { "code": null, "e": 1942, "s": 1934, "text": "Output:" }, { "code": null, "e": 1974, "s": 1942, "text": "CartesianIndexing for 3D Array:" }, { "code": "# Create a 3D array of size 2x1x2arr = reshape(Vector(1:2:8), (2, 1, 2)) # Select cartesian index 1, 1, 1arr[CartesianIndex(1, 1, 1)] # Select index number 1, 1, 2arr[CartesianIndex(1, 1, 2)]", "e": 2168, "s": 1974, "text": null }, { "code": null, "e": 2176, "s": 2168, "text": "Output:" }, { "code": null, "e": 2208, "s": 2176, "text": "CartesianIndexing for nD array:" }, { "code": "# Create a 5D array of size 2x2x1x2x2arr = reshape(Vector(1:2:32), (2, 2, 1, 2, 2)) # Select cartesian index 1, 2, 1, 2, 2arr[CartesianIndex(2, 2, 1, 2, 2)]", "e": 2366, "s": 2208, "text": null }, { "code": null, "e": 2374, "s": 2366, "text": "Output:" }, { "code": null, "e": 2773, "s": 2374, "text": "From the above examples, it becomes pretty clear that CartesianIndex simply gathers multiple integers together into one object that represents a single multidimensional index.Having discussed scalar representations, let’s talk about arrays of CartesianIndex{N}, which represent a collection of scalar indices each spanning N dimensions, such form of indexing is referred to as “pointwise” indexing." }, { "code": null, "e": 2817, "s": 2773, "text": "Array based CartesianIndexing for 1D Array:" }, { "code": "# Create a 1D array of size 5arr = reshape(Vector(2:6), 5) # Select an array of cartesian indices 2, 3, 5arr[[CartesianIndex(2), CartesianIndex(3), CartesianIndex(5)]]", "e": 2991, "s": 2817, "text": null }, { "code": null, "e": 2999, "s": 2991, "text": "Output:" }, { "code": null, "e": 3043, "s": 2999, "text": "Array based CartesianIndexing for 2D Array:" }, { "code": "# Create a 2D array of size 5x6arr = reshape(Vector(1:30), (5, 6)) # Select an array of cartesian indices (5, 2), (3, 6), (1, 4)arr[[CartesianIndex(5, 2), CartesianIndex(3, 6), CartesianIndex(1, 4)]]", "e": 3249, "s": 3043, "text": null }, { "code": null, "e": 3257, "s": 3249, "text": "Output:" }, { "code": null, "e": 3301, "s": 3257, "text": "Array based CartesianIndexing for 3D array:" }, { "code": "# Create a 3D array of size 2x3x1arr = reshape(Vector(1:12), (2, 3, 2)) # Select an array of cartesian indices (1, 2, 1), (2, 2, 2), (1, 3, 1)arr[[CartesianIndex(1, 2, 1), CartesianIndex(1, 3, 1), CartesianIndex(2, 2, 2)]]", "e": 3529, "s": 3301, "text": null }, { "code": null, "e": 3537, "s": 3529, "text": "Output:" }, { "code": null, "e": 3581, "s": 3537, "text": "Array based CartesianIndexing for nD array:" }, { "code": "# Create a 5D array of size 2x2x1x2x2arr = reshape(Vector(1:2:32), (2, 2, 1, 2, 2)) # Select an array of cartesian indices # (1, 2, 1, 1, 1), (1, 2, 1, 2, 2), (2, 1, 1, 2, 1)arr[[CartesianIndex(1, 2, 1, 1, 1), CartesianIndex(1, 2, 1, 2, 2), CartesianIndex(2, 1, 1, 2, 1)]]", "e": 3865, "s": 3581, "text": null }, { "code": null, "e": 3873, "s": 3865, "text": "Output:" }, { "code": null, "e": 4126, "s": 3873, "text": "This is really useful, in case we want to select specific elements of an array if they are not in order. But what if we have an array of 1000 and we need to extract 100 elements, it’ll be quite tedious!This is where dot(.) broadcasting comes into play." }, { "code": "# Create a 3D array of size 3x3x3arr = reshape(Vector(1:27), (3, 3, 3)) # Select diagonal elements in all the # 3 planes of cartesian coordinatesarr[[CartesianIndex(1, 1, 1), CartesianIndex(2, 2, 1), CartesianIndex(3, 3, 1), CartesianIndex(1, 1, 2), CartesianIndex(2, 2, 2), CartesianIndex(3, 3, 2), CartesianIndex(1, 1, 3), CartesianIndex(2, 2, 3), CartesianIndex(3, 3, 3)]] # Using dot broadcasting and (:)colon, to reduce codearr[CartesianIndex.(axes(arr, 1), axes(arr, 2), :)]", "e": 4628, "s": 4126, "text": null }, { "code": null, "e": 4708, "s": 4628, "text": "Output:How efficiently we have been able to reduce our code in the third step!!" }, { "code": null, "e": 4867, "s": 4708, "text": "What should we do with Cartesian Indexing ?We observe, CartesianIndices bear close resemblence to Cartesian coordinates and function in a similar way.Example:" }, { "code": null, "e": 5128, "s": 4867, "text": "We have a 3D shape in space, and it is mapped out by storing the coordinates of it's \nedges in an array and we might want to mask out a region from the shape. It becomes \neasy to deal with by using CartesianIndices, since they resemble the coordinate system. \n" }, { "code": null, "e": 5215, "s": 5128, "text": "In computing/electronics, the basis is a logic that is deterministic in nature. It is:" }, { "code": null, "e": 5246, "s": 5215, "text": "true, false\none, zero\non, off\n" }, { "code": null, "e": 5480, "s": 5246, "text": "It is basically a selection of elements at the indices where the values of our logical indexing array are true.A logical indexing array is called a “mask” since it masks out the values that are false. A mask is of type bool(boolean)." }, { "code": null, "e": 5513, "s": 5480, "text": "Relation with CartesianIndexing:" }, { "code": null, "e": 5647, "s": 5513, "text": "Indexing by a N-dimensional boolean array is equivalent to indexing by the vector \nof CartesianIndex{N}s where its values are true. \n" }, { "code": null, "e": 5690, "s": 5647, "text": "Example : Implementation of a logical mask" }, { "code": "# Create a 2D array of size 5x5arr = reshape(Vector(1:25), (5, 5)) # Apply a logical mask to the arrayarr[[true, false, true, false, true], :]", "e": 5834, "s": 5690, "text": null }, { "code": null, "e": 5971, "s": 5834, "text": "Output:So we see how only the rows whose index matches with the index of trues in our mask[true, false, true, false, true] are selected." }, { "code": null, "e": 6057, "s": 5971, "text": "Any condition that yields a boolean value can be used as a mask.Example for 1D array:" }, { "code": "# Create a 1D array of size 10arr = reshape(Vector(4:2:22), 10) # Create a power of 2 logic mask # and map it with the size of arrmask = map(ispow2, arr) # Apply it to the arrayarr[mask]", "e": 6246, "s": 6057, "text": null }, { "code": null, "e": 6254, "s": 6246, "text": "Output:" }, { "code": null, "e": 6276, "s": 6254, "text": "Example for 2D array:" }, { "code": "# Create a 2D array of size 10x10arr = reshape(Vector(1:100), (10, 10)) # Create a prime number logic mask and # map it with the size of arr # Julia library for working with prime numbers using Primes mask = map(isprime, arr) # Apply it to the arrayarr[mask]", "e": 6537, "s": 6276, "text": null }, { "code": null, "e": 6545, "s": 6537, "text": "Output:" }, { "code": null, "e": 6567, "s": 6545, "text": "Example for 3D array:" }, { "code": "# Create a 3D array of size 3x2x3arr = reshape(Vector(2:19), (3, 2, 3)) # Create a prime number logic mask # and map it with the size of arr# Julia library for working with prime numbers using Primesmask = map(isprime, arr) # Apply it to the arrayarr[mask]", "e": 6826, "s": 6567, "text": null }, { "code": null, "e": 6834, "s": 6826, "text": "Output:" }, { "code": null, "e": 6977, "s": 6834, "text": "One of the most used cases of logical indexing is when we want to filter elements out of an array on the basis of multiple conditions.Example:" }, { "code": "# Create a 3D array of size 3x2x3arr = reshape(Vector(2:19), (3, 2, 3)) # Create a function that checks for # both prime number or power of two# Julia library for working with prime numbers using Primes function prime_and_2pow(arr) if isprime(arr) || ispow2(arr) return true else return false endend # Create a logic mask and map it# with the size of arrmask = map(prime_and_2pow, arr) # Apply it to the arrayarr[mask]", "e": 7429, "s": 6977, "text": null }, { "code": null, "e": 7437, "s": 7429, "text": "Output:" }, { "code": null, "e": 7444, "s": 7437, "text": "Picked" }, { "code": null, "e": 7450, "s": 7444, "text": "Julia" }, { "code": null, "e": 7471, "s": 7450, "text": "Programming Language" } ]
Python program to find the highest 3 values in a dictionary
25 Aug, 2021 Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Examples: Input : my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} Output : {'F': 69, 'A': 67, 'D': 56} Let’s see different methods we can find the highest 3 values in a dictionary. Method #1: Using collections.Counter()A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.most_common([n]) returns a list of the n most common elements and their counts from the most common to the least. Python3 # Python program to demonstrate# finding 3 highest values in a Dictionary from collections import Counter # Initial Dictionarymy_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} k = Counter(my_dict) # Finding 3 highest valueshigh = k.most_common(3) print("Initial Dictionary:")print(my_dict, "\n") print("Dictionary with 3 highest values:")print("Keys: Values") for i in high: print(i[0]," :",i[1]," ") Initial Dictionary: {'C': 45, 'B': 23, 'D': 56, 'A': 67, 'E': 12, 'F': 69} Dictionary with 3 highest values: Keys: Values F : 69 A : 67 D : 56 Method #2: Using heapq.nlargest() Python3 # Python program to demonstrate# finding 3 highest values in a Dictionaryfrom heapq import nlargest # Initial Dictionarymy_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} print("Initial Dictionary:")print(my_dict, "\n") ThreeHighest = nlargest(3, my_dict, key = my_dict.get) print("Dictionary with 3 highest values:")print("Keys: Values") for val in ThreeHighest: print(val, ":", my_dict.get(val)) Initial Dictionary: {'D': 56, 'E': 12, 'F': 69, 'C': 45, 'B': 23, 'A': 67} Dictionary with 3 highest values: Keys: Values F : 69 A : 67 D : 56 anikakapoor Python dictionary-programs python-dict Python Python Programs python-dict 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() Python program to convert a list to string Defaultdict in Python Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 52, "s": 24, "text": "\n25 Aug, 2021" }, { "code": null, "e": 260, "s": 52, "text": "Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair." }, { "code": null, "e": 271, "s": 260, "text": "Examples: " }, { "code": null, "e": 402, "s": 271, "text": "Input : my_dict = {'A': 67, 'B': 23, 'C': 45,\n 'D': 56, 'E': 12, 'F': 69} \n\nOutput : {'F': 69, 'A': 67, 'D': 56}" }, { "code": null, "e": 967, "s": 402, "text": "Let’s see different methods we can find the highest 3 values in a dictionary. Method #1: Using collections.Counter()A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.most_common([n]) returns a list of the n most common elements and their counts from the most common to the least. " }, { "code": null, "e": 975, "s": 967, "text": "Python3" }, { "code": "# Python program to demonstrate# finding 3 highest values in a Dictionary from collections import Counter # Initial Dictionarymy_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} k = Counter(my_dict) # Finding 3 highest valueshigh = k.most_common(3) print(\"Initial Dictionary:\")print(my_dict, \"\\n\") print(\"Dictionary with 3 highest values:\")print(\"Keys: Values\") for i in high: print(i[0],\" :\",i[1],\" \")", "e": 1405, "s": 975, "text": null }, { "code": null, "e": 1557, "s": 1405, "text": "Initial Dictionary:\n{'C': 45, 'B': 23, 'D': 56, 'A': 67, 'E': 12, 'F': 69} \n\nDictionary with 3 highest values:\nKeys: Values\nF : 69 \nA : 67 \nD : 56" }, { "code": null, "e": 1593, "s": 1559, "text": "Method #2: Using heapq.nlargest()" }, { "code": null, "e": 1601, "s": 1593, "text": "Python3" }, { "code": "# Python program to demonstrate# finding 3 highest values in a Dictionaryfrom heapq import nlargest # Initial Dictionarymy_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} print(\"Initial Dictionary:\")print(my_dict, \"\\n\") ThreeHighest = nlargest(3, my_dict, key = my_dict.get) print(\"Dictionary with 3 highest values:\")print(\"Keys: Values\") for val in ThreeHighest: print(val, \":\", my_dict.get(val))", "e": 2026, "s": 1601, "text": null }, { "code": null, "e": 2171, "s": 2026, "text": "Initial Dictionary:\n{'D': 56, 'E': 12, 'F': 69, 'C': 45, 'B': 23, 'A': 67} \n\nDictionary with 3 highest values:\nKeys: Values\nF : 69\nA : 67\nD : 56" }, { "code": null, "e": 2185, "s": 2173, "text": "anikakapoor" }, { "code": null, "e": 2212, "s": 2185, "text": "Python dictionary-programs" }, { "code": null, "e": 2224, "s": 2212, "text": "python-dict" }, { "code": null, "e": 2231, "s": 2224, "text": "Python" }, { "code": null, "e": 2247, "s": 2231, "text": "Python Programs" }, { "code": null, "e": 2259, "s": 2247, "text": "python-dict" }, { "code": null, "e": 2357, "s": 2259, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2375, "s": 2357, "text": "Python Dictionary" }, { "code": null, "e": 2417, "s": 2375, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2439, "s": 2417, "text": "Enumerate() in Python" }, { "code": null, "e": 2474, "s": 2439, "text": "Read a file line by line in Python" }, { "code": null, "e": 2500, "s": 2474, "text": "Python String | replace()" }, { "code": null, "e": 2543, "s": 2500, "text": "Python program to convert a list to string" }, { "code": null, "e": 2565, "s": 2543, "text": "Defaultdict in Python" }, { "code": null, "e": 2603, "s": 2565, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2640, "s": 2603, "text": "Python Program for Fibonacci numbers" } ]
C# Program to Get and Print the Command Line Arguments Using Environment Class
01 Nov, 2021 In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. By just using some predefined methods we can get the information of the Operating System using the Environment class. In this article, we will discuss how to get and display the command line arguments using the Environment class. So to do this task we use the CommandLine property of the Environment Class. This property is used to find the command line for the current process. Syntax: Environment.CommandLine Return Type: The return type of this property is a string. This string represents the command-line arguments. Example: Input : Hello Geeks Output : Hello Geeks Input : Hello 123 Output : Hello 123 C# // C# program to display the command line arguments// using Environment Classusing System; class GFG{ static public void Main(){ // Declaring a string variable string commandlineResult = ""; // Getting the command line argument // Using the CommandLine property of // Environment class commandlineResult = Environment.CommandLine; // Display the data Console.WriteLine("Command Line Data: \n" + commandlineResult);}} Output: E:\> example.exe Hello Geeks Command Line Data: example.exe Hello Geeks CSharp-programs Picked C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class C# | .NET Framework (Basic Architecture and Component Stack) HashSet in C# with Examples Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2021" }, { "code": null, "e": 856, "s": 28, "text": "In C#, Environment Class provides information about the current platform and manipulates, the current platform. It is useful for getting and setting various operating system-related information. We can use it in such a way that it retrieves command-line arguments information, exit codes information, environment variable settings information, contents of the call stack information, and time since the last system boot in milliseconds information. By just using some predefined methods we can get the information of the Operating System using the Environment class. In this article, we will discuss how to get and display the command line arguments using the Environment class. So to do this task we use the CommandLine property of the Environment Class. This property is used to find the command line for the current process." }, { "code": null, "e": 864, "s": 856, "text": "Syntax:" }, { "code": null, "e": 888, "s": 864, "text": "Environment.CommandLine" }, { "code": null, "e": 998, "s": 888, "text": "Return Type: The return type of this property is a string. This string represents the command-line arguments." }, { "code": null, "e": 1007, "s": 998, "text": "Example:" }, { "code": null, "e": 1088, "s": 1007, "text": "Input : Hello Geeks\nOutput : Hello Geeks\n\nInput : Hello 123\nOutput : Hello 123" }, { "code": null, "e": 1091, "s": 1088, "text": "C#" }, { "code": "// C# program to display the command line arguments// using Environment Classusing System; class GFG{ static public void Main(){ // Declaring a string variable string commandlineResult = \"\"; // Getting the command line argument // Using the CommandLine property of // Environment class commandlineResult = Environment.CommandLine; // Display the data Console.WriteLine(\"Command Line Data: \\n\" + commandlineResult);}}", "e": 1575, "s": 1091, "text": null }, { "code": null, "e": 1583, "s": 1575, "text": "Output:" }, { "code": null, "e": 1655, "s": 1583, "text": "E:\\> example.exe Hello Geeks\nCommand Line Data:\nexample.exe Hello Geeks" }, { "code": null, "e": 1671, "s": 1655, "text": "CSharp-programs" }, { "code": null, "e": 1678, "s": 1671, "text": "Picked" }, { "code": null, "e": 1681, "s": 1678, "text": "C#" }, { "code": null, "e": 1779, "s": 1681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1822, "s": 1779, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1871, "s": 1822, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 1894, "s": 1871, "text": "Extension Method in C#" }, { "code": null, "e": 1910, "s": 1894, "text": "C# | List Class" }, { "code": null, "e": 1971, "s": 1910, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 1999, "s": 1971, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2022, "s": 1999, "text": "Switch Statement in C#" }, { "code": null, "e": 2047, "s": 2022, "text": "Lambda Expressions in C#" }, { "code": null, "e": 2069, "s": 2047, "text": "Partial Classes in C#" } ]
Given a matrix of ‘O’ and ‘X’, find the largest subsquare surrounded by ‘X’
24 Jun, 2022 Given a matrix where every element is either ‘O’ or ‘X’, find the largest subsquare surrounded by ‘X’. In the below article, it is assumed that the given matrix is also a square matrix. The code given below can be easily extended for rectangular matrices. Examples: Input: mat[N][N] = { {'X', 'O', 'X', 'X', 'X'}, {'X', 'X', 'X', 'X', 'X'}, {'X', 'X', 'O', 'X', 'O'}, {'X', 'X', 'X', 'X', 'X'}, {'X', 'X', 'X', 'O', 'O'}, }; Output: 3 The square submatrix starting at (1, 1) is the largest submatrix surrounded by 'X' Input: mat[M][N] = { {'X', 'O', 'X', 'X', 'X', 'X'}, {'X', 'O', 'X', 'X', 'O', 'X'}, {'X', 'X', 'X', 'O', 'O', 'X'}, {'X', 'X', 'X', 'X', 'X', 'X'}, {'X', 'X', 'X', 'O', 'X', 'O'}, }; Output: 4 The square submatrix starting at (0, 2) is the largest submatrix surrounded by 'X' A Simple Solution is to consider every square submatrix and check whether is has all corner edges filled with ‘X’. The time complexity of this solution is O(N4).We can solve this problem in O(N3) time using extra space. The idea is to create two auxiliary arrays hor[N][N] and ver[N][N]. The value stored in hor[i][j] is the number of horizontal continuous ‘X’ characters till mat[i][j] in mat[][]. Similarly, the value stored in ver[i][j] is the number of vertical continuous ‘X’ characters till mat[i][j] in mat[][]. Example: mat[6][6] = X O X X X X X O X X O X X X X O O X O X X X X X X X X O X O O O X O O O hor[6][6] = 1 0 1 2 3 4 1 0 1 2 0 1 1 2 3 0 0 1 0 1 2 3 4 5 1 2 3 0 1 0 0 0 1 0 0 0 ver[6][6] = 1 0 1 1 1 1 2 0 2 2 0 2 3 1 3 0 0 3 0 2 4 1 1 4 1 3 5 0 2 0 0 0 6 0 0 0 Once we have filled values in hor[][] and ver[][], we start from the bottommost-rightmost corner of matrix and move toward the leftmost-topmost in row by row manner. For every visited entry mat[i][j], we compare the values of hor[i][j] and ver[i][j], and pick the smaller of two as we need a square. Let the smaller of two be ‘small’. After picking smaller of two, we check if both ver[][] and hor[][] for left and up edges respectively. If they have entries for the same, then we found a subsquare. Otherwise we try for small-1. Below is implementation of the above idea. C++ Java Python3 C# PHP Javascript // A C++ program to find the largest subsquare// surrounded by 'X' in a given matrix of 'O' and 'X'#include <iostream>using namespace std; // Size of given matrix is N X N#define N 6 // A utility function to find minimum of two numbersint getMin(int x, int y) { return (x < y) ? x : y; } // Returns size of maximum size subsquare matrix// surrounded by 'X'int findSubSquare(int mat[][N]){ int max = 0; // Initialize result // Initialize the left-top value in hor[][] and ver[][] int hor[N][N], ver[N][N]; hor[0][0] = ver[0][0] = (mat[0][0] == 'X'); // Fill values in hor[][] and ver[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (mat[i][j] == 'O') ver[i][j] = hor[i][j] = 0; else { hor[i][j] = (j == 0) ? 1 : hor[i][j - 1] + 1; ver[i][j] = (i == 0) ? 1 : ver[i - 1][j] + 1; } } } // Start from the rightmost-bottommost corner element // and find the largest ssubsquare with the help of // hor[][] and ver[][] for (int i = N - 1; i >= 1; i--) { for (int j = N - 1; j >= 1; j--) { // Find smaller of values in hor[][] and ver[][] // A Square can only be made by taking smaller // value int small = getMin(hor[i][j], ver[i][j]); // At this point, we are sure that there is a // right vertical line and bottom horizontal // line of length at least 'small'. // We found a bigger square if following // conditions are met: 1)If side of square is // greater than max. 2)There is a left vertical // line of length >= 'small' 3)There is a top // horizontal line of length >= 'small' while (small > max) { if (ver[i][j - small + 1] >= small && hor[i - small + 1][j] >= small) { max = small; } small--; } } } return max;} // Driver codeint main(){ int mat[][N] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call cout << findSubSquare(mat); return 0;} // A JAVA program to find the// largest subsquare surrounded// by 'X' in a given matrix of// 'O' and 'X'import java.util.*; class GFG{ // Size of given // matrix is N X N static int N = 6; // A utility function to // find minimum of two numbers static int getMin(int x, int y) { return (x < y) ? x : y; } // Returns size of maximum // size subsquare matrix // surrounded by 'X' static int findSubSquare(int mat[][]) { int max = 0; // Initialize result // Initialize the left-top // value in hor[][] and ver[][] int hor[][] = new int[N][N]; int ver[][] = new int[N][N]; hor[0][0] = ver[0][0] = 'X'; // Fill values in // hor[][] and ver[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (mat[i][j] == 'O') ver[i][j] = hor[i][j] = 0; else { hor[i][j] = (j == 0) ? 1 : hor[i][j - 1] + 1; ver[i][j] = (i == 0) ? 1 : ver[i - 1][j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help // of hor[][] and ver[][] for (int i = N - 1; i >= 1; i--) { for (int j = N - 1; j >= 1; j--) { // Find smaller of values in // hor[][] and ver[][] A Square // can only be made by taking // smaller value int small = getMin(hor[i][j], ver[i][j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least 'small'. // We found a bigger square // if following conditions // are met: // 1)If side of square // is greater than max. // 2)There is a left vertical // line of length >= 'small' // 3)There is a top horizontal // line of length >= 'small' while (small > max) { if (ver[i][j - small + 1] >= small && hor[i - small + 1][j] >= small) { max = small; } small--; } } } return max; } // Driver Code public static void main(String[] args) { // TODO Auto-generated method stub int mat[][] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' } }; // Function call System.out.println(findSubSquare(mat)); }} // This code is contributed// by ChitraNayal # A Python3 program to find the largest# subsquare surrounded by 'X' in a given# matrix of 'O' and 'X'import math as mt # Size of given matrix is N X NN = 6 # A utility function to find minimum# of two numbers def getMin(x, y): if x < y: return x else: return y # Returns size of Maximum size# subsquare matrix surrounded by 'X' def findSubSquare(mat): Max = 0 # Initialize result # Initialize the left-top value # in hor[][] and ver[][] hor = [[0 for i in range(N)] for i in range(N)] ver = [[0 for i in range(N)] for i in range(N)] if mat[0][0] == 'X': hor[0][0] = 1 ver[0][0] = 1 # Fill values in hor[][] and ver[][] for i in range(N): for j in range(N): if (mat[i][j] == 'O'): ver[i][j], hor[i][j] = 0, 0 else: if j == 0: ver[i][j], hor[i][j] = 1, 1 else: (ver[i][j], hor[i][j]) = (ver[i - 1][j] + 1, hor[i][j - 1] + 1) # Start from the rightmost-bottommost corner # element and find the largest ssubsquare # with the help of hor[][] and ver[][] for i in range(N - 1, 0, -1): for j in range(N - 1, 0, -1): # Find smaller of values in hor[][] and # ver[][]. A Square can only be made by # taking smaller value small = getMin(hor[i][j], ver[i][j]) # At this point, we are sure that there # is a right vertical line and bottom # horizontal line of length at least 'small'. # We found a bigger square if following # conditions are met: # 1)If side of square is greater than Max. # 2)There is a left vertical line # of length >= 'small' # 3)There is a top horizontal line # of length >= 'small' while (small > Max): if (ver[i][j - small + 1] >= small and hor[i - small + 1][j] >= small): Max = small small -= 1 return Max # Driver Codemat = [['X', 'O', 'X', 'X', 'X', 'X'], ['X', 'O', 'X', 'X', 'O', 'X'], ['X', 'X', 'X', 'O', 'O', 'X'], ['O', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'O', 'X', 'O'], ['O', 'O', 'X', 'O', 'O', 'O']] # Function callprint(findSubSquare(mat)) # This code is contributed by# Mohit kumar 29 // A C# program to find the// largest subsquare surrounded// by 'X' in a given matrix of// 'O' and 'X'using System; class GFG{ // Size of given // matrix is N X N static int N = 6; // A utility function to // find minimum of two numbers static int getMin(int x, int y) { return (x < y) ? x : y; } // Returns size of maximum // size subsquare matrix // surrounded by 'X' static int findSubSquare(int[, ] mat) { int max = 0; // Initialize result // Initialize the left-top // value in hor[][] and ver[][] int[, ] hor = new int[N, N]; int[, ] ver = new int[N, N]; hor[0, 0] = ver[0, 0] = 'X'; // Fill values in // hor[][] and ver[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (mat[i, j] == 'O') ver[i, j] = hor[i, j] = 0; else { hor[i, j] = (j == 0) ? 1 : hor[i, j - 1] + 1; ver[i, j] = (i == 0) ? 1 : ver[i - 1, j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help // of hor[][] and ver[][] for (int i = N - 1; i >= 1; i--) { for (int j = N - 1; j >= 1; j--) { // Find smaller of values in // hor[][] and ver[][] A Square // can only be made by taking // smaller value int small = getMin(hor[i, j], ver[i, j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least 'small'. // We found a bigger square // if following conditions // are met: // 1)If side of square // is greater than max. // 2)There is a left vertical // line of length >= 'small' // 3)There is a top horizontal // line of length >= 'small' while (small > max) { if (ver[i, j - small + 1] >= small && hor[i - small + 1, j] >= small) { max = small; } small--; } } } return max; } // Driver Code public static void Main() { // TODO Auto-generated method stub int[, ] mat = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' } }; // Function call Console.WriteLine(findSubSquare(mat)); }} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// A PHP program to find// the largest subsquare// surrounded by 'X' in a// given matrix of 'O' and 'X' // Size of given// matrix is N X N$N = 6; // A utility function to find// minimum of two numbersfunction getMin($x, $y){ return ($x < $y) ? $x : $y;} // Returns size of maximum// size subsquare matrix// surrounded by 'X'function findSubSquare($mat){ $max = 0; // Initialize result $hor[0][0] = $ver[0][0] = ($mat[0][0] == 'X'); // Fill values in // $hor and $ver for ($i = 0; $i < $GLOBALS['N']; $i++) { for ($j = 0; $j < $GLOBALS['N']; $j++) { if ($mat[$i][$j] == 'O') $ver[$i][$j] = $hor[$i][$j] = 0; else { $hor[$i][$j] = ($j == 0) ? 1 : $hor[$i][$j - 1] + 1; $ver[$i][$j] = ($i == 0) ? 1 : $ver[$i - 1][$j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help of // $hor and $ver for ($i = $GLOBALS['N'] - 1; $i >= 1; $i--) { for ($j = $GLOBALS['N'] - 1; $j >= 1; $j--) { // Find smaller of values in // $hor and $ver A Square can // only be made by taking // smaller value $small = getMin($hor[$i][$j], $ver[$i][$j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least '$small'. // We found a bigger square if // following conditions are met: // 1)If side of square is // greater than $max. // 2)There is a left vertical // line of length >= '$small' // 3)There is a top horizontal // line of length >= '$small' while ($small > $max) { if ($ver[$i][$j - $small + 1] >= $small && $hor[$i - $small + 1][$j] >= $small) { $max = $small; } $small--; } } } return $max;} // Driver Code$mat = array(array('X', 'O', 'X', 'X', 'X', 'X'), array('X', 'O', 'X', 'X', 'O', 'X'), array('X', 'X', 'X', 'O', 'O', 'X'), array('O', 'X', 'X', 'X', 'X', 'X'), array('X', 'X', 'X', 'O', 'X', 'O'), array('O', 'O', 'X', 'O', 'O', 'O')); // Function callecho findSubSquare($mat); // This code is contributed// by ChitraNayal?> <script> // A JavaScript program to find the// largest subsquare surrounded// by 'X' in a given matrix of// 'O' and 'X' // Size of given // matrix is N X N let N = 6; // A utility function to // find minimum of two numbers function getMin(x,y) { return (x < y) ? x : y; } // Returns size of maximum // size subsquare matrix // surrounded by 'X' function findSubSquare(mat) { let max = 0; // Initialize result // Initialize the left-top // value in hor[][] and ver[][] let hor = new Array(N); let ver = new Array(N); for (let i = 0; i < N; i++) { hor[i]=new Array(N); ver[i]=new Array(N); for (let j = 0; j < N; j++) { hor[i][j]=""; ver[i][j]=""; } } hor[0][0] = 'X'; ver[0][0] = 'X'; // Fill values in // hor[][] and ver[][] for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (mat[i][j] == 'O') ver[i][j] = hor[i][j] = 0; else { hor[i][j] = (j == 0) ? 1 : hor[i][j - 1] + 1; ver[i][j] = (i == 0) ? 1 : ver[i - 1][j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help // of hor[][] and ver[][] for (let i = N - 1; i >= 1; i--) { for (let j = N - 1; j >= 1; j--) { // Find smaller of values in // hor[][] and ver[][] A Square // can only be made by taking // smaller value let small = getMin(hor[i][j], ver[i][j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least 'small'. // We found a bigger square // if following conditions // are met: // 1)If side of square // is greater than max. // 2)There is a left vertical // line of length >= 'small' // 3)There is a top horizontal // line of length >= 'small' while (small > max) { if (ver[i][j - small + 1] >= small && hor[i - small + 1][j] >= small) { max = small; } small--; } } } return max; } // Driver Code // TODO Auto-generated method stub let mat = [['X', 'O', 'X', 'X', 'X', 'X'], ['X', 'O', 'X', 'X', 'O', 'X'], ['X', 'X', 'X', 'O', 'O', 'X'], ['O', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'O', 'X', 'O'], ['O', 'O', 'X', 'O', 'O', 'O']] //Function call document.write(findSubSquare(mat)) // This code is contributed by unknown2108 </script> 4 Time complexity: O(N2).Auxiliary Space: O(N2) Optimized approach: A more optimized solution would be to pre-compute the number of contiguous ‘X’ horizontally and vertically, in a matrix of pairs named dp. Now for every entry of dp we have a pair (int, int) which denotes the maximum contiguous ‘X’ till that point, i.e. dp[i][j].first denotes contiguous ‘X’ taken horizontally till that point. dp[i][j].second denotes contiguous ‘X’ taken vertically till that point. Now, a square can be formed with dp[i][j] as the bottom right corner, having sides atmost of length, min(dp[i][j].first, dp[i][j].second) So, we make another matrix maxside, which will denote the maximum square side formed having the bottom right corner as arr[i][j]. We’ll try to get some intuition from the properties of a square, i.e. all the sides of the square are equal. Let’s store maximum value that can be obtained, as val = min(dp[i][j].first, dp[i][j].second). From point (i, j), we traverse back horizontally by distance Val, and check if the minimum vertical contiguous ‘X’ till that point is equal to Val. Similarly, we traverse back vertically by distance Val and check if the minimum horizontal contiguous ‘X’ till that point is equal to Val? Here we are making use of the fact that all sides of square are equal. Input Matrix: X O X X X X X O X X O X X X X O O X O X X X X X X X X O X O O O X O O O Value of matrix dp: (1,1) (0,0) (1,1) (2,7) (3,1) (4,1) (1,2) (0,0) (1,2) (2,8) (0,0) (1,2) (1,3) (2,1) (3,3) (0,0) (0,0) (1,3) (0,0) (1,2) (2,4) (3,1) (4,1) (5,4) (1,1) (2,3) (3,5) (0,0) (1,2) (0,0) (0,0) (0,0) (1,6) (0,0) (0,0) (0,0) Below is the implementation of the above idea: C++ Java Python3 C# Javascript // A C++ program to find the largest subsquare// surrounded by 'X' in a given matrix of 'O' and 'X'#include <bits/stdc++.h>using namespace std; // Size of given matrix is N X N#define N 6 int maximumSubSquare(int arr[][N]){ pair<int, int> dp[51][51]; int maxside[51][51]; // Initialize maxside with 0 memset(maxside, 0, sizeof(maxside)); int x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (int i = 0; i < N; i++) { x = 0; for (int j = 0; j < N; j++) { if (arr[i][j] == 'X') x += 1; else x = 0; dp[i][j].first = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[j][i] == 'X') y += 1; else y = 0; dp[j][i].second = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. int maxval = 0, val = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { val = min(dp[i][j].first, dp[i][j].second); if (dp[i][j - val + 1].second >= val && dp[i - val + 1][j].first >= val) maxside[i][j] = val; else maxside[i][j] = 0; // store the final answer in maxval maxval = max(maxval, maxside[i][j]); } } // return the final answe. return maxval;} // Driver codeint main(){ int mat[][N] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call cout << maximumSubSquare(mat); return 0;} /*package whatever //do not write package name here */import java.io.*;import java.util.*; class GFG{ static int N = 6; static int maximumSubSquare(int[][] arr) { int[][][] dp = new int[51][51][2]; int[][] maxside = new int[51][51]; // Initialize maxside with 0 for (int[] row : maxside) Arrays.fill(row, 10); int x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (int i = 0; i < N; i++) { x = 0; for (int j = 0; j < N; j++) { if (arr[i][j] == 'X') x += 1; else x = 0; dp[i][j][0] = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[j][i] == 'X') y += 1; else y = 0; dp[j][i][1] = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. int maxval = 0, val = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { val = Math.min(dp[i][j][0], dp[i][j][1]); if (dp[i][j - val + 1][1] >= val && dp[i - val + 1][j][0] >= val) maxside[i][j] = val; else maxside[i][j] = 0; // store the final answer in maxval maxval = Math.max(maxval, maxside[i][j]); } } // return the final answe. return maxval; } // Driver code public static void main (String[] args) { int mat[][] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call System.out.println(maximumSubSquare(mat)); }} // This code is contributed by rag2127. # Python3 program to find the largest# subsquare surrounded by 'X' in a given# matrix of 'O' and 'X' # Size of given matrix is N X NN = 6 def maximumSubSquare(arr): dp = [[[-1, -1] for i in range(51)] for j in range(51)] # Initialize maxside with 0 maxside = [[0 for i in range(51)] for j in range(51)] x = 0 y = 0 # Fill the dp matrix horizontally. # for contiguous 'X' increment the # value of x, otherwise make it 0 for i in range(N): x = 0 for j in range(N): if (arr[i][j] == 'X'): x += 1 else: x = 0 dp[i][j][0] = x # Fill the dp matrix vertically. # For contiguous 'X' increment # the value of y, otherwise # make it 0 for i in range(N): for j in range(N): if (arr[j][i] == 'X'): y += 1 else: y = 0 dp[j][i][1] = y # Now check , for every value of (i, j) if sub-square # is possible, # traverse back horizontally by value val, and check if # vertical contiguous # 'X'enfing at (i , j-val+1) is greater than equal to # val. # Similarly, check if traversing back vertically, the # horizontal contiguous # 'X'ending at (i-val+1, j) is greater than equal to # val. maxval = 0 val = 0 for i in range(N): for j in range(N): val = min(dp[i][j][0], dp[i][j][1]) if (dp[i][j - val + 1][1] >= val and dp[i - val + 1][j][0] >= val): maxside[i][j] = val else: maxside[i][j] = 0 # Store the final answer in maxval maxval = max(maxval, maxside[i][j]) # Return the final answe. return maxval # Driver codemat = [ [ 'X', 'O', 'X', 'X', 'X', 'X' ], [ 'X', 'O', 'X', 'X', 'O', 'X' ], [ 'X', 'X', 'X', 'O', 'O', 'X' ], [ 'O', 'X', 'X', 'X', 'X', 'X' ], [ 'X', 'X', 'X', 'O', 'X', 'O' ], [ 'O', 'O', 'X', 'O', 'O', 'O' ] ] # Function callprint(maximumSubSquare(mat)) # This code is contributed by avanitrachhadiya2155 // A C# program to find the largest subsquare// surrounded by 'X' in a given matrix of 'O' and 'X'using System; public class GFG{ static int N = 6; static int maximumSubSquare(int[,] arr) { int[,,] dp = new int[51,51,2]; int[,] maxside = new int[51,51]; // Initialize maxside with 0 for(int i = 0; i < 51; i++) { for(int j = 0; j < 51; j++) { maxside[i,j] = 10; } } int x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (int i = 0; i < N; i++) { x = 0; for (int j = 0; j < N; j++) { if (arr[i,j] == 'X') x += 1; else x = 0; dp[i,j,0] = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[j,i] == 'X') y += 1; else y = 0; dp[j,i,1] = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. int maxval = 0, val = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { val = Math.Min(dp[i,j,0], dp[i,j,1]); if (dp[i,j - val + 1,1] >= val && dp[i - val + 1,j,0] >= val) maxside[i,j] = val; else maxside[i,j] = 0; // store the final answer in maxval maxval = Math.Max(maxval, maxside[i,j]); } } // return the final answe. return maxval; } // Driver code static public void Main (){ int[,] mat = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call Console.WriteLine(maximumSubSquare(mat)); }} // This code is contributed by patel2127 <script>/*package whatever //do not write package name here */let N = 6; function maximumSubSquare(arr){ let dp = new Array(51); for(let i = 0; i < 51; i++) { dp[i] = new Array(51); for(let j = 0; j < 51; j++) { dp[i][j] = new Array(2); for(let k = 0; k < 2; k++) { dp[i][j][k] = 0; } } } let maxside = new Array(51); for(let i = 0; i < 51; i++) { maxside[i] = new Array(51); for(let j = 0; j < 51; j++) { maxside[i][j] = 10; } } let x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (let i = 0; i < N; i++) { x = 0; for (let j = 0; j < N; j++) { if (arr[i][j] == 'X') x += 1; else x = 0; dp[i][j][0] = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (arr[j][i] == 'X') y += 1; else y = 0; dp[j][i][1] = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. let maxval = 0, val = 0; for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { val = Math.min(dp[i][j][0], dp[i][j][1]); if (dp[i][j - val + 1][1] >= val && dp[i - val + 1][j][0] >= val) maxside[i][j] = val; else maxside[i][j] = 0; // store the final answer in maxval maxval = Math.max(maxval, maxside[i][j]); } } // return the final answe. return maxval; } // Driver codelet mat=[[ 'X', 'O', 'X', 'X', 'X', 'X' ], [ 'X', 'O', 'X', 'X', 'O', 'X' ], [ 'X', 'X', 'X', 'O', 'O', 'X' ], [ 'O', 'X', 'X', 'X', 'X', 'X' ], [ 'X', 'X', 'X', 'O', 'X', 'O' ], [ 'O', 'O', 'X', 'O', 'O', 'O' ] ]; // Function calldocument.write(maximumSubSquare(mat)); // This code is contributed by ab2127</script> 4 Time complexity: O(N2) Auxiliary space: O(N2) ukasp Suryaveer Singh Akanksha_Rai mohit kumar 29 Ar26 avanitrachhadiya2155 rag2127 unknown2108 ab2127 patel2127 codewithshinchan hardikkoriintern D-E-Shaw Matrix D-E-Shaw Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 308, "s": 52, "text": "Given a matrix where every element is either ‘O’ or ‘X’, find the largest subsquare surrounded by ‘X’. In the below article, it is assumed that the given matrix is also a square matrix. The code given below can be easily extended for rectangular matrices." }, { "code": null, "e": 319, "s": 308, "text": "Examples: " }, { "code": null, "e": 1057, "s": 319, "text": "Input: mat[N][N] = { {'X', 'O', 'X', 'X', 'X'},\n {'X', 'X', 'X', 'X', 'X'},\n {'X', 'X', 'O', 'X', 'O'},\n {'X', 'X', 'X', 'X', 'X'},\n {'X', 'X', 'X', 'O', 'O'},\n };\nOutput: 3\nThe square submatrix starting at (1, 1) is the largest\nsubmatrix surrounded by 'X'\n\nInput: mat[M][N] = { {'X', 'O', 'X', 'X', 'X', 'X'},\n {'X', 'O', 'X', 'X', 'O', 'X'},\n {'X', 'X', 'X', 'O', 'O', 'X'},\n {'X', 'X', 'X', 'X', 'X', 'X'},\n {'X', 'X', 'X', 'O', 'X', 'O'},\n };\nOutput: 4\nThe square submatrix starting at (0, 2) is the largest\nsubmatrix surrounded by 'X'" }, { "code": null, "e": 1577, "s": 1057, "text": "A Simple Solution is to consider every square submatrix and check whether is has all corner edges filled with ‘X’. The time complexity of this solution is O(N4).We can solve this problem in O(N3) time using extra space. The idea is to create two auxiliary arrays hor[N][N] and ver[N][N]. The value stored in hor[i][j] is the number of horizontal continuous ‘X’ characters till mat[i][j] in mat[][]. Similarly, the value stored in ver[i][j] is the number of vertical continuous ‘X’ characters till mat[i][j] in mat[][]. " }, { "code": null, "e": 1586, "s": 1577, "text": "Example:" }, { "code": null, "e": 2116, "s": 1586, "text": "mat[6][6] = X O X X X X\n X O X X O X\n X X X O O X\n O X X X X X\n X X X O X O\n O O X O O O\n\nhor[6][6] = 1 0 1 2 3 4\n 1 0 1 2 0 1\n 1 2 3 0 0 1\n 0 1 2 3 4 5\n 1 2 3 0 1 0\n 0 0 1 0 0 0\n\nver[6][6] = 1 0 1 1 1 1\n 2 0 2 2 0 2\n 3 1 3 0 0 3\n 0 2 4 1 1 4\n 1 3 5 0 2 0\n 0 0 6 0 0 0" }, { "code": null, "e": 2647, "s": 2116, "text": "Once we have filled values in hor[][] and ver[][], we start from the bottommost-rightmost corner of matrix and move toward the leftmost-topmost in row by row manner. For every visited entry mat[i][j], we compare the values of hor[i][j] and ver[i][j], and pick the smaller of two as we need a square. Let the smaller of two be ‘small’. After picking smaller of two, we check if both ver[][] and hor[][] for left and up edges respectively. If they have entries for the same, then we found a subsquare. Otherwise we try for small-1. " }, { "code": null, "e": 2691, "s": 2647, "text": "Below is implementation of the above idea. " }, { "code": null, "e": 2695, "s": 2691, "text": "C++" }, { "code": null, "e": 2700, "s": 2695, "text": "Java" }, { "code": null, "e": 2708, "s": 2700, "text": "Python3" }, { "code": null, "e": 2711, "s": 2708, "text": "C#" }, { "code": null, "e": 2715, "s": 2711, "text": "PHP" }, { "code": null, "e": 2726, "s": 2715, "text": "Javascript" }, { "code": "// A C++ program to find the largest subsquare// surrounded by 'X' in a given matrix of 'O' and 'X'#include <iostream>using namespace std; // Size of given matrix is N X N#define N 6 // A utility function to find minimum of two numbersint getMin(int x, int y) { return (x < y) ? x : y; } // Returns size of maximum size subsquare matrix// surrounded by 'X'int findSubSquare(int mat[][N]){ int max = 0; // Initialize result // Initialize the left-top value in hor[][] and ver[][] int hor[N][N], ver[N][N]; hor[0][0] = ver[0][0] = (mat[0][0] == 'X'); // Fill values in hor[][] and ver[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (mat[i][j] == 'O') ver[i][j] = hor[i][j] = 0; else { hor[i][j] = (j == 0) ? 1 : hor[i][j - 1] + 1; ver[i][j] = (i == 0) ? 1 : ver[i - 1][j] + 1; } } } // Start from the rightmost-bottommost corner element // and find the largest ssubsquare with the help of // hor[][] and ver[][] for (int i = N - 1; i >= 1; i--) { for (int j = N - 1; j >= 1; j--) { // Find smaller of values in hor[][] and ver[][] // A Square can only be made by taking smaller // value int small = getMin(hor[i][j], ver[i][j]); // At this point, we are sure that there is a // right vertical line and bottom horizontal // line of length at least 'small'. // We found a bigger square if following // conditions are met: 1)If side of square is // greater than max. 2)There is a left vertical // line of length >= 'small' 3)There is a top // horizontal line of length >= 'small' while (small > max) { if (ver[i][j - small + 1] >= small && hor[i - small + 1][j] >= small) { max = small; } small--; } } } return max;} // Driver codeint main(){ int mat[][N] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call cout << findSubSquare(mat); return 0;}", "e": 5207, "s": 2726, "text": null }, { "code": "// A JAVA program to find the// largest subsquare surrounded// by 'X' in a given matrix of// 'O' and 'X'import java.util.*; class GFG{ // Size of given // matrix is N X N static int N = 6; // A utility function to // find minimum of two numbers static int getMin(int x, int y) { return (x < y) ? x : y; } // Returns size of maximum // size subsquare matrix // surrounded by 'X' static int findSubSquare(int mat[][]) { int max = 0; // Initialize result // Initialize the left-top // value in hor[][] and ver[][] int hor[][] = new int[N][N]; int ver[][] = new int[N][N]; hor[0][0] = ver[0][0] = 'X'; // Fill values in // hor[][] and ver[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (mat[i][j] == 'O') ver[i][j] = hor[i][j] = 0; else { hor[i][j] = (j == 0) ? 1 : hor[i][j - 1] + 1; ver[i][j] = (i == 0) ? 1 : ver[i - 1][j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help // of hor[][] and ver[][] for (int i = N - 1; i >= 1; i--) { for (int j = N - 1; j >= 1; j--) { // Find smaller of values in // hor[][] and ver[][] A Square // can only be made by taking // smaller value int small = getMin(hor[i][j], ver[i][j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least 'small'. // We found a bigger square // if following conditions // are met: // 1)If side of square // is greater than max. // 2)There is a left vertical // line of length >= 'small' // 3)There is a top horizontal // line of length >= 'small' while (small > max) { if (ver[i][j - small + 1] >= small && hor[i - small + 1][j] >= small) { max = small; } small--; } } } return max; } // Driver Code public static void main(String[] args) { // TODO Auto-generated method stub int mat[][] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' } }; // Function call System.out.println(findSubSquare(mat)); }} // This code is contributed// by ChitraNayal", "e": 8366, "s": 5207, "text": null }, { "code": "# A Python3 program to find the largest# subsquare surrounded by 'X' in a given# matrix of 'O' and 'X'import math as mt # Size of given matrix is N X NN = 6 # A utility function to find minimum# of two numbers def getMin(x, y): if x < y: return x else: return y # Returns size of Maximum size# subsquare matrix surrounded by 'X' def findSubSquare(mat): Max = 0 # Initialize result # Initialize the left-top value # in hor[][] and ver[][] hor = [[0 for i in range(N)] for i in range(N)] ver = [[0 for i in range(N)] for i in range(N)] if mat[0][0] == 'X': hor[0][0] = 1 ver[0][0] = 1 # Fill values in hor[][] and ver[][] for i in range(N): for j in range(N): if (mat[i][j] == 'O'): ver[i][j], hor[i][j] = 0, 0 else: if j == 0: ver[i][j], hor[i][j] = 1, 1 else: (ver[i][j], hor[i][j]) = (ver[i - 1][j] + 1, hor[i][j - 1] + 1) # Start from the rightmost-bottommost corner # element and find the largest ssubsquare # with the help of hor[][] and ver[][] for i in range(N - 1, 0, -1): for j in range(N - 1, 0, -1): # Find smaller of values in hor[][] and # ver[][]. A Square can only be made by # taking smaller value small = getMin(hor[i][j], ver[i][j]) # At this point, we are sure that there # is a right vertical line and bottom # horizontal line of length at least 'small'. # We found a bigger square if following # conditions are met: # 1)If side of square is greater than Max. # 2)There is a left vertical line # of length >= 'small' # 3)There is a top horizontal line # of length >= 'small' while (small > Max): if (ver[i][j - small + 1] >= small and hor[i - small + 1][j] >= small): Max = small small -= 1 return Max # Driver Codemat = [['X', 'O', 'X', 'X', 'X', 'X'], ['X', 'O', 'X', 'X', 'O', 'X'], ['X', 'X', 'X', 'O', 'O', 'X'], ['O', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'O', 'X', 'O'], ['O', 'O', 'X', 'O', 'O', 'O']] # Function callprint(findSubSquare(mat)) # This code is contributed by# Mohit kumar 29", "e": 10842, "s": 8366, "text": null }, { "code": "// A C# program to find the// largest subsquare surrounded// by 'X' in a given matrix of// 'O' and 'X'using System; class GFG{ // Size of given // matrix is N X N static int N = 6; // A utility function to // find minimum of two numbers static int getMin(int x, int y) { return (x < y) ? x : y; } // Returns size of maximum // size subsquare matrix // surrounded by 'X' static int findSubSquare(int[, ] mat) { int max = 0; // Initialize result // Initialize the left-top // value in hor[][] and ver[][] int[, ] hor = new int[N, N]; int[, ] ver = new int[N, N]; hor[0, 0] = ver[0, 0] = 'X'; // Fill values in // hor[][] and ver[][] for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (mat[i, j] == 'O') ver[i, j] = hor[i, j] = 0; else { hor[i, j] = (j == 0) ? 1 : hor[i, j - 1] + 1; ver[i, j] = (i == 0) ? 1 : ver[i - 1, j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help // of hor[][] and ver[][] for (int i = N - 1; i >= 1; i--) { for (int j = N - 1; j >= 1; j--) { // Find smaller of values in // hor[][] and ver[][] A Square // can only be made by taking // smaller value int small = getMin(hor[i, j], ver[i, j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least 'small'. // We found a bigger square // if following conditions // are met: // 1)If side of square // is greater than max. // 2)There is a left vertical // line of length >= 'small' // 3)There is a top horizontal // line of length >= 'small' while (small > max) { if (ver[i, j - small + 1] >= small && hor[i - small + 1, j] >= small) { max = small; } small--; } } } return max; } // Driver Code public static void Main() { // TODO Auto-generated method stub int[, ] mat = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' } }; // Function call Console.WriteLine(findSubSquare(mat)); }} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 13985, "s": 10842, "text": null }, { "code": "<?php// A PHP program to find// the largest subsquare// surrounded by 'X' in a// given matrix of 'O' and 'X' // Size of given// matrix is N X N$N = 6; // A utility function to find// minimum of two numbersfunction getMin($x, $y){ return ($x < $y) ? $x : $y;} // Returns size of maximum// size subsquare matrix// surrounded by 'X'function findSubSquare($mat){ $max = 0; // Initialize result $hor[0][0] = $ver[0][0] = ($mat[0][0] == 'X'); // Fill values in // $hor and $ver for ($i = 0; $i < $GLOBALS['N']; $i++) { for ($j = 0; $j < $GLOBALS['N']; $j++) { if ($mat[$i][$j] == 'O') $ver[$i][$j] = $hor[$i][$j] = 0; else { $hor[$i][$j] = ($j == 0) ? 1 : $hor[$i][$j - 1] + 1; $ver[$i][$j] = ($i == 0) ? 1 : $ver[$i - 1][$j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help of // $hor and $ver for ($i = $GLOBALS['N'] - 1; $i >= 1; $i--) { for ($j = $GLOBALS['N'] - 1; $j >= 1; $j--) { // Find smaller of values in // $hor and $ver A Square can // only be made by taking // smaller value $small = getMin($hor[$i][$j], $ver[$i][$j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least '$small'. // We found a bigger square if // following conditions are met: // 1)If side of square is // greater than $max. // 2)There is a left vertical // line of length >= '$small' // 3)There is a top horizontal // line of length >= '$small' while ($small > $max) { if ($ver[$i][$j - $small + 1] >= $small && $hor[$i - $small + 1][$j] >= $small) { $max = $small; } $small--; } } } return $max;} // Driver Code$mat = array(array('X', 'O', 'X', 'X', 'X', 'X'), array('X', 'O', 'X', 'X', 'O', 'X'), array('X', 'X', 'X', 'O', 'O', 'X'), array('O', 'X', 'X', 'X', 'X', 'X'), array('X', 'X', 'X', 'O', 'X', 'O'), array('O', 'O', 'X', 'O', 'O', 'O')); // Function callecho findSubSquare($mat); // This code is contributed// by ChitraNayal?>", "e": 16599, "s": 13985, "text": null }, { "code": "<script> // A JavaScript program to find the// largest subsquare surrounded// by 'X' in a given matrix of// 'O' and 'X' // Size of given // matrix is N X N let N = 6; // A utility function to // find minimum of two numbers function getMin(x,y) { return (x < y) ? x : y; } // Returns size of maximum // size subsquare matrix // surrounded by 'X' function findSubSquare(mat) { let max = 0; // Initialize result // Initialize the left-top // value in hor[][] and ver[][] let hor = new Array(N); let ver = new Array(N); for (let i = 0; i < N; i++) { hor[i]=new Array(N); ver[i]=new Array(N); for (let j = 0; j < N; j++) { hor[i][j]=\"\"; ver[i][j]=\"\"; } } hor[0][0] = 'X'; ver[0][0] = 'X'; // Fill values in // hor[][] and ver[][] for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (mat[i][j] == 'O') ver[i][j] = hor[i][j] = 0; else { hor[i][j] = (j == 0) ? 1 : hor[i][j - 1] + 1; ver[i][j] = (i == 0) ? 1 : ver[i - 1][j] + 1; } } } // Start from the rightmost- // bottommost corner element // and find the largest // subsquare with the help // of hor[][] and ver[][] for (let i = N - 1; i >= 1; i--) { for (let j = N - 1; j >= 1; j--) { // Find smaller of values in // hor[][] and ver[][] A Square // can only be made by taking // smaller value let small = getMin(hor[i][j], ver[i][j]); // At this point, we are sure // that there is a right vertical // line and bottom horizontal // line of length at least 'small'. // We found a bigger square // if following conditions // are met: // 1)If side of square // is greater than max. // 2)There is a left vertical // line of length >= 'small' // 3)There is a top horizontal // line of length >= 'small' while (small > max) { if (ver[i][j - small + 1] >= small && hor[i - small + 1][j] >= small) { max = small; } small--; } } } return max; } // Driver Code // TODO Auto-generated method stub let mat = [['X', 'O', 'X', 'X', 'X', 'X'], ['X', 'O', 'X', 'X', 'O', 'X'], ['X', 'X', 'X', 'O', 'O', 'X'], ['O', 'X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'O', 'X', 'O'], ['O', 'O', 'X', 'O', 'O', 'O']] //Function call document.write(findSubSquare(mat)) // This code is contributed by unknown2108 </script>", "e": 19833, "s": 16599, "text": null }, { "code": null, "e": 19835, "s": 19833, "text": "4" }, { "code": null, "e": 19881, "s": 19835, "text": "Time complexity: O(N2).Auxiliary Space: O(N2)" }, { "code": null, "e": 19901, "s": 19881, "text": "Optimized approach:" }, { "code": null, "e": 20156, "s": 19901, "text": "A more optimized solution would be to pre-compute the number of contiguous ‘X’ horizontally and vertically, in a matrix of pairs named dp. Now for every entry of dp we have a pair (int, int) which denotes the maximum contiguous ‘X’ till that point, i.e." }, { "code": null, "e": 20230, "s": 20156, "text": "dp[i][j].first denotes contiguous ‘X’ taken horizontally till that point." }, { "code": null, "e": 20303, "s": 20230, "text": "dp[i][j].second denotes contiguous ‘X’ taken vertically till that point." }, { "code": null, "e": 20441, "s": 20303, "text": "Now, a square can be formed with dp[i][j] as the bottom right corner, having sides atmost of length, min(dp[i][j].first, dp[i][j].second)" }, { "code": null, "e": 20680, "s": 20441, "text": "So, we make another matrix maxside, which will denote the maximum square side formed having the bottom right corner as arr[i][j]. We’ll try to get some intuition from the properties of a square, i.e. all the sides of the square are equal." }, { "code": null, "e": 20923, "s": 20680, "text": "Let’s store maximum value that can be obtained, as val = min(dp[i][j].first, dp[i][j].second). From point (i, j), we traverse back horizontally by distance Val, and check if the minimum vertical contiguous ‘X’ till that point is equal to Val." }, { "code": null, "e": 21133, "s": 20923, "text": "Similarly, we traverse back vertically by distance Val and check if the minimum horizontal contiguous ‘X’ till that point is equal to Val? Here we are making use of the fact that all sides of square are equal." }, { "code": null, "e": 21147, "s": 21133, "text": "Input Matrix:" }, { "code": null, "e": 21164, "s": 21147, "text": "X O X X X X" }, { "code": null, "e": 21181, "s": 21164, "text": "X O X X O X" }, { "code": null, "e": 21198, "s": 21181, "text": "X X X O O X" }, { "code": null, "e": 21215, "s": 21198, "text": "O X X X X X" }, { "code": null, "e": 21232, "s": 21215, "text": "X X X O X O" }, { "code": null, "e": 21249, "s": 21232, "text": "O O X O O O" }, { "code": null, "e": 21269, "s": 21249, "text": "Value of matrix dp:" }, { "code": null, "e": 21307, "s": 21269, "text": "(1,1) (0,0) (1,1) (2,7) (3,1) (4,1) " }, { "code": null, "e": 21345, "s": 21307, "text": "(1,2) (0,0) (1,2) (2,8) (0,0) (1,2) " }, { "code": null, "e": 21383, "s": 21345, "text": "(1,3) (2,1) (3,3) (0,0) (0,0) (1,3) " }, { "code": null, "e": 21421, "s": 21383, "text": "(0,0) (1,2) (2,4) (3,1) (4,1) (5,4) " }, { "code": null, "e": 21459, "s": 21421, "text": "(1,1) (2,3) (3,5) (0,0) (1,2) (0,0) " }, { "code": null, "e": 21496, "s": 21459, "text": "(0,0) (0,0) (1,6) (0,0) (0,0) (0,0) " }, { "code": null, "e": 21543, "s": 21496, "text": "Below is the implementation of the above idea:" }, { "code": null, "e": 21547, "s": 21543, "text": "C++" }, { "code": null, "e": 21552, "s": 21547, "text": "Java" }, { "code": null, "e": 21560, "s": 21552, "text": "Python3" }, { "code": null, "e": 21563, "s": 21560, "text": "C#" }, { "code": null, "e": 21574, "s": 21563, "text": "Javascript" }, { "code": "// A C++ program to find the largest subsquare// surrounded by 'X' in a given matrix of 'O' and 'X'#include <bits/stdc++.h>using namespace std; // Size of given matrix is N X N#define N 6 int maximumSubSquare(int arr[][N]){ pair<int, int> dp[51][51]; int maxside[51][51]; // Initialize maxside with 0 memset(maxside, 0, sizeof(maxside)); int x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (int i = 0; i < N; i++) { x = 0; for (int j = 0; j < N; j++) { if (arr[i][j] == 'X') x += 1; else x = 0; dp[i][j].first = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[j][i] == 'X') y += 1; else y = 0; dp[j][i].second = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. int maxval = 0, val = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { val = min(dp[i][j].first, dp[i][j].second); if (dp[i][j - val + 1].second >= val && dp[i - val + 1][j].first >= val) maxside[i][j] = val; else maxside[i][j] = 0; // store the final answer in maxval maxval = max(maxval, maxside[i][j]); } } // return the final answe. return maxval;} // Driver codeint main(){ int mat[][N] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call cout << maximumSubSquare(mat); return 0;}", "e": 23895, "s": 21574, "text": null }, { "code": "/*package whatever //do not write package name here */import java.io.*;import java.util.*; class GFG{ static int N = 6; static int maximumSubSquare(int[][] arr) { int[][][] dp = new int[51][51][2]; int[][] maxside = new int[51][51]; // Initialize maxside with 0 for (int[] row : maxside) Arrays.fill(row, 10); int x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (int i = 0; i < N; i++) { x = 0; for (int j = 0; j < N; j++) { if (arr[i][j] == 'X') x += 1; else x = 0; dp[i][j][0] = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[j][i] == 'X') y += 1; else y = 0; dp[j][i][1] = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. int maxval = 0, val = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { val = Math.min(dp[i][j][0], dp[i][j][1]); if (dp[i][j - val + 1][1] >= val && dp[i - val + 1][j][0] >= val) maxside[i][j] = val; else maxside[i][j] = 0; // store the final answer in maxval maxval = Math.max(maxval, maxside[i][j]); } } // return the final answe. return maxval; } // Driver code public static void main (String[] args) { int mat[][] = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call System.out.println(maximumSubSquare(mat)); }} // This code is contributed by rag2127.", "e": 26148, "s": 23895, "text": null }, { "code": "# Python3 program to find the largest# subsquare surrounded by 'X' in a given# matrix of 'O' and 'X' # Size of given matrix is N X NN = 6 def maximumSubSquare(arr): dp = [[[-1, -1] for i in range(51)] for j in range(51)] # Initialize maxside with 0 maxside = [[0 for i in range(51)] for j in range(51)] x = 0 y = 0 # Fill the dp matrix horizontally. # for contiguous 'X' increment the # value of x, otherwise make it 0 for i in range(N): x = 0 for j in range(N): if (arr[i][j] == 'X'): x += 1 else: x = 0 dp[i][j][0] = x # Fill the dp matrix vertically. # For contiguous 'X' increment # the value of y, otherwise # make it 0 for i in range(N): for j in range(N): if (arr[j][i] == 'X'): y += 1 else: y = 0 dp[j][i][1] = y # Now check , for every value of (i, j) if sub-square # is possible, # traverse back horizontally by value val, and check if # vertical contiguous # 'X'enfing at (i , j-val+1) is greater than equal to # val. # Similarly, check if traversing back vertically, the # horizontal contiguous # 'X'ending at (i-val+1, j) is greater than equal to # val. maxval = 0 val = 0 for i in range(N): for j in range(N): val = min(dp[i][j][0], dp[i][j][1]) if (dp[i][j - val + 1][1] >= val and dp[i - val + 1][j][0] >= val): maxside[i][j] = val else: maxside[i][j] = 0 # Store the final answer in maxval maxval = max(maxval, maxside[i][j]) # Return the final answe. return maxval # Driver codemat = [ [ 'X', 'O', 'X', 'X', 'X', 'X' ], [ 'X', 'O', 'X', 'X', 'O', 'X' ], [ 'X', 'X', 'X', 'O', 'O', 'X' ], [ 'O', 'X', 'X', 'X', 'X', 'X' ], [ 'X', 'X', 'X', 'O', 'X', 'O' ], [ 'O', 'O', 'X', 'O', 'O', 'O' ] ] # Function callprint(maximumSubSquare(mat)) # This code is contributed by avanitrachhadiya2155", "e": 28399, "s": 26148, "text": null }, { "code": "// A C# program to find the largest subsquare// surrounded by 'X' in a given matrix of 'O' and 'X'using System; public class GFG{ static int N = 6; static int maximumSubSquare(int[,] arr) { int[,,] dp = new int[51,51,2]; int[,] maxside = new int[51,51]; // Initialize maxside with 0 for(int i = 0; i < 51; i++) { for(int j = 0; j < 51; j++) { maxside[i,j] = 10; } } int x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (int i = 0; i < N; i++) { x = 0; for (int j = 0; j < N; j++) { if (arr[i,j] == 'X') x += 1; else x = 0; dp[i,j,0] = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (arr[j,i] == 'X') y += 1; else y = 0; dp[j,i,1] = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. int maxval = 0, val = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { val = Math.Min(dp[i,j,0], dp[i,j,1]); if (dp[i,j - val + 1,1] >= val && dp[i - val + 1,j,0] >= val) maxside[i,j] = val; else maxside[i,j] = 0; // store the final answer in maxval maxval = Math.Max(maxval, maxside[i,j]); } } // return the final answe. return maxval; } // Driver code static public void Main (){ int[,] mat = { { 'X', 'O', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X' }, { 'X', 'X', 'X', 'O', 'O', 'X' }, { 'O', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'X', 'X', 'O', 'X', 'O' }, { 'O', 'O', 'X', 'O', 'O', 'O' }, }; // Function call Console.WriteLine(maximumSubSquare(mat)); }} // This code is contributed by patel2127", "e": 30767, "s": 28399, "text": null }, { "code": "<script>/*package whatever //do not write package name here */let N = 6; function maximumSubSquare(arr){ let dp = new Array(51); for(let i = 0; i < 51; i++) { dp[i] = new Array(51); for(let j = 0; j < 51; j++) { dp[i][j] = new Array(2); for(let k = 0; k < 2; k++) { dp[i][j][k] = 0; } } } let maxside = new Array(51); for(let i = 0; i < 51; i++) { maxside[i] = new Array(51); for(let j = 0; j < 51; j++) { maxside[i][j] = 10; } } let x = 0, y = 0; // Fill the dp matrix horizontally. // for contiguous 'X' increment the value of x, // otherwise make it 0 for (let i = 0; i < N; i++) { x = 0; for (let j = 0; j < N; j++) { if (arr[i][j] == 'X') x += 1; else x = 0; dp[i][j][0] = x; } } // Fill the dp matrix vertically. // For contiguous 'X' increment the value of y, // otherwise make it 0 for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { if (arr[j][i] == 'X') y += 1; else y = 0; dp[j][i][1] = y; } } // Now check , for every value of (i, j) if sub-square // is possible, // traverse back horizontally by value val, and check if // vertical contiguous // 'X'enfing at (i , j-val+1) is greater than equal to // val. // Similarly, check if traversing back vertically, the // horizontal contiguous // 'X'ending at (i-val+1, j) is greater than equal to // val. let maxval = 0, val = 0; for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { val = Math.min(dp[i][j][0], dp[i][j][1]); if (dp[i][j - val + 1][1] >= val && dp[i - val + 1][j][0] >= val) maxside[i][j] = val; else maxside[i][j] = 0; // store the final answer in maxval maxval = Math.max(maxval, maxside[i][j]); } } // return the final answe. return maxval; } // Driver codelet mat=[[ 'X', 'O', 'X', 'X', 'X', 'X' ], [ 'X', 'O', 'X', 'X', 'O', 'X' ], [ 'X', 'X', 'X', 'O', 'O', 'X' ], [ 'O', 'X', 'X', 'X', 'X', 'X' ], [ 'X', 'X', 'X', 'O', 'X', 'O' ], [ 'O', 'O', 'X', 'O', 'O', 'O' ] ]; // Function calldocument.write(maximumSubSquare(mat)); // This code is contributed by ab2127</script>", "e": 33220, "s": 30767, "text": null }, { "code": null, "e": 33222, "s": 33220, "text": "4" }, { "code": null, "e": 33268, "s": 33222, "text": "Time complexity: O(N2) Auxiliary space: O(N2)" }, { "code": null, "e": 33274, "s": 33268, "text": "ukasp" }, { "code": null, "e": 33290, "s": 33274, "text": "Suryaveer Singh" }, { "code": null, "e": 33303, "s": 33290, "text": "Akanksha_Rai" }, { "code": null, "e": 33318, "s": 33303, "text": "mohit kumar 29" }, { "code": null, "e": 33323, "s": 33318, "text": "Ar26" }, { "code": null, "e": 33344, "s": 33323, "text": "avanitrachhadiya2155" }, { "code": null, "e": 33352, "s": 33344, "text": "rag2127" }, { "code": null, "e": 33364, "s": 33352, "text": "unknown2108" }, { "code": null, "e": 33371, "s": 33364, "text": "ab2127" }, { "code": null, "e": 33381, "s": 33371, "text": "patel2127" }, { "code": null, "e": 33398, "s": 33381, "text": "codewithshinchan" }, { "code": null, "e": 33415, "s": 33398, "text": "hardikkoriintern" }, { "code": null, "e": 33424, "s": 33415, "text": "D-E-Shaw" }, { "code": null, "e": 33431, "s": 33424, "text": "Matrix" }, { "code": null, "e": 33440, "s": 33431, "text": "D-E-Shaw" }, { "code": null, "e": 33447, "s": 33440, "text": "Matrix" } ]
How to create content area scrollable instead of the page using CSS ?
14 Dec, 2020 Making a particular content area scrollable is done by using CSS overflow property. There are different values in overflow property that are listed below. visible: The property indicates that it can be rendered outside the block box and it is not clipped. hidden: This property indicates that the overflow is clipped. The rest of the content will be invisible. auto: If overflow is clipped, then automatically a scroll-bar is added for the rest of the content. scroll: This property indicates that the scroll-bar is added to see the rest of the content if it is clipped. initial: This property sets to its default value. inherit: This property inherits the property from its parent element. We can disable page scrolling by setting body overflow property to hidden. In both the examples, we will be using this property to disable the page scrolling. Example 1: In this example, we use overflow: scroll property to make “div” vertically and horizontally scrollable. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"></head> <style> body { /* disabling body scrolling */ overflow: hidden; margin: auto; background: white; margin-top: 4%; text-align: center; } h1 { color: Green; } .scroll { /* enable div scrolling */ overflow: scroll; height: 8%; background-color: aqua; border: 1px black solid; padding: 2%; width: 300px; margin: 0 auto; white-space: nowrap; font-size: large; }</style> <body> <h1>GeeksforGeeks</h1> <h2> Making content area scrollable instead of the page </h2> <div class="scroll"> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are<br> Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with<br> a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by<br> writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </div></body> </html> Output: Example 2: In this example, use overflow:auto; to make “div” vertically and horizontally scrollable. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <style> body { /* disabling body scrolling */ overflow: hidden; margin: auto; background: white; margin-top: 4%; text-align: center; } h1 { color: Green; } .scroll { /* enable div scrolling */ overflow: auto; height: 8%; background-color: aqua; border: 1px black solid; padding: 2%; width: 300px; margin: 0 auto; white-space: nowrap; font-size: large; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Making content area scrollable instead of the page </h2> <div class="scroll"> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are<br> Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with<br> a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by<br> writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </div></body> </html> Output: Note: You can enable only vertical scrolling by setting overflow-y to scroll and auto and overflow-x to hidden. Similarly for horizontal scrolling, set overflow-x to scroll or auto and overflow-y to hidden. Example 3: This example is used only for vertical scrolling of content area. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <style> body { overflow: hidden; margin: auto; background: white; margin-top: 4%; text-align: center; } h1 { color: Green; } .scroll { overflow-y: auto; overflow-x: hidden; height: 50%; background-color: aqua; border: 1px black solid; padding: 2%; width: 500px; margin: 0 auto; font-size: large; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Making content area scrollable instead of the page </h2> <div class="scroll"> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are<br> Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with<br> a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by<br> writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </div></body> </html> Output: CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Dec, 2020" }, { "code": null, "e": 208, "s": 52, "text": "Making a particular content area scrollable is done by using CSS overflow property. There are different values in overflow property that are listed below. " }, { "code": null, "e": 309, "s": 208, "text": "visible: The property indicates that it can be rendered outside the block box and it is not clipped." }, { "code": null, "e": 414, "s": 309, "text": "hidden: This property indicates that the overflow is clipped. The rest of the content will be invisible." }, { "code": null, "e": 514, "s": 414, "text": "auto: If overflow is clipped, then automatically a scroll-bar is added for the rest of the content." }, { "code": null, "e": 624, "s": 514, "text": "scroll: This property indicates that the scroll-bar is added to see the rest of the content if it is clipped." }, { "code": null, "e": 674, "s": 624, "text": "initial: This property sets to its default value." }, { "code": null, "e": 744, "s": 674, "text": "inherit: This property inherits the property from its parent element." }, { "code": null, "e": 819, "s": 744, "text": "We can disable page scrolling by setting body overflow property to hidden." }, { "code": null, "e": 903, "s": 819, "text": "In both the examples, we will be using this property to disable the page scrolling." }, { "code": null, "e": 1018, "s": 903, "text": "Example 1: In this example, we use overflow: scroll property to make “div” vertically and horizontally scrollable." }, { "code": null, "e": 1023, "s": 1018, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"></head> <style> body { /* disabling body scrolling */ overflow: hidden; margin: auto; background: white; margin-top: 4%; text-align: center; } h1 { color: Green; } .scroll { /* enable div scrolling */ overflow: scroll; height: 8%; background-color: aqua; border: 1px black solid; padding: 2%; width: 300px; margin: 0 auto; white-space: nowrap; font-size: large; }</style> <body> <h1>GeeksforGeeks</h1> <h2> Making content area scrollable instead of the page </h2> <div class=\"scroll\"> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are<br> Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with<br> a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by<br> writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </div></body> </html>", "e": 3782, "s": 1023, "text": null }, { "code": null, "e": 3790, "s": 3782, "text": "Output:" }, { "code": null, "e": 3891, "s": 3790, "text": "Example 2: In this example, use overflow:auto; to make “div” vertically and horizontally scrollable." }, { "code": null, "e": 3896, "s": 3891, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <style> body { /* disabling body scrolling */ overflow: hidden; margin: auto; background: white; margin-top: 4%; text-align: center; } h1 { color: Green; } .scroll { /* enable div scrolling */ overflow: auto; height: 8%; background-color: aqua; border: 1px black solid; padding: 2%; width: 300px; margin: 0 auto; white-space: nowrap; font-size: large; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Making content area scrollable instead of the page </h2> <div class=\"scroll\"> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are<br> Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with<br> a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by<br> writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </div></body> </html>", "e": 6761, "s": 3896, "text": null }, { "code": null, "e": 6769, "s": 6761, "text": "Output:" }, { "code": null, "e": 6881, "s": 6769, "text": "Note: You can enable only vertical scrolling by setting overflow-y to scroll and auto and overflow-x to hidden." }, { "code": null, "e": 6976, "s": 6881, "text": "Similarly for horizontal scrolling, set overflow-x to scroll or auto and overflow-y to hidden." }, { "code": null, "e": 7053, "s": 6976, "text": "Example 3: This example is used only for vertical scrolling of content area." }, { "code": null, "e": 7058, "s": 7053, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <style> body { overflow: hidden; margin: auto; background: white; margin-top: 4%; text-align: center; } h1 { color: Green; } .scroll { overflow-y: auto; overflow-x: hidden; height: 50%; background-color: aqua; border: 1px black solid; padding: 2%; width: 500px; margin: 0 auto; font-size: large; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> Making content area scrollable instead of the page </h2> <div class=\"scroll\"> It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. The course focuses on various MCQ & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by writing articles on the GeeksforGeeks, publishing articles follow few steps that are<br> Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. It is a good platform to learn programming. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with<br> a free online placement preparation course. The course focuses on various MCQ's & Coding question likely to be asked in the interviews & make your upcoming placement season efficient and successful. Also, any geeks can help other geeks by<br> writing articles on the GeeksforGeeks, publishing articles follow few steps that are Articles that need little modification or improvement from reviewers are published first. To quickly get your articles reviewed, please refer existing articles, their formatting style, coding style, and try to make you are close to them. In case you are a beginner, you may refer Guidelines to write an Article. </div></body> </html>", "e": 9845, "s": 7058, "text": null }, { "code": null, "e": 9853, "s": 9845, "text": "Output:" }, { "code": null, "e": 9862, "s": 9853, "text": "CSS-Misc" }, { "code": null, "e": 9872, "s": 9862, "text": "HTML-Misc" }, { "code": null, "e": 9876, "s": 9872, "text": "CSS" }, { "code": null, "e": 9881, "s": 9876, "text": "HTML" }, { "code": null, "e": 9898, "s": 9881, "text": "Web Technologies" }, { "code": null, "e": 9925, "s": 9898, "text": "Web technologies Questions" }, { "code": null, "e": 9930, "s": 9925, "text": "HTML" } ]
VBScript Split Function
A Split Function returns an array that contains a specific number of values split based on a Delimiter. Split(expression[,delimiter[,count[,compare]]]) expression, a Required parameter. The String Expression that can contain strings with delimiters. expression, a Required parameter. The String Expression that can contain strings with delimiters. delimiter, an Optional Parameter. The Parameter, which is used to convert into arrays based on a delimiter. delimiter, an Optional Parameter. The Parameter, which is used to convert into arrays based on a delimiter. count, an Optional Parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned. count, an Optional Parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned. compare, an Optional Parameter. This parameter specifies which comparison method to be used. 0 = vbBinaryCompare - Performs a binary comparison 1 = vbTextCompare - Performs a textual comparison compare, an Optional Parameter. This parameter specifies which comparison method to be used. 0 = vbBinaryCompare - Performs a binary comparison 0 = vbBinaryCompare - Performs a binary comparison 1 = vbTextCompare - Performs a textual comparison 1 = vbTextCompare - Performs a textual comparison <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> ' Splitting based on delimiter comma '$' a = Split("Red $ Blue $ Yellow","$") b = ubound(a) For i = 0 to b document.write("The value of array in " & i & " is :" & a(i)& "<br />") Next </script> </body> </html> When the above code is saved as .HTML and executed in Internet Explorer, it produces the following result− The value of array in 0 is :Red The value of array in 1 is : Blue The value of array in 2 is : Yellow
[ { "code": null, "e": 2318, "s": 2214, "text": "A Split Function returns an array that contains a specific number of values split based on a Delimiter." }, { "code": null, "e": 2368, "s": 2318, "text": "Split(expression[,delimiter[,count[,compare]]]) \n" }, { "code": null, "e": 2466, "s": 2368, "text": "expression, a Required parameter. The String Expression that can contain strings with delimiters." }, { "code": null, "e": 2564, "s": 2466, "text": "expression, a Required parameter. The String Expression that can contain strings with delimiters." }, { "code": null, "e": 2672, "s": 2564, "text": "delimiter, an Optional Parameter. The Parameter, which is used to convert into arrays based on a delimiter." }, { "code": null, "e": 2780, "s": 2672, "text": "delimiter, an Optional Parameter. The Parameter, which is used to convert into arrays based on a delimiter." }, { "code": null, "e": 2913, "s": 2780, "text": "count, an Optional Parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned." }, { "code": null, "e": 3046, "s": 2913, "text": "count, an Optional Parameter. The number of substrings to be returned, and if specified as -1, then all the substrings are returned." }, { "code": null, "e": 3243, "s": 3046, "text": "compare, an Optional Parameter. This parameter specifies which comparison method to be used.\n\n0 = vbBinaryCompare - Performs a binary comparison\n1 = vbTextCompare - Performs a textual comparison\n\n" }, { "code": null, "e": 3336, "s": 3243, "text": "compare, an Optional Parameter. This parameter specifies which comparison method to be used." }, { "code": null, "e": 3387, "s": 3336, "text": "0 = vbBinaryCompare - Performs a binary comparison" }, { "code": null, "e": 3438, "s": 3387, "text": "0 = vbBinaryCompare - Performs a binary comparison" }, { "code": null, "e": 3488, "s": 3438, "text": "1 = vbTextCompare - Performs a textual comparison" }, { "code": null, "e": 3538, "s": 3488, "text": "1 = vbTextCompare - Performs a textual comparison" }, { "code": null, "e": 3919, "s": 3538, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n ' Splitting based on delimiter comma '$'\n a = Split(\"Red $ Blue $ Yellow\",\"$\")\n b = ubound(a)\n \n For i = 0 to b\n document.write(\"The value of array in \" & i & \" is :\" & a(i)& \"<br />\")\n Next\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 4026, "s": 3919, "text": "When the above code is saved as .HTML and executed in Internet Explorer, it produces the following result−" } ]
Java.io.ObjectStreamClass in Java
29 Apr, 2022 This class is serialization’s descriptor for classes. It contains the name and serialVersionUID of the class. The ObjectStreamClass for a specific class loaded in this Java VM can be found/created using the lookup method. It extends class Object and implement serialisable. Fields: static ObjectStreamField[] NO_FIELDS– This is the serialPersistentFields value indicating no serializable fields. Methods: Class forClass(): This method return the class in the local VM that this version is mapped to. Null is returned if there is no corresponding local class. Class forClass(): This method return the class in the local VM that this version is mapped to. Null is returned if there is no corresponding local class. Syntax: public Class forClass() Returns: the Class instance that this descriptor represents Exception: NA static ObjectStreamClass lookup(Class class): Find the descriptor for a class that can be serialized. Creates an ObjectStreamClass instance if one does not exist yet for class. Null is returned if the specified class does not implement java.io.Serializable or java.io.Externalizable. static ObjectStreamClass lookup(Class class): Find the descriptor for a class that can be serialized. Creates an ObjectStreamClass instance if one does not exist yet for class. Null is returned if the specified class does not implement java.io.Serializable or java.io.Externalizable. Syntax: public static ObjectStreamClass lookup(Class cl) Return: the class descriptor for the specified class Exception: NA static ObjectStreamClass lookupAny(Class class): Returns the descriptor for any class, regardless of whether it implements Serializable. static ObjectStreamClass lookupAny(Class class): Returns the descriptor for any class, regardless of whether it implements Serializable. Syntax: public static ObjectStreamClass lookupAny(Class class) Return: the class descriptor for the specified class Exception: NA Java // Java code illustrating forClass(),// lookup() and lookupAny() method import java.io.ObjectStreamClass;import java.util.ArrayList; public class ObjectStreamDemo{ public static void main(String arg[]) { // creating object stream class for Number ObjectStreamClass geeks_stream = ObjectStreamClass.lookup(Number.class); ObjectStreamClass quiz_stream = ObjectStreamClass.lookupAny(ArrayList.class); // checking class instance System.out.println(geeks_stream.forClass()); System.out.println(quiz_stream.forClass()); } } Output: Output: class java.lang.Number class java.util.ArrayList ObjectStreamField getField(String name): Get the field of this class by name. ObjectStreamField getField(String name): Get the field of this class by name. Syntax: public ObjectStreamField getField(String name) Return: The ObjectStreamField object of the named field or null if there is no such named field. Exception: NA ObjectStreamField[] getFields(): Return an array of the fields of this serializable class. ObjectStreamField[] getFields(): Return an array of the fields of this serializable class. Syntax: public ObjectStreamField[] getFields() Returns: an array containing an element for each persistent field of this class. Returns an array of length zero if there are no fields. Exception: NA String getName(): Returns the name of the class described by this descriptor. This method returns the name of the class in the format that is used by the Class.getName() method. String getName(): Returns the name of the class described by this descriptor. This method returns the name of the class in the format that is used by the Class.getName() method. Syntax: public String getName() Return: a string representing the name of the class Exception: NA long getSerialVersionUID(): Return the serialVersionUID for this class. The serialVersionUID defines a set of classes all with the same name that have evolved from a common root class and agree to be serialized and deserialized using a common format. NonSerializable classes have a serialVersionUID of 0L. long getSerialVersionUID(): Return the serialVersionUID for this class. The serialVersionUID defines a set of classes all with the same name that have evolved from a common root class and agree to be serialized and deserialized using a common format. NonSerializable classes have a serialVersionUID of 0L. Syntax: public long getSerialVersionUID() Returns: the SUID of the class described by this descriptor Exception: NA String toString(): Return a string describing this ObjectStreamClass. String toString(): Return a string describing this ObjectStreamClass. Syntax: public String toString() Returns: a string representation of the object. Exception: NA Java // Java code illustrating getField(), toString()// getClass(), getSerialVersionUID() import java.io.ObjectStreamClass;import java.util.ArrayList; public class ObjectStreamDemo{ public static void main(String arg[]) { // creating object stream class for Number ObjectStreamClass geeks_stream = ObjectStreamClass.lookup(Number.class); // checking field System.out.println(geeks_stream.getField("quiz_stream")); System.out.println(geeks_stream.getFields()); // class name System.out.println("class name: " + geeks_stream.getClass()); // checking serial version UID System.out.println(geeks_stream.getSerialVersionUID()); System.out.println(geeks_stream.toString()); } } Output: Output: null [Ljava.io.ObjectStreamField;@45ee12a7 class name: class java.io.ObjectStreamClass -8742448824652078965 java.lang.Number: static final long serialVersionUID = -8742448824652078965L; This article is contributed by Abhishek Verma. 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. surinderdawra388 Java-I/O Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Apr, 2022" }, { "code": null, "e": 460, "s": 54, "text": "This class is serialization’s descriptor for classes. It contains the name and serialVersionUID of the class. The ObjectStreamClass for a specific class loaded in this Java VM can be found/created using the lookup method. It extends class Object and implement serialisable. Fields: static ObjectStreamField[] NO_FIELDS– This is the serialPersistentFields value indicating no serializable fields. Methods: " }, { "code": null, "e": 614, "s": 460, "text": "Class forClass(): This method return the class in the local VM that this version is mapped to. Null is returned if there is no corresponding local class." }, { "code": null, "e": 768, "s": 614, "text": "Class forClass(): This method return the class in the local VM that this version is mapped to. Null is returned if there is no corresponding local class." }, { "code": null, "e": 874, "s": 768, "text": "Syntax: public Class forClass()\nReturns: the Class instance that this descriptor represents\nException: NA" }, { "code": null, "e": 1158, "s": 874, "text": "static ObjectStreamClass lookup(Class class): Find the descriptor for a class that can be serialized. Creates an ObjectStreamClass instance if one does not exist yet for class. Null is returned if the specified class does not implement java.io.Serializable or java.io.Externalizable." }, { "code": null, "e": 1442, "s": 1158, "text": "static ObjectStreamClass lookup(Class class): Find the descriptor for a class that can be serialized. Creates an ObjectStreamClass instance if one does not exist yet for class. Null is returned if the specified class does not implement java.io.Serializable or java.io.Externalizable." }, { "code": null, "e": 1566, "s": 1442, "text": "Syntax: public static ObjectStreamClass lookup(Class cl)\nReturn: the class descriptor for the specified class\nException: NA" }, { "code": null, "e": 1703, "s": 1566, "text": "static ObjectStreamClass lookupAny(Class class): Returns the descriptor for any class, regardless of whether it implements Serializable." }, { "code": null, "e": 1840, "s": 1703, "text": "static ObjectStreamClass lookupAny(Class class): Returns the descriptor for any class, regardless of whether it implements Serializable." }, { "code": null, "e": 1970, "s": 1840, "text": "Syntax: public static ObjectStreamClass lookupAny(Class class)\nReturn: the class descriptor for the specified class\nException: NA" }, { "code": null, "e": 1975, "s": 1970, "text": "Java" }, { "code": "// Java code illustrating forClass(),// lookup() and lookupAny() method import java.io.ObjectStreamClass;import java.util.ArrayList; public class ObjectStreamDemo{ public static void main(String arg[]) { // creating object stream class for Number ObjectStreamClass geeks_stream = ObjectStreamClass.lookup(Number.class); ObjectStreamClass quiz_stream = ObjectStreamClass.lookupAny(ArrayList.class); // checking class instance System.out.println(geeks_stream.forClass()); System.out.println(quiz_stream.forClass()); } }", "e": 2589, "s": 1975, "text": null }, { "code": null, "e": 2597, "s": 2589, "text": "Output:" }, { "code": null, "e": 2605, "s": 2597, "text": "Output:" }, { "code": null, "e": 2654, "s": 2605, "text": "class java.lang.Number\nclass java.util.ArrayList" }, { "code": null, "e": 2732, "s": 2654, "text": "ObjectStreamField getField(String name): Get the field of this class by name." }, { "code": null, "e": 2810, "s": 2732, "text": "ObjectStreamField getField(String name): Get the field of this class by name." }, { "code": null, "e": 2977, "s": 2810, "text": "Syntax: public ObjectStreamField getField(String name)\nReturn: The ObjectStreamField object of the named \nfield or null if there is no such named field.\nException: NA" }, { "code": null, "e": 3068, "s": 2977, "text": "ObjectStreamField[] getFields(): Return an array of the fields of this serializable class." }, { "code": null, "e": 3159, "s": 3068, "text": "ObjectStreamField[] getFields(): Return an array of the fields of this serializable class." }, { "code": null, "e": 3359, "s": 3159, "text": "Syntax: public ObjectStreamField[] getFields()\nReturns: an array containing an element for each \npersistent field of this class. Returns an array of length zero if\n there are no fields.\nException: NA" }, { "code": null, "e": 3537, "s": 3359, "text": "String getName(): Returns the name of the class described by this descriptor. This method returns the name of the class in the format that is used by the Class.getName() method." }, { "code": null, "e": 3715, "s": 3537, "text": "String getName(): Returns the name of the class described by this descriptor. This method returns the name of the class in the format that is used by the Class.getName() method." }, { "code": null, "e": 3813, "s": 3715, "text": "Syntax: public String getName()\nReturn: a string representing the name of the class\nException: NA" }, { "code": null, "e": 4119, "s": 3813, "text": "long getSerialVersionUID(): Return the serialVersionUID for this class. The serialVersionUID defines a set of classes all with the same name that have evolved from a common root class and agree to be serialized and deserialized using a common format. NonSerializable classes have a serialVersionUID of 0L." }, { "code": null, "e": 4425, "s": 4119, "text": "long getSerialVersionUID(): Return the serialVersionUID for this class. The serialVersionUID defines a set of classes all with the same name that have evolved from a common root class and agree to be serialized and deserialized using a common format. NonSerializable classes have a serialVersionUID of 0L." }, { "code": null, "e": 4541, "s": 4425, "text": "Syntax: public long getSerialVersionUID()\nReturns: the SUID of the class described by this descriptor\nException: NA" }, { "code": null, "e": 4611, "s": 4541, "text": "String toString(): Return a string describing this ObjectStreamClass." }, { "code": null, "e": 4681, "s": 4611, "text": "String toString(): Return a string describing this ObjectStreamClass." }, { "code": null, "e": 4776, "s": 4681, "text": "Syntax: public String toString()\nReturns: a string representation of the object.\nException: NA" }, { "code": null, "e": 4781, "s": 4776, "text": "Java" }, { "code": "// Java code illustrating getField(), toString()// getClass(), getSerialVersionUID() import java.io.ObjectStreamClass;import java.util.ArrayList; public class ObjectStreamDemo{ public static void main(String arg[]) { // creating object stream class for Number ObjectStreamClass geeks_stream = ObjectStreamClass.lookup(Number.class); // checking field System.out.println(geeks_stream.getField(\"quiz_stream\")); System.out.println(geeks_stream.getFields()); // class name System.out.println(\"class name: \" + geeks_stream.getClass()); // checking serial version UID System.out.println(geeks_stream.getSerialVersionUID()); System.out.println(geeks_stream.toString()); } }", "e": 5579, "s": 4781, "text": null }, { "code": null, "e": 5587, "s": 5579, "text": "Output:" }, { "code": null, "e": 5595, "s": 5587, "text": "Output:" }, { "code": null, "e": 5781, "s": 5595, "text": "null\n[Ljava.io.ObjectStreamField;@45ee12a7\nclass name: class java.io.ObjectStreamClass\n-8742448824652078965\njava.lang.Number: static final long serialVersionUID = -8742448824652078965L;" }, { "code": null, "e": 6204, "s": 5781, "text": "This article is contributed by Abhishek Verma. 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": 6221, "s": 6204, "text": "surinderdawra388" }, { "code": null, "e": 6230, "s": 6221, "text": "Java-I/O" }, { "code": null, "e": 6235, "s": 6230, "text": "Java" }, { "code": null, "e": 6240, "s": 6235, "text": "Java" }, { "code": null, "e": 6338, "s": 6240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6353, "s": 6338, "text": "Stream In Java" }, { "code": null, "e": 6374, "s": 6353, "text": "Introduction to Java" }, { "code": null, "e": 6395, "s": 6374, "text": "Constructors in Java" }, { "code": null, "e": 6414, "s": 6395, "text": "Exceptions in Java" }, { "code": null, "e": 6431, "s": 6414, "text": "Generics in Java" }, { "code": null, "e": 6461, "s": 6431, "text": "Functional Interfaces in Java" }, { "code": null, "e": 6487, "s": 6461, "text": "Java Programming Examples" }, { "code": null, "e": 6503, "s": 6487, "text": "Strings in Java" }, { "code": null, "e": 6540, "s": 6503, "text": "Differences between JDK, JRE and JVM" } ]
C# | Difference between Static Constructors and Non-Static Constructors
10 Feb, 2022 Static constructors are used to initialize the static members of the class and are implicitly called before the creation of the first instance of the class. Non-static constructors are used to initialize the non-static members of the class. Below are the differences between the Static Constructors and Non-Static Constructors. Declaration: Static constructors are declared using a static modifier explicitly while all other remaining constructors are non-static constructors. Non-static constructors can also be called as Instance Constructors as they need instance to get executed.Example: C# // C# Program to demonstrate// how to declare the static// constructor and non-static// constructorusing System; class Geeks{ // Static variablestatic int s; // Non-static variableint ns; // Declaration of// static constructorstatic Geeks(){ Console.WriteLine("It is static constructor");} // Declaration of// non-static constructorpublic Geeks(){ Console.WriteLine("It is non-static constructor");} // Main Methodstatic void Main(string[] args){ // Static constructor will call implicitly // as soon as the class start to execute // the first block of code to execute // will be static constructor // Calling non-static constructor Geeks obj1 = new Geeks();}} Output: It is static constructor It is non-static constructor Calling: Static constructors are always called implicitly but the non-static constructors are called explicitly i.e by creating the instance of the class.Example: In the above program, we have static constructor i.e static Geeks() which is called in the main method implicitly. See the output carefully, the code inside the static constructor is executing. But to call non-static constructor i.e Geeks(), you need to create an instance of the class, i.e obj1. So the creation of the object is to call the non-static constructor explicitly. Execution: Static constructor executes as soon as the execution of a class starts and it is the first block of code which runs under a class. But the non-static constructors executes only after the creation of the instance of the class. Each and every time the instance of the class is created, it will call the non-static constructor.Example: C# // C# Program to demonstrate// the execution of static// constructor and non-static// constructorusing System; class Geeks{ // Declaration of// static constructorstatic Geeks(){ Console.WriteLine("Static constructor");} // Declaration of// non-static constructorpublic Geeks(){ Console.WriteLine("Non-Static constructor");} // Main Methodstatic void Main(string[] args){ // static constructor will call implicitly // as soon as the class start to execute // the first block of code to execute // inside the class will be static // constructor // calling non-static constructor // here we are calling non-static // constructor twice as we are // creating two objects Geeks obj1 = new Geeks(); Geeks obj2 = new Geeks();}} Output: Static constructor Non-Static constructor Non-Static constructor Explanation: In the above program, there are two objects of Geeks() class is created i.e obj1 and obj2. obj1 and obj2 will call the non-static constructor twice because each and every time the instance of the class is created, it will call the non-static constructor. Although, in the Main method(entry point of a program), the first statement is “Geeks obj1 = new Geeks();” but as soon as the compiler found the Main Method control will transfer to class and the static block will be executed first. That’s why you can see in the output that Static Constructor is called first. Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.Example: In the above program, you can see the static constructor is executing only once but the non-static constructor is executing 2 times as the two instances of the class is created. If you will not create an instance of the class then the non-static constructor will not execute. Initialization of fields: Static constructors are used to initialize the static fields and non-static constructors are used to initialize the non-static fields.Example: C# // C# Program to demonstrate// initialization of fields// by using static constructor// and non-static constructorusing System; class Geeks{ // Static variablestatic int s; // Non-static variableint ns; // Declaration of// static constructorstatic Geeks(){ Console.WriteLine("Static constructor");} // Declaration of// non-static constructorpublic Geeks(){ Console.WriteLine("Non-Static constructor");} // Main Methodstatic void Main(string[] args){ // Static fields can // be accessed directly Console.WriteLine("Value of s is: " + s); // Calling non-static constructor Geeks obj1 = new Geeks(); // Printing the value // of non-static field Console.WriteLine("Value of ns is: " + obj1.ns);}} Output: Static constructor Value of s is: 0 Non-Static constructor Value of ns is: 0 Explanation: Here, both the static and non-static fields are initialized with default value. The default value of int type is zero. Static constructor will initialize only static fields. Here static field is s. While the non-static field(ns) is initialized by the non-static constructor. Parameters: We cannot pass any parameters to the static constructors because these are called implicitly and for passing parameters, we have to call it explicitly which is not possible. It will give runtime error as shown in below example. However, we can pass the parameters to the non-static constructors.Example: C# // C# Program to demonstrate// the passing of parameters// to constructorusing System; class Geeks { // static variable static int s; // non-static variable int ns; // declaration of // static constructor // and passing parameter // to static constructor static Geeks(int k) { k = s; Console.WriteLine("Static constructor & K = " + k); } // declaration of // non-static constructor Geeks() { Console.WriteLine("Non-Static constructor"); } // Main Method static void Main(string[] args) { }} Runtime Error: prog.cs(18, 16): error CS0132: `Geeks.Geeks(int)’: The static constructor must be parameterless Overloading: Non-static constructors can be overloaded but not the static constructors. Overloading is done on the parameters criteria. So if you cannot pass the parameters to the Static constructors then we can’t overload it. Cases in which the constructor will be implicit: Every class except the static class(which contains only static members) always contains an implicit constructor if the user is not defining an explicit constructor. If the class contains any static fields then the static constructors are defined implicitly. nidhi_biet qwertyhot741 manikarora059 chhabradhanvi CSharp-OOP C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates Introduction to .NET Framework C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Data Types C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Replace() Method C# | Arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Feb, 2022" }, { "code": null, "e": 380, "s": 52, "text": "Static constructors are used to initialize the static members of the class and are implicitly called before the creation of the first instance of the class. Non-static constructors are used to initialize the non-static members of the class. Below are the differences between the Static Constructors and Non-Static Constructors." }, { "code": null, "e": 644, "s": 380, "text": "Declaration: Static constructors are declared using a static modifier explicitly while all other remaining constructors are non-static constructors. Non-static constructors can also be called as Instance Constructors as they need instance to get executed.Example:" }, { "code": null, "e": 647, "s": 644, "text": "C#" }, { "code": "// C# Program to demonstrate// how to declare the static// constructor and non-static// constructorusing System; class Geeks{ // Static variablestatic int s; // Non-static variableint ns; // Declaration of// static constructorstatic Geeks(){ Console.WriteLine(\"It is static constructor\");} // Declaration of// non-static constructorpublic Geeks(){ Console.WriteLine(\"It is non-static constructor\");} // Main Methodstatic void Main(string[] args){ // Static constructor will call implicitly // as soon as the class start to execute // the first block of code to execute // will be static constructor // Calling non-static constructor Geeks obj1 = new Geeks();}}", "e": 1344, "s": 647, "text": null }, { "code": null, "e": 1352, "s": 1344, "text": "Output:" }, { "code": null, "e": 1406, "s": 1352, "text": "It is static constructor\nIt is non-static constructor" }, { "code": null, "e": 1946, "s": 1406, "text": "Calling: Static constructors are always called implicitly but the non-static constructors are called explicitly i.e by creating the instance of the class.Example: In the above program, we have static constructor i.e static Geeks() which is called in the main method implicitly. See the output carefully, the code inside the static constructor is executing. But to call non-static constructor i.e Geeks(), you need to create an instance of the class, i.e obj1. So the creation of the object is to call the non-static constructor explicitly." }, { "code": null, "e": 2290, "s": 1946, "text": "Execution: Static constructor executes as soon as the execution of a class starts and it is the first block of code which runs under a class. But the non-static constructors executes only after the creation of the instance of the class. Each and every time the instance of the class is created, it will call the non-static constructor.Example:" }, { "code": null, "e": 2293, "s": 2290, "text": "C#" }, { "code": "// C# Program to demonstrate// the execution of static// constructor and non-static// constructorusing System; class Geeks{ // Declaration of// static constructorstatic Geeks(){ Console.WriteLine(\"Static constructor\");} // Declaration of// non-static constructorpublic Geeks(){ Console.WriteLine(\"Non-Static constructor\");} // Main Methodstatic void Main(string[] args){ // static constructor will call implicitly // as soon as the class start to execute // the first block of code to execute // inside the class will be static // constructor // calling non-static constructor // here we are calling non-static // constructor twice as we are // creating two objects Geeks obj1 = new Geeks(); Geeks obj2 = new Geeks();}}", "e": 3060, "s": 2293, "text": null }, { "code": null, "e": 3069, "s": 3060, "text": "Output: " }, { "code": null, "e": 3134, "s": 3069, "text": "Static constructor\nNon-Static constructor\nNon-Static constructor" }, { "code": null, "e": 3713, "s": 3134, "text": "Explanation: In the above program, there are two objects of Geeks() class is created i.e obj1 and obj2. obj1 and obj2 will call the non-static constructor twice because each and every time the instance of the class is created, it will call the non-static constructor. Although, in the Main method(entry point of a program), the first statement is “Geeks obj1 = new Geeks();” but as soon as the compiler found the Main Method control will transfer to class and the static block will be executed first. That’s why you can see in the output that Static Constructor is called first." }, { "code": null, "e": 4234, "s": 3713, "text": "Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.Example: In the above program, you can see the static constructor is executing only once but the non-static constructor is executing 2 times as the two instances of the class is created. If you will not create an instance of the class then the non-static constructor will not execute." }, { "code": null, "e": 4403, "s": 4234, "text": "Initialization of fields: Static constructors are used to initialize the static fields and non-static constructors are used to initialize the non-static fields.Example:" }, { "code": null, "e": 4406, "s": 4403, "text": "C#" }, { "code": "// C# Program to demonstrate// initialization of fields// by using static constructor// and non-static constructorusing System; class Geeks{ // Static variablestatic int s; // Non-static variableint ns; // Declaration of// static constructorstatic Geeks(){ Console.WriteLine(\"Static constructor\");} // Declaration of// non-static constructorpublic Geeks(){ Console.WriteLine(\"Non-Static constructor\");} // Main Methodstatic void Main(string[] args){ // Static fields can // be accessed directly Console.WriteLine(\"Value of s is: \" + s); // Calling non-static constructor Geeks obj1 = new Geeks(); // Printing the value // of non-static field Console.WriteLine(\"Value of ns is: \" + obj1.ns);}}", "e": 5145, "s": 4406, "text": null }, { "code": null, "e": 5154, "s": 5145, "text": "Output: " }, { "code": null, "e": 5231, "s": 5154, "text": "Static constructor\nValue of s is: 0\nNon-Static constructor\nValue of ns is: 0" }, { "code": null, "e": 5519, "s": 5231, "text": "Explanation: Here, both the static and non-static fields are initialized with default value. The default value of int type is zero. Static constructor will initialize only static fields. Here static field is s. While the non-static field(ns) is initialized by the non-static constructor." }, { "code": null, "e": 5835, "s": 5519, "text": "Parameters: We cannot pass any parameters to the static constructors because these are called implicitly and for passing parameters, we have to call it explicitly which is not possible. It will give runtime error as shown in below example. However, we can pass the parameters to the non-static constructors.Example:" }, { "code": null, "e": 5838, "s": 5835, "text": "C#" }, { "code": "// C# Program to demonstrate// the passing of parameters// to constructorusing System; class Geeks { // static variable static int s; // non-static variable int ns; // declaration of // static constructor // and passing parameter // to static constructor static Geeks(int k) { k = s; Console.WriteLine(\"Static constructor & K = \" + k); } // declaration of // non-static constructor Geeks() { Console.WriteLine(\"Non-Static constructor\"); } // Main Method static void Main(string[] args) { }}", "e": 6423, "s": 5838, "text": null }, { "code": null, "e": 6438, "s": 6423, "text": "Runtime Error:" }, { "code": null, "e": 6534, "s": 6438, "text": "prog.cs(18, 16): error CS0132: `Geeks.Geeks(int)’: The static constructor must be parameterless" }, { "code": null, "e": 6761, "s": 6534, "text": "Overloading: Non-static constructors can be overloaded but not the static constructors. Overloading is done on the parameters criteria. So if you cannot pass the parameters to the Static constructors then we can’t overload it." }, { "code": null, "e": 7068, "s": 6761, "text": "Cases in which the constructor will be implicit: Every class except the static class(which contains only static members) always contains an implicit constructor if the user is not defining an explicit constructor. If the class contains any static fields then the static constructors are defined implicitly." }, { "code": null, "e": 7081, "s": 7070, "text": "nidhi_biet" }, { "code": null, "e": 7094, "s": 7081, "text": "qwertyhot741" }, { "code": null, "e": 7108, "s": 7094, "text": "manikarora059" }, { "code": null, "e": 7122, "s": 7108, "text": "chhabradhanvi" }, { "code": null, "e": 7133, "s": 7122, "text": "CSharp-OOP" }, { "code": null, "e": 7136, "s": 7133, "text": "C#" }, { "code": null, "e": 7234, "s": 7136, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7262, "s": 7234, "text": "C# Dictionary with examples" }, { "code": null, "e": 7277, "s": 7262, "text": "C# | Delegates" }, { "code": null, "e": 7308, "s": 7277, "text": "Introduction to .NET Framework" }, { "code": null, "e": 7351, "s": 7308, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 7400, "s": 7351, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 7416, "s": 7400, "text": "C# | Data Types" }, { "code": null, "e": 7456, "s": 7416, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 7479, "s": 7456, "text": "Extension Method in C#" }, { "code": null, "e": 7501, "s": 7479, "text": "C# | Replace() Method" } ]
File.ReadAllBytes() Method in C# with Examples
09 Mar, 2021 File.ReadAllBytes(String) is an inbuilt File class method that is used to open a specified or created binary file and then reads the contents of the file into a byte array and then closes the file.Syntax: public static byte[] ReadAllBytes (string path); Parameter: This function accepts a parameter which is illustrated below: path: This is the specified file to open for reading. Exceptions: ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars. ArgumentNullException: The path is null. PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length. DirectoryNotFoundException: The specified path is invalid. IOException: An I/O error occurred while opening the file. UnauthorizedAccessException: This operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission. FileNotFoundException: The file specified in the path was not found. NotSupportedException: The path is in an invalid format. SecurityException: The caller does not have the required permission. Return Value: Returns a byte array containing the contents of the file.Below are the programs to illustrate the File.ReadAllBytes(String) method.Program 1: Initially, a file file.txt is created with some contents shown below- C# // C# program to illustrate the usage// of File.ReadAllBytes(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Calling the ReadAllBytes() function byte[] readText = File.ReadAllBytes(path); foreach(byte s in readText) { // Printing the binary array value of // the file contents Console.WriteLine(s); } }} Output: 53 Program 2: Initially, no file was created. Below code itself create a file file.txt with some specified contents. C# // C# program to illustrate the usage// of File.ReadAllBytes(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { public static void Main() { // Specifying a file string path = @"file.txt"; // Adding below contents to the file string[] createText = { "GFG" }; File.WriteAllLines(path, createText); // Calling the ReadAllBytes() function byte[] readText = File.ReadAllBytes(path); foreach(byte s in readText) { // Printing the binary array value of // the file contents Console.WriteLine(s); } }} Output: 71 70 71 10 arorakashish0911 CSharp-File-Handling C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples Introduction to .NET Framework C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | Method Overriding C# | Data Types C# | Constructors C# | String.IndexOf( ) Method | Set - 1 C# | Class and Object
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Mar, 2021" }, { "code": null, "e": 235, "s": 28, "text": "File.ReadAllBytes(String) is an inbuilt File class method that is used to open a specified or created binary file and then reads the contents of the file into a byte array and then closes the file.Syntax: " }, { "code": null, "e": 284, "s": 235, "text": "public static byte[] ReadAllBytes (string path);" }, { "code": null, "e": 359, "s": 284, "text": "Parameter: This function accepts a parameter which is illustrated below: " }, { "code": null, "e": 413, "s": 359, "text": "path: This is the specified file to open for reading." }, { "code": null, "e": 426, "s": 413, "text": "Exceptions: " }, { "code": null, "e": 572, "s": 426, "text": "ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars." }, { "code": null, "e": 613, "s": 572, "text": "ArgumentNullException: The path is null." }, { "code": null, "e": 716, "s": 613, "text": "PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length." }, { "code": null, "e": 775, "s": 716, "text": "DirectoryNotFoundException: The specified path is invalid." }, { "code": null, "e": 834, "s": 775, "text": "IOException: An I/O error occurred while opening the file." }, { "code": null, "e": 1008, "s": 834, "text": "UnauthorizedAccessException: This operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission." }, { "code": null, "e": 1077, "s": 1008, "text": "FileNotFoundException: The file specified in the path was not found." }, { "code": null, "e": 1134, "s": 1077, "text": "NotSupportedException: The path is in an invalid format." }, { "code": null, "e": 1203, "s": 1134, "text": "SecurityException: The caller does not have the required permission." }, { "code": null, "e": 1430, "s": 1203, "text": "Return Value: Returns a byte array containing the contents of the file.Below are the programs to illustrate the File.ReadAllBytes(String) method.Program 1: Initially, a file file.txt is created with some contents shown below- " }, { "code": null, "e": 1435, "s": 1432, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.ReadAllBytes(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Calling the ReadAllBytes() function byte[] readText = File.ReadAllBytes(path); foreach(byte s in readText) { // Printing the binary array value of // the file contents Console.WriteLine(s); } }}", "e": 1962, "s": 1435, "text": null }, { "code": null, "e": 1972, "s": 1962, "text": "Output: " }, { "code": null, "e": 1975, "s": 1972, "text": "53" }, { "code": null, "e": 2090, "s": 1975, "text": "Program 2: Initially, no file was created. Below code itself create a file file.txt with some specified contents. " }, { "code": null, "e": 2093, "s": 2090, "text": "C#" }, { "code": "// C# program to illustrate the usage// of File.ReadAllBytes(String) method // Using System and System.IO namespacesusing System;using System.IO; class GFG { public static void Main() { // Specifying a file string path = @\"file.txt\"; // Adding below contents to the file string[] createText = { \"GFG\" }; File.WriteAllLines(path, createText); // Calling the ReadAllBytes() function byte[] readText = File.ReadAllBytes(path); foreach(byte s in readText) { // Printing the binary array value of // the file contents Console.WriteLine(s); } }}", "e": 2751, "s": 2093, "text": null }, { "code": null, "e": 2761, "s": 2751, "text": "Output: " }, { "code": null, "e": 2773, "s": 2761, "text": "71\n70\n71\n10" }, { "code": null, "e": 2790, "s": 2773, "text": "arorakashish0911" }, { "code": null, "e": 2811, "s": 2790, "text": "CSharp-File-Handling" }, { "code": null, "e": 2814, "s": 2811, "text": "C#" }, { "code": null, "e": 2912, "s": 2814, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2940, "s": 2912, "text": "C# Dictionary with examples" }, { "code": null, "e": 2971, "s": 2940, "text": "Introduction to .NET Framework" }, { "code": null, "e": 2986, "s": 2971, "text": "C# | Delegates" }, { "code": null, "e": 3029, "s": 2986, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 3078, "s": 3029, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 3101, "s": 3078, "text": "C# | Method Overriding" }, { "code": null, "e": 3117, "s": 3101, "text": "C# | Data Types" }, { "code": null, "e": 3135, "s": 3117, "text": "C# | Constructors" }, { "code": null, "e": 3175, "s": 3135, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Count BST nodes that lie in a given range | Practice | GeeksforGeeks
Given a Binary Search Tree (BST) and a range l-h(inclusive), count the number of nodes in the BST that lie in the given range. The values smaller than root go to the left side The values greater and equal to the root go to the right side Example 1: Input: 10 / \ 5 50 / / \ 1 40 100 l = 5, h = 45 Output: 3 Explanation: 5 10 40 are the node in the range Example 2: Input: 5 / \ 4 6 / \ 3 7 l = 2, h = 8 Output: 5 Explanation: All the nodes are in the given range. Your Task: This is a function problem. You don't have to take input. You are required to complete the function getCountOfNode() that takes root, l ,h as parameters and returns the count. Expected Time Complexity: O(N) Expected Auxiliary Space: O(Height of the BST). Constraints: 1 <= Number of nodes <= 100 1 <= l < h < 103 0 yjayaswal1 week ago Easiest Solution in C++ int getCount(Node *root, int l, int h){ if(!root) return 0; int x=getCount(root->left,l,h); int y=getCount(root->right,l,h); if(root->data>=l&&root->data<=h) return x+y+1; else return x+y;} 0 mayanksingh08012 weeks ago c++ simple code void helper(Node*root,int l,int h,int &count){ if(root==NULL) return ; if(root->data>=l&&root->data<=h) count++; helper(root->left,l,h,count); helper(root->right,l,h,count);}int getCount(Node *root, int l, int h){ // your code goes here if(root==NULL) return 0; int count=0; helper(root,l,h,count); return count; } 0 aryankhatana353 weeks ago c++ void inorder(Node *root,vector<int>&a){ if(root==NULL){ return; } inorder(root->left,a); a.push_back(root->data); inorder(root->right,a);}int getCount(Node *root, int l, int h){ // your code goes here vector<int> ans; inorder(root,ans); int cnt=0; for(int i=0;i<ans.size();i++){ if(ans[i]>=l && ans[i]<=h){ cnt++; } } return cnt; 0 dipanshusharma93133 weeks ago // java solution class Tree{ //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { //Your code here if(root == null){ return 0; } int x = 0; x = x + getCount(root.left, l, h); x = x + getCount(root.right, l, h); if(root.data >= l && root.data <= h){ return x+1; } else{ return x; } }} 0 joyrockok3 weeks ago class Tree{static int count=0;public Tree() { count=0;} //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { //Your code here if(l <= root.data && root.data <= h) { count++; } if (root.left != null) { getCount(root.left, l, h); } if(root.right != null) { getCount(root.right, l, h); } return count; }} 0 gujjulassr3 weeks ago 0.1/1.3 class Tree{ int res=0; //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { //Your code here count(root,l,h); return res; } int count(Node root,int l,int h){ if(root==null){ return 0; } count(root.left,l,h); count(root.right,l,h); if(root.data>=l && root.data<=h){ res++; } return res; }} 0 sachinsinghss194 weeks ago op = [] def getRange(l:int, h:int, root:Node): if root: getRange(l, h, root.left) if root.data >= l and root.data <= h: op.append(root.data) getRange(l, h, root.right) getRange(low, high, root) return len(op) 0 luffysama11 month ago void inOrder(Node* root , int l , int h , int& count ){ if(root == NULL) return; if(root->data >= l && root->data <= h && root!=NULL){ count++; inOrder(root->left,l,h,count); inOrder(root->right,l,h,count); } if(root->data > l) } int getCount(Node *root, int l, int h){ // your code goes here int count = 0; inOrder(root,l,h,count); return count;} 0 sandeep55211 month ago 7 Lines C++ Solution (Recursive) int getCount(Node *root, int l, int h) { int f=0; if(!root) return 0; if(root->data>=l and root->data<=h) f++; return f+getCount(root->left,l,h)+getCount(root->right,l,h); } 0 jatinsuthar3001 month ago Simple 5 line code: 0.2s Java Solution class Tree { //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { if(root==null) return 0; int count=0; count+=getCount(root.left, l, h); count+=getCount(root.right, l, h); return (root.data>=l && root.data<=h) ? 1+count : count; } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 366, "s": 238, "text": "Given a Binary Search Tree (BST) and a range l-h(inclusive), count the number of nodes in the BST that lie in the given range. " }, { "code": null, "e": 415, "s": 366, "text": "The values smaller than root go to the left side" }, { "code": null, "e": 477, "s": 415, "text": "The values greater and equal to the root go to the right side" }, { "code": null, "e": 488, "s": 477, "text": "Example 1:" }, { "code": null, "e": 626, "s": 488, "text": "Input:\n 10\n / \\\n 5 50\n / / \\\n 1 40 100\nl = 5, h = 45\nOutput: 3\nExplanation: 5 10 40 are the node in the\nrange\n" }, { "code": null, "e": 637, "s": 626, "text": "Example 2:" }, { "code": null, "e": 768, "s": 637, "text": "Input:\n 5\n / \\\n 4 6\n / \\\n 3 7\nl = 2, h = 8\nOutput: 5\nExplanation: All the nodes are in the\ngiven range.\n" }, { "code": null, "e": 955, "s": 768, "text": "Your Task:\nThis is a function problem. You don't have to take input. You are required to complete the function getCountOfNode() that takes root, l ,h as parameters and returns the count." }, { "code": null, "e": 1034, "s": 955, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(Height of the BST)." }, { "code": null, "e": 1092, "s": 1034, "text": "Constraints:\n1 <= Number of nodes <= 100\n1 <= l < h < 103" }, { "code": null, "e": 1094, "s": 1092, "text": "0" }, { "code": null, "e": 1114, "s": 1094, "text": "yjayaswal1 week ago" }, { "code": null, "e": 1138, "s": 1114, "text": "Easiest Solution in C++" }, { "code": null, "e": 1357, "s": 1138, "text": "int getCount(Node *root, int l, int h){ if(!root) return 0; int x=getCount(root->left,l,h); int y=getCount(root->right,l,h); if(root->data>=l&&root->data<=h) return x+y+1; else return x+y;} " }, { "code": null, "e": 1359, "s": 1357, "text": "0" }, { "code": null, "e": 1386, "s": 1359, "text": "mayanksingh08012 weeks ago" }, { "code": null, "e": 1402, "s": 1386, "text": "c++ simple code" }, { "code": null, "e": 1734, "s": 1402, "text": "void helper(Node*root,int l,int h,int &count){ if(root==NULL) return ; if(root->data>=l&&root->data<=h) count++; helper(root->left,l,h,count); helper(root->right,l,h,count);}int getCount(Node *root, int l, int h){ // your code goes here if(root==NULL) return 0; int count=0; helper(root,l,h,count); return count; } " }, { "code": null, "e": 1736, "s": 1734, "text": "0" }, { "code": null, "e": 1762, "s": 1736, "text": "aryankhatana353 weeks ago" }, { "code": null, "e": 1766, "s": 1762, "text": "c++" }, { "code": null, "e": 2131, "s": 1766, "text": "void inorder(Node *root,vector<int>&a){ if(root==NULL){ return; } inorder(root->left,a); a.push_back(root->data); inorder(root->right,a);}int getCount(Node *root, int l, int h){ // your code goes here vector<int> ans; inorder(root,ans); int cnt=0; for(int i=0;i<ans.size();i++){ if(ans[i]>=l && ans[i]<=h){ cnt++; } } return cnt;" }, { "code": null, "e": 2133, "s": 2131, "text": "0" }, { "code": null, "e": 2163, "s": 2133, "text": "dipanshusharma93133 weeks ago" }, { "code": null, "e": 2180, "s": 2163, "text": "// java solution" }, { "code": null, "e": 2601, "s": 2180, "text": "class Tree{ //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { //Your code here if(root == null){ return 0; } int x = 0; x = x + getCount(root.left, l, h); x = x + getCount(root.right, l, h); if(root.data >= l && root.data <= h){ return x+1; } else{ return x; } }}" }, { "code": null, "e": 2603, "s": 2601, "text": "0" }, { "code": null, "e": 2624, "s": 2603, "text": "joyrockok3 weeks ago" }, { "code": null, "e": 3051, "s": 2624, "text": "class Tree{static int count=0;public Tree() { count=0;} //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { //Your code here if(l <= root.data && root.data <= h) { count++; } if (root.left != null) { getCount(root.left, l, h); } if(root.right != null) { getCount(root.right, l, h); } return count; }}" }, { "code": null, "e": 3053, "s": 3051, "text": "0" }, { "code": null, "e": 3075, "s": 3053, "text": "gujjulassr3 weeks ago" }, { "code": null, "e": 3083, "s": 3075, "text": "0.1/1.3" }, { "code": null, "e": 3533, "s": 3085, "text": "class Tree{ int res=0; //Function to count number of nodes in BST that lie in the given range. int getCount(Node root,int l, int h) { //Your code here count(root,l,h); return res; } int count(Node root,int l,int h){ if(root==null){ return 0; } count(root.left,l,h); count(root.right,l,h); if(root.data>=l && root.data<=h){ res++; } return res; }}" }, { "code": null, "e": 3535, "s": 3533, "text": "0" }, { "code": null, "e": 3562, "s": 3535, "text": "sachinsinghss194 weeks ago" }, { "code": null, "e": 3842, "s": 3564, "text": "op = [] def getRange(l:int, h:int, root:Node): if root: getRange(l, h, root.left) if root.data >= l and root.data <= h: op.append(root.data) getRange(l, h, root.right) getRange(low, high, root) return len(op)" }, { "code": null, "e": 3844, "s": 3842, "text": "0" }, { "code": null, "e": 3866, "s": 3844, "text": "luffysama11 month ago" }, { "code": null, "e": 4128, "s": 3866, "text": "void inOrder(Node* root , int l , int h , int& count ){ if(root == NULL) return; if(root->data >= l && root->data <= h && root!=NULL){ count++; inOrder(root->left,l,h,count); inOrder(root->right,l,h,count); } if(root->data > l) }" }, { "code": null, "e": 4250, "s": 4128, "text": "int getCount(Node *root, int l, int h){ // your code goes here int count = 0; inOrder(root,l,h,count); return count;} " }, { "code": null, "e": 4252, "s": 4250, "text": "0" }, { "code": null, "e": 4275, "s": 4252, "text": "sandeep55211 month ago" }, { "code": null, "e": 4308, "s": 4275, "text": "7 Lines C++ Solution (Recursive)" }, { "code": null, "e": 4494, "s": 4308, "text": "int getCount(Node *root, int l, int h)\n{\n int f=0;\n if(!root) return 0;\n if(root->data>=l and root->data<=h) f++;\n return f+getCount(root->left,l,h)+getCount(root->right,l,h);\n}" }, { "code": null, "e": 4496, "s": 4494, "text": "0" }, { "code": null, "e": 4522, "s": 4496, "text": "jatinsuthar3001 month ago" }, { "code": null, "e": 4561, "s": 4522, "text": "Simple 5 line code: 0.2s Java Solution" }, { "code": null, "e": 4924, "s": 4561, "text": "class Tree\n{\n //Function to count number of nodes in BST that lie in the given range.\n int getCount(Node root,int l, int h)\n {\n if(root==null) return 0;\n int count=0;\n count+=getCount(root.left, l, h);\n count+=getCount(root.right, l, h);\n return (root.data>=l && root.data<=h) \n ? 1+count : count;\n }\n}" }, { "code": null, "e": 5070, "s": 4924, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5106, "s": 5070, "text": " Login to access your submissions. " }, { "code": null, "e": 5116, "s": 5106, "text": "\nProblem\n" }, { "code": null, "e": 5126, "s": 5116, "text": "\nContest\n" }, { "code": null, "e": 5189, "s": 5126, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5337, "s": 5189, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5545, "s": 5337, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 5651, "s": 5545, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Neo4j - Unwind Clause
The unwind clause is used to unwind a list into a sequence of rows. Following is a sample Cypher Query which unwinds a list. UNWIND [a, b, c, d] AS x RETURN x To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2407, "s": 2339, "text": "The unwind clause is used to unwind a list into a sequence of rows." }, { "code": null, "e": 2464, "s": 2407, "text": "Following is a sample Cypher Query which unwinds a list." }, { "code": null, "e": 2500, "s": 2464, "text": "UNWIND [a, b, c, d] AS x \nRETURN x " }, { "code": null, "e": 2560, "s": 2500, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 2738, "s": 2560, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 2891, "s": 2738, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 2940, "s": 2891, "text": "On executing, you will get the following result." }, { "code": null, "e": 2947, "s": 2940, "text": " Print" }, { "code": null, "e": 2958, "s": 2947, "text": " Add Notes" } ]
Intuitive Understanding of Randomized Singular Value Decomposition | by Xinyu Chen (陈新宇) | Towards Data Science
Matrix decomposition is a powerful tool for many machine learning problems and which has been widely used in data compression, dimensionality reduction, and sparsity learning, to name but a few. In many cases, for purposes of approximating a data matrix by a low-rank structure, Singular Value Decomposition (SVD) is often verified as the best choice. However, the accurate and efficient SVD of large data matrices (e.g., 8k-by-10k matrix) is computationally challenging. To resolve the SVD in this situation, there are many algorithms have been developed by applying randomized linear algebra methods. One of the most important algorithms is randomized SVD, which is competitively efficient for decomposing any large matrix with a relatively low rank. This post will introduce the preliminary and essential idea of the randomized SVD. To help readers gain a better understanding of randomized SVD, we also provide the corresponding Python implementation in this post. In addition, Jupyter notebook of this post can be found here. SVD Formula We start by recalling the concept of SVD. As you may already know, SVD is one of the most important decomposition formula in linear algebra. For any given matrix A, SVD has the form of A = UΣV^T where the matrices U and V consist of left and right singular vectors, respectively. The diagonal entries of Σ are singular values. A Small Matrix Example Take a 3-by-3 matrix for example, we can compute the SVD by using numpy.linalg.svd() in Python. Let us have a look: import numpy as npA = np.array([[1, 3, 2], [5, 3, 1], [3, 4, 5]])u, s, v = np.linalg.svd(A, full_matrices = 0)print('Left singular vectors:')print(u)print()print('Singular values:')print(s)print()print('Right singular vectors:')print(v)print() In this case, the singular values are 9.3427, 3.2450, and 1.0885. Left singular vectors:[[-0.37421754 0.28475648 -0.88253894] [-0.56470638 -0.82485997 -0.02669705] [-0.7355732 0.48838486 0.46948087]]Singular values:[9.34265841 3.24497827 1.08850813]Right singular vectors:[[-0.57847229 -0.61642675 -0.53421706] [-0.73171177 0.10269066 0.67383419] [ 0.36051032 -0.78068732 0.51045041]] Essential Idea Randomized SVD can be broken into three main steps. For any given m-by-n matrix A, if we impose a target rank k with k < min(m, n), then the first step as shown in Figure 2 is to 1) generate a Gaussian random matrix Ω with size of n-by-k, 2) compute a new m-by-k matrix Y, and 3) apply QR decomposition to the matrix Y. Note that the first step needs to return the m-by-k matrix Q. Then, the second step as shown in Figure 3 is to 4) derive a k-by-n matrix B by multiplying the transposed matrix of Q and the matrix A together, and 5) compute the SVD of the matrix B. Here, instead of computing the SVD of the original matrix A, B is a smaller matrix to work with. For the fact that the singular values (i.e., Σ)and right singular vectors (i.e., V) of the matrix B are also the singular values and right singular vectors of the original matrix A, we should preserve the singular values and right singular vectors computed by the matrix B in this step. As shown in Figure 3, if we combine the matrix Q derived in the first step with the left singular vectors of B, we can get the left singular vectors (i.e., U) of the matrix A in the third step. A Small Matrix Example Even though we have learned the essential idea of randomized SVD in above, it would not be really clear if there is no intuitive example. To this end, we follow the aforementioned small matrix SVD. First, let us try to write the Python function of randomized SVD. Here, we will use two Numpy functions, i.e., np.linalg.qr() and np.linalg.svd() . import numpy as npdef rsvd(A, Omega): Y = A @ Omega Q, _ = np.linalg.qr(Y) B = Q.T @ A u_tilde, s, v = np.linalg.svd(B, full_matrices = 0) u = Q @ u_tilde return u, s, v Now, let us test it with 3-by-3 matrix (rank = 2 for indicating k with k < min(m, n)): np.random.seed(1000)A = np.array([[1, 3, 2], [5, 3, 1], [3, 4, 5]])rank = 2Omega = np.random.randn(A.shape[1], rank)u, s, v = rsvd(A, Omega)print('Left singular vectors:')print(u)print()print('Singular values:')print(s)print()print('Right singular vectors:')print(v)print() The result of this randomized SVD example is: Left singular vectors:[[ 0.38070859 0.60505354] [ 0.56830191 -0.74963644] [ 0.72944767 0.26824507]]Singular values:[9.34224023 3.02039888]Right singular vectors:[[ 0.57915029 0.61707064 0.53273704] [-0.77420021 0.21163814 0.59650929]] Recall that the singular values of this matrix are 9.3427, 3.2450, and 1.0885. In this case, randomized SVD has the first two singular values as 9.3422 and 3.0204. We can see that the first singular values computed by these two SVD algorithms are extremely close. However, the second singular value of randomized SVD has a slight bias. Is there any other method to improve this result? And how? The answer is yes! To improve the quality of randomized SVD, power iteration method can be used directly. For more detail about power iteration, please see the page 39 in [1] and there is also a Matlab implementation in the page 40. In the following Python codes, power_iteration() is the function for computing the m-by-k matrix Y iteratively (the default power_iter is 3) and then derive the m-by-k matrix Q by QR decomposition. import numpy as npdef power_iteration(A, Omega, power_iter = 3): Y = A @ Omega for q in range(power_iter): Y = A @ (A.T @ Y) Q, _ = np.linalg.qr(Y) return Qdef rsvd(A, Omega): Q = power_iteration(A, Omega) B = Q.T @ A u_tilde, s, v = np.linalg.svd(B, full_matrices = 0) u = Q @ u_tilde return u, s, v Let us test our new rsvd() function: np.random.seed(1000)A = np.array([[1, 3, 2], [5, 3, 1], [3, 4, 5]])rank = 2Omega = np.random.randn(A.shape[1], rank)u, s, v = rsvd(A, Omega)print('Left singular vectors:')print(u)print()print('Singular values:')print(s)print()print('Right singular vectors:')print(v)print() The result is: Left singular vectors:[[ 0.37421757 0.28528579] [ 0.56470638 -0.82484381] [ 0.73557319 0.48810317]]Singular values:[9.34265841 3.24497775]Right singular vectors:[[ 0.57847229 0.61642675 0.53421706] [-0.73178429 0.10284774 0.67373147]] Recall that: Singular values of SVD are: 9.3427, 3.2450, and 1.0885. Singular values of randomized SVD without power iteration are: 9.3422 and 3.0204. Singular values of randomized SVD with power iteration are: 9.3427 and 3.2450. As you can see, the randomized SVD with power iteration provides extremely accurate singular values. As mentioned above, it is possible to compress (low-rank) signal matrix using the SVD or randomized SVD. In fact, the way to compress an image using the SVD is rather simple: taking the SVD of the image directly and only keeping the dominant singular values and left/right singular vectors. In terms of randomized SVD, we can predefine the number of dominant singular values first, and then obtain the singular values and left/right singular vectors by the randomized SVD. For our evaluation, we choose the color image of Lena as our data. The size of this image is 256×256×3. Here, we build a matrix A of size 256×256 by only selecting the green chanel. Using SVD directly Using randomized SVD instead We can see from this image compression experiment that: 1) By comparing to the SVD, the randomized SVD can also produce accurate compression with a prescribed low rank (here, we set rank = 50). 2) The randomized SVD is computational friendly. By specifying rank = 50, the total CPU times of the randomized SVD is about 11.6 ms, while the total CPU times of the SVD is 31.5 ms. In this post, you discovered the randomized linear algebra method for SVD. Specifically, you learned: The essential idea of randomized SVD. How to implement randomized SVD in Python. Do you have any questions? [1] Steven L. Brunton, J. Nathan Kutz (2019). Data-Driven Science and Engineering: Machine Learning, Dynamical Systems, and Control. Page 37–41. [2] N. Benjamin Erichson, Sergey Voronin, Steven L. Brunton, J. Nathan Kutz (2016). Randomized Matrix Decompositions Using R. arXiv:1608.02148. [PDF]
[ { "code": null, "e": 924, "s": 171, "text": "Matrix decomposition is a powerful tool for many machine learning problems and which has been widely used in data compression, dimensionality reduction, and sparsity learning, to name but a few. In many cases, for purposes of approximating a data matrix by a low-rank structure, Singular Value Decomposition (SVD) is often verified as the best choice. However, the accurate and efficient SVD of large data matrices (e.g., 8k-by-10k matrix) is computationally challenging. To resolve the SVD in this situation, there are many algorithms have been developed by applying randomized linear algebra methods. One of the most important algorithms is randomized SVD, which is competitively efficient for decomposing any large matrix with a relatively low rank." }, { "code": null, "e": 1202, "s": 924, "text": "This post will introduce the preliminary and essential idea of the randomized SVD. To help readers gain a better understanding of randomized SVD, we also provide the corresponding Python implementation in this post. In addition, Jupyter notebook of this post can be found here." }, { "code": null, "e": 1214, "s": 1202, "text": "SVD Formula" }, { "code": null, "e": 1399, "s": 1214, "text": "We start by recalling the concept of SVD. As you may already know, SVD is one of the most important decomposition formula in linear algebra. For any given matrix A, SVD has the form of" }, { "code": null, "e": 1409, "s": 1399, "text": "A = UΣV^T" }, { "code": null, "e": 1541, "s": 1409, "text": "where the matrices U and V consist of left and right singular vectors, respectively. The diagonal entries of Σ are singular values." }, { "code": null, "e": 1564, "s": 1541, "text": "A Small Matrix Example" }, { "code": null, "e": 1680, "s": 1564, "text": "Take a 3-by-3 matrix for example, we can compute the SVD by using numpy.linalg.svd() in Python. Let us have a look:" }, { "code": null, "e": 1950, "s": 1680, "text": "import numpy as npA = np.array([[1, 3, 2], [5, 3, 1], [3, 4, 5]])u, s, v = np.linalg.svd(A, full_matrices = 0)print('Left singular vectors:')print(u)print()print('Singular values:')print(s)print()print('Right singular vectors:')print(v)print()" }, { "code": null, "e": 2016, "s": 1950, "text": "In this case, the singular values are 9.3427, 3.2450, and 1.0885." }, { "code": null, "e": 2335, "s": 2016, "text": "Left singular vectors:[[-0.37421754 0.28475648 -0.88253894] [-0.56470638 -0.82485997 -0.02669705] [-0.7355732 0.48838486 0.46948087]]Singular values:[9.34265841 3.24497827 1.08850813]Right singular vectors:[[-0.57847229 -0.61642675 -0.53421706] [-0.73171177 0.10269066 0.67383419] [ 0.36051032 -0.78068732 0.51045041]]" }, { "code": null, "e": 2350, "s": 2335, "text": "Essential Idea" }, { "code": null, "e": 2529, "s": 2350, "text": "Randomized SVD can be broken into three main steps. For any given m-by-n matrix A, if we impose a target rank k with k < min(m, n), then the first step as shown in Figure 2 is to" }, { "code": null, "e": 2589, "s": 2529, "text": "1) generate a Gaussian random matrix Ω with size of n-by-k," }, { "code": null, "e": 2623, "s": 2589, "text": "2) compute a new m-by-k matrix Y," }, { "code": null, "e": 2670, "s": 2623, "text": "and 3) apply QR decomposition to the matrix Y." }, { "code": null, "e": 2732, "s": 2670, "text": "Note that the first step needs to return the m-by-k matrix Q." }, { "code": null, "e": 2781, "s": 2732, "text": "Then, the second step as shown in Figure 3 is to" }, { "code": null, "e": 2878, "s": 2781, "text": "4) derive a k-by-n matrix B by multiplying the transposed matrix of Q and the matrix A together," }, { "code": null, "e": 3015, "s": 2878, "text": "and 5) compute the SVD of the matrix B. Here, instead of computing the SVD of the original matrix A, B is a smaller matrix to work with." }, { "code": null, "e": 3302, "s": 3015, "text": "For the fact that the singular values (i.e., Σ)and right singular vectors (i.e., V) of the matrix B are also the singular values and right singular vectors of the original matrix A, we should preserve the singular values and right singular vectors computed by the matrix B in this step." }, { "code": null, "e": 3496, "s": 3302, "text": "As shown in Figure 3, if we combine the matrix Q derived in the first step with the left singular vectors of B, we can get the left singular vectors (i.e., U) of the matrix A in the third step." }, { "code": null, "e": 3519, "s": 3496, "text": "A Small Matrix Example" }, { "code": null, "e": 3717, "s": 3519, "text": "Even though we have learned the essential idea of randomized SVD in above, it would not be really clear if there is no intuitive example. To this end, we follow the aforementioned small matrix SVD." }, { "code": null, "e": 3865, "s": 3717, "text": "First, let us try to write the Python function of randomized SVD. Here, we will use two Numpy functions, i.e., np.linalg.qr() and np.linalg.svd() ." }, { "code": null, "e": 4053, "s": 3865, "text": "import numpy as npdef rsvd(A, Omega): Y = A @ Omega Q, _ = np.linalg.qr(Y) B = Q.T @ A u_tilde, s, v = np.linalg.svd(B, full_matrices = 0) u = Q @ u_tilde return u, s, v" }, { "code": null, "e": 4140, "s": 4053, "text": "Now, let us test it with 3-by-3 matrix (rank = 2 for indicating k with k < min(m, n)):" }, { "code": null, "e": 4440, "s": 4140, "text": "np.random.seed(1000)A = np.array([[1, 3, 2], [5, 3, 1], [3, 4, 5]])rank = 2Omega = np.random.randn(A.shape[1], rank)u, s, v = rsvd(A, Omega)print('Left singular vectors:')print(u)print()print('Singular values:')print(s)print()print('Right singular vectors:')print(v)print()" }, { "code": null, "e": 4486, "s": 4440, "text": "The result of this randomized SVD example is:" }, { "code": null, "e": 4727, "s": 4486, "text": "Left singular vectors:[[ 0.38070859 0.60505354] [ 0.56830191 -0.74963644] [ 0.72944767 0.26824507]]Singular values:[9.34224023 3.02039888]Right singular vectors:[[ 0.57915029 0.61707064 0.53273704] [-0.77420021 0.21163814 0.59650929]]" }, { "code": null, "e": 4891, "s": 4727, "text": "Recall that the singular values of this matrix are 9.3427, 3.2450, and 1.0885. In this case, randomized SVD has the first two singular values as 9.3422 and 3.0204." }, { "code": null, "e": 5122, "s": 4891, "text": "We can see that the first singular values computed by these two SVD algorithms are extremely close. However, the second singular value of randomized SVD has a slight bias. Is there any other method to improve this result? And how?" }, { "code": null, "e": 5141, "s": 5122, "text": "The answer is yes!" }, { "code": null, "e": 5355, "s": 5141, "text": "To improve the quality of randomized SVD, power iteration method can be used directly. For more detail about power iteration, please see the page 39 in [1] and there is also a Matlab implementation in the page 40." }, { "code": null, "e": 5553, "s": 5355, "text": "In the following Python codes, power_iteration() is the function for computing the m-by-k matrix Y iteratively (the default power_iter is 3) and then derive the m-by-k matrix Q by QR decomposition." }, { "code": null, "e": 5888, "s": 5553, "text": "import numpy as npdef power_iteration(A, Omega, power_iter = 3): Y = A @ Omega for q in range(power_iter): Y = A @ (A.T @ Y) Q, _ = np.linalg.qr(Y) return Qdef rsvd(A, Omega): Q = power_iteration(A, Omega) B = Q.T @ A u_tilde, s, v = np.linalg.svd(B, full_matrices = 0) u = Q @ u_tilde return u, s, v" }, { "code": null, "e": 5925, "s": 5888, "text": "Let us test our new rsvd() function:" }, { "code": null, "e": 6225, "s": 5925, "text": "np.random.seed(1000)A = np.array([[1, 3, 2], [5, 3, 1], [3, 4, 5]])rank = 2Omega = np.random.randn(A.shape[1], rank)u, s, v = rsvd(A, Omega)print('Left singular vectors:')print(u)print()print('Singular values:')print(s)print()print('Right singular vectors:')print(v)print()" }, { "code": null, "e": 6240, "s": 6225, "text": "The result is:" }, { "code": null, "e": 6481, "s": 6240, "text": "Left singular vectors:[[ 0.37421757 0.28528579] [ 0.56470638 -0.82484381] [ 0.73557319 0.48810317]]Singular values:[9.34265841 3.24497775]Right singular vectors:[[ 0.57847229 0.61642675 0.53421706] [-0.73178429 0.10284774 0.67373147]]" }, { "code": null, "e": 6494, "s": 6481, "text": "Recall that:" }, { "code": null, "e": 6550, "s": 6494, "text": "Singular values of SVD are: 9.3427, 3.2450, and 1.0885." }, { "code": null, "e": 6632, "s": 6550, "text": "Singular values of randomized SVD without power iteration are: 9.3422 and 3.0204." }, { "code": null, "e": 6711, "s": 6632, "text": "Singular values of randomized SVD with power iteration are: 9.3427 and 3.2450." }, { "code": null, "e": 6812, "s": 6711, "text": "As you can see, the randomized SVD with power iteration provides extremely accurate singular values." }, { "code": null, "e": 7285, "s": 6812, "text": "As mentioned above, it is possible to compress (low-rank) signal matrix using the SVD or randomized SVD. In fact, the way to compress an image using the SVD is rather simple: taking the SVD of the image directly and only keeping the dominant singular values and left/right singular vectors. In terms of randomized SVD, we can predefine the number of dominant singular values first, and then obtain the singular values and left/right singular vectors by the randomized SVD." }, { "code": null, "e": 7467, "s": 7285, "text": "For our evaluation, we choose the color image of Lena as our data. The size of this image is 256×256×3. Here, we build a matrix A of size 256×256 by only selecting the green chanel." }, { "code": null, "e": 7486, "s": 7467, "text": "Using SVD directly" }, { "code": null, "e": 7515, "s": 7486, "text": "Using randomized SVD instead" }, { "code": null, "e": 7571, "s": 7515, "text": "We can see from this image compression experiment that:" }, { "code": null, "e": 7709, "s": 7571, "text": "1) By comparing to the SVD, the randomized SVD can also produce accurate compression with a prescribed low rank (here, we set rank = 50)." }, { "code": null, "e": 7892, "s": 7709, "text": "2) The randomized SVD is computational friendly. By specifying rank = 50, the total CPU times of the randomized SVD is about 11.6 ms, while the total CPU times of the SVD is 31.5 ms." }, { "code": null, "e": 7994, "s": 7892, "text": "In this post, you discovered the randomized linear algebra method for SVD. Specifically, you learned:" }, { "code": null, "e": 8032, "s": 7994, "text": "The essential idea of randomized SVD." }, { "code": null, "e": 8075, "s": 8032, "text": "How to implement randomized SVD in Python." }, { "code": null, "e": 8102, "s": 8075, "text": "Do you have any questions?" }, { "code": null, "e": 8247, "s": 8102, "text": "[1] Steven L. Brunton, J. Nathan Kutz (2019). Data-Driven Science and Engineering: Machine Learning, Dynamical Systems, and Control. Page 37–41." } ]
Difference between HTML and CSS - GeeksforGeeks
28 Jul, 2020 HTMLHTML stands for Hyper Text Markup Language and it is the language which is used to define the structure of a web page. HTML is used along with CSS and Java script to design web pages. HTML is the basic building block of a website. It has different attributes and elements with different properties.Each element has a opening and a closing tag. We can also add images by the help of HTML.Example:<html><body> <h1>Welcome to GeeksForGeeks</h1></body></html>Output: <html><body> <h1>Welcome to GeeksForGeeks</h1></body></html> Output: CSS:CSS stands for Cascading Style Sheets and it is used to style web documents. It is used to provide the background color and is also used for styling. It can also be used to style the font and change its size. We can also style many different web pages with the same specifications by the help of CSS. CSS is also recommended by World Wide Web Consortium (W3C). It can also be used along with HTML and Java script to design web pages.Example:<html><head><style>body { background-color:red;}</style></head><body> <h1>Welcome to GeeksForGeeks!</h1> <p>This page has red background color</p> </body></html>Output: <html><head><style>body { background-color:red;}</style></head><body> <h1>Welcome to GeeksForGeeks!</h1> <p>This page has red background color</p> </body></html> Output: Difference between HTML and CSS: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Basics HTML-Basics CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 31761, "s": 31733, "text": "\n28 Jul, 2020" }, { "code": null, "e": 32231, "s": 31761, "text": "HTMLHTML stands for Hyper Text Markup Language and it is the language which is used to define the structure of a web page. HTML is used along with CSS and Java script to design web pages. HTML is the basic building block of a website. It has different attributes and elements with different properties.Each element has a opening and a closing tag. We can also add images by the help of HTML.Example:<html><body> <h1>Welcome to GeeksForGeeks</h1></body></html>Output:" }, { "code": "<html><body> <h1>Welcome to GeeksForGeeks</h1></body></html>", "e": 32295, "s": 32231, "text": null }, { "code": null, "e": 32303, "s": 32295, "text": "Output:" }, { "code": null, "e": 32921, "s": 32303, "text": "CSS:CSS stands for Cascading Style Sheets and it is used to style web documents. It is used to provide the background color and is also used for styling. It can also be used to style the font and change its size. We can also style many different web pages with the same specifications by the help of CSS. CSS is also recommended by World Wide Web Consortium (W3C). It can also be used along with HTML and Java script to design web pages.Example:<html><head><style>body { background-color:red;}</style></head><body> <h1>Welcome to GeeksForGeeks!</h1> <p>This page has red background color</p> </body></html>Output:" }, { "code": "<html><head><style>body { background-color:red;}</style></head><body> <h1>Welcome to GeeksForGeeks!</h1> <p>This page has red background color</p> </body></html>", "e": 33087, "s": 32921, "text": null }, { "code": null, "e": 33095, "s": 33087, "text": "Output:" }, { "code": null, "e": 33128, "s": 33095, "text": "Difference between HTML and CSS:" }, { "code": null, "e": 33265, "s": 33128, "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": 33276, "s": 33265, "text": "CSS-Basics" }, { "code": null, "e": 33288, "s": 33276, "text": "HTML-Basics" }, { "code": null, "e": 33292, "s": 33288, "text": "CSS" }, { "code": null, "e": 33297, "s": 33292, "text": "HTML" }, { "code": null, "e": 33314, "s": 33297, "text": "Web Technologies" }, { "code": null, "e": 33319, "s": 33314, "text": "HTML" }, { "code": null, "e": 33417, "s": 33319, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33426, "s": 33417, "text": "Comments" }, { "code": null, "e": 33439, "s": 33426, "text": "Old Comments" }, { "code": null, "e": 33501, "s": 33439, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33551, "s": 33501, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33599, "s": 33551, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33657, "s": 33599, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 33707, "s": 33657, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 33769, "s": 33707, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33819, "s": 33769, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33867, "s": 33819, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33927, "s": 33867, "text": "How to set the default value for an HTML <select> element ?" } ]
Graph Theory | BFS Shortest Path Problem on a Grid | by Kelvin Jose | Towards Data Science
Hi all, welcome back to another post of my brand new series on Graph Theory named Graph Theory: Go Hero. I undoubtedly recommend the complete series, if you are planning to get started with or want to have a quick refresher. We’re going to see how we can use Breadth First Search (BFS) to solve a shortest path problem. I have already done an another post on BFS, earlier. So, let’s dive into deep. I hope you have an idea about what is Breadth First Search (BFS) and how it works because we would be using the BFS concepts intensively. Many problems in Graph Theory could be represented using grids because interestingly grids are a form of implicit graph. We can determine the neighbors of our current location by searching within the grid. A type of problem where we find the shortest path in a grid is solving a maze, like below. Another example could be routing through obstacles (like trees, rivers, rocks etc) to get to a location. A common approach to solve graph problems is to first convert the structure into some representational formats like adjacency matrix or list. Basically, these are data structures which store the neighborhood information within the graph. Let’s see a more intuitive version of it. Consider we have an imaginary graph. No, this is not a graph. Look at figure 1, but that’s what I was talking about. Imagine that every cell in figure 1 has neighbors to it’s left, right, bottom and up. For more clarity, cell 0 has two neighbors, 1 and 2. In the same way, cell 4 also has two neighbors 2 and 3. We can review these cells as the vertices in a graph where rows * columns would be the total number of vertices. Figure 2 is the adjacency list representing our imaginary graph, now you can relate it with the first figure, right? The last figure depicts the adjacency matrix of the same graph. Every cell (i, j) of adjacency matrix is filled with 1s where nodes i and j have an edge in between them. We used just 1s and 0s here because we have no information about the cost from vertex i to j. If we had that, we could have used that information, as well. Once we have an adjacency list/matrix representation of a graph, we can run multiple graph algorithms on top it to solve different use cases like finding the shortest path and connected components. This is probably a problem statement we have encountered in many interviews and programming competitions and it goes as follows. Suppose you are trapped in a 2D dungeon and you have to find the easiest way out. Hold on, we have some obstacles too. The dungeon is composed of unit cubes which may or may not be filled with rocks. It would take exactly one minute to move either east, west, south or north. You can’t move diagonally as the maze is tightly packed with solid rocks. The dungeon has a size of R x C where R is number of rows and c is number of columns. We have to start at cell ‘S’ and we have an exit at cell ‘E’. The number (#) symbol depicts the roadblocks in the route and period (.) shows an open route. In the given setup, one solution could be drawn as above in the green route. Our approach is to do a BFS starting from cell S, until we find the exit cell E. If you remember, we used a queue to store the points to be visited later in the graph. We use the same here too. We start from cell (0,0) and add it to our queue. Once it’s visited we add all the neighbors of the visited cell to the queue. Cell (0,0) has two neighbors, (0,1) and (1,0). The queue becomes bigger and bigger as we visit and add more neighbors into the queue, iteratively. We stop this process when we meet the exit condition i.e. we visit the exit cell E (4,3). Then we can regenerate the path from Exit to Start by backtracking. We have been using a single queue to keep track of the next node to be visited say a (i, j) pair, so far. But this is not the best approach to follow, because it requires a lot of packing and unpacking to and forth the queue. Instead, let’s try another better method which scales really well with higher dimensional data, also possesses less complexity. An alternative method would be to use separate queues for every dimensions, so in a 3D grid, we would have one queue for each dimension. As soon as we enqueue some potential information into the queue, x, y and z would go to respective queues. In the same way, dequeue retrieves a triplet of (x,y,z) values at a time. # Global variables, I intentionally leave the values as ... because # I don't have any meaningful values yet. But it won't affect how# you understand the problem, I promise.R, C = ...m = ...sr, sc = ...rq, cq = ...# Variables used to keep track of total number of steps to be takenmove_count = 0nodes_left_in_layer = 0nodes_in_next_layer = 1# Variable to see whether we already reached at the end or notreached_end = false# Matrix to keep track of visited cells.visited = ...# North, South, East and West direction vectorsdr = [-1, +1, 0, 0]dc = [0, 0, +1, -1] We start by initializing some global variables. R and C stand for number rows and columns of the dungeon, respectively. The variable m is the input character matrix of size R x C. We store the initial row and column values where we store the starting point of our BFS in variables sr and sc. We use two separate queues rq and cr to store the respective row and column indices of the next node to be visited. Also, we use a couple of variables to keep track of total steps taken to reach the end. nodes_left_in_layer shows the count that how many nodes we have to dequeue before we take a step further and nodes_in_next_layer tracks how many nodes we have added in the BFS expansion, so that we can update nodes_left_in_layer accordingly. The variable reached_end stores whether we already reached the exit cell or not. The variable visited is a matrix of size R x C which is used to mark the cells visited, because we don’t want to visit the same cell again. Variables dr and dc need some explanation, I will cover it soon. Suppose we are in the red cell (i, j). We have an assumption like a row index can only move between rows and a column index can move between columns. So the only possible row operation is either we can go North by subtracting 1 from i or move South by adding 1 to i. In the same way, we are restricted to move either East or West by adding or subtracting 1 to the column index i.e. j. We use different combinations of direction values to move around the dungeon and that’s why defined it before as variables. I think you got the point. We’re not done with the problem yet. We just defined a couple of important variables only. The core idea is about to come out. function solve(): rq.enqueue(sr) cq.enqueue(sc) visited[sr][sc] = true while rq.size() > 0: r = rq.dequeue() c = cq.dequeue() if m[r][c] == 'E': reached_end = true break explore_neighbors(r, c) nodes_left_in_layer -- if nodes_left_in_layer == 0: nodes_left_in_layer = nodes_in_next_layer nodes_in_next_layer = 0 move_count ++ if reached_end == true: return move_count return -1function explore_neighbors(r, c): for(i=0; i<4: i++): rr = r + dr[i] cc = c + dc[i] if rr < 0 or cc < 0: continue if rr >= R or cc >= C: continue if visited[r][c] == true: continue if m[r][c] == '#': continue rq.enqueue(rr) rc.enqueue(cc) visited[r][c] = true nodes_in_next_layer ++ Here I have defined two functions namely solve() and explore_neighbors(). We start by enqueuing the initial (i, j) positions from where we start the BFS process and we mark the cell as visited. Then we do the following steps iteratively until either rq or cq becomes empty. dequeue each element from both rq and cq.we check whether the current position is an exit or not, if yes, we get out of the loop.If the current position isn’t an exit point, then we have to explore its neighbors by invoking the explore_neighbors() function.Inside the explore_neighbors() function, we iteratively find all possible locations and checks for a couple of conditions. I think the conditions are self-explanatory. dequeue each element from both rq and cq. we check whether the current position is an exit or not, if yes, we get out of the loop. If the current position isn’t an exit point, then we have to explore its neighbors by invoking the explore_neighbors() function. Inside the explore_neighbors() function, we iteratively find all possible locations and checks for a couple of conditions. I think the conditions are self-explanatory. The first two conditions check whether we’re out the grid or not. That means, we can’t go beyond the minimum or maximum rows and columns. Then we check whether the current location is already been visited before or not. If it’s true, we don’t have to visit it again. Also, we have to make sure the current location isn’t blocked, all blocked cells are marked with #. 5. We enqueue the values of current cell and mark it as visited. (Don’t forget, we are inside the explore_neighbors() function call). What happens here is like, we try moving to all possible locations such as north, east, south and west. We then iteratively explore its neighbors. That’s it. 6. Finally, we update the value of nodes_in_next_layer and leave. We’re going back to the solve() function again. 7. We update a couple of parameters to keep track of how many steps we took so far. 8. As soon as we serve an exit point, we go out. TADAAA!!! The whole idea and the algorithm are relatively super easy even the pseudo-code looks scary. We started looking at how a maze works and how we can port the same problem into a more scientific one. We saw how we could use grids and adjacency lists to represent the problem. We understood what’s a dungeon problem and how it’s solved using BFS. My idea was to show how we can use BFS to solve a shortest path problem on a grid. That’s pretty much all about it. In the next post, we will have an Introduction to tree algorithms. Until then, bye.
[ { "code": null, "e": 571, "s": 172, "text": "Hi all, welcome back to another post of my brand new series on Graph Theory named Graph Theory: Go Hero. I undoubtedly recommend the complete series, if you are planning to get started with or want to have a quick refresher. We’re going to see how we can use Breadth First Search (BFS) to solve a shortest path problem. I have already done an another post on BFS, earlier. So, let’s dive into deep." }, { "code": null, "e": 709, "s": 571, "text": "I hope you have an idea about what is Breadth First Search (BFS) and how it works because we would be using the BFS concepts intensively." }, { "code": null, "e": 1006, "s": 709, "text": "Many problems in Graph Theory could be represented using grids because interestingly grids are a form of implicit graph. We can determine the neighbors of our current location by searching within the grid. A type of problem where we find the shortest path in a grid is solving a maze, like below." }, { "code": null, "e": 1111, "s": 1006, "text": "Another example could be routing through obstacles (like trees, rivers, rocks etc) to get to a location." }, { "code": null, "e": 1391, "s": 1111, "text": "A common approach to solve graph problems is to first convert the structure into some representational formats like adjacency matrix or list. Basically, these are data structures which store the neighborhood information within the graph. Let’s see a more intuitive version of it." }, { "code": null, "e": 1428, "s": 1391, "text": "Consider we have an imaginary graph." }, { "code": null, "e": 2259, "s": 1428, "text": "No, this is not a graph. Look at figure 1, but that’s what I was talking about. Imagine that every cell in figure 1 has neighbors to it’s left, right, bottom and up. For more clarity, cell 0 has two neighbors, 1 and 2. In the same way, cell 4 also has two neighbors 2 and 3. We can review these cells as the vertices in a graph where rows * columns would be the total number of vertices. Figure 2 is the adjacency list representing our imaginary graph, now you can relate it with the first figure, right? The last figure depicts the adjacency matrix of the same graph. Every cell (i, j) of adjacency matrix is filled with 1s where nodes i and j have an edge in between them. We used just 1s and 0s here because we have no information about the cost from vertex i to j. If we had that, we could have used that information, as well." }, { "code": null, "e": 2457, "s": 2259, "text": "Once we have an adjacency list/matrix representation of a graph, we can run multiple graph algorithms on top it to solve different use cases like finding the shortest path and connected components." }, { "code": null, "e": 2586, "s": 2457, "text": "This is probably a problem statement we have encountered in many interviews and programming competitions and it goes as follows." }, { "code": null, "e": 2936, "s": 2586, "text": "Suppose you are trapped in a 2D dungeon and you have to find the easiest way out. Hold on, we have some obstacles too. The dungeon is composed of unit cubes which may or may not be filled with rocks. It would take exactly one minute to move either east, west, south or north. You can’t move diagonally as the maze is tightly packed with solid rocks." }, { "code": null, "e": 3178, "s": 2936, "text": "The dungeon has a size of R x C where R is number of rows and c is number of columns. We have to start at cell ‘S’ and we have an exit at cell ‘E’. The number (#) symbol depicts the roadblocks in the route and period (.) shows an open route." }, { "code": null, "e": 3336, "s": 3178, "text": "In the given setup, one solution could be drawn as above in the green route. Our approach is to do a BFS starting from cell S, until we find the exit cell E." }, { "code": null, "e": 3881, "s": 3336, "text": "If you remember, we used a queue to store the points to be visited later in the graph. We use the same here too. We start from cell (0,0) and add it to our queue. Once it’s visited we add all the neighbors of the visited cell to the queue. Cell (0,0) has two neighbors, (0,1) and (1,0). The queue becomes bigger and bigger as we visit and add more neighbors into the queue, iteratively. We stop this process when we meet the exit condition i.e. we visit the exit cell E (4,3). Then we can regenerate the path from Exit to Start by backtracking." }, { "code": null, "e": 4235, "s": 3881, "text": "We have been using a single queue to keep track of the next node to be visited say a (i, j) pair, so far. But this is not the best approach to follow, because it requires a lot of packing and unpacking to and forth the queue. Instead, let’s try another better method which scales really well with higher dimensional data, also possesses less complexity." }, { "code": null, "e": 4372, "s": 4235, "text": "An alternative method would be to use separate queues for every dimensions, so in a 3D grid, we would have one queue for each dimension." }, { "code": null, "e": 4553, "s": 4372, "text": "As soon as we enqueue some potential information into the queue, x, y and z would go to respective queues. In the same way, dequeue retrieves a triplet of (x,y,z) values at a time." }, { "code": null, "e": 5114, "s": 4553, "text": "# Global variables, I intentionally leave the values as ... because # I don't have any meaningful values yet. But it won't affect how# you understand the problem, I promise.R, C = ...m = ...sr, sc = ...rq, cq = ...# Variables used to keep track of total number of steps to be takenmove_count = 0nodes_left_in_layer = 0nodes_in_next_layer = 1# Variable to see whether we already reached at the end or notreached_end = false# Matrix to keep track of visited cells.visited = ...# North, South, East and West direction vectorsdr = [-1, +1, 0, 0]dc = [0, 0, +1, -1]" }, { "code": null, "e": 6138, "s": 5114, "text": "We start by initializing some global variables. R and C stand for number rows and columns of the dungeon, respectively. The variable m is the input character matrix of size R x C. We store the initial row and column values where we store the starting point of our BFS in variables sr and sc. We use two separate queues rq and cr to store the respective row and column indices of the next node to be visited. Also, we use a couple of variables to keep track of total steps taken to reach the end. nodes_left_in_layer shows the count that how many nodes we have to dequeue before we take a step further and nodes_in_next_layer tracks how many nodes we have added in the BFS expansion, so that we can update nodes_left_in_layer accordingly. The variable reached_end stores whether we already reached the exit cell or not. The variable visited is a matrix of size R x C which is used to mark the cells visited, because we don’t want to visit the same cell again. Variables dr and dc need some explanation, I will cover it soon." }, { "code": null, "e": 6674, "s": 6138, "text": "Suppose we are in the red cell (i, j). We have an assumption like a row index can only move between rows and a column index can move between columns. So the only possible row operation is either we can go North by subtracting 1 from i or move South by adding 1 to i. In the same way, we are restricted to move either East or West by adding or subtracting 1 to the column index i.e. j. We use different combinations of direction values to move around the dungeon and that’s why defined it before as variables. I think you got the point." }, { "code": null, "e": 6801, "s": 6674, "text": "We’re not done with the problem yet. We just defined a couple of important variables only. The core idea is about to come out." }, { "code": null, "e": 7750, "s": 6801, "text": "function solve(): rq.enqueue(sr) cq.enqueue(sc) visited[sr][sc] = true while rq.size() > 0: r = rq.dequeue() c = cq.dequeue() if m[r][c] == 'E': reached_end = true break explore_neighbors(r, c) nodes_left_in_layer -- if nodes_left_in_layer == 0: nodes_left_in_layer = nodes_in_next_layer nodes_in_next_layer = 0 move_count ++ if reached_end == true: return move_count return -1function explore_neighbors(r, c): for(i=0; i<4: i++): rr = r + dr[i] cc = c + dc[i] if rr < 0 or cc < 0: continue if rr >= R or cc >= C: continue if visited[r][c] == true: continue if m[r][c] == '#': continue rq.enqueue(rr) rc.enqueue(cc) visited[r][c] = true nodes_in_next_layer ++" }, { "code": null, "e": 7944, "s": 7750, "text": "Here I have defined two functions namely solve() and explore_neighbors(). We start by enqueuing the initial (i, j) positions from where we start the BFS process and we mark the cell as visited." }, { "code": null, "e": 8024, "s": 7944, "text": "Then we do the following steps iteratively until either rq or cq becomes empty." }, { "code": null, "e": 8449, "s": 8024, "text": "dequeue each element from both rq and cq.we check whether the current position is an exit or not, if yes, we get out of the loop.If the current position isn’t an exit point, then we have to explore its neighbors by invoking the explore_neighbors() function.Inside the explore_neighbors() function, we iteratively find all possible locations and checks for a couple of conditions. I think the conditions are self-explanatory." }, { "code": null, "e": 8491, "s": 8449, "text": "dequeue each element from both rq and cq." }, { "code": null, "e": 8580, "s": 8491, "text": "we check whether the current position is an exit or not, if yes, we get out of the loop." }, { "code": null, "e": 8709, "s": 8580, "text": "If the current position isn’t an exit point, then we have to explore its neighbors by invoking the explore_neighbors() function." }, { "code": null, "e": 8877, "s": 8709, "text": "Inside the explore_neighbors() function, we iteratively find all possible locations and checks for a couple of conditions. I think the conditions are self-explanatory." }, { "code": null, "e": 9015, "s": 8877, "text": "The first two conditions check whether we’re out the grid or not. That means, we can’t go beyond the minimum or maximum rows and columns." }, { "code": null, "e": 9144, "s": 9015, "text": "Then we check whether the current location is already been visited before or not. If it’s true, we don’t have to visit it again." }, { "code": null, "e": 9244, "s": 9144, "text": "Also, we have to make sure the current location isn’t blocked, all blocked cells are marked with #." }, { "code": null, "e": 9536, "s": 9244, "text": "5. We enqueue the values of current cell and mark it as visited. (Don’t forget, we are inside the explore_neighbors() function call). What happens here is like, we try moving to all possible locations such as north, east, south and west. We then iteratively explore its neighbors. That’s it." }, { "code": null, "e": 9602, "s": 9536, "text": "6. Finally, we update the value of nodes_in_next_layer and leave." }, { "code": null, "e": 9650, "s": 9602, "text": "We’re going back to the solve() function again." }, { "code": null, "e": 9734, "s": 9650, "text": "7. We update a couple of parameters to keep track of how many steps we took so far." }, { "code": null, "e": 9783, "s": 9734, "text": "8. As soon as we serve an exit point, we go out." }, { "code": null, "e": 9793, "s": 9783, "text": "TADAAA!!!" }, { "code": null, "e": 9886, "s": 9793, "text": "The whole idea and the algorithm are relatively super easy even the pseudo-code looks scary." }, { "code": null, "e": 10252, "s": 9886, "text": "We started looking at how a maze works and how we can port the same problem into a more scientific one. We saw how we could use grids and adjacency lists to represent the problem. We understood what’s a dungeon problem and how it’s solved using BFS. My idea was to show how we can use BFS to solve a shortest path problem on a grid. That’s pretty much all about it." } ]
Checking the Given Indexes are Equal or not in C# - GeeksforGeeks
28 Nov, 2019 The Index Structure is introduced in C# 8.0. It represents a type that can be used to index a collection or sequence and it can be started from the start or the end. You are allowed to compare two indexes with each to check whether they are equal or not with the help of the following methods(Equal Method) provided by the Index struct: This method returns a value that shows that the given object is equal to the other object. The result is in the form of bool if it returns true, then the current object is equal to another object or if it returns false, then the current object is not equal to another object. Syntax: public virtual bool Equals(Index other); Example: // C# program to illustrate the// concept of the Equals(index) methodusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] greetings = new string[] {"Hello", "Hola", "Namaste", "Bonjour", "Ohayo", "Ahnyounghaseyo"}; // Get the end index var res = Index.Start; // Checking the given index // is the start index or not // Using Equals(index) method if (res.Equals(0) == true) { Console.WriteLine("The given index is start index"+ " and the element is " + greetings[res]); } else { Console.WriteLine("The given index is not the start index "); } }}} Output: The given index is start index and the element is Hello This method returns a value that shows that the given index object is equal to the other index object. The result is in the form of bool if it returns true, then the current index object is equal to another index object or if it returns false, then the current index object is not equal to another index object. Syntax: public override bool Equals(System::Object ^ value); Example: // C# program to illustrate the concept// of the Equals(object) methodusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] greetings = new string[] {"Hello", "Hola", "Namaste", "Bonjour", "Ohayo", "Ahnyounghaseyo"}; // Creating index // Using Index() constructor var val1 = new Index(1, true); var val2 = new Index(2, false); // Checking the given both the // index values are equal or not // Using Equals(object) if (val1.Value.Equals(val2.Value) == true) { Console.WriteLine("Both the indexes are equal and"+ " their elements are :{0}, {1}", greetings[val1], greetings[val2]); } else { Console.WriteLine("Both the indexes are not equal and"+ " their elements are: {0}, {1}", greetings[val1], greetings[val2]); } }}} Output: Both the indexes are not equal and their elements are: Ahnyounghaseyo, Namaste CSharp-8.0 C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Extension Method in C# HashSet in C# with Examples Top 50 C# Interview Questions & Answers C# | How to insert an element in an Array? C# | Inheritance C# | List Class Partial Classes in C# Convert String to Character Array in C# Lambda Expressions in C# Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 24302, "s": 24274, "text": "\n28 Nov, 2019" }, { "code": null, "e": 24639, "s": 24302, "text": "The Index Structure is introduced in C# 8.0. It represents a type that can be used to index a collection or sequence and it can be started from the start or the end. You are allowed to compare two indexes with each to check whether they are equal or not with the help of the following methods(Equal Method) provided by the Index struct:" }, { "code": null, "e": 24915, "s": 24639, "text": "This method returns a value that shows that the given object is equal to the other object. The result is in the form of bool if it returns true, then the current object is equal to another object or if it returns false, then the current object is not equal to another object." }, { "code": null, "e": 24923, "s": 24915, "text": "Syntax:" }, { "code": null, "e": 24964, "s": 24923, "text": "public virtual bool Equals(Index other);" }, { "code": null, "e": 24973, "s": 24964, "text": "Example:" }, { "code": "// C# program to illustrate the// concept of the Equals(index) methodusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] greetings = new string[] {\"Hello\", \"Hola\", \"Namaste\", \"Bonjour\", \"Ohayo\", \"Ahnyounghaseyo\"}; // Get the end index var res = Index.Start; // Checking the given index // is the start index or not // Using Equals(index) method if (res.Equals(0) == true) { Console.WriteLine(\"The given index is start index\"+ \" and the element is \" + greetings[res]); } else { Console.WriteLine(\"The given index is not the start index \"); } }}}", "e": 25794, "s": 24973, "text": null }, { "code": null, "e": 25802, "s": 25794, "text": "Output:" }, { "code": null, "e": 25858, "s": 25802, "text": "The given index is start index and the element is Hello" }, { "code": null, "e": 26170, "s": 25858, "text": "This method returns a value that shows that the given index object is equal to the other index object. The result is in the form of bool if it returns true, then the current index object is equal to another index object or if it returns false, then the current index object is not equal to another index object." }, { "code": null, "e": 26178, "s": 26170, "text": "Syntax:" }, { "code": null, "e": 26231, "s": 26178, "text": "public override bool Equals(System::Object ^ value);" }, { "code": null, "e": 26240, "s": 26231, "text": "Example:" }, { "code": "// C# program to illustrate the concept// of the Equals(object) methodusing System; namespace example { class GFG { // Main Method static void Main(string[] args) { // Creating and initializing an array string[] greetings = new string[] {\"Hello\", \"Hola\", \"Namaste\", \"Bonjour\", \"Ohayo\", \"Ahnyounghaseyo\"}; // Creating index // Using Index() constructor var val1 = new Index(1, true); var val2 = new Index(2, false); // Checking the given both the // index values are equal or not // Using Equals(object) if (val1.Value.Equals(val2.Value) == true) { Console.WriteLine(\"Both the indexes are equal and\"+ \" their elements are :{0}, {1}\", greetings[val1], greetings[val2]); } else { Console.WriteLine(\"Both the indexes are not equal and\"+ \" their elements are: {0}, {1}\", greetings[val1], greetings[val2]); } }}}", "e": 27340, "s": 26240, "text": null }, { "code": null, "e": 27348, "s": 27340, "text": "Output:" }, { "code": null, "e": 27427, "s": 27348, "text": "Both the indexes are not equal and their elements are: Ahnyounghaseyo, Namaste" }, { "code": null, "e": 27438, "s": 27427, "text": "CSharp-8.0" }, { "code": null, "e": 27441, "s": 27438, "text": "C#" }, { "code": null, "e": 27539, "s": 27441, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27548, "s": 27539, "text": "Comments" }, { "code": null, "e": 27561, "s": 27548, "text": "Old Comments" }, { "code": null, "e": 27584, "s": 27561, "text": "Extension Method in C#" }, { "code": null, "e": 27612, "s": 27584, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27652, "s": 27612, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27695, "s": 27652, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 27712, "s": 27695, "text": "C# | Inheritance" }, { "code": null, "e": 27728, "s": 27712, "text": "C# | List Class" }, { "code": null, "e": 27750, "s": 27728, "text": "Partial Classes in C#" }, { "code": null, "e": 27790, "s": 27750, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 27815, "s": 27790, "text": "Lambda Expressions in C#" } ]
Eigenvalues, eigenvectors and PCA | Towards Data Science
I have learned about eigenvalues and eigenvectors in University in a linear algebra course. It was very dry and mathematical, so I did not get, what it is all about. But I want to present this topic to you in a more intuitive way and I will use many animations to illustrate it. First, we will look at how applying a matrix to a vector rotates and scales a vector. This will show us what eigenvalues and eigenvectors are. Then we will learn about principal components and that they are the eigenvectors of the covariance matrix. This knowledge will help us understand our final topic, principal component analysis. To understand eigenvalues and eigenvectors, we have to first take a look at matrix multiplication. Let’s consider the following matrix. When we take the dot product of a matrix and a vector, the resulting vector is a rotated and scaled version of the original one. In data science, we mostly talk of data points, not vectors. But they are the same essentially and can be used interchangeably. And data points can also be transformed by matrix multiplication in the same way as vectors. But even if matrix multiplication rotates and scales, it is a linear transformation. Why is matrix multiplication a linear transformation? Consider a bunch of data points (denoted in red). Imagine a grid on which these points are located. When we apply the matrix to our data points and move the grid along with the data points, we see that the lines of the grid remain straight. If the lines would curve, then the transformation would be non-linear. We consider the same matrix as above. When applying this matrix to different vectors, they behave differently. Some of them may get rotated and scaled. Some of them only rotated, some of them only scaled and some of them may not change at all. Eigenvectors are the vectors, which only get scaled. or do not change at all. You can see, that the eigenvectors stay on the same line and other vectors(generic vectors) get rotated by some degree. A 2x2 matrix has always two eigenvectors, but there are not always orthogonal to each other. Each Eigenvector has a corresponding eigenvalue. It is the factor by which the eigenvector gets scaled, when it gets transformed by the matrix. We consider the same matrix and therefore the same two eigenvectors as mentioned above. One of the two eigenvectors of this matrix (I call it Eigenvector 1, but this is arbitrary) is scaled by a factor of 1.4. Eigenvector 2 get’s also scaled by a factor of 1.4 but it’s direction get’s inverted. Therefore, eigenvalue 2 is -1.4. Using eigenvalues and eigenvectors, we can find the main axes of our data. The first main axis (also called “first principal component”) is the axis in which the data varies the most. The second main axis (also called “second principal component”) is the axis with the second largest variation and so on. Let’s consider a 2-dimensional dataset. To find the principal components, we first calculate the Variance-Covariance matrix C. We can use numpy to calculate them. Note that our data (X) must be ordered like a pandas data frame. Each column represents a different variable/feature. import numpy as npC = np.cov(X, rowvar = False) And then we can calculate the eigenvectors and eigenvalues of C. import numpy as npeigenvalues,eigenvectors = np.linalg.eig(C) The eigenvectors show us the direction of our main axes (principal components) of our data. The greater the eigenvalue, the greater the variation along this axis. So the eigenvector with the largest eigenvalue corresponds to the axis with the most variance. We should remember, that matrices represent a linear transformation. When we multiply the Covariance matrix with our data, we can see that the center of the data does not change. And the data gets stretched in the direction of the eigenvector with the bigger variance/eigenvalue and squeezed along the axis of the eigenvector with the smaller variance. Data points lying directly on the eigenvectors do not get rotated. Principal component analysis uses the power of eigenvectors and eigenvalues to reduce the number of features in our data, while keeping most of the variance (and therefore most of the information). In PCA we specify the number of components we want to keep beforehand. The PCA algorithm consists of the following steps. Standardizing data by subtracting the mean and dividing by the standard deviationCalculate the Covariance matrix.Calculate eigenvalues and eigenvectorsMerge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features.Keep the new features which account for the most variation and discard the rest. Standardizing data by subtracting the mean and dividing by the standard deviation Calculate the Covariance matrix. Calculate eigenvalues and eigenvectors Merge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features. Keep the new features which account for the most variation and discard the rest. Let’s look at what PCA does on a 2-dimensional dataset. In this example, we do not reduce the number of features. Reducing the number of features makes sense for high dimensional data because then it reduces the number of features. Let’s load the iris dataset. It contains measurements of three different species of iris flowers. Those species are iris-virginica, iris-versicolor and iris-setosa. Let’s take a quick glimpse at the dataset. print(iris_df.head()) We can create a so called “scree plot” to look at which variables account for the most variability in the data. For this, we perform a first PCA. As we can see, the first two components account for most of the variability in the data. Therefore I have decided to keep only the first two components and discard the Rest. When having determined the number of components to keep, we can run a second PCA in which we reduce the number of features. We take a look at our data, which is an array now. print(iris_transformed[:5,:]) We can see, that we have only two columns left. These columns/variables are a linear combination of our original data and do not correspond to a feature of the original dataset ( like sepal width, sepal length, ...). Let’s visualize our data. We see our new combined features on the x and y axes. The plant species is indicated by the color of a data point. We can see, that much of the information in the data has been preserved and we could now train an ML model, that classifies the data points according to the three species. I will now summarize the most important concepts. When we multiply a matrix with a vector, the vector get’s transformed linearly. This linear transformation is a mixture of rotating and scaling the vector. The vectors, which get only scaled and not rotated are called eigenvectors. The factor by which they get scaled is the corresponding eigenvalue. Principal components are the axes in which our data shows the most variation. The first principal component explains the biggest part of the observed variation and the second principal component the second largest part and so on. The Principal components are the eigenvectors of the covariance matrix. The first principal component corresponds to the eigenvector with the largest eigenvalue. Principal component analysis is a technique to reduce the number of features in our dataset. It consists of the following processing steps. Standardizing data by subtracting the mean and dividing by the standard deviationCalculate the covariance matrix.Calculate eigenvalues and eigenvectorsMerge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features.Keep as many new features as we specified and discard the rest. We keep the features which can explain the most variation in the data. Standardizing data by subtracting the mean and dividing by the standard deviation Calculate the covariance matrix. Calculate eigenvalues and eigenvectors Merge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features. Keep as many new features as we specified and discard the rest. We keep the features which can explain the most variation in the data. https://datascienceplus.com/understanding-the-covariance-matrix/ https://en.wikipedia.org/wiki/Iris_flower_data_set https://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_iris.html The Iris dataset and license can be found under: https://www.openml.org/d/61 It is licensed under creative commons which means you can copy, modify, distribute and perform the work, even for commercial purposes, all without asking for permission. towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Want to connect? Linkedinhttps://www.linkedin.com/in/vincent-m%C3%BCller-6b3542214/Facebookhttps://www.facebook.com/profile.php?id=100072095823739Twitterhttps://twitter.com/Vincent02770108Mediumhttps://medium.com/@Vincent.MuellerYou can become a Medium member and support me at the same timehttps://medium.com/@Vincent.Mueller/membership If you like mathematics and want to dive deeper, I have summarized some of the math used in this blog post. We can easily calculate the eigenvectors and eigenvalues in python. import numpy as npeigenvalues,eigenvectors = np.linalg.eig(M) If we want to calculate them by hand, it gets a little bit more complicated. As we have seen, when we multiply the matrix M with an eigenvector (denoted by v), it is the same as scaling its eigenvalue λ. We now rearrange the equation. Where I is the identity matrix, which has ones in the diagonal and zeros elsewhere. It has the same shape as A. And the only way for this equation to be true. This is only true when the determinant of the matrix (A -λ⋅I) becomes 0. The determinant of a matrix is the factor by which the matrix scales the area in case of a 2x2 matrix and the volume in case of a 3x3 matrix. If the determinant is zero, then the matrix (A -λ⋅I) squeezes points to the origin (origin is the zero point). This is the only way for a non-zero vector to become a zero-vector. So we search for all eigenvalues λ, which make the determinant 0. After we found the eigenvalues, we can solve this equation: And we find the eigenvectors. The variance-covariance matrix can be estimated from data using the following formula:
[ { "code": null, "e": 451, "s": 172, "text": "I have learned about eigenvalues and eigenvectors in University in a linear algebra course. It was very dry and mathematical, so I did not get, what it is all about. But I want to present this topic to you in a more intuitive way and I will use many animations to illustrate it." }, { "code": null, "e": 787, "s": 451, "text": "First, we will look at how applying a matrix to a vector rotates and scales a vector. This will show us what eigenvalues and eigenvectors are. Then we will learn about principal components and that they are the eigenvectors of the covariance matrix. This knowledge will help us understand our final topic, principal component analysis." }, { "code": null, "e": 886, "s": 787, "text": "To understand eigenvalues and eigenvectors, we have to first take a look at matrix multiplication." }, { "code": null, "e": 923, "s": 886, "text": "Let’s consider the following matrix." }, { "code": null, "e": 1052, "s": 923, "text": "When we take the dot product of a matrix and a vector, the resulting vector is a rotated and scaled version of the original one." }, { "code": null, "e": 1273, "s": 1052, "text": "In data science, we mostly talk of data points, not vectors. But they are the same essentially and can be used interchangeably. And data points can also be transformed by matrix multiplication in the same way as vectors." }, { "code": null, "e": 1358, "s": 1273, "text": "But even if matrix multiplication rotates and scales, it is a linear transformation." }, { "code": null, "e": 1724, "s": 1358, "text": "Why is matrix multiplication a linear transformation? Consider a bunch of data points (denoted in red). Imagine a grid on which these points are located. When we apply the matrix to our data points and move the grid along with the data points, we see that the lines of the grid remain straight. If the lines would curve, then the transformation would be non-linear." }, { "code": null, "e": 1762, "s": 1724, "text": "We consider the same matrix as above." }, { "code": null, "e": 1968, "s": 1762, "text": "When applying this matrix to different vectors, they behave differently. Some of them may get rotated and scaled. Some of them only rotated, some of them only scaled and some of them may not change at all." }, { "code": null, "e": 2004, "s": 1968, "text": "Eigenvectors are the vectors, which" }, { "code": null, "e": 2021, "s": 2004, "text": "only get scaled." }, { "code": null, "e": 2046, "s": 2021, "text": "or do not change at all." }, { "code": null, "e": 2166, "s": 2046, "text": "You can see, that the eigenvectors stay on the same line and other vectors(generic vectors) get rotated by some degree." }, { "code": null, "e": 2259, "s": 2166, "text": "A 2x2 matrix has always two eigenvectors, but there are not always orthogonal to each other." }, { "code": null, "e": 2491, "s": 2259, "text": "Each Eigenvector has a corresponding eigenvalue. It is the factor by which the eigenvector gets scaled, when it gets transformed by the matrix. We consider the same matrix and therefore the same two eigenvectors as mentioned above." }, { "code": null, "e": 2613, "s": 2491, "text": "One of the two eigenvectors of this matrix (I call it Eigenvector 1, but this is arbitrary) is scaled by a factor of 1.4." }, { "code": null, "e": 2732, "s": 2613, "text": "Eigenvector 2 get’s also scaled by a factor of 1.4 but it’s direction get’s inverted. Therefore, eigenvalue 2 is -1.4." }, { "code": null, "e": 3037, "s": 2732, "text": "Using eigenvalues and eigenvectors, we can find the main axes of our data. The first main axis (also called “first principal component”) is the axis in which the data varies the most. The second main axis (also called “second principal component”) is the axis with the second largest variation and so on." }, { "code": null, "e": 3077, "s": 3037, "text": "Let’s consider a 2-dimensional dataset." }, { "code": null, "e": 3164, "s": 3077, "text": "To find the principal components, we first calculate the Variance-Covariance matrix C." }, { "code": null, "e": 3318, "s": 3164, "text": "We can use numpy to calculate them. Note that our data (X) must be ordered like a pandas data frame. Each column represents a different variable/feature." }, { "code": null, "e": 3366, "s": 3318, "text": "import numpy as npC = np.cov(X, rowvar = False)" }, { "code": null, "e": 3431, "s": 3366, "text": "And then we can calculate the eigenvectors and eigenvalues of C." }, { "code": null, "e": 3493, "s": 3431, "text": "import numpy as npeigenvalues,eigenvectors = np.linalg.eig(C)" }, { "code": null, "e": 3751, "s": 3493, "text": "The eigenvectors show us the direction of our main axes (principal components) of our data. The greater the eigenvalue, the greater the variation along this axis. So the eigenvector with the largest eigenvalue corresponds to the axis with the most variance." }, { "code": null, "e": 4104, "s": 3751, "text": "We should remember, that matrices represent a linear transformation. When we multiply the Covariance matrix with our data, we can see that the center of the data does not change. And the data gets stretched in the direction of the eigenvector with the bigger variance/eigenvalue and squeezed along the axis of the eigenvector with the smaller variance." }, { "code": null, "e": 4171, "s": 4104, "text": "Data points lying directly on the eigenvectors do not get rotated." }, { "code": null, "e": 4440, "s": 4171, "text": "Principal component analysis uses the power of eigenvectors and eigenvalues to reduce the number of features in our data, while keeping most of the variance (and therefore most of the information). In PCA we specify the number of components we want to keep beforehand." }, { "code": null, "e": 4491, "s": 4440, "text": "The PCA algorithm consists of the following steps." }, { "code": null, "e": 4891, "s": 4491, "text": "Standardizing data by subtracting the mean and dividing by the standard deviationCalculate the Covariance matrix.Calculate eigenvalues and eigenvectorsMerge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features.Keep the new features which account for the most variation and discard the rest." }, { "code": null, "e": 4973, "s": 4891, "text": "Standardizing data by subtracting the mean and dividing by the standard deviation" }, { "code": null, "e": 5006, "s": 4973, "text": "Calculate the Covariance matrix." }, { "code": null, "e": 5045, "s": 5006, "text": "Calculate eigenvalues and eigenvectors" }, { "code": null, "e": 5214, "s": 5045, "text": "Merge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features." }, { "code": null, "e": 5295, "s": 5214, "text": "Keep the new features which account for the most variation and discard the rest." }, { "code": null, "e": 5527, "s": 5295, "text": "Let’s look at what PCA does on a 2-dimensional dataset. In this example, we do not reduce the number of features. Reducing the number of features makes sense for high dimensional data because then it reduces the number of features." }, { "code": null, "e": 5692, "s": 5527, "text": "Let’s load the iris dataset. It contains measurements of three different species of iris flowers. Those species are iris-virginica, iris-versicolor and iris-setosa." }, { "code": null, "e": 5735, "s": 5692, "text": "Let’s take a quick glimpse at the dataset." }, { "code": null, "e": 5757, "s": 5735, "text": "print(iris_df.head())" }, { "code": null, "e": 5903, "s": 5757, "text": "We can create a so called “scree plot” to look at which variables account for the most variability in the data. For this, we perform a first PCA." }, { "code": null, "e": 6201, "s": 5903, "text": "As we can see, the first two components account for most of the variability in the data. Therefore I have decided to keep only the first two components and discard the Rest. When having determined the number of components to keep, we can run a second PCA in which we reduce the number of features." }, { "code": null, "e": 6252, "s": 6201, "text": "We take a look at our data, which is an array now." }, { "code": null, "e": 6282, "s": 6252, "text": "print(iris_transformed[:5,:])" }, { "code": null, "e": 6499, "s": 6282, "text": "We can see, that we have only two columns left. These columns/variables are a linear combination of our original data and do not correspond to a feature of the original dataset ( like sepal width, sepal length, ...)." }, { "code": null, "e": 6525, "s": 6499, "text": "Let’s visualize our data." }, { "code": null, "e": 6640, "s": 6525, "text": "We see our new combined features on the x and y axes. The plant species is indicated by the color of a data point." }, { "code": null, "e": 6812, "s": 6640, "text": "We can see, that much of the information in the data has been preserved and we could now train an ML model, that classifies the data points according to the three species." }, { "code": null, "e": 6862, "s": 6812, "text": "I will now summarize the most important concepts." }, { "code": null, "e": 7163, "s": 6862, "text": "When we multiply a matrix with a vector, the vector get’s transformed linearly. This linear transformation is a mixture of rotating and scaling the vector. The vectors, which get only scaled and not rotated are called eigenvectors. The factor by which they get scaled is the corresponding eigenvalue." }, { "code": null, "e": 7555, "s": 7163, "text": "Principal components are the axes in which our data shows the most variation. The first principal component explains the biggest part of the observed variation and the second principal component the second largest part and so on. The Principal components are the eigenvectors of the covariance matrix. The first principal component corresponds to the eigenvector with the largest eigenvalue." }, { "code": null, "e": 7695, "s": 7555, "text": "Principal component analysis is a technique to reduce the number of features in our dataset. It consists of the following processing steps." }, { "code": null, "e": 8149, "s": 7695, "text": "Standardizing data by subtracting the mean and dividing by the standard deviationCalculate the covariance matrix.Calculate eigenvalues and eigenvectorsMerge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features.Keep as many new features as we specified and discard the rest. We keep the features which can explain the most variation in the data." }, { "code": null, "e": 8231, "s": 8149, "text": "Standardizing data by subtracting the mean and dividing by the standard deviation" }, { "code": null, "e": 8264, "s": 8231, "text": "Calculate the covariance matrix." }, { "code": null, "e": 8303, "s": 8264, "text": "Calculate eigenvalues and eigenvectors" }, { "code": null, "e": 8472, "s": 8303, "text": "Merge the eigenvectors into a matrix and apply it to the data. This rotates and scales the data. The principal components are now aligned with the axes of our features." }, { "code": null, "e": 8607, "s": 8472, "text": "Keep as many new features as we specified and discard the rest. We keep the features which can explain the most variation in the data." }, { "code": null, "e": 8672, "s": 8607, "text": "https://datascienceplus.com/understanding-the-covariance-matrix/" }, { "code": null, "e": 8723, "s": 8672, "text": "https://en.wikipedia.org/wiki/Iris_flower_data_set" }, { "code": null, "e": 8802, "s": 8723, "text": "https://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_iris.html" }, { "code": null, "e": 8851, "s": 8802, "text": "The Iris dataset and license can be found under:" }, { "code": null, "e": 8879, "s": 8851, "text": "https://www.openml.org/d/61" }, { "code": null, "e": 9049, "s": 8879, "text": "It is licensed under creative commons which means you can copy, modify, distribute and perform the work, even for commercial purposes, all without asking for permission." }, { "code": null, "e": 9072, "s": 9049, "text": "towardsdatascience.com" }, { "code": null, "e": 9095, "s": 9072, "text": "towardsdatascience.com" }, { "code": null, "e": 9118, "s": 9095, "text": "towardsdatascience.com" }, { "code": null, "e": 9141, "s": 9118, "text": "towardsdatascience.com" }, { "code": null, "e": 9164, "s": 9141, "text": "towardsdatascience.com" }, { "code": null, "e": 9187, "s": 9164, "text": "towardsdatascience.com" }, { "code": null, "e": 9204, "s": 9187, "text": "Want to connect?" }, { "code": null, "e": 9525, "s": 9204, "text": "Linkedinhttps://www.linkedin.com/in/vincent-m%C3%BCller-6b3542214/Facebookhttps://www.facebook.com/profile.php?id=100072095823739Twitterhttps://twitter.com/Vincent02770108Mediumhttps://medium.com/@Vincent.MuellerYou can become a Medium member and support me at the same timehttps://medium.com/@Vincent.Mueller/membership" }, { "code": null, "e": 9633, "s": 9525, "text": "If you like mathematics and want to dive deeper, I have summarized some of the math used in this blog post." }, { "code": null, "e": 9701, "s": 9633, "text": "We can easily calculate the eigenvectors and eigenvalues in python." }, { "code": null, "e": 9763, "s": 9701, "text": "import numpy as npeigenvalues,eigenvectors = np.linalg.eig(M)" }, { "code": null, "e": 9840, "s": 9763, "text": "If we want to calculate them by hand, it gets a little bit more complicated." }, { "code": null, "e": 9967, "s": 9840, "text": "As we have seen, when we multiply the matrix M with an eigenvector (denoted by v), it is the same as scaling its eigenvalue λ." }, { "code": null, "e": 9998, "s": 9967, "text": "We now rearrange the equation." }, { "code": null, "e": 10110, "s": 9998, "text": "Where I is the identity matrix, which has ones in the diagonal and zeros elsewhere. It has the same shape as A." }, { "code": null, "e": 10157, "s": 10110, "text": "And the only way for this equation to be true." }, { "code": null, "e": 10230, "s": 10157, "text": "This is only true when the determinant of the matrix (A -λ⋅I) becomes 0." }, { "code": null, "e": 10551, "s": 10230, "text": "The determinant of a matrix is the factor by which the matrix scales the area in case of a 2x2 matrix and the volume in case of a 3x3 matrix. If the determinant is zero, then the matrix (A -λ⋅I) squeezes points to the origin (origin is the zero point). This is the only way for a non-zero vector to become a zero-vector." }, { "code": null, "e": 10617, "s": 10551, "text": "So we search for all eigenvalues λ, which make the determinant 0." }, { "code": null, "e": 10677, "s": 10617, "text": "After we found the eigenvalues, we can solve this equation:" }, { "code": null, "e": 10707, "s": 10677, "text": "And we find the eigenvectors." } ]
C# - Anonymous Methods
We discussed that delegates are used to reference any methods that has the same signature as that of the delegate. In other words, you can call a method that can be referenced by a delegate using that delegate object. Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body. Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example, delegate void NumberChanger(int n); ... NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; The code block Console.WriteLine("Anonymous Method: {0}", x); is the body of the anonymous method. The delegate could be called both with anonymous methods as well as named methods in the same way, i.e., by passing the method parameters to the delegate object. For example, nc(10); The following example demonstrates the concept − using System; delegate void NumberChanger(int n); namespace DelegateAppl { class TestDelegate { static int num = 10; public static void AddNum(int p) { num += p; Console.WriteLine("Named Method: {0}", num); } public static void MultNum(int q) { num *= q; Console.WriteLine("Named Method: {0}", num); } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances using anonymous method NumberChanger nc = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; //calling the delegate using the anonymous method nc(10); //instantiating the delegate using the named methods nc = new NumberChanger(AddNum); //calling the delegate using the named methods nc(5); //instantiating the delegate using another named methods nc = new NumberChanger(MultNum); //calling the delegate using the named methods nc(2); Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result − Anonymous Method: 10 Named Method: 15 Named Method: 30 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2488, "s": 2270, "text": "We discussed that delegates are used to reference any methods that has the same signature as that of the delegate. In other words, you can call a method that can be referenced by a delegate using that delegate object." }, { "code": null, "e": 2637, "s": 2488, "text": "Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body." }, { "code": null, "e": 2763, "s": 2637, "text": "You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body." }, { "code": null, "e": 2876, "s": 2763, "text": "Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example," }, { "code": null, "e": 3007, "s": 2876, "text": "delegate void NumberChanger(int n);\n...\nNumberChanger nc = delegate(int x) {\n Console.WriteLine(\"Anonymous Method: {0}\", x);\n};\n" }, { "code": null, "e": 3106, "s": 3007, "text": "The code block Console.WriteLine(\"Anonymous Method: {0}\", x); is the body of the anonymous method." }, { "code": null, "e": 3268, "s": 3106, "text": "The delegate could be called both with anonymous methods as well as named methods in the same way, i.e., by passing the method parameters to the delegate object." }, { "code": null, "e": 3281, "s": 3268, "text": "For example," }, { "code": null, "e": 3290, "s": 3281, "text": "nc(10);\n" }, { "code": null, "e": 3339, "s": 3290, "text": "The following example demonstrates the concept −" }, { "code": null, "e": 4530, "s": 3339, "text": "using System;\n\ndelegate void NumberChanger(int n);\nnamespace DelegateAppl {\n class TestDelegate {\n static int num = 10;\n \n public static void AddNum(int p) {\n num += p;\n Console.WriteLine(\"Named Method: {0}\", num);\n }\n public static void MultNum(int q) {\n num *= q;\n Console.WriteLine(\"Named Method: {0}\", num);\n }\n public static int getNum() {\n return num;\n }\n static void Main(string[] args) {\n //create delegate instances using anonymous method\n NumberChanger nc = delegate(int x) {\n Console.WriteLine(\"Anonymous Method: {0}\", x);\n };\n \n //calling the delegate using the anonymous method \n nc(10);\n \n //instantiating the delegate using the named methods \n nc = new NumberChanger(AddNum);\n \n //calling the delegate using the named methods \n nc(5);\n \n //instantiating the delegate using another named methods \n nc = new NumberChanger(MultNum);\n \n //calling the delegate using the named methods \n nc(2);\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 4611, "s": 4530, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4667, "s": 4611, "text": "Anonymous Method: 10\nNamed Method: 15\nNamed Method: 30\n" }, { "code": null, "e": 4704, "s": 4667, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 4717, "s": 4704, "text": " Raja Biswas" }, { "code": null, "e": 4751, "s": 4717, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 4769, "s": 4751, "text": " Trevoir Williams" }, { "code": null, "e": 4802, "s": 4769, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4816, "s": 4802, "text": " Peter Jepson" }, { "code": null, "e": 4853, "s": 4816, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 4868, "s": 4853, "text": " Ebenezer Ogbu" }, { "code": null, "e": 4903, "s": 4868, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 4918, "s": 4903, "text": " Arnold Higuit" }, { "code": null, "e": 4953, "s": 4918, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4965, "s": 4953, "text": " Eric Frick" }, { "code": null, "e": 4972, "s": 4965, "text": " Print" }, { "code": null, "e": 4983, "s": 4972, "text": " Add Notes" } ]
How to resolve ‘node’ is not recognized as an internal or external command error after installing Node.js ?
10 Jul, 2020 There are many different ways to install node.js on a computer. The simplest method to verify whether node.js has been properly installed in your computer is simply type node-v in the command prompt or Windows PowerShell. But many times, it happens, most commonly if you’re a beginner, the command prompt prints the output something like this: 'node' is not recognized as an internal or external command, operable program or batch file. This is the most common error and it is very simple to resolve this. It might be a case that the user might have properly installed node from the official node website. But sometimes, the reason is that the path variable is not defined in your system. So to properly define a path variable and resolve this error, follow these simple steps: Open the Environment Variables option in your Control Panel. (Go to Control Panel -> System and Security ->System -> Advanced System Settings-> Environment Variables ->User Variables or System Variables.)Select the variable named Path. A dialogue box named Edit user variable will appear. In the variable value option inside that dialogue box, paste the complete path of the location where node.js is installed in your system.Then click on OK.Restart the command prompt again and now verify by typing node-v in the command prompt. It will now display the version of the node which you’ve installed from the internet . Open the Environment Variables option in your Control Panel. (Go to Control Panel -> System and Security ->System -> Advanced System Settings-> Environment Variables ->User Variables or System Variables.) Select the variable named Path. A dialogue box named Edit user variable will appear. In the variable value option inside that dialogue box, paste the complete path of the location where node.js is installed in your system.Then click on OK. Restart the command prompt again and now verify by typing node-v in the command prompt. It will now display the version of the node which you’ve installed from the internet . Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jul, 2020" }, { "code": null, "e": 250, "s": 28, "text": "There are many different ways to install node.js on a computer. The simplest method to verify whether node.js has been properly installed in your computer is simply type node-v in the command prompt or Windows PowerShell." }, { "code": null, "e": 372, "s": 250, "text": "But many times, it happens, most commonly if you’re a beginner, the command prompt prints the output something like this:" }, { "code": null, "e": 466, "s": 372, "text": "'node' is not recognized as an internal or external command,\noperable program or batch file.\n" }, { "code": null, "e": 807, "s": 466, "text": "This is the most common error and it is very simple to resolve this. It might be a case that the user might have properly installed node from the official node website. But sometimes, the reason is that the path variable is not defined in your system. So to properly define a path variable and resolve this error, follow these simple steps:" }, { "code": null, "e": 1425, "s": 807, "text": "Open the Environment Variables option in your Control Panel. (Go to Control Panel -> System and Security ->System -> Advanced System Settings-> Environment Variables ->User Variables or System Variables.)Select the variable named Path. A dialogue box named Edit user variable will appear. In the variable value option inside that dialogue box, paste the complete path of the location where node.js is installed in your system.Then click on OK.Restart the command prompt again and now verify by typing node-v in the command prompt. It will now display the version of the node which you’ve installed from the internet ." }, { "code": null, "e": 1630, "s": 1425, "text": "Open the Environment Variables option in your Control Panel. (Go to Control Panel -> System and Security ->System -> Advanced System Settings-> Environment Variables ->User Variables or System Variables.)" }, { "code": null, "e": 1870, "s": 1630, "text": "Select the variable named Path. A dialogue box named Edit user variable will appear. In the variable value option inside that dialogue box, paste the complete path of the location where node.js is installed in your system.Then click on OK." }, { "code": null, "e": 2045, "s": 1870, "text": "Restart the command prompt again and now verify by typing node-v in the command prompt. It will now display the version of the node which you’ve installed from the internet ." }, { "code": null, "e": 2058, "s": 2045, "text": "Node.js-Misc" }, { "code": null, "e": 2066, "s": 2058, "text": "Node.js" }, { "code": null, "e": 2083, "s": 2066, "text": "Web Technologies" } ]
mkdir command in Linux with Examples
08 Sep, 2021 mkdir command in Linux allows the user to create directories (also referred to as folders in some operating systems ). This command can create multiple directories at once as well as set the permissions for the directories. It is important to note that the user executing this command must have enough permissions to create a directory in the parent directory, or he/she may receive a ‘permission denied’ error. Syntax: mkdir [options...] [directories ...] –version: It displays the version number, some information regarding the license and exits. Syntax: mkdir --version Output: –help: It displays the help related information and exits. Syntax: mkdir --help Output: -v or –verbose: It displays a message for every directory created. Syntax: mkdir -v [directories] Output: -p: A flag which enables the command to create parent directories as necessary. If the directories exist, no error is specified. Syntax: Syntax: mkdir -p [directories] Suppose you execute the following command – mkdir -p first/second/third If the first and second directories do not exist, due to the -p option, mkdir will create these directories for us. If we do not specify the -p option, and request the creation of directories, where parent directory doesn’t exist, we will get the following output – If we specify the -p option, the directories will be created, and no error will be reported. Following is the output of one such execution. We’ve also provided the -v option, so that we can see it in action. Output: -m: This option is used to set the file modes, i.e. permissions, etc. for the created directories. The syntax of the mode is the same as the chmod command. Syntax: Syntax: mkdir -m a=rwx [directories] The above syntax specifies that the directories created give access to all the users to read from, write to and execute the contents of the created directories. You can use ‘a=r’ to only allow all the users to read from the directories and so on. Output: sweetyty linux-command Linux-directory-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ZIP command in Linux with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script TCP Server-Client implementation in C Tail command in Linux with examples Docker - COPY Instruction scp command in Linux with Examples UDP Server-Client implementation in C echo command in Linux with Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2021" }, { "code": null, "e": 441, "s": 28, "text": "mkdir command in Linux allows the user to create directories (also referred to as folders in some operating systems ). This command can create multiple directories at once as well as set the permissions for the directories. It is important to note that the user executing this command must have enough permissions to create a directory in the parent directory, or he/she may receive a ‘permission denied’ error. " }, { "code": null, "e": 450, "s": 441, "text": "Syntax: " }, { "code": null, "e": 487, "s": 450, "text": "mkdir [options...] [directories ...]" }, { "code": null, "e": 588, "s": 487, "text": "–version: It displays the version number, some information regarding the license and exits. Syntax: " }, { "code": null, "e": 604, "s": 588, "text": "mkdir --version" }, { "code": null, "e": 613, "s": 604, "text": "Output: " }, { "code": null, "e": 681, "s": 613, "text": "–help: It displays the help related information and exits. Syntax: " }, { "code": null, "e": 694, "s": 681, "text": "mkdir --help" }, { "code": null, "e": 703, "s": 694, "text": "Output: " }, { "code": null, "e": 779, "s": 703, "text": "-v or –verbose: It displays a message for every directory created. Syntax: " }, { "code": null, "e": 802, "s": 779, "text": "mkdir -v [directories]" }, { "code": null, "e": 811, "s": 802, "text": "Output: " }, { "code": null, "e": 949, "s": 811, "text": "-p: A flag which enables the command to create parent directories as necessary. If the directories exist, no error is specified. Syntax: " }, { "code": null, "e": 958, "s": 949, "text": "Syntax: " }, { "code": null, "e": 981, "s": 958, "text": "mkdir -p [directories]" }, { "code": null, "e": 1026, "s": 981, "text": "Suppose you execute the following command – " }, { "code": null, "e": 1054, "s": 1026, "text": "mkdir -p first/second/third" }, { "code": null, "e": 1321, "s": 1054, "text": "If the first and second directories do not exist, due to the -p option, mkdir will create these directories for us. If we do not specify the -p option, and request the creation of directories, where parent directory doesn’t exist, we will get the following output – " }, { "code": null, "e": 1538, "s": 1321, "text": "If we specify the -p option, the directories will be created, and no error will be reported. Following is the output of one such execution. We’ve also provided the -v option, so that we can see it in action. Output: " }, { "code": null, "e": 1703, "s": 1538, "text": "-m: This option is used to set the file modes, i.e. permissions, etc. for the created directories. The syntax of the mode is the same as the chmod command. Syntax: " }, { "code": null, "e": 1712, "s": 1703, "text": "Syntax: " }, { "code": null, "e": 1741, "s": 1712, "text": "mkdir -m a=rwx [directories]" }, { "code": null, "e": 1998, "s": 1741, "text": "The above syntax specifies that the directories created give access to all the users to read from, write to and execute the contents of the created directories. You can use ‘a=r’ to only allow all the users to read from the directories and so on. Output: " }, { "code": null, "e": 2007, "s": 1998, "text": "sweetyty" }, { "code": null, "e": 2021, "s": 2007, "text": "linux-command" }, { "code": null, "e": 2046, "s": 2021, "text": "Linux-directory-commands" }, { "code": null, "e": 2053, "s": 2046, "text": "Picked" }, { "code": null, "e": 2064, "s": 2053, "text": "Linux-Unix" }, { "code": null, "e": 2162, "s": 2064, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2197, "s": 2162, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 2232, "s": 2197, "text": "tar command in Linux with examples" }, { "code": null, "e": 2268, "s": 2232, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2306, "s": 2268, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2344, "s": 2306, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2380, "s": 2344, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2406, "s": 2380, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2441, "s": 2406, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2479, "s": 2441, "text": "UDP Server-Client implementation in C" } ]
How to add an element horizontally in Html page using JavaScript?
26 Oct, 2021 There can be some cases where we have the requirement to add elements in a horizontal manner. Like, if your elements are linked list nodes and you want to add them horizontally. Now the question arises how we can do this in better way.One approach can be to use “display” property with the value “inline grid” as shown in the following program:When the user clicks the button to add the node. The node starts to prepend in the linked list sequentially. To achieve this we have created the “div” with the “display” property whose value we have given as “inline-grid”. Example-1 javascript <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"></head> <body> <center> <h1 style="color:green"> Inserting node horizontally </h1> </center> <br><br> <h1>click to insert</h1> <div> <input type = 'button' onclick = 'javascript: insert()' value = 'insert'><br> </div> <br><br><br><br> <div id = 'division' style = 'min-width: 300px; min-height: 80px;'></div> </div> <style> @keyframes addnode { from { transform: translateX(-100px); } to { transform: translateX(200px); } } </style> <script> var array = [];var number =1 ; function insert(){ var div = document.createElement('div'); div.innerHTML = number; document.getElementById('division').prepend(div); div.style = 'min-width: 80px; height: 80px; border: 4px solid green; display: inline-grid; text-align: center;background: green;border-radius: 50%;animation-name: addnode; animation-duration: 2s;animation-direction: all; transition-property: transform; transform: translateX(200px);'; array.push(number); number++; div.addEventListener('animationend', function() { });} </script></body></html> Output: Code explanation-We have created a html “<div>” element with id as “division” which will be our main division in which we add different “div” as node. In the “insert()” function we have created the. html “<div>” which will be the element of our linked list we have added a “number” which will start from 1 and will increment as we add more elements in the list. For the node to be prepended horizontally we have used the display property with value ” inline-grid”. But, there is a problem here in this solution, as we keep on adding elements in the list after a certain node the elements start to jump to the line which is not desired. This is what demonstrated in the output below. What if we want to add every node on the single line?Another approach: In this approach, to achieve the same thing we have used html “<table>”. So, the idea is that in a table we can create one table row i.e. html ” <tr>” and for adding each node we will create table data i.e. html ”<td>” . So, there will be one “tr” and every node will be treated as html “<td>” . So, in this way an infinite number of nodes can be added by using a table. We can see its implementation through program. Example- 2: javascript <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"></head><body> <center><h1 style="color:green"> Inserting node horizontally</h1></center><br><br> <h1>click to insert</h1> <div id = 'division' style = 'visibility: visible; position: absolute; margin-top: 0px;'><div> <input type = 'button' onclick = 'javascript: insert()' value = 'insert'><br></div> <br><br><br><br> <table><tr id = 'tablerow'><td id = 'tabledata' style = 'min-width: 300px; height: 58px;'></td></tr></table> </div> <style> @keyframes addnode { from {transform: translateX(-100px);} to {transform: translateX(200px);}} </style> <script>var array = []; var number = 1 ; function insert(){var td = document.createElement('td');td.innerHTML = number; document.getElementById('tablerow').prepend(td); td.style = 'min-width: 80px; height: 80px; border: 4px solid green; text-align: center;background: green; border-radius: 50%;animation-name: addnode; animation-duration: 2s; animation-direction: all; transition-property: transform; transform: translateX(200px);'; array.push(number); number++; td.addEventListener('animationend', function() { });} </script> </body> </html> Output After inserting many nodes yagyeshbagaya surindertarika1234 CSS-Properties JavaScript-DS javascript-functions JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Oct, 2021" }, { "code": null, "e": 596, "s": 28, "text": "There can be some cases where we have the requirement to add elements in a horizontal manner. Like, if your elements are linked list nodes and you want to add them horizontally. Now the question arises how we can do this in better way.One approach can be to use “display” property with the value “inline grid” as shown in the following program:When the user clicks the button to add the node. The node starts to prepend in the linked list sequentially. To achieve this we have created the “div” with the “display” property whose value we have given as “inline-grid”. " }, { "code": null, "e": 606, "s": 596, "text": "Example-1" }, { "code": null, "e": 617, "s": 606, "text": "javascript" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"></head> <body> <center> <h1 style=\"color:green\"> Inserting node horizontally </h1> </center> <br><br> <h1>click to insert</h1> <div> <input type = 'button' onclick = 'javascript: insert()' value = 'insert'><br> </div> <br><br><br><br> <div id = 'division' style = 'min-width: 300px; min-height: 80px;'></div> </div> <style> @keyframes addnode { from { transform: translateX(-100px); } to { transform: translateX(200px); } } </style> <script> var array = [];var number =1 ; function insert(){ var div = document.createElement('div'); div.innerHTML = number; document.getElementById('division').prepend(div); div.style = 'min-width: 80px; height: 80px; border: 4px solid green; display: inline-grid; text-align: center;background: green;border-radius: 50%;animation-name: addnode; animation-duration: 2s;animation-direction: all; transition-property: transform; transform: translateX(200px);'; array.push(number); number++; div.addEventListener('animationend', function() { });} </script></body></html>", "e": 1827, "s": 617, "text": null }, { "code": null, "e": 1835, "s": 1827, "text": "Output:" }, { "code": null, "e": 1870, "s": 1835, "text": "Code explanation-We have created a" }, { "code": null, "e": 1875, "s": 1870, "text": "html" }, { "code": "“<div>”", "e": 1883, "s": 1875, "text": null }, { "code": null, "e": 2034, "s": 1883, "text": "element with id as “division” which will be our main division in which we add different “div” as node. In the “insert()” function we have created the." }, { "code": null, "e": 2039, "s": 2034, "text": "html" }, { "code": "“<div>”", "e": 2047, "s": 2039, "text": null }, { "code": null, "e": 2519, "s": 2047, "text": "which will be the element of our linked list we have added a “number” which will start from 1 and will increment as we add more elements in the list. For the node to be prepended horizontally we have used the display property with value ” inline-grid”. But, there is a problem here in this solution, as we keep on adding elements in the list after a certain node the elements start to jump to the line which is not desired. This is what demonstrated in the output below. " }, { "code": null, "e": 2648, "s": 2519, "text": "What if we want to add every node on the single line?Another approach: In this approach, to achieve the same thing we have used " }, { "code": null, "e": 2653, "s": 2648, "text": "html" }, { "code": "“<table>”.", "e": 2664, "s": 2653, "text": null }, { "code": null, "e": 2730, "s": 2664, "text": "So, the idea is that in a table we can create one table row i.e. " }, { "code": null, "e": 2735, "s": 2730, "text": "html" }, { "code": "” <tr>”", "e": 2743, "s": 2735, "text": null }, { "code": null, "e": 2799, "s": 2743, "text": "and for adding each node we will create table data i.e." }, { "code": null, "e": 2804, "s": 2799, "text": "html" }, { "code": "”<td>”", "e": 2811, "s": 2804, "text": null }, { "code": null, "e": 2875, "s": 2811, "text": ". So, there will be one “tr” and every node will be treated as " }, { "code": null, "e": 2880, "s": 2875, "text": "html" }, { "code": "“<td>”", "e": 2887, "s": 2880, "text": null }, { "code": null, "e": 3011, "s": 2887, "text": ". So, in this way an infinite number of nodes can be added by using a table. We can see its implementation through program." }, { "code": null, "e": 3024, "s": 3011, "text": "Example- 2: " }, { "code": null, "e": 3035, "s": 3024, "text": "javascript" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"></head><body> <center><h1 style=\"color:green\"> Inserting node horizontally</h1></center><br><br> <h1>click to insert</h1> <div id = 'division' style = 'visibility: visible; position: absolute; margin-top: 0px;'><div> <input type = 'button' onclick = 'javascript: insert()' value = 'insert'><br></div> <br><br><br><br> <table><tr id = 'tablerow'><td id = 'tabledata' style = 'min-width: 300px; height: 58px;'></td></tr></table> </div> <style> @keyframes addnode { from {transform: translateX(-100px);} to {transform: translateX(200px);}} </style> <script>var array = []; var number = 1 ; function insert(){var td = document.createElement('td');td.innerHTML = number; document.getElementById('tablerow').prepend(td); td.style = 'min-width: 80px; height: 80px; border: 4px solid green; text-align: center;background: green; border-radius: 50%;animation-name: addnode; animation-duration: 2s; animation-direction: all; transition-property: transform; transform: translateX(200px);'; array.push(number); number++; td.addEventListener('animationend', function() { });} </script> </body> </html>", "e": 4287, "s": 3035, "text": null }, { "code": null, "e": 4295, "s": 4287, "text": "Output " }, { "code": null, "e": 4323, "s": 4295, "text": "After inserting many nodes " }, { "code": null, "e": 4339, "s": 4325, "text": "yagyeshbagaya" }, { "code": null, "e": 4358, "s": 4339, "text": "surindertarika1234" }, { "code": null, "e": 4373, "s": 4358, "text": "CSS-Properties" }, { "code": null, "e": 4387, "s": 4373, "text": "JavaScript-DS" }, { "code": null, "e": 4408, "s": 4387, "text": "javascript-functions" }, { "code": null, "e": 4419, "s": 4408, "text": "JavaScript" } ]
How to read multiple data files into Pandas?
23 Aug, 2021 In this article, we are going to see how to read multiple data files into pandas, data files are of multiple types, here are a few ways to read multiple files by using the pandas package in python. The demonstrative files can be download from here If our data files are in CSV format then the read_csv() method must be used. read_csv takes a file path as an argument. it reads the content of the CSV. To read multiple CSV files we can just use a simple for loop and iterate over all the files. Example: Reading Multiple CSV files using Pandas In this example we make a list of our data files or file path and then iterate through the file paths using a for loop, a for loop is used to iterate through iterables like list, tuples, strings, etc. And then create a data frame using pd.DataFrame(), concatenate each dataframe into a main dataframe using pd.concat(), then convert the final main dataframe into a CSV file using to_csv() method which takes the name of the new CSV file we want to create as an argument. Python3 # importing pandasimport pandas as pd file_list=['a.csv','b.csv','c.csv'] main_dataframe = pd.DataFrame(pd.read_csv(file_list[0])) for i in range(1,len(file_list)): data = pd.read_csv(file_list[i]) df = pd.DataFrame(data) main_dataframe = pd.concat([main_dataframe,df],axis=1)print(main_dataframe) Output: The glob module in python is used to retrieve files or pathnames matching a specified pattern. This program is similar to the above program but the only difference is instead of keeping track of file names using a list we use the glob package to retrieve files matching a specified pattern. Example: Reading multiple CSV files using Pandas and glob. Python3 # importing packagesimport pandas as pdimport glob folder_path = 'Path_of_file/csv_files'file_list = glob.glob(folder_path + "/*.csv")main_dataframe = pd.DataFrame(pd.read_csv(file_list[0]))for i in range(1,len(file_list)): data = pd.read_csv(file_list[i]) df = pd.DataFrame(data) main_dataframe = pd.concat([main_dataframe,df],axis=1)print(main_dataframe) Output: To read text files, the panda’s method read_table() must be used. Example: Reading text file using pandas and glob. Using glob package to retrieve files or pathnames and then iterate through the file paths using a for loop. Create a data frame of the contents of each file after reading it using pd.read_table() method which takes the file path as an argument. Concatenate each dataframe into a main dataframe using pd.concat(), then convert the final main dataframe into a CSV file using to_csv() method which takes the name of the new CSV file we want to create as an argument. Python3 # importing packagesimport pandas as pdimport glob folder_path = 'Path_/files'file_list = glob.glob(folder_path + "/*.txt")main_dataframe = pd.DataFrame(pd.read_table(file_list[0])) for i in range(1,len(file_list)): data = pd.read_table(file_list[i]) df = pd.DataFrame(data) main_dataframe = pd.concat([main_dataframe, df], axis = 1) print(main_dataframe) # creating a new csv file with# the dataframe we createdmain_dataframe.to_csv('new_csv1.csv') Output: Picked Python pandas-io Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 226, "s": 28, "text": "In this article, we are going to see how to read multiple data files into pandas, data files are of multiple types, here are a few ways to read multiple files by using the pandas package in python." }, { "code": null, "e": 276, "s": 226, "text": "The demonstrative files can be download from here" }, { "code": null, "e": 523, "s": 276, "text": "If our data files are in CSV format then the read_csv() method must be used. read_csv takes a file path as an argument. it reads the content of the CSV. To read multiple CSV files we can just use a simple for loop and iterate over all the files. " }, { "code": null, "e": 572, "s": 523, "text": "Example: Reading Multiple CSV files using Pandas" }, { "code": null, "e": 1043, "s": 572, "text": "In this example we make a list of our data files or file path and then iterate through the file paths using a for loop, a for loop is used to iterate through iterables like list, tuples, strings, etc. And then create a data frame using pd.DataFrame(), concatenate each dataframe into a main dataframe using pd.concat(), then convert the final main dataframe into a CSV file using to_csv() method which takes the name of the new CSV file we want to create as an argument." }, { "code": null, "e": 1051, "s": 1043, "text": "Python3" }, { "code": "# importing pandasimport pandas as pd file_list=['a.csv','b.csv','c.csv'] main_dataframe = pd.DataFrame(pd.read_csv(file_list[0])) for i in range(1,len(file_list)): data = pd.read_csv(file_list[i]) df = pd.DataFrame(data) main_dataframe = pd.concat([main_dataframe,df],axis=1)print(main_dataframe)", "e": 1361, "s": 1051, "text": null }, { "code": null, "e": 1369, "s": 1361, "text": "Output:" }, { "code": null, "e": 1465, "s": 1369, "text": "The glob module in python is used to retrieve files or pathnames matching a specified pattern. " }, { "code": null, "e": 1661, "s": 1465, "text": "This program is similar to the above program but the only difference is instead of keeping track of file names using a list we use the glob package to retrieve files matching a specified pattern." }, { "code": null, "e": 1720, "s": 1661, "text": "Example: Reading multiple CSV files using Pandas and glob." }, { "code": null, "e": 1728, "s": 1720, "text": "Python3" }, { "code": "# importing packagesimport pandas as pdimport glob folder_path = 'Path_of_file/csv_files'file_list = glob.glob(folder_path + \"/*.csv\")main_dataframe = pd.DataFrame(pd.read_csv(file_list[0]))for i in range(1,len(file_list)): data = pd.read_csv(file_list[i]) df = pd.DataFrame(data) main_dataframe = pd.concat([main_dataframe,df],axis=1)print(main_dataframe)", "e": 2095, "s": 1728, "text": null }, { "code": null, "e": 2103, "s": 2095, "text": "Output:" }, { "code": null, "e": 2169, "s": 2103, "text": "To read text files, the panda’s method read_table() must be used." }, { "code": null, "e": 2219, "s": 2169, "text": "Example: Reading text file using pandas and glob." }, { "code": null, "e": 2683, "s": 2219, "text": "Using glob package to retrieve files or pathnames and then iterate through the file paths using a for loop. Create a data frame of the contents of each file after reading it using pd.read_table() method which takes the file path as an argument. Concatenate each dataframe into a main dataframe using pd.concat(), then convert the final main dataframe into a CSV file using to_csv() method which takes the name of the new CSV file we want to create as an argument." }, { "code": null, "e": 2691, "s": 2683, "text": "Python3" }, { "code": "# importing packagesimport pandas as pdimport glob folder_path = 'Path_/files'file_list = glob.glob(folder_path + \"/*.txt\")main_dataframe = pd.DataFrame(pd.read_table(file_list[0])) for i in range(1,len(file_list)): data = pd.read_table(file_list[i]) df = pd.DataFrame(data) main_dataframe = pd.concat([main_dataframe, df], axis = 1) print(main_dataframe) # creating a new csv file with# the dataframe we createdmain_dataframe.to_csv('new_csv1.csv')", "e": 3154, "s": 2691, "text": null }, { "code": null, "e": 3162, "s": 3154, "text": "Output:" }, { "code": null, "e": 3169, "s": 3162, "text": "Picked" }, { "code": null, "e": 3186, "s": 3169, "text": "Python pandas-io" }, { "code": null, "e": 3200, "s": 3186, "text": "Python-pandas" }, { "code": null, "e": 3207, "s": 3200, "text": "Python" } ]
Split Pandas Dataframe by Column Index
29 Aug, 2020 Pandas support two data structures for storing data the series (single column) and dataframe where values are stored in a 2D table (rows and columns). To index a dataframe using the index we need to make use of dataframe.iloc() method which takes Syntax: pandas.DataFrame.iloc[] Parameters:Index Position: Index position of rows in integer or list of integer. Return type: Data frame or Series depending on parameters Let’s create a dataframe. In the below example we will use a simple binary dataset used to classify if a species is a mammal or reptile. The species column holds the labels where 1 stands for mammal and 0 for reptile. The data is stored in the dict which can be passed to the DataFrame function outputting a dataframe. Python3 import pandas as pd dataset = {'toothed': [1, 1, 1, 0, 1, 1, 1, 1, 1, 0], 'hair': [1, 1, 0, 1, 1, 1, 0, 0, 1, 0], 'breathes': [1, 1, 1, 1, 1, 1, 0, 1, 1, 1], 'legs': [1, 1, 0, 1, 1, 1, 0, 0, 1, 1], 'species': [1, 1, 0, 1, 1, 1, 0, 0, 1, 0] } df = pd.DataFrame(dataset) df.head() Output : output of head() Example 1: Now we would like to separate species columns from the feature columns (toothed, hair, breathes, legs) for this we are going to make use of the iloc[rows, columns] method offered by pandas. Here ‘:’ stands for all the rows and -1 stands for the last column so the below cell is going to take the all the rows and all columns except the last one (‘species’) as can be seen in the output: Python3 X = df.iloc[:,:-1]X Output: To split the species column from the rest of the dataset we make you of a similar code except in the cols position instead of padding a slice we pass in an integer value -1. Python3 Y = df.iloc[:,-1]Y Output : Example 2: Splitting using list of integers Similar output can be obtained by passing in a list of integers instead of a slice Python3 X = df.iloc[:,[0,1,2,3]]X Output: To the species column we are going to use the index of the column which is 4 we can use -1 as well Python3 Y = df.iloc[:,4]Y Output: Example 3: Splitting dataframes into 2 separate dataframes In the above two examples, the output for Y was a Series and not a dataframe Now we are going to split the dataframe into two separate dataframe’s this can be useful when dealing with multi-label datasets. Will be using the same dataset. In the first, we are going to split at column hair Python3 df.iloc[:,[0,1]] Output: The second dataframe will contain 3 columns breathes , legs , species Python3 df.iloc[:,[2,3,4]] Output: Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Aug, 2020" }, { "code": null, "e": 303, "s": 52, "text": "Pandas support two data structures for storing data the series (single column) and dataframe where values are stored in a 2D table (rows and columns). To index a dataframe using the index we need to make use of dataframe.iloc() method which takes " }, { "code": null, "e": 335, "s": 303, "text": "Syntax: pandas.DataFrame.iloc[]" }, { "code": null, "e": 416, "s": 335, "text": "Parameters:Index Position: Index position of rows in integer or list of integer." }, { "code": null, "e": 474, "s": 416, "text": "Return type: Data frame or Series depending on parameters" }, { "code": null, "e": 793, "s": 474, "text": "Let’s create a dataframe. In the below example we will use a simple binary dataset used to classify if a species is a mammal or reptile. The species column holds the labels where 1 stands for mammal and 0 for reptile. The data is stored in the dict which can be passed to the DataFrame function outputting a dataframe." }, { "code": null, "e": 801, "s": 793, "text": "Python3" }, { "code": "import pandas as pd dataset = {'toothed': [1, 1, 1, 0, 1, 1, 1, 1, 1, 0], 'hair': [1, 1, 0, 1, 1, 1, 0, 0, 1, 0], 'breathes': [1, 1, 1, 1, 1, 1, 0, 1, 1, 1], 'legs': [1, 1, 0, 1, 1, 1, 0, 0, 1, 1], 'species': [1, 1, 0, 1, 1, 1, 0, 0, 1, 0] } df = pd.DataFrame(dataset) df.head()", "e": 1133, "s": 801, "text": null }, { "code": null, "e": 1142, "s": 1133, "text": "Output :" }, { "code": null, "e": 1159, "s": 1142, "text": "output of head()" }, { "code": null, "e": 1361, "s": 1159, "text": "Example 1: Now we would like to separate species columns from the feature columns (toothed, hair, breathes, legs) for this we are going to make use of the iloc[rows, columns] method offered by pandas. " }, { "code": null, "e": 1558, "s": 1361, "text": "Here ‘:’ stands for all the rows and -1 stands for the last column so the below cell is going to take the all the rows and all columns except the last one (‘species’) as can be seen in the output:" }, { "code": null, "e": 1566, "s": 1558, "text": "Python3" }, { "code": "X = df.iloc[:,:-1]X", "e": 1586, "s": 1566, "text": null }, { "code": null, "e": 1595, "s": 1586, "text": "Output: " }, { "code": null, "e": 1769, "s": 1595, "text": "To split the species column from the rest of the dataset we make you of a similar code except in the cols position instead of padding a slice we pass in an integer value -1." }, { "code": null, "e": 1777, "s": 1769, "text": "Python3" }, { "code": "Y = df.iloc[:,-1]Y", "e": 1796, "s": 1777, "text": null }, { "code": null, "e": 1806, "s": 1796, "text": "Output : " }, { "code": null, "e": 1851, "s": 1806, "text": "Example 2: Splitting using list of integers " }, { "code": null, "e": 1935, "s": 1851, "text": "Similar output can be obtained by passing in a list of integers instead of a slice " }, { "code": null, "e": 1943, "s": 1935, "text": "Python3" }, { "code": "X = df.iloc[:,[0,1,2,3]]X", "e": 1969, "s": 1943, "text": null }, { "code": null, "e": 1977, "s": 1969, "text": "Output:" }, { "code": null, "e": 2077, "s": 1977, "text": "To the species column we are going to use the index of the column which is 4 we can use -1 as well " }, { "code": null, "e": 2085, "s": 2077, "text": "Python3" }, { "code": "Y = df.iloc[:,4]Y", "e": 2103, "s": 2085, "text": null }, { "code": null, "e": 2111, "s": 2103, "text": "Output:" }, { "code": null, "e": 2171, "s": 2111, "text": "Example 3: Splitting dataframes into 2 separate dataframes " }, { "code": null, "e": 2410, "s": 2171, "text": "In the above two examples, the output for Y was a Series and not a dataframe Now we are going to split the dataframe into two separate dataframe’s this can be useful when dealing with multi-label datasets. Will be using the same dataset. " }, { "code": null, "e": 2462, "s": 2410, "text": "In the first, we are going to split at column hair " }, { "code": null, "e": 2470, "s": 2462, "text": "Python3" }, { "code": "df.iloc[:,[0,1]]", "e": 2487, "s": 2470, "text": null }, { "code": null, "e": 2495, "s": 2487, "text": "Output:" }, { "code": null, "e": 2566, "s": 2495, "text": "The second dataframe will contain 3 columns breathes , legs , species " }, { "code": null, "e": 2574, "s": 2566, "text": "Python3" }, { "code": "df.iloc[:,[2,3,4]] ", "e": 2594, "s": 2574, "text": null }, { "code": null, "e": 2602, "s": 2594, "text": "Output:" }, { "code": null, "e": 2626, "s": 2602, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2649, "s": 2626, "text": "Python Pandas-exercise" }, { "code": null, "e": 2663, "s": 2649, "text": "Python-pandas" }, { "code": null, "e": 2670, "s": 2663, "text": "Python" } ]
C# - Passing Parameters by Value
This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument. The following example demonstrates the concept − using System; namespace CalculatorApplication { class NumberManipulator { public void swap(int x, int y) { int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* local variable definition */ int a = 100; int b = 200; Console.WriteLine("Before swap, value of a : {0}", a); Console.WriteLine("Before swap, value of b : {0}", b); /* calling a function to swap the values */ n.swap(a, b); Console.WriteLine("After swap, value of a : {0}", a); Console.WriteLine("After swap, value of b : {0}", b); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200 It shows that there is no change in the values though they had changed inside the function. 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2440, "s": 2270, "text": "This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter." }, { "code": null, "e": 2638, "s": 2440, "text": "The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument. The following example demonstrates the concept −" }, { "code": null, "e": 3521, "s": 2638, "text": "using System;\n\nnamespace CalculatorApplication {\n class NumberManipulator {\n public void swap(int x, int y) {\n int temp;\n \n temp = x; /* save the value of x */\n x = y; /* put y into x */\n y = temp; /* put temp into y */\n }\n static void Main(string[] args) {\n NumberManipulator n = new NumberManipulator();\n \n /* local variable definition */\n int a = 100;\n int b = 200;\n \n Console.WriteLine(\"Before swap, value of a : {0}\", a);\n Console.WriteLine(\"Before swap, value of b : {0}\", b);\n \n /* calling a function to swap the values */\n n.swap(a, b);\n \n Console.WriteLine(\"After swap, value of a : {0}\", a);\n Console.WriteLine(\"After swap, value of b : {0}\", b);\n \n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 3602, "s": 3521, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3717, "s": 3602, "text": "Before swap, value of a :100\nBefore swap, value of b :200\nAfter swap, value of a :100\nAfter swap, value of b :200\n" }, { "code": null, "e": 3809, "s": 3717, "text": "It shows that there is no change in the values though they had changed inside the function." }, { "code": null, "e": 3846, "s": 3809, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 3859, "s": 3846, "text": " Raja Biswas" }, { "code": null, "e": 3893, "s": 3859, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 3911, "s": 3893, "text": " Trevoir Williams" }, { "code": null, "e": 3944, "s": 3911, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 3958, "s": 3944, "text": " Peter Jepson" }, { "code": null, "e": 3995, "s": 3958, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 4010, "s": 3995, "text": " Ebenezer Ogbu" }, { "code": null, "e": 4045, "s": 4010, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 4060, "s": 4045, "text": " Arnold Higuit" }, { "code": null, "e": 4095, "s": 4060, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4107, "s": 4095, "text": " Eric Frick" }, { "code": null, "e": 4114, "s": 4107, "text": " Print" }, { "code": null, "e": 4125, "s": 4114, "text": " Add Notes" } ]
Variable number of arguments in C++
Sometimes, you may come across a situation, when you want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters. The C/C++ programming language provides a solution for this situation and you are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function. int func(int, ... ) { . . . } int main() { func(1, 2, 3); func(1, 2, 3, 4); } It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just before the ellipses is always an int which will represent the total number variable arguments passed. To use such functionality, you need to make use of stdarg.h header file which provides the functions and macros to implement the functionality of variable arguments and follow the given steps − Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments. Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments. Create a va_list type variable in the function definition. This type is defined in stdarg.h header file. Create a va_list type variable in the function definition. This type is defined in stdarg.h header file. Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file. Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file. Use va_arg macro and va_list variable to access each item in argument list. Use va_arg macro and va_list variable to access each item in argument list. Use a macro va_end to clean up the memory assigned to va_list variable. Use a macro va_end to clean up the memory assigned to va_list variable. Now let us follow the above steps and write down a simple function which can take the variable number of parameters and return their average − Live Demo #include <iostream> #include <cstdarg> using namespace std; double average(int num,...) { va_list valist; double sum = 0.0; int i; va_start(valist, num); //initialize valist for num number of arguments for (i = 0; i < num; i++) { //access all the arguments assigned to valist sum += va_arg(valist, int); } va_end(valist); //clean memory reserved for valist return sum/num; } int main() { cout << "Average of 2, 3, 4, 5 = "<< average(4, 2,3,4,5) << endl; cout << "Average of 5, 10, 15 = "<< average(3, 5,10,15)<< endl; } Average of 2, 3, 4, 5 = 3.5 Average of 5, 10, 15 = 10
[ { "code": null, "e": 1495, "s": 1062, "text": "Sometimes, you may come across a situation, when you want to have a function, which can take variable number of arguments, i.e., parameters, instead of predefined number of parameters. The C/C++ programming language provides a solution for this situation and you are allowed to define a function which can accept variable number of parameters based on your requirement. The following example shows the definition of such a function." }, { "code": null, "e": 1588, "s": 1495, "text": "int func(int, ... ) {\n .\n .\n .\n}\nint main() {\n func(1, 2, 3);\n func(1, 2, 3, 4);\n}" }, { "code": null, "e": 2003, "s": 1588, "text": "It should be noted that the function func() has its last argument as ellipses, i.e. three dotes (...) and the one just before the ellipses is always an int which will represent the total number variable arguments passed. To use such functionality, you need to make use of stdarg.h header file which provides the functions and macros to implement the functionality of variable arguments and follow the given steps −" }, { "code": null, "e": 2157, "s": 2003, "text": "Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments." }, { "code": null, "e": 2311, "s": 2157, "text": "Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments." }, { "code": null, "e": 2416, "s": 2311, "text": "Create a va_list type variable in the function definition. This type is defined in stdarg.h header file." }, { "code": null, "e": 2521, "s": 2416, "text": "Create a va_list type variable in the function definition. This type is defined in stdarg.h header file." }, { "code": null, "e": 2669, "s": 2521, "text": "Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file." }, { "code": null, "e": 2817, "s": 2669, "text": "Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file." }, { "code": null, "e": 2893, "s": 2817, "text": "Use va_arg macro and va_list variable to access each item in argument list." }, { "code": null, "e": 2969, "s": 2893, "text": "Use va_arg macro and va_list variable to access each item in argument list." }, { "code": null, "e": 3041, "s": 2969, "text": "Use a macro va_end to clean up the memory assigned to va_list variable." }, { "code": null, "e": 3113, "s": 3041, "text": "Use a macro va_end to clean up the memory assigned to va_list variable." }, { "code": null, "e": 3256, "s": 3113, "text": "Now let us follow the above steps and write down a simple function which can take the variable number of parameters and return their average −" }, { "code": null, "e": 3267, "s": 3256, "text": " Live Demo" }, { "code": null, "e": 3823, "s": 3267, "text": "#include <iostream>\n#include <cstdarg>\nusing namespace std;\ndouble average(int num,...) {\n va_list valist;\n double sum = 0.0;\n int i;\n va_start(valist, num); //initialize valist for num number of arguments\n for (i = 0; i < num; i++) { //access all the arguments assigned to valist\n sum += va_arg(valist, int);\n }\n va_end(valist); //clean memory reserved for valist\n return sum/num;\n}\nint main() {\n cout << \"Average of 2, 3, 4, 5 = \"<< average(4, 2,3,4,5) << endl;\n cout << \"Average of 5, 10, 15 = \"<< average(3, 5,10,15)<< endl;\n}" }, { "code": null, "e": 3877, "s": 3823, "text": "Average of 2, 3, 4, 5 = 3.5\nAverage of 5, 10, 15 = 10" } ]
Looping through the content of a file in Bash
Often it is a requirement to read each of the line from a file using a bash script. There are various approaches to read the lines form a file. In the below example we have first described how to create a sample file and then run a script reading that sample file. # Open vi Editor vi a_file.txt # Input the below lines Monday Tuesday Wednesday Thursday Friday Saturday Sunday # cat the file cat a_file.txt Running the above code gives us the following result − Monday Tuesday Wednesday Thursday Friday Saturday Sunday In this approach we use a do-while loop to read a file. We give the file name as an input at the end of the file. First we create a script and give the execute permission to it. Then only it can read the file and show the result. #!/bin/bash while read LINE do echo "$LINE" done < a_file.txt Running the above code gives us the following result − Monday Tuesday Wednesday Thursday Friday Saturday Sunday In next approach we use a for loop along with the in clause. Here we store the result of cat command (which is each line) in a variable which is part of for loop and echo the variable. #!/bin/bash file=a_file.txt for i in `cat $file` do echo "$i" done Running the above code gives us the following result − Monday Tuesday Wednesday Thursday Friday Saturday Sunday We can also get the content of the file by using only echo. But the result will come out as an array of lines and printed out as one-line output showing combination of all the lines. echo $( < a_file.txt ) Running the above code gives us the following result: Monday Tuesday Wednesday Thursday Friday Saturday Sunday If a file has some lines which are blank then we ca avoid them in the output by using the following code. This uses the IFS (internal Field Separator) is set to empty string so that the blank lines are treated as field separator and avoided in the output. Assuming there are blank lines between 3rd and 4th line, those blank liens will not be printed. #!/bin/bash while IFS = read -r LINE do echo "$LINE" done < a_file.txt Running the above code gives us the following result − Monday Tuesday Wednesday Thursday Friday Saturday Sunday
[ { "code": null, "e": 1327, "s": 1062, "text": "Often it is a requirement to read each of the line from a file using a bash script. There are various approaches to read the lines form a file. In the below example we have first described how to create a sample file and then run a script reading that sample file." }, { "code": null, "e": 1469, "s": 1327, "text": "# Open vi Editor\nvi a_file.txt\n# Input the below lines\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n# cat the file\ncat a_file.txt" }, { "code": null, "e": 1524, "s": 1469, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1581, "s": 1524, "text": "Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday" }, { "code": null, "e": 1811, "s": 1581, "text": "In this approach we use a do-while loop to read a file. We give the file name as an input at the end of the file. First we create a script and give the execute permission to it. Then only it can read the file and show the result." }, { "code": null, "e": 1873, "s": 1811, "text": "#!/bin/bash\nwhile read LINE\ndo echo \"$LINE\"\ndone < a_file.txt" }, { "code": null, "e": 1928, "s": 1873, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1985, "s": 1928, "text": "Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday" }, { "code": null, "e": 2170, "s": 1985, "text": "In next approach we use a for loop along with the in clause. Here we store the result of cat command (which is each line) in a variable which is part of for loop and echo the variable." }, { "code": null, "e": 2237, "s": 2170, "text": "#!/bin/bash\nfile=a_file.txt\nfor i in `cat $file`\ndo\necho \"$i\"\ndone" }, { "code": null, "e": 2292, "s": 2237, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2349, "s": 2292, "text": "Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday" }, { "code": null, "e": 2532, "s": 2349, "text": "We can also get the content of the file by using only echo. But the result will come out as an array of lines and printed out as one-line output showing combination of all the lines." }, { "code": null, "e": 2555, "s": 2532, "text": "echo $( < a_file.txt )" }, { "code": null, "e": 2609, "s": 2555, "text": "Running the above code gives us the following result:" }, { "code": null, "e": 2666, "s": 2609, "text": "Monday Tuesday Wednesday Thursday Friday Saturday Sunday" }, { "code": null, "e": 3018, "s": 2666, "text": "If a file has some lines which are blank then we ca avoid them in the output by using the following code. This uses the IFS (internal Field Separator) is set to empty string so that the blank lines are treated as field separator and avoided in the output. Assuming there are blank lines between 3rd and 4th line, those blank liens will not be printed." }, { "code": null, "e": 3089, "s": 3018, "text": "#!/bin/bash\nwhile IFS = read -r LINE\ndo echo \"$LINE\"\ndone < a_file.txt" }, { "code": null, "e": 3144, "s": 3089, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3201, "s": 3144, "text": "Monday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday" } ]
How to create everyday notifications at certain time in Android?
This example demonstrate about How to create everyday notifications at certain time in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <? xml version = "1.0" encoding = "utf-8" ?> <RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android :layout_width = "match_parent" android :layout_height = "match_parent" android :padding = "16dp" tools :context = ".MainActivity" > <TextView android :id = "@+id/tvDate" android :layout_width = "match_parent" android :layout_height = "wrap_content" android :hint = "Select Date" android :onClick = "setDate" android :padding = "16dp" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity. package app.tutorialspoint.com.notifyme ; import android.app.AlarmManager ; import android.app.DatePickerDialog ; import android.app.Notification ; import android.app.PendingIntent ; import android.content.Context ; import android.content.Intent ; import android.os.Bundle ; import android.support.v4.app.NotificationCompat ; import android.support.v7.app.AppCompatActivity ; import android.view.View ; import android.widget.Button ; import android.widget.DatePicker ; import java.text.SimpleDateFormat ; import java.util.Calendar ; import java.util.Date ; import java.util.Locale ; public class MainActivity extends AppCompatActivity { public static final String NOTIFICATION_CHANNEL_ID = "10001" ; private final static String default_notification_channel_id = "default" ; Button btnDate ; final Calendar myCalendar = Calendar. getInstance () ; @Override protected void onCreate (Bundle savedInstanceState) { super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; btnDate = findViewById(R.id. btnDate ) ; } private void scheduleNotification (Notification notification , long delay) { Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ; notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ; notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ; PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ; AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ; assert alarmManager != null; alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , delay , pendingIntent) ; } private Notification getNotification (String content) { NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ; builder.setContentTitle( "Scheduled Notification" ) ; builder.setContentText(content) ; builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ; builder.setAutoCancel( true ) ; builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ; return builder.build() ; } DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet (DatePicker view , int year , int monthOfYear , int dayOfMonth) { myCalendar .set(Calendar. YEAR , year) ; myCalendar .set(Calendar. MONTH , monthOfYear) ; myCalendar .set(Calendar. DAY_OF_MONTH , dayOfMonth) ; updateLabel() ; } } ; public void setDate (View view) { new DatePickerDialog(MainActivity. this, date , myCalendar .get(Calendar. YEAR ) , myCalendar .get(Calendar. MONTH ) , myCalendar .get(Calendar. DAY_OF_MONTH ) ).show() ; } private void updateLabel () { String myFormat = "dd/MM/yy" ; //In which you need put here SimpleDateFormat sdf = new SimpleDateFormat(myFormat , Locale. getDefault ()) ; Date date = myCalendar .getTime() ; btnDate .setText(sdf.format(date)) ; scheduleNotification(getNotification( btnDate .getText().toString()) , date.getTime()) ; } } Step 4 − Add the following code to src/MyNotificationPublisher. package app.tutorialspoint.com.notifyme ; import android.app.Notification ; import android.app.NotificationChannel ; import android.app.NotificationManager ; import android.content.BroadcastReceiver ; import android.content.Context ; import android.content.Intent ; import static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ; public class MyNotificationPublisher extends BroadcastReceiver { public static String NOTIFICATION_ID = "notification-id" ; public static String NOTIFICATION = "notification" ; public void onReceive (Context context , Intent intent) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ; Notification notification = intent.getParcelableExtra( NOTIFICATION ) ; if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) { int importance = NotificationManager. IMPORTANCE_HIGH ; NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , importance) ; assert notificationManager != null; notificationManager.createNotificationChannel(notificationChannel) ; } int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ; assert notificationManager != null; notificationManager.notify(id , notification) ; } } Step 5 − Add the following code to AndroidManifest.xml <? xml version = "1.0" encoding = "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package = "app.tutorialspoint.com.notifyme" > <uses-permission android :name = "android.permission.VIBRATE" /> <application android :allowBackup = "true" android :icon = "@mipmap/ic_launcher" android :label = "@string/app_name" android :roundIcon = "@mipmap/ic_launcher_round" android :supportsRtl = "true" android :theme = "@style/AppTheme" > <activity android :name = ".MainActivity" > <intent-filter> <action android :name = "android.intent.action.MAIN" /> <category android :name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android :name= ".MyNotificationPublisher" /> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1157, "s": 1062, "text": "This example demonstrate about How to create everyday notifications at certain time in Android" }, { "code": null, "e": 1286, "s": 1157, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1351, "s": 1286, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1941, "s": 1351, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<RelativeLayout xmlns: android = \"http://schemas.android.com/apk/res/android\"\n xmlns: tools = \"http://schemas.android.com/tools\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"match_parent\"\n android :padding = \"16dp\"\n tools :context = \".MainActivity\" >\n <TextView\n android :id = \"@+id/tvDate\"\n android :layout_width = \"match_parent\"\n android :layout_height = \"wrap_content\"\n android :hint = \"Select Date\"\n android :onClick = \"setDate\"\n android :padding = \"16dp\" />\n</RelativeLayout>" }, { "code": null, "e": 1994, "s": 1941, "text": "Step 3 − Add the following code to src/MainActivity." }, { "code": null, "e": 5270, "s": 1994, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.AlarmManager ;\nimport android.app.DatePickerDialog ;\nimport android.app.Notification ;\nimport android.app.PendingIntent ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport android.os.Bundle ;\nimport android.support.v4.app.NotificationCompat ;\nimport android.support.v7.app.AppCompatActivity ;\nimport android.view.View ;\nimport android.widget.Button ;\nimport android.widget.DatePicker ;\nimport java.text.SimpleDateFormat ;\nimport java.util.Calendar ;\nimport java.util.Date ;\nimport java.util.Locale ;\npublic class MainActivity extends AppCompatActivity {\n public static final String NOTIFICATION_CHANNEL_ID = \"10001\" ;\n private final static String default_notification_channel_id = \"default\" ;\n Button btnDate ;\n final Calendar myCalendar = Calendar. getInstance () ;\n @Override\n protected void onCreate (Bundle savedInstanceState) {\n super .onCreate(savedInstanceState) ;\n setContentView(R.layout. activity_main ) ;\n btnDate = findViewById(R.id. btnDate ) ;\n }\n private void scheduleNotification (Notification notification , long delay) {\n Intent notificationIntent = new Intent( this, MyNotificationPublisher. class ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION_ID , 1 ) ;\n notificationIntent.putExtra(MyNotificationPublisher. NOTIFICATION , notification) ;\n PendingIntent pendingIntent = PendingIntent. getBroadcast ( this, 0 , notificationIntent , PendingIntent. FLAG_UPDATE_CURRENT ) ;\n AlarmManager alarmManager = (AlarmManager) getSystemService(Context. ALARM_SERVICE ) ;\n assert alarmManager != null;\n alarmManager.set(AlarmManager. ELAPSED_REALTIME_WAKEUP , delay , pendingIntent) ;\n }\n private Notification getNotification (String content) {\n NotificationCompat.Builder builder = new NotificationCompat.Builder( this, default_notification_channel_id ) ;\n builder.setContentTitle( \"Scheduled Notification\" ) ;\n builder.setContentText(content) ;\n builder.setSmallIcon(R.drawable. ic_launcher_foreground ) ;\n builder.setAutoCancel( true ) ;\n builder.setChannelId( NOTIFICATION_CHANNEL_ID ) ;\n return builder.build() ;\n }\n DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {\n @Override\n public void onDateSet (DatePicker view , int year , int monthOfYear , int dayOfMonth) {\n myCalendar .set(Calendar. YEAR , year) ;\n myCalendar .set(Calendar. MONTH , monthOfYear) ;\n myCalendar .set(Calendar. DAY_OF_MONTH , dayOfMonth) ;\n updateLabel() ;\n }\n } ;\n public void setDate (View view) {\n new DatePickerDialog(MainActivity. this, date ,\n myCalendar .get(Calendar. YEAR ) ,\n myCalendar .get(Calendar. MONTH ) ,\n myCalendar .get(Calendar. DAY_OF_MONTH )\n ).show() ;\n }\n private void updateLabel () {\n String myFormat = \"dd/MM/yy\" ; //In which you need put here\n SimpleDateFormat sdf = new SimpleDateFormat(myFormat , Locale. getDefault ()) ;\n Date date = myCalendar .getTime() ;\n btnDate .setText(sdf.format(date)) ;\n scheduleNotification(getNotification( btnDate .getText().toString()) , date.getTime()) ;\n }\n}" }, { "code": null, "e": 5334, "s": 5270, "text": "Step 4 − Add the following code to src/MyNotificationPublisher." }, { "code": null, "e": 6726, "s": 5334, "text": "package app.tutorialspoint.com.notifyme ;\nimport android.app.Notification ;\nimport android.app.NotificationChannel ;\nimport android.app.NotificationManager ;\nimport android.content.BroadcastReceiver ;\nimport android.content.Context ;\nimport android.content.Intent ;\nimport static app.tutorialspoint.com.notifyme.MainActivity. NOTIFICATION_CHANNEL_ID ;\npublic class MyNotificationPublisher extends BroadcastReceiver {\n public static String NOTIFICATION_ID = \"notification-id\" ;\n public static String NOTIFICATION = \"notification\" ;\n public void onReceive (Context context , Intent intent) {\n NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context. NOTIFICATION_SERVICE ) ;\n Notification notification = intent.getParcelableExtra( NOTIFICATION ) ;\n if (android.os.Build.VERSION. SDK_INT >= android.os.Build.VERSION_CODES. O ) {\n int importance = NotificationManager. IMPORTANCE_HIGH ;\n NotificationChannel notificationChannel = new NotificationChannel( NOTIFICATION_CHANNEL_ID , \"NOTIFICATION_CHANNEL_NAME\" , importance) ;\n assert notificationManager != null;\n notificationManager.createNotificationChannel(notificationChannel) ;\n }\n int id = intent.getIntExtra( NOTIFICATION_ID , 0 ) ;\n assert notificationManager != null;\n notificationManager.notify(id , notification) ;\n }\n}" }, { "code": null, "e": 6781, "s": 6726, "text": "Step 5 − Add the following code to AndroidManifest.xml" }, { "code": null, "e": 7641, "s": 6781, "text": "<? xml version = \"1.0\" encoding = \"utf-8\" ?>\n<manifest xmlns: android = \"http://schemas.android.com/apk/res/android\"\n package = \"app.tutorialspoint.com.notifyme\" >\n <uses-permission android :name = \"android.permission.VIBRATE\" />\n <application\n android :allowBackup = \"true\"\n android :icon = \"@mipmap/ic_launcher\"\n android :label = \"@string/app_name\"\n android :roundIcon = \"@mipmap/ic_launcher_round\"\n android :supportsRtl = \"true\"\n android :theme = \"@style/AppTheme\" >\n <activity android :name = \".MainActivity\" >\n <intent-filter>\n <action android :name = \"android.intent.action.MAIN\" />\n <category android :name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n <receiver android :name= \".MyNotificationPublisher\" />\n </application>\n</manifest>" }, { "code": null, "e": 7988, "s": 7641, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 8030, "s": 7988, "text": "Click here to download the project code" } ]
How to get the list of local groups using PowerShell?
To get the local groups on the windows system using PowerShell, you can use the Get-LocalGroup (Module: Microsoft.PowerShell.LocalAccounts) command. This command will list down all the groups on the particular system. If we check the properties of this command, it supports Name, Description, ObjectClass (user or group), PrincipalSource (ComputerName – Local or Remote), SID (Security Identifier). We will select them, PS C:\> Get-LocalGroup | Select Name, Objectclass, Principalsource,sid Name ObjectClass PrincipalSource SID ---- ----------- --------------- --- LocalAdminGroup Group S-1-5-21- 3679408808-4189780139-2861908768-1003 Access Control Assistance Operators Group S-1-5-32-579 Administrators Group S-1-5-32-544 Backup Operators Group S-1-5-32-551 Certificate Service DCOM Access Group S-1-5-32-574 Cryptographic Operators Group S-1-5-32-569 Distributed COM Users Group S-1-5-32-562 Event Log Readers Group S-1-5-32-573 Guests Group S-1-5-32-546 Hyper-V Administrators Group S-1-5-32-578 IIS_IUSRS Group S-1-5-32-568 You can retrieve the Local Groups information on the remote system using the Invoke-Command method. Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{ Get-LocalGroup} Please note − This command supports from the PS version 5.1 onwards. For the earlier versions, we can use the cmd command “Net LocalGroup”. For example, PS C:\Users\Administrator> net localgroup Aliases for \\ADDC ------------------------------------------------------------------ *Access Control Assistance Operators *Account Operators *Administrators *Allowed RODC Password Replication Group *Backup Operators *Cert Publishers *Certificate Service DCOM Access *Cryptographic Operators *Denied RODC Password Replication Group *Distributed COM Users *DnsAdmins *Event Log Readers *Guests *Hyper-V Administrators *IIS_IUSRS *Incoming Forest Trust Builders *LocalAdminGroup *Network Configuration Operators *Performance Log Users *Performance Monitor Users *Pre-Windows 2000 Compatible Access *Print Operators *RAS and IAS Servers *RDS Endpoint Servers On the remote server, Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Net localgroup} Please note − To run the above command, Remote servers must use the PowerShell version 5.1 or the advanced.
[ { "code": null, "e": 1280, "s": 1062, "text": "To get the local groups on the windows system using PowerShell, you can use the Get-LocalGroup (Module: Microsoft.PowerShell.LocalAccounts) command. This command will list down all the groups on the particular system." }, { "code": null, "e": 1461, "s": 1280, "text": "If we check the properties of this command, it supports Name, Description, ObjectClass (user or group), PrincipalSource (ComputerName – Local or Remote), SID (Security Identifier)." }, { "code": null, "e": 1482, "s": 1461, "text": "We will select them," }, { "code": null, "e": 2803, "s": 1482, "text": "PS C:\\> Get-LocalGroup | Select Name, Objectclass, Principalsource,sid\nName ObjectClass PrincipalSource SID\n---- ----------- --------------- ---\nLocalAdminGroup Group S-1-5-21-\n3679408808-4189780139-2861908768-1003\nAccess Control Assistance Operators Group S-1-5-32-579\nAdministrators Group S-1-5-32-544\nBackup Operators Group S-1-5-32-551\nCertificate Service DCOM Access Group S-1-5-32-574\nCryptographic Operators Group S-1-5-32-569\nDistributed COM Users Group S-1-5-32-562\nEvent Log Readers Group S-1-5-32-573\nGuests Group S-1-5-32-546\nHyper-V Administrators Group S-1-5-32-578\nIIS_IUSRS Group S-1-5-32-568" }, { "code": null, "e": 2903, "s": 2803, "text": "You can retrieve the Local Groups information on the remote system using the Invoke-Command method." }, { "code": null, "e": 2976, "s": 2903, "text": "Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{ Get-LocalGroup}" }, { "code": null, "e": 3129, "s": 2976, "text": "Please note − This command supports from the PS version 5.1 onwards. For the earlier versions, we can use the cmd command “Net LocalGroup”. For example," }, { "code": null, "e": 3827, "s": 3129, "text": "PS C:\\Users\\Administrator> net localgroup\nAliases for \\\\ADDC\n------------------------------------------------------------------\n*Access Control Assistance Operators\n*Account Operators\n*Administrators\n*Allowed RODC Password Replication Group\n*Backup Operators\n*Cert Publishers\n*Certificate Service DCOM Access\n*Cryptographic Operators\n*Denied RODC Password Replication Group\n*Distributed COM Users\n*DnsAdmins\n*Event Log Readers\n*Guests\n*Hyper-V Administrators\n*IIS_IUSRS\n*Incoming Forest Trust Builders\n*LocalAdminGroup\n*Network Configuration Operators\n*Performance Log Users\n*Performance Monitor Users\n*Pre-Windows 2000 Compatible Access\n*Print Operators\n*RAS and IAS Servers\n*RDS Endpoint Servers" }, { "code": null, "e": 3849, "s": 3827, "text": "On the remote server," }, { "code": null, "e": 3921, "s": 3849, "text": "Invoke-Command -ComputerName Test1-Win2k16 -ScriptBlock{Net localgroup}" }, { "code": null, "e": 4029, "s": 3921, "text": "Please note − To run the above command, Remote servers must use the PowerShell version 5.1 or the advanced." } ]
How to remove the outline of an oval in Tkinter?
With Tkinter canvas, we can draw shapes for 2D or 3D applications, we can create images, draw animation, and many more things. Let us suppose that we have to create an oval that should be drawn aesthetically on the canvas. There can be other features that can be present to give the oval and other shapes an aesthetic look. To remove the outlining from the shapes in the canvas, we can provide an empty value to the outline property in the method. #Import tkinter library from tkinter import * #Create an instance of tkinter frame or window win= Tk() #Set the geometry of tkinter frame win.geometry("750x350") #Create a canvas and an oval canvas= Canvas(win, width=400, height=350,bg= "#458a4a") canvas.create_oval(50,50,250,250, fill="white", outline="") canvas.pack() win.mainloop() Now, execute the code to display the output that contains an oval inside the canvas.
[ { "code": null, "e": 1510, "s": 1062, "text": "With Tkinter canvas, we can draw shapes for 2D or 3D applications, we can create images, draw animation, and many more things. Let us suppose that we have to create an oval that should be drawn aesthetically on the canvas. There can be other features that can be present to give the oval and other shapes an aesthetic look. To remove the outlining from the shapes in the canvas, we can provide an empty value to the outline property in the method." }, { "code": null, "e": 1847, "s": 1510, "text": "#Import tkinter library\nfrom tkinter import *\n#Create an instance of tkinter frame or window\nwin= Tk()\n#Set the geometry of tkinter frame\nwin.geometry(\"750x350\")\n#Create a canvas and an oval\ncanvas= Canvas(win, width=400, height=350,bg= \"#458a4a\")\ncanvas.create_oval(50,50,250,250, fill=\"white\", outline=\"\")\ncanvas.pack()\nwin.mainloop()" }, { "code": null, "e": 1932, "s": 1847, "text": "Now, execute the code to display the output that contains an oval inside the canvas." } ]
Create DataFrame Row by Row in R - GeeksforGeeks
27 Jun, 2021 In this article, we will discuss how to create dataframe row by row in R Programming Language. An empty data frame in R language can be created using the data.frame() method in R. For better clarity, the data types of the columns can be defined during the declaration. Each row of the data frame is a vector consisting of values belonging to different columns. The ith row in the data frame can then be assigned to this vector. Syntax: dataframe[ i, ] <- vec The rows are appended to the end of the data frame. The addition of rows can also be done in a for loop, with the loop iterations equivalent to the number of rows to add. The length of the vector appended should be equivalent to the number of columns in the data frame. Example: R # declaring an empty data framedata_frame = data.frame( col1 = numeric(), col2 = character(),stringsAsFactors = FALSE)print ("Original dataframe")print (data_frame) # appending rows to the data framefor(i in 1:3) { # creating a vector to append to # data frame vec <- c(i+1, LETTERS[i]) # assigning this vector to ith row data_frame[i, ] <- vec } print ("Modified dataframe")print (data_frame) Output [1] "Original dataframe" [1] col1 col2 <0 rows> (or 0-length row.names) [1] "Modified dataframe" col1 col2 1 2 A 2 3 B 3 4 C The rows in an empty data frame can also be inserted using the row index reference. After each iteration, a new row is appended to the data frame. Modifications are made to the original data frame. Example: R # declaring an empty data framedata_frame = data.frame(col1 = numeric(), col2 = character(), stringsAsFactors = FALSE) print ("Original dataframe")print (data_frame) # appending rows to the data framedata_frame[1,] <- c(1,"firstrow") print ("Dataframe : Iteration 1")print (data_frame) # appending rows to the data framedata_frame[2,] <- c(2,"secondrow")print ("Dataframe : Iteration 2")print (data_frame) data_frame[3,] <- c(3,"thirdrow")print ("Dataframe : Iteration 3")print (data_frame) Output [1] "Original dataframe" [1] col1 col2 <0 rows> (or 0-length row.names) [1] "Dataframe : Iteration 1" col1 col2 1 1 firstrow [1] "Dataframe : Iteration 2" col1 col2 1 1 firstrow 2 2 secondrow [1] "Dataframe : Iteration 3" col1 col2 1 1 firstrow 2 2 secondrow 3 3 thirdrow The current number of rows of the data frame can be captured by the nrow(dataframe) method. An individual row can be added to the data frame at the nrow(df)+1 index. Syntax: df[ nrow(df)+1, ] <- vec Example: R # declaring an empty data framedata_frame = data.frame(col1 = c(2:3), col2 = letters[1:2], stringsAsFactors = FALSE) print ("Original dataframe")print (data_frame) # appending rows at the endvec <- c(8,"n")data_frame[nrow(data_frame)+1,] <- vec print ("Modified dataframe")print (data_frame) Output [1] "Original dataframe" col1 col2 1 2 a 2 3 b [1] "Modified dataframe" col1 col2 1 2 a 2 3 b 3 8 n rbind() method is used to bind vectors or data frame objects together to form a larger object. Initially, we can create an empty data frame and then define a new row using a vector, and bind the declared row to the data frame using the rbind() method. The new row is appended at the end. The data types of the row should be compatible with the data types declared for the original data frame. This can be enclosed within a loop to bind rows during each loop iteration. Syntax: rbind(df , vec) Example: R # declaring an empty data framedata_frame = data.frame(col1 = numeric(), col2 = character(), stringsAsFactors = FALSE) print ("Original dataframe")print (data_frame) # appending rows at the endvec <- c(8,"n") # binding row at the end of the data framedata_frame <- rbind(data_frame,vec,stringsAsFactors = FALSE) print ("Modified dataframe")print (data_frame) Output [1] "Original dataframe" [1] col1 col2 <0 rows> (or 0-length row.names) [1] "Modified dataframe" X.8. X.n. 1 8 n A data frame can also be created row by row, using repeated rbind() operations on the data frame in the for loop, with number of iterations equivalent to the number of rows to insert. Example: R # declaring an empty data framedata_frame = data.frame(col1 = numeric(), col2 = character(), stringsAsFactors = FALSE) print ("Original dataframe")print (data_frame) # appending rows at the endfor(i in 1:3) { # creating a vector to append # to data frame vec <- c(i, LETTERS[i]) # assigning this vector to ith row data_frame <- rbind(data_frame,vec,stringsAsFactors=FALSE)} print ("Modified dataframe")print (data_frame) Output [1] "Original dataframe" [1] col1 col2 <0 rows> (or 0-length row.names) [1] "Modified dataframe" X.1. X.A. 1 1 A 2 2 B 3 3 C anikakapoor 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. Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to change Row Names of DataFrame in R ? Remove rows with NA in one column of R DataFrame How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 24618, "s": 24590, "text": "\n27 Jun, 2021" }, { "code": null, "e": 24713, "s": 24618, "text": "In this article, we will discuss how to create dataframe row by row in R Programming Language." }, { "code": null, "e": 25047, "s": 24713, "text": "An empty data frame in R language can be created using the data.frame() method in R. For better clarity, the data types of the columns can be defined during the declaration. Each row of the data frame is a vector consisting of values belonging to different columns. The ith row in the data frame can then be assigned to this vector. " }, { "code": null, "e": 25055, "s": 25047, "text": "Syntax:" }, { "code": null, "e": 25078, "s": 25055, "text": "dataframe[ i, ] <- vec" }, { "code": null, "e": 25350, "s": 25078, "text": "The rows are appended to the end of the data frame. The addition of rows can also be done in a for loop, with the loop iterations equivalent to the number of rows to add. The length of the vector appended should be equivalent to the number of columns in the data frame. " }, { "code": null, "e": 25359, "s": 25350, "text": "Example:" }, { "code": null, "e": 25361, "s": 25359, "text": "R" }, { "code": "# declaring an empty data framedata_frame = data.frame( col1 = numeric(), col2 = character(),stringsAsFactors = FALSE)print (\"Original dataframe\")print (data_frame) # appending rows to the data framefor(i in 1:3) { # creating a vector to append to # data frame vec <- c(i+1, LETTERS[i]) # assigning this vector to ith row data_frame[i, ] <- vec } print (\"Modified dataframe\")print (data_frame)", "e": 25801, "s": 25361, "text": null }, { "code": null, "e": 25808, "s": 25801, "text": "Output" }, { "code": null, "e": 25952, "s": 25808, "text": "[1] \"Original dataframe\"\n[1] col1 col2\n<0 rows> (or 0-length row.names)\n[1] \"Modified dataframe\"\n col1 col2\n1 2 A\n2 3 B\n3 4 C" }, { "code": null, "e": 26150, "s": 25952, "text": "The rows in an empty data frame can also be inserted using the row index reference. After each iteration, a new row is appended to the data frame. Modifications are made to the original data frame." }, { "code": null, "e": 26159, "s": 26150, "text": "Example:" }, { "code": null, "e": 26161, "s": 26159, "text": "R" }, { "code": "# declaring an empty data framedata_frame = data.frame(col1 = numeric(), col2 = character(), stringsAsFactors = FALSE) print (\"Original dataframe\")print (data_frame) # appending rows to the data framedata_frame[1,] <- c(1,\"firstrow\") print (\"Dataframe : Iteration 1\")print (data_frame) # appending rows to the data framedata_frame[2,] <- c(2,\"secondrow\")print (\"Dataframe : Iteration 2\")print (data_frame) data_frame[3,] <- c(3,\"thirdrow\")print (\"Dataframe : Iteration 3\")print (data_frame)", "e": 26698, "s": 26161, "text": null }, { "code": null, "e": 26705, "s": 26698, "text": "Output" }, { "code": null, "e": 27015, "s": 26705, "text": "[1] \"Original dataframe\"\n[1] col1 col2\n<0 rows> (or 0-length row.names)\n[1] \"Dataframe : Iteration 1\"\n col1 col2\n1 1 firstrow\n[1] \"Dataframe : Iteration 2\"\n col1 col2\n1 1 firstrow\n2 2 secondrow\n[1] \"Dataframe : Iteration 3\"\n col1 col2\n1 1 firstrow\n2 2 secondrow\n3 3 thirdrow" }, { "code": null, "e": 27182, "s": 27015, "text": "The current number of rows of the data frame can be captured by the nrow(dataframe) method. An individual row can be added to the data frame at the nrow(df)+1 index. " }, { "code": null, "e": 27190, "s": 27182, "text": "Syntax:" }, { "code": null, "e": 27215, "s": 27190, "text": "df[ nrow(df)+1, ] <- vec" }, { "code": null, "e": 27224, "s": 27215, "text": "Example:" }, { "code": null, "e": 27226, "s": 27224, "text": "R" }, { "code": "# declaring an empty data framedata_frame = data.frame(col1 = c(2:3), col2 = letters[1:2], stringsAsFactors = FALSE) print (\"Original dataframe\")print (data_frame) # appending rows at the endvec <- c(8,\"n\")data_frame[nrow(data_frame)+1,] <- vec print (\"Modified dataframe\")print (data_frame)", "e": 27564, "s": 27226, "text": null }, { "code": null, "e": 27571, "s": 27564, "text": "Output" }, { "code": null, "e": 27703, "s": 27571, "text": "[1] \"Original dataframe\"\n col1 col2\n1 2 a\n2 3 b\n[1] \"Modified dataframe\"\n col1 col2\n1 2 a\n2 3 b\n3 8 n" }, { "code": null, "e": 28173, "s": 27703, "text": "rbind() method is used to bind vectors or data frame objects together to form a larger object. Initially, we can create an empty data frame and then define a new row using a vector, and bind the declared row to the data frame using the rbind() method. The new row is appended at the end. The data types of the row should be compatible with the data types declared for the original data frame. This can be enclosed within a loop to bind rows during each loop iteration. " }, { "code": null, "e": 28181, "s": 28173, "text": "Syntax:" }, { "code": null, "e": 28197, "s": 28181, "text": "rbind(df , vec)" }, { "code": null, "e": 28206, "s": 28197, "text": "Example:" }, { "code": null, "e": 28208, "s": 28206, "text": "R" }, { "code": "# declaring an empty data framedata_frame = data.frame(col1 = numeric(), col2 = character(), stringsAsFactors = FALSE) print (\"Original dataframe\")print (data_frame) # appending rows at the endvec <- c(8,\"n\") # binding row at the end of the data framedata_frame <- rbind(data_frame,vec,stringsAsFactors = FALSE) print (\"Modified dataframe\")print (data_frame)", "e": 28613, "s": 28208, "text": null }, { "code": null, "e": 28620, "s": 28613, "text": "Output" }, { "code": null, "e": 28741, "s": 28620, "text": "[1] \"Original dataframe\"\n[1] col1 col2\n<0 rows> (or 0-length row.names)\n[1] \"Modified dataframe\"\n X.8. X.n.\n1 8 n" }, { "code": null, "e": 28925, "s": 28741, "text": "A data frame can also be created row by row, using repeated rbind() operations on the data frame in the for loop, with number of iterations equivalent to the number of rows to insert." }, { "code": null, "e": 28934, "s": 28925, "text": "Example:" }, { "code": null, "e": 28936, "s": 28934, "text": "R" }, { "code": "# declaring an empty data framedata_frame = data.frame(col1 = numeric(), col2 = character(), stringsAsFactors = FALSE) print (\"Original dataframe\")print (data_frame) # appending rows at the endfor(i in 1:3) { # creating a vector to append # to data frame vec <- c(i, LETTERS[i]) # assigning this vector to ith row data_frame <- rbind(data_frame,vec,stringsAsFactors=FALSE)} print (\"Modified dataframe\")print (data_frame)", "e": 29413, "s": 28936, "text": null }, { "code": null, "e": 29420, "s": 29413, "text": "Output" }, { "code": null, "e": 29565, "s": 29420, "text": "[1] \"Original dataframe\"\n[1] col1 col2\n<0 rows> (or 0-length row.names)\n[1] \"Modified dataframe\"\n X.1. X.A.\n1 1 A\n2 2 B\n3 3 C" }, { "code": null, "e": 29577, "s": 29565, "text": "anikakapoor" }, { "code": null, "e": 29584, "s": 29577, "text": "Picked" }, { "code": null, "e": 29605, "s": 29584, "text": "R DataFrame-Programs" }, { "code": null, "e": 29617, "s": 29605, "text": "R-DataFrame" }, { "code": null, "e": 29628, "s": 29617, "text": "R Language" }, { "code": null, "e": 29639, "s": 29628, "text": "R Programs" }, { "code": null, "e": 29737, "s": 29639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29789, "s": 29737, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 29821, "s": 29789, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 29873, "s": 29821, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29917, "s": 29873, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 29955, "s": 29917, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29999, "s": 29955, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 30048, "s": 29999, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 30106, "s": 30048, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30155, "s": 30106, "text": "How to filter R DataFrame by values in a column?" } ]
Program to calculate value of nCr in C++
Given with n C r, where C represents combination, n represents total numbers and r represents selection from the set, the task is to calculate the value of nCr. Combination is the selection of data from the given in a without the concern of arrangement. Permutation and combination differs in the sense that permutation is the process of arranging whereas combination is the process of selection of elements from the given set. Formula for permutation is -: nPr = (n!)/(r!*(n-r)!) Input-: n=12 r=4 Output-: value of 12c4 is :495 Start Step 1 -> Declare function for calculating factorial int cal_n(int n) int temp = 1 Loop for int i = 2 and i <= n and i++ Set temp = temp * i End return temp step 2 -> declare function to calculate ncr int nCr(int n, int r) return cal_n(n) / (cal_n(r) * cal_n(n - r)) step 3 -> In main() declare variable as int n = 12, r = 4 print nCr(n, r) Stop #include <bits/stdc++.h> using namespace std; //it will calculate factorial for n int cal_n(int n){ int temp = 1; for (int i = 2; i <= n; i++) temp = temp * i; return temp; } //function to calculate ncr int nCr(int n, int r){ return cal_n(n) / (cal_n(r) * cal_n(n - r)); } int main(){ int n = 12, r = 4; cout <<"value of "<<n<<"c"<<r<<" is :"<<nCr(n, r); return 0; } value of 12c4 is :495
[ { "code": null, "e": 1223, "s": 1062, "text": "Given with n C r, where C represents combination, n represents total numbers and r represents selection from the set, the task is to calculate the value of nCr." }, { "code": null, "e": 1490, "s": 1223, "text": "Combination is the selection of data from the given in a without the concern of arrangement. Permutation and combination differs in the sense that permutation is the process of arranging whereas combination is the process of selection of elements from the given set." }, { "code": null, "e": 1520, "s": 1490, "text": "Formula for permutation is -:" }, { "code": null, "e": 1543, "s": 1520, "text": "nPr = (n!)/(r!*(n-r)!)" }, { "code": null, "e": 1591, "s": 1543, "text": "Input-: n=12 r=4\nOutput-: value of 12c4 is :495" }, { "code": null, "e": 1979, "s": 1591, "text": "Start\nStep 1 -> Declare function for calculating factorial\n int cal_n(int n)\n int temp = 1\n Loop for int i = 2 and i <= n and i++\n Set temp = temp * i\n End\n return temp\nstep 2 -> declare function to calculate ncr\n int nCr(int n, int r)\n return cal_n(n) / (cal_n(r) * cal_n(n - r))\nstep 3 -> In main()\n declare variable as int n = 12, r = 4\n print nCr(n, r)\nStop" }, { "code": null, "e": 2373, "s": 1979, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//it will calculate factorial for n\nint cal_n(int n){\n int temp = 1;\n for (int i = 2; i <= n; i++)\n temp = temp * i;\n return temp;\n}\n//function to calculate ncr\nint nCr(int n, int r){\n return cal_n(n) / (cal_n(r) * cal_n(n - r));\n}\nint main(){\n int n = 12, r = 4;\n cout <<\"value of \"<<n<<\"c\"<<r<<\" is :\"<<nCr(n, r);\n return 0;\n}" }, { "code": null, "e": 2395, "s": 2373, "text": "value of 12c4 is :495" } ]
JSF - h:outputStylesheet
The h:outputStylesheet tag renders an HTML element of the type "link" with type "text/css". This tag is used to add external stylesheet file to JSF page. <h:outputStylesheet library = "css" name = "styles.css" /> <link type = "text/css" rel = "stylesheet" href = "/helloworld/javax.faces.resource/styles.css.jsf?ln = css" /> Let us create a test JSF application to test the above tag. .message{ color:green; } <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint.test</groupId> <artifactId>helloworld</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>helloworld Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.1.7</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>helloworld</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <executions> <execution> <id>copy-resources</id> <phase>validate</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/helloworld/resources </outputDirectory> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <h:head> <title>JSF Tutorial!</title> <h:outputStylesheet library = "css" name = "styles.css" /> </h:head> <h:body> <h2>h:outputStylesheet example</h2> <hr /> <h:form> <div class = "message">Hello World!</div> </h:form> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2106, "s": 1952, "text": "The h:outputStylesheet tag renders an HTML element of the type \"link\" with type \"text/css\". This tag is used to add external stylesheet file to JSF page." }, { "code": null, "e": 2166, "s": 2106, "text": "<h:outputStylesheet library = \"css\" name = \"styles.css\" /> " }, { "code": null, "e": 2284, "s": 2166, "text": "<link type = \"text/css\" rel = \"stylesheet\" \n href = \"/helloworld/javax.faces.resource/styles.css.jsf?ln = css\" /> " }, { "code": null, "e": 2344, "s": 2284, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 2372, "s": 2344, "text": ".message{\n color:green;\n}" }, { "code": null, "e": 4951, "s": 2372, "text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/maven-v4_0_0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.test</groupId>\n <artifactId>helloworld</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>helloworld Maven Webapp</name>\n <url>http://maven.apache.org</url>\n \n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>javax.servlet</groupId>\n <artifactId>jstl</artifactId>\n <version>1.2</version>\n </dependency>\n </dependencies>\n \n <build>\n <finalName>helloworld</finalName>\n <plugins>\n \n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.1</version>\n <configuration>\n <source>1.6</source>\n <target>1.6</target>\n </configuration>\n </plugin>\n \n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <version>2.6</version>\n <executions>\n <execution>\n <id>copy-resources</id>\n <phase>validate</phase>\n <goals>\n <goal>copy-resources</goal>\n </goals>\n \n <configuration>\n <outputDirectory>${basedir}/target/helloworld/resources\n </outputDirectory>\n <resources> \n <resource>\n <directory>src/main/resources</directory>\n <filtering>true</filtering>\n </resource>\n </resources> \n </configuration> \n </execution>\n </executions>\n </plugin>\n \n </plugins>\n </build>\n</project>" }, { "code": null, "e": 5566, "s": 4951, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title>\n <h:outputStylesheet library = \"css\" name = \"styles.css\" /> \n </h:head>\n \n <h:body>\n <h2>h:outputStylesheet example</h2>\n <hr />\n <h:form>\n <div class = \"message\">Hello World!</div>\n </h:form> \t\t\n </h:body>\n\n</html> " }, { "code": null, "e": 5782, "s": 5566, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 5817, "s": 5782, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5832, "s": 5817, "text": " Chaand Sheikh" }, { "code": null, "e": 5839, "s": 5832, "text": " Print" }, { "code": null, "e": 5850, "s": 5839, "text": " Add Notes" } ]
Real-time and video processing object detection using Tensorflow, OpenCV and Docker. | by Léo Beaucourt | Towards Data Science
In this article, I will present how I managed to use Tensorflow Object-detection API in a Docker container to perform both real-time (webcam) and video post-processing. I used OpenCV with python3 multiprocessing and multi-threading libraries. I will focus on hurdles I have encountered, and what solutions I have found (or not!). The full code is on my Github. I started from this excellent Dat Tran article to explore the real-time object detection challenge, leading me to study python multiprocessing library to increase FPS with the Adrian Rosebrock’s website. To go further and in order to enhance portability, I wanted to integrate my project into a Docker container. Main difficulty here was to deal with video stream going into and coming from the container. In addition, I added a video post-processing feature to my project also using multiprocessing to reduce processing time (which could be very very long when using raw Tensorflow object detection API). Both real-time and video processing can run with high performances on my personal laptop using only 8GB CPU. I will not spend time describing Tensorflow object-detection API implementation, since there is ton of articles on this subject. Instead, I will show how I use Docker in my all-day jobs as data scientist. Just note that I used the classical ssd_mobilenet_v2_coco model from Tensorflow for speed performance. I copy the model (the .pb file) and the corresponding label map locally (in the model/ directory) to keep the possibility to use personal model later. I believe that using Docker today become a primary data scientist skill. In data science and machine learning world, lots of new algorithms, tools and programs are released every weeks and install them on your computer to test them is the best way to crash your OS (experienced!). To prevent this, I now use Docker containers to create my data science workspaces. You can find on my repository the Dockerfile I’m working with for this project. Here is how I installed Tensorflow object-detection (follow the official installation guide): # Install tensorFlowRUN pip install -U tensorflow# Install tensorflow models object detectionRUN git clone https://github.com/tensorflow/models /usr/local/lib/python3.5/dist-packages/tensorflow/modelsRUN apt-get install -y protobuf-compiler python-pil python-lxml python-tk#Set TF object detection availableENV PYTHONPATH "$PYTHONPATH:/usr/local/lib/python3.5/dist-packages/tensorflow/models/research:/usr/local/lib/python3.5/dist-packages/tensorflow/models/research/slim"RUN cd /usr/local/lib/python3.5/dist-packages/tensorflow/models/research && protoc object_detection/protos/*.proto --python_out=. Similarly, I installed OpenCV: # Install OpenCVRUN git clone https://github.com/opencv/opencv.git /usr/local/src/opencvRUN cd /usr/local/src/opencv/ && mkdir buildRUN cd /usr/local/src/opencv/build && cmake -D CMAKE_INSTALL_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local/ .. && make -j4 && make install Image building is a bit long and take several minutes. Then, using it is quick and easy. I first try to apply object detection to my webcam stream. The main part of this work is fully described in the Dat Tran’s article. The difficulty was to send the webcam stream into the docker container and recover the output stream to display it using X11 server. With Linux, devices are found in the /dev/ directory and can be manipulated as files. Commonly, your laptop webcam is the “0” device. To send its stream into docker container, use the device argument when running the docker image: docker run --device=/dev/video0 For Mac and Windows users, the way to send the webcam stream into containers is not as simple as for Linux (despite Mac is based on Unix). I have not dug so much into this problem, but the solution for Windows user would be to use Virtual Box to launch the docker container. Here is the point which takes me some time to resolve (with an unsatisfactory solution). I found useful information on using graphical user interfaces with Docker here, in particular to connect a container to a host’s X server for display. First, you must expose your xhost so that the container can render to the correct display by reading and writing though the X11 unix socket. Start by setting the permissions of the X server host (this is not the safest way to do it) to let docker access it: xhost +local:docker Then, once you are finished using the project, return the access controls at their default value: xhost -local:docker Then, create two environment variables XSOCK and XAUTH: XSOCK=/tmp/.X11-unixXAUTH=/tmp/.docker.xauth The first refers to the X11 Unix socket, the second refers to an X authentication file with proper permissions we create now: xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge - Finally, we just have to update our docker run line command. We forward our DISPLAY environment variable, mount a volume for the X11 Unix socket and the X authentication file with an environment variable called XAUTHORITY which link to it: docker run -it --rm --device=/dev/video0 -e DISPLAY=$DISPLAY -v $XSOCK:$XSOCK -v $XAUTH:$XAUTH -e XAUTHORITY=$XAUTH Now we could run our docker container and it’s done: Despite the host’s X server configuration, I was not able do completely remove what seems to be a bug in my code. OpenCV need to be “initialize” by calling a python script (init-openCV.py) using the cv2.imshow function. I get the following error message: The program 'frame' received an X Window System error. Then, it is possible to call the main python script (my-object-detection.py) and the video stream is well sent to the host display. I’m not very satisfied with the solution of using a first python script to initialize the X11 system, but I have not found anything that solves this problem so far. EDIT: I finally (and accidentally!) found a solution to this problem by using a stable version of OpenCV (3.4.1) instead of cloning the git repo locally. Therefore, there is no need now to call the init-openCV.py before the main python script. To manage to run the object-detection API in real-time with my webcam, I used the threading and multiprocessing python libraries. A thread is used to read the webcam stream. Frames are put into a queue to be processed by a pool of workers (in which Tensorflow object-detection is running). For video processing purpose, it is not possible to use threading since all video’s frames are read before workers are able to apply object-detection on first ones put in the input queue. Frames which are read when input queue is full are lost. Maybe using a lot of workers and huge queues may resolve the problem (with a prohibitive computational cost). Another problem with simple queue is that frames are not published in output queue with the same order as in the input queue, due to ever-changing analysis time. To add my video processing feature, I remove the thread to read frames. Instead, I used the following lines of codes to read frames: while True: # Check input queue is not full if not input_q.full(): # Read frame and store in input queue ret, frame = vs.read() if ret: input_q.put((int(vs.get(cv2.CAP_PROP_POS_FRAMES)),frame)) If the input queue is not full, the next frame is read from the video stream and put into the queue. Else, nothing is done while a frame is not getting from the input queue. To address the problem of frame order, I used a priority queue as a second output queue: Frames are read and put into the input queue with their corresponding frame numbers (in fact a python list object is put into the queue).Then, workers take frames from the input queue, treat them and put them into the first output queue (still with their relative frame number). Frames are read and put into the input queue with their corresponding frame numbers (in fact a python list object is put into the queue). Then, workers take frames from the input queue, treat them and put them into the first output queue (still with their relative frame number). while True: frame = input_q.get()frame_rgb = cv2.cvtColor(frame[1], cv2.COLOR_BGR2RGB) output_q.put((frame[0], detect_objects(frame_rgb, sess, detection_graph))) 3. If output queue is not empty, frames are extracted and put into the priority queue with their corresponding frame number as a priority number. The size of the priority queue is set, arbitrary, to three times the size of the others queues. # Check output queue is not emptyif not output_q.empty(): # Recover treated frame in output queue and feed priority queue output_pq.put(output_q.get()) 4. Finally, if output priority queue is not empty, the frame with the highest priority (smallest prior number) is taken (this is the standard priority queue working). If the prior corresponds to the expected frame number, the frame is added to the output video stream (and write if needed), else the frame is put back into the priority queue. # Check output priority queue is not empty if not output_pq.empty(): prior, output_frame = output_pq.get() if prior > countWriteFrame: output_pq.put((prior, output_frame)) else: countWriteFrame = countWriteFrame + 1 # Do something with your frame To stop the process, I check that all queues are empty and that all frames have been extracted from the video stream: if((not ret) & input_q.empty() & output_q.empty() & output_pq.empty()): break In this article, I present how I used docker to implement a real-time object-detection project with Tensorflow. As said, docker is the safest way to test new data science tools as well as to package the solution we deliver to customers. I also show you how I have adapted the original python script from Dat Tran to perform video processing with multiprocessing. Thanks you if you read this article from the beginning to end! As you have seen, there are lots of possible improvement with this project. Don’t hesitate to give me some feedback, I’m always keen to get advices or comments.
[ { "code": null, "e": 290, "s": 47, "text": "In this article, I will present how I managed to use Tensorflow Object-detection API in a Docker container to perform both real-time (webcam) and video post-processing. I used OpenCV with python3 multiprocessing and multi-threading libraries." }, { "code": null, "e": 408, "s": 290, "text": "I will focus on hurdles I have encountered, and what solutions I have found (or not!). The full code is on my Github." }, { "code": null, "e": 814, "s": 408, "text": "I started from this excellent Dat Tran article to explore the real-time object detection challenge, leading me to study python multiprocessing library to increase FPS with the Adrian Rosebrock’s website. To go further and in order to enhance portability, I wanted to integrate my project into a Docker container. Main difficulty here was to deal with video stream going into and coming from the container." }, { "code": null, "e": 1014, "s": 814, "text": "In addition, I added a video post-processing feature to my project also using multiprocessing to reduce processing time (which could be very very long when using raw Tensorflow object detection API)." }, { "code": null, "e": 1123, "s": 1014, "text": "Both real-time and video processing can run with high performances on my personal laptop using only 8GB CPU." }, { "code": null, "e": 1582, "s": 1123, "text": "I will not spend time describing Tensorflow object-detection API implementation, since there is ton of articles on this subject. Instead, I will show how I use Docker in my all-day jobs as data scientist. Just note that I used the classical ssd_mobilenet_v2_coco model from Tensorflow for speed performance. I copy the model (the .pb file) and the corresponding label map locally (in the model/ directory) to keep the possibility to use personal model later." }, { "code": null, "e": 1946, "s": 1582, "text": "I believe that using Docker today become a primary data scientist skill. In data science and machine learning world, lots of new algorithms, tools and programs are released every weeks and install them on your computer to test them is the best way to crash your OS (experienced!). To prevent this, I now use Docker containers to create my data science workspaces." }, { "code": null, "e": 2120, "s": 1946, "text": "You can find on my repository the Dockerfile I’m working with for this project. Here is how I installed Tensorflow object-detection (follow the official installation guide):" }, { "code": null, "e": 2722, "s": 2120, "text": "# Install tensorFlowRUN pip install -U tensorflow# Install tensorflow models object detectionRUN git clone https://github.com/tensorflow/models /usr/local/lib/python3.5/dist-packages/tensorflow/modelsRUN apt-get install -y protobuf-compiler python-pil python-lxml python-tk#Set TF object detection availableENV PYTHONPATH \"$PYTHONPATH:/usr/local/lib/python3.5/dist-packages/tensorflow/models/research:/usr/local/lib/python3.5/dist-packages/tensorflow/models/research/slim\"RUN cd /usr/local/lib/python3.5/dist-packages/tensorflow/models/research && protoc object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 2753, "s": 2722, "text": "Similarly, I installed OpenCV:" }, { "code": null, "e": 3026, "s": 2753, "text": "# Install OpenCVRUN git clone https://github.com/opencv/opencv.git /usr/local/src/opencvRUN cd /usr/local/src/opencv/ && mkdir buildRUN cd /usr/local/src/opencv/build && cmake -D CMAKE_INSTALL_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local/ .. && make -j4 && make install" }, { "code": null, "e": 3115, "s": 3026, "text": "Image building is a bit long and take several minutes. Then, using it is quick and easy." }, { "code": null, "e": 3380, "s": 3115, "text": "I first try to apply object detection to my webcam stream. The main part of this work is fully described in the Dat Tran’s article. The difficulty was to send the webcam stream into the docker container and recover the output stream to display it using X11 server." }, { "code": null, "e": 3611, "s": 3380, "text": "With Linux, devices are found in the /dev/ directory and can be manipulated as files. Commonly, your laptop webcam is the “0” device. To send its stream into docker container, use the device argument when running the docker image:" }, { "code": null, "e": 3643, "s": 3611, "text": "docker run --device=/dev/video0" }, { "code": null, "e": 3918, "s": 3643, "text": "For Mac and Windows users, the way to send the webcam stream into containers is not as simple as for Linux (despite Mac is based on Unix). I have not dug so much into this problem, but the solution for Windows user would be to use Virtual Box to launch the docker container." }, { "code": null, "e": 4158, "s": 3918, "text": "Here is the point which takes me some time to resolve (with an unsatisfactory solution). I found useful information on using graphical user interfaces with Docker here, in particular to connect a container to a host’s X server for display." }, { "code": null, "e": 4416, "s": 4158, "text": "First, you must expose your xhost so that the container can render to the correct display by reading and writing though the X11 unix socket. Start by setting the permissions of the X server host (this is not the safest way to do it) to let docker access it:" }, { "code": null, "e": 4436, "s": 4416, "text": "xhost +local:docker" }, { "code": null, "e": 4534, "s": 4436, "text": "Then, once you are finished using the project, return the access controls at their default value:" }, { "code": null, "e": 4554, "s": 4534, "text": "xhost -local:docker" }, { "code": null, "e": 4610, "s": 4554, "text": "Then, create two environment variables XSOCK and XAUTH:" }, { "code": null, "e": 4655, "s": 4610, "text": "XSOCK=/tmp/.X11-unixXAUTH=/tmp/.docker.xauth" }, { "code": null, "e": 4781, "s": 4655, "text": "The first refers to the X11 Unix socket, the second refers to an X authentication file with proper permissions we create now:" }, { "code": null, "e": 4854, "s": 4781, "text": "xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -" }, { "code": null, "e": 5094, "s": 4854, "text": "Finally, we just have to update our docker run line command. We forward our DISPLAY environment variable, mount a volume for the X11 Unix socket and the X authentication file with an environment variable called XAUTHORITY which link to it:" }, { "code": null, "e": 5210, "s": 5094, "text": "docker run -it --rm --device=/dev/video0 -e DISPLAY=$DISPLAY -v $XSOCK:$XSOCK -v $XAUTH:$XAUTH -e XAUTHORITY=$XAUTH" }, { "code": null, "e": 5263, "s": 5210, "text": "Now we could run our docker container and it’s done:" }, { "code": null, "e": 5518, "s": 5263, "text": "Despite the host’s X server configuration, I was not able do completely remove what seems to be a bug in my code. OpenCV need to be “initialize” by calling a python script (init-openCV.py) using the cv2.imshow function. I get the following error message:" }, { "code": null, "e": 5573, "s": 5518, "text": "The program 'frame' received an X Window System error." }, { "code": null, "e": 5870, "s": 5573, "text": "Then, it is possible to call the main python script (my-object-detection.py) and the video stream is well sent to the host display. I’m not very satisfied with the solution of using a first python script to initialize the X11 system, but I have not found anything that solves this problem so far." }, { "code": null, "e": 6114, "s": 5870, "text": "EDIT: I finally (and accidentally!) found a solution to this problem by using a stable version of OpenCV (3.4.1) instead of cloning the git repo locally. Therefore, there is no need now to call the init-openCV.py before the main python script." }, { "code": null, "e": 6404, "s": 6114, "text": "To manage to run the object-detection API in real-time with my webcam, I used the threading and multiprocessing python libraries. A thread is used to read the webcam stream. Frames are put into a queue to be processed by a pool of workers (in which Tensorflow object-detection is running)." }, { "code": null, "e": 6759, "s": 6404, "text": "For video processing purpose, it is not possible to use threading since all video’s frames are read before workers are able to apply object-detection on first ones put in the input queue. Frames which are read when input queue is full are lost. Maybe using a lot of workers and huge queues may resolve the problem (with a prohibitive computational cost)." }, { "code": null, "e": 6921, "s": 6759, "text": "Another problem with simple queue is that frames are not published in output queue with the same order as in the input queue, due to ever-changing analysis time." }, { "code": null, "e": 7054, "s": 6921, "text": "To add my video processing feature, I remove the thread to read frames. Instead, I used the following lines of codes to read frames:" }, { "code": null, "e": 7282, "s": 7054, "text": "while True: # Check input queue is not full if not input_q.full(): # Read frame and store in input queue ret, frame = vs.read() if ret: input_q.put((int(vs.get(cv2.CAP_PROP_POS_FRAMES)),frame))" }, { "code": null, "e": 7456, "s": 7282, "text": "If the input queue is not full, the next frame is read from the video stream and put into the queue. Else, nothing is done while a frame is not getting from the input queue." }, { "code": null, "e": 7545, "s": 7456, "text": "To address the problem of frame order, I used a priority queue as a second output queue:" }, { "code": null, "e": 7824, "s": 7545, "text": "Frames are read and put into the input queue with their corresponding frame numbers (in fact a python list object is put into the queue).Then, workers take frames from the input queue, treat them and put them into the first output queue (still with their relative frame number)." }, { "code": null, "e": 7962, "s": 7824, "text": "Frames are read and put into the input queue with their corresponding frame numbers (in fact a python list object is put into the queue)." }, { "code": null, "e": 8104, "s": 7962, "text": "Then, workers take frames from the input queue, treat them and put them into the first output queue (still with their relative frame number)." }, { "code": null, "e": 8268, "s": 8104, "text": "while True: frame = input_q.get()frame_rgb = cv2.cvtColor(frame[1], cv2.COLOR_BGR2RGB) output_q.put((frame[0], detect_objects(frame_rgb, sess, detection_graph)))" }, { "code": null, "e": 8510, "s": 8268, "text": "3. If output queue is not empty, frames are extracted and put into the priority queue with their corresponding frame number as a priority number. The size of the priority queue is set, arbitrary, to three times the size of the others queues." }, { "code": null, "e": 8664, "s": 8510, "text": "# Check output queue is not emptyif not output_q.empty(): # Recover treated frame in output queue and feed priority queue output_pq.put(output_q.get())" }, { "code": null, "e": 9007, "s": 8664, "text": "4. Finally, if output priority queue is not empty, the frame with the highest priority (smallest prior number) is taken (this is the standard priority queue working). If the prior corresponds to the expected frame number, the frame is added to the output video stream (and write if needed), else the frame is put back into the priority queue." }, { "code": null, "e": 9284, "s": 9007, "text": "# Check output priority queue is not empty if not output_pq.empty(): prior, output_frame = output_pq.get() if prior > countWriteFrame: output_pq.put((prior, output_frame)) else: countWriteFrame = countWriteFrame + 1 # Do something with your frame" }, { "code": null, "e": 9402, "s": 9284, "text": "To stop the process, I check that all queues are empty and that all frames have been extracted from the video stream:" }, { "code": null, "e": 9485, "s": 9402, "text": "if((not ret) & input_q.empty() & output_q.empty() & output_pq.empty()): break" }, { "code": null, "e": 9848, "s": 9485, "text": "In this article, I present how I used docker to implement a real-time object-detection project with Tensorflow. As said, docker is the safest way to test new data science tools as well as to package the solution we deliver to customers. I also show you how I have adapted the original python script from Dat Tran to perform video processing with multiprocessing." } ]
How to find the size of a variable without using sizeof in C#?
To get the size of a variable, sizeof is used. int x; x = sizeof(int); To get the size of a variable, without using the sizeof, try the following code − // without using sizeof byte[] dataBytes = BitConverter.GetBytes(x); int d = dataBytes.Length; Here is the complete code. Live Demo using System; class Demo { public static void Main() { int x; // using sizeof x = sizeof(int); Console.WriteLine(x); // without using sizeof byte[] dataBytes = BitConverter.GetBytes(x); int d = dataBytes.Length; Console.WriteLine(d); } } 4 4
[ { "code": null, "e": 1109, "s": 1062, "text": "To get the size of a variable, sizeof is used." }, { "code": null, "e": 1133, "s": 1109, "text": "int x;\nx = sizeof(int);" }, { "code": null, "e": 1215, "s": 1133, "text": "To get the size of a variable, without using the sizeof, try the following code −" }, { "code": null, "e": 1310, "s": 1215, "text": "// without using sizeof\nbyte[] dataBytes = BitConverter.GetBytes(x);\nint d = dataBytes.Length;" }, { "code": null, "e": 1337, "s": 1310, "text": "Here is the complete code." }, { "code": null, "e": 1348, "s": 1337, "text": " Live Demo" }, { "code": null, "e": 1640, "s": 1348, "text": "using System;\nclass Demo {\n public static void Main() {\n int x;\n // using sizeof\n x = sizeof(int);\n Console.WriteLine(x);\n // without using sizeof\n byte[] dataBytes = BitConverter.GetBytes(x);\n int d = dataBytes.Length;\n Console.WriteLine(d);\n }\n}" }, { "code": null, "e": 1644, "s": 1640, "text": "4\n4" } ]
Function pointer to member function in C++
In C++ , function pointers when dealing with member functions of classes or structs, it is invoked using an object pointer or a this call. We can only call members of that class (or derivatives) using a pointer of that type as they are type safe. Live Demo #include <iostream> using namespace std; class AB { public: int sub(int a, int b) { return a-b; } int div(int a, int b) { return a/b; } }; //using function pointer int res1(int m, int n, AB* obj, int(AB::*fp)(int,int)) { return (obj->*fp)(m,n); } //using function pointer int res2(int m, int n, AB* obj, int(AB::*fp2)(int,int)) { return (obj->*fp2)(m,n); } int main() { AB ob; cout << "Subtraction is = " << res1(8,5, &ob, &AB::sub) << endl; cout << "Division is = " << res2(4,2, &ob, &AB::div) << endl; return 0; } Subtraction is = 3 Division is = 2
[ { "code": null, "e": 1309, "s": 1062, "text": "In C++ , function pointers when dealing with member functions of classes or structs, it is invoked using an object pointer or a this call. We can only call members of that class (or derivatives) using a pointer of that type as they are type safe." }, { "code": null, "e": 1320, "s": 1309, "text": " Live Demo" }, { "code": null, "e": 1899, "s": 1320, "text": "#include <iostream>\nusing namespace std;\nclass AB {\n public:\n int sub(int a, int b) {\n return a-b;\n }\n int div(int a, int b) {\n return a/b;\n }\n};\n//using function pointer\nint res1(int m, int n, AB* obj, int(AB::*fp)(int,int)) {\n return (obj->*fp)(m,n);\n}\n//using function pointer\nint res2(int m, int n, AB* obj, int(AB::*fp2)(int,int)) {\n return (obj->*fp2)(m,n);\n}\nint main() {\n AB ob;\n cout << \"Subtraction is = \" << res1(8,5, &ob, &AB::sub) << endl;\n cout << \"Division is = \" << res2(4,2, &ob, &AB::div) << endl;\n return 0;\n}" }, { "code": null, "e": 1934, "s": 1899, "text": "Subtraction is = 3\nDivision is = 2" } ]
How to train a Tensorflow face object detection model | by Dion van Velde | Towards Data Science
Artificial Intelligence makes it possible to analyse images. In this blogpost I will focus on training a object detector with customized classes. The first thing you will have to do is the setup. In the Tensorflow documentation is written how to setup on your local machine. We are going to train a real-time object recognition application using Tensorflow object detection. The trained models are available in this repository This is a translation of ‘Train een tensorflow gezicht object detectie model’ and Objectherkenning met de Computer Vision library Tensorflow You can auto install OpenCV on Ubuntu in /usr/local. with the following script. This script installs OpenCV 3.2 and works with Ubuntu 16.04. $ curl -L https://raw.githubusercontent.com/qdraw/tensorflow-object-detection-tutorial/master/install.opencv.ubuntu.sh | bash On my Mac I use OpenCV 3.3.0 en Python 2.7.13. I’ve tried it with OpenCV 3.2 and 3.3 but this fails with Python 3.6. However, on Ubuntu Linux this combination does works. $ brew install homebrew/science/opencv The first step is cloning the Tensorflow-models repository. For this tutorial we use only the slim and object_detection module. $ nano .profileexport PYTHONPATH=$PYTHONPATH:/home/dion/models/research:/home/dion/models/research/slim You also need to compile the protobuf libraries $ protoc object_detection/protos/*.proto --python_out=. The example code is available in the tensorflow-face-object-detector-tutorial repository. You can clone this repo. $ git clone https://github.com/qdraw/tensorflow-face-object-detector-tutorial.git Go to the subfolder: $ cd tensorflow-face-object-detector-tutorial/ Install the dependencies using PIP: I use Python 3.6 and OpenCV is installed with Python bindings. $ pip install -r requirements.txt The Chinese University of Hong Kong has a large dataset of labelled images. The WIDER FACE dataset is a face detection benchmark dataset. I have used labelImg to show the bounding boxes. The selected text are the face annotations. The script 001_down_data.py will be used to download WIDERFace and ssd_mobilenet_v1_coco_11_06_2017. I will use a pre trained model to speed up training time. $ python 001_down_data.py First we need to convert the dataset to Pascal XML. Tensorflow and labelImg use a different format. The images are downloaded in the WIDER_train folder. With 002_data-to-pascal-xml.py we convert the WIDERFace data and copy it to a different subfolder. It takes on my computer 5 minutes to process 9263 images. $ python 002_data-to-pascal-xml.py When the data is converted to Pascal XML, an index is created. By training and validating the dataset, we use these files as input to make TFRecords. However, it is also possible to label images with a tool like labelImg manually and use this step to create an index here. $ python 003_xml-to-csv.py A TFRecords file is a large binary file that can be read to train the Machine Learning model. The file is sequentially read by Tensorflow in the next step. The training and validation data will be converted into binary files. Trainings data to TFRecord (847.6 MB) $ python 004_generate_tfrecord.py --images_path=data/tf_wider_train/images --csv_input=data/tf_wider_train/train.csv --output_path=data/train.record Validation data to TFRecord (213.1MB) $ python 004_generate_tfrecord.py --images_path=data/tf_wider_val/images --csv_input=data/tf_wider_val/val.csv --output_path=data/val.record In the repository, ssd_mobilenet_v1_face.config is a configuration file that is used to train an Artificial Neural Network. This file is based on a pet detector. In this case, the number of num_classes remains one because only faces will be recognized. The variable fine_tune_checkpoint is used to indicate the path to a previous model to get learning. This location will fit you in this file. The fine tune checkpoint file is used to apply transfer learning. Transfer learning is a method in Machine Learning that is focused on applying knowledge gained from one problem to another problem. In the class train_input_reader, a link is made with the TFRecord files for training the model. In the config file, you need to customize it to the correct location. The variable label_map_path contains index IDs and names. With this file, zero is used as a placeholder, so we start with numbers from one. item { id: 1 name: 'face'} For validation, two variables are important. The variable num_examples within the class eval_config are used to set the number of examples. The eval_input_reader class describes the location of the validation data. There is also a path in this location. Furthermore, it is still possible to change learning rate, batch size and other settings. For now, I have kept the default settings. Now it’s going to start real work. The computer is going to learn from the dataset and make a Neural Network here. As I model the train on a CPU, this will take several days to get a good result. With powerful Nvidia graphics card it is possible to shorten this to a few hours. $ python ~/tensorflow_models/object_detection/train.py --logtostderr --pipeline_config_path=ssd_mobilenet_v1_face.config --train_dir=model_output Tensorboard gives insight into the learning process. The tool is part of Tensorflow and is automatically installed. $ tensorboard --logdir= model_output To use the model in Object Recognition with the Computer Vision library Tensorflow. The command below provides a location to the models repository and to the last checkpoint. The folder folder will contain frozen_inference_graph.pb. $ python ~/tensorflow_models/object_detection/export_inference_graph.py \--input_type image_tensor \--pipeline_config_path ssd_mobilenet_v1_face.config \--trained_checkpoint_prefix model_output/model.ckpt-12262 \--output_directory model/ TL; DR;In the model/frozen_inference_graph.pb folder on the github repository is a frozen model of the Artificial Neural Network. The Chinese University of Hong Kong has WIDERFace and this dataset has been used to train model. In addition to the data used for training, there is also an evaluation dataset. Based on this evaluation dataset, it is possible to calculate the accuracy. For my model I calculated the accuracy (Mean Average Precision). I came to a score of 83.80% at 14337 steps (epochs). For this process, Tensorflow has a script and makes it possible to see in Tensorboard what the score is. It is recommended that you run an evaluation process in addition to training. python ~/tensorflow_models/object_detection/eval.py --logtostderr --pipeline_config_path=ssd_mobilenet_v1_face.config --checkpoint_dir=model_output --eval_dir=eval You can then monitor the process with Tensorboard. tensorboard --logdir=eval --port=6010 It has been possible to train a face recognition model. The frozen model model / frozen_inference_graph.pb can be deployed in, for example, Object Recognition with the Computer Vision Library Tensorflow. Should the world of Computer Vision interest you, but you still do not know how to apply this and have the necessary questions? Send me an email then we can have a cup of coffee.
[ { "code": null, "e": 599, "s": 172, "text": "Artificial Intelligence makes it possible to analyse images. In this blogpost I will focus on training a object detector with customized classes. The first thing you will have to do is the setup. In the Tensorflow documentation is written how to setup on your local machine. We are going to train a real-time object recognition application using Tensorflow object detection. The trained models are available in this repository" }, { "code": null, "e": 740, "s": 599, "text": "This is a translation of ‘Train een tensorflow gezicht object detectie model’ and Objectherkenning met de Computer Vision library Tensorflow" }, { "code": null, "e": 881, "s": 740, "text": "You can auto install OpenCV on Ubuntu in /usr/local. with the following script. This script installs OpenCV 3.2 and works with Ubuntu 16.04." }, { "code": null, "e": 1007, "s": 881, "text": "$ curl -L https://raw.githubusercontent.com/qdraw/tensorflow-object-detection-tutorial/master/install.opencv.ubuntu.sh | bash" }, { "code": null, "e": 1178, "s": 1007, "text": "On my Mac I use OpenCV 3.3.0 en Python 2.7.13. I’ve tried it with OpenCV 3.2 and 3.3 but this fails with Python 3.6. However, on Ubuntu Linux this combination does works." }, { "code": null, "e": 1217, "s": 1178, "text": "$ brew install homebrew/science/opencv" }, { "code": null, "e": 1345, "s": 1217, "text": "The first step is cloning the Tensorflow-models repository. For this tutorial we use only the slim and object_detection module." }, { "code": null, "e": 1449, "s": 1345, "text": "$ nano .profileexport PYTHONPATH=$PYTHONPATH:/home/dion/models/research:/home/dion/models/research/slim" }, { "code": null, "e": 1497, "s": 1449, "text": "You also need to compile the protobuf libraries" }, { "code": null, "e": 1553, "s": 1497, "text": "$ protoc object_detection/protos/*.proto --python_out=." }, { "code": null, "e": 1668, "s": 1553, "text": "The example code is available in the tensorflow-face-object-detector-tutorial repository. You can clone this repo." }, { "code": null, "e": 1750, "s": 1668, "text": "$ git clone https://github.com/qdraw/tensorflow-face-object-detector-tutorial.git" }, { "code": null, "e": 1771, "s": 1750, "text": "Go to the subfolder:" }, { "code": null, "e": 1819, "s": 1771, "text": " $ cd tensorflow-face-object-detector-tutorial/" }, { "code": null, "e": 1918, "s": 1819, "text": "Install the dependencies using PIP: I use Python 3.6 and OpenCV is installed with Python bindings." }, { "code": null, "e": 1952, "s": 1918, "text": "$ pip install -r requirements.txt" }, { "code": null, "e": 2183, "s": 1952, "text": "The Chinese University of Hong Kong has a large dataset of labelled images. The WIDER FACE dataset is a face detection benchmark dataset. I have used labelImg to show the bounding boxes. The selected text are the face annotations." }, { "code": null, "e": 2342, "s": 2183, "text": "The script 001_down_data.py will be used to download WIDERFace and ssd_mobilenet_v1_coco_11_06_2017. I will use a pre trained model to speed up training time." }, { "code": null, "e": 2368, "s": 2342, "text": "$ python 001_down_data.py" }, { "code": null, "e": 2678, "s": 2368, "text": "First we need to convert the dataset to Pascal XML. Tensorflow and labelImg use a different format. The images are downloaded in the WIDER_train folder. With 002_data-to-pascal-xml.py we convert the WIDERFace data and copy it to a different subfolder. It takes on my computer 5 minutes to process 9263 images." }, { "code": null, "e": 2713, "s": 2678, "text": "$ python 002_data-to-pascal-xml.py" }, { "code": null, "e": 2986, "s": 2713, "text": "When the data is converted to Pascal XML, an index is created. By training and validating the dataset, we use these files as input to make TFRecords. However, it is also possible to label images with a tool like labelImg manually and use this step to create an index here." }, { "code": null, "e": 3013, "s": 2986, "text": "$ python 003_xml-to-csv.py" }, { "code": null, "e": 3239, "s": 3013, "text": "A TFRecords file is a large binary file that can be read to train the Machine Learning model. The file is sequentially read by Tensorflow in the next step. The training and validation data will be converted into binary files." }, { "code": null, "e": 3277, "s": 3239, "text": "Trainings data to TFRecord (847.6 MB)" }, { "code": null, "e": 3427, "s": 3277, "text": "$ python 004_generate_tfrecord.py --images_path=data/tf_wider_train/images --csv_input=data/tf_wider_train/train.csv --output_path=data/train.record" }, { "code": null, "e": 3465, "s": 3427, "text": "Validation data to TFRecord (213.1MB)" }, { "code": null, "e": 3607, "s": 3465, "text": "$ python 004_generate_tfrecord.py --images_path=data/tf_wider_val/images --csv_input=data/tf_wider_val/val.csv --output_path=data/val.record" }, { "code": null, "e": 3769, "s": 3607, "text": "In the repository, ssd_mobilenet_v1_face.config is a configuration file that is used to train an Artificial Neural Network. This file is based on a pet detector." }, { "code": null, "e": 3860, "s": 3769, "text": "In this case, the number of num_classes remains one because only faces will be recognized." }, { "code": null, "e": 4199, "s": 3860, "text": "The variable fine_tune_checkpoint is used to indicate the path to a previous model to get learning. This location will fit you in this file. The fine tune checkpoint file is used to apply transfer learning. Transfer learning is a method in Machine Learning that is focused on applying knowledge gained from one problem to another problem." }, { "code": null, "e": 4365, "s": 4199, "text": "In the class train_input_reader, a link is made with the TFRecord files for training the model. In the config file, you need to customize it to the correct location." }, { "code": null, "e": 4505, "s": 4365, "text": "The variable label_map_path contains index IDs and names. With this file, zero is used as a placeholder, so we start with numbers from one." }, { "code": null, "e": 4534, "s": 4505, "text": "item { id: 1 name: 'face'}" }, { "code": null, "e": 4922, "s": 4534, "text": "For validation, two variables are important. The variable num_examples within the class eval_config are used to set the number of examples. The eval_input_reader class describes the location of the validation data. There is also a path in this location. Furthermore, it is still possible to change learning rate, batch size and other settings. For now, I have kept the default settings." }, { "code": null, "e": 5200, "s": 4922, "text": "Now it’s going to start real work. The computer is going to learn from the dataset and make a Neural Network here. As I model the train on a CPU, this will take several days to get a good result. With powerful Nvidia graphics card it is possible to shorten this to a few hours." }, { "code": null, "e": 5347, "s": 5200, "text": "$ python ~/tensorflow_models/object_detection/train.py --logtostderr --pipeline_config_path=ssd_mobilenet_v1_face.config --train_dir=model_output" }, { "code": null, "e": 5463, "s": 5347, "text": "Tensorboard gives insight into the learning process. The tool is part of Tensorflow and is automatically installed." }, { "code": null, "e": 5500, "s": 5463, "text": "$ tensorboard --logdir= model_output" }, { "code": null, "e": 5733, "s": 5500, "text": "To use the model in Object Recognition with the Computer Vision library Tensorflow. The command below provides a location to the models repository and to the last checkpoint. The folder folder will contain frozen_inference_graph.pb." }, { "code": null, "e": 5971, "s": 5733, "text": "$ python ~/tensorflow_models/object_detection/export_inference_graph.py \\--input_type image_tensor \\--pipeline_config_path ssd_mobilenet_v1_face.config \\--trained_checkpoint_prefix model_output/model.ckpt-12262 \\--output_directory model/" }, { "code": null, "e": 6198, "s": 5971, "text": "TL; DR;In the model/frozen_inference_graph.pb folder on the github repository is a frozen model of the Artificial Neural Network. The Chinese University of Hong Kong has WIDERFace and this dataset has been used to train model." }, { "code": null, "e": 6655, "s": 6198, "text": "In addition to the data used for training, there is also an evaluation dataset. Based on this evaluation dataset, it is possible to calculate the accuracy. For my model I calculated the accuracy (Mean Average Precision). I came to a score of 83.80% at 14337 steps (epochs). For this process, Tensorflow has a script and makes it possible to see in Tensorboard what the score is. It is recommended that you run an evaluation process in addition to training." }, { "code": null, "e": 6820, "s": 6655, "text": "python ~/tensorflow_models/object_detection/eval.py --logtostderr --pipeline_config_path=ssd_mobilenet_v1_face.config --checkpoint_dir=model_output --eval_dir=eval" }, { "code": null, "e": 6871, "s": 6820, "text": "You can then monitor the process with Tensorboard." }, { "code": null, "e": 6909, "s": 6871, "text": "tensorboard --logdir=eval --port=6010" }, { "code": null, "e": 7113, "s": 6909, "text": "It has been possible to train a face recognition model. The frozen model model / frozen_inference_graph.pb can be deployed in, for example, Object Recognition with the Computer Vision Library Tensorflow." } ]
How to print date using GregorianCalendar class in Java?
The GregorianCalendar class supports standard calendars it supports Julian and Gregorian calendars you can create an object of GregorianCalendar using one of its constructors. Following are various examples demonstrating how to print date using this class − Following example creates GregorianCalander by passing year, month and date values as parameters to its constructor and prints the date − Live Demo import java.util.Calendar; import java.util.GregorianCalendar; public class Test { public static void main(String args[]){ //Instantiating the GregorianCalendar GregorianCalendar cal = new GregorianCalendar(2018, 6, 27); System.out.println(cal); System.out.println("Date: "+cal.get(Calendar.DATE)); System.out.println("Month: "+cal.get(Calendar.MONTH)); System.out.println("Year: "+cal.get(Calendar.YEAR)); } } java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=2018,MONTH=6,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=27,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?] Date: 27 Month: 6 Year: 2018 Following example creates GregorianCalander by passing the Locale object as a parameter to its constructor and prints the date − Live Demo import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; public class Test { public static void main(String args[]){ Locale locale = new Locale("en", "IN"); //Instantiating the GregorianCalendar GregorianCalendar cal = new GregorianCalendar(locale); System.out.println("Date: "+cal.get(Calendar.DATE)); System.out.println("Month: "+cal.get(Calendar.MONTH)); System.out.println("Year: "+cal.get(Calendar.YEAR)); } } Date: 7 Month: 10 Year: 2020 Following example creates GregorianCalander by passing the TimeZone object as a parameter to its constructor and prints the date − Live Demo import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; public class Test { public static void main(String args[]){ TimeZone timeZone = TimeZone.getTimeZone("GMT+5:30"); //Instantiating the GregorianCalendar GregorianCalendar cal = new GregorianCalendar(timeZone); System.out.println("Date: "+cal.get(Calendar.DATE)); System.out.println("Month: "+cal.get(Calendar.MONTH)); System.out.println("Year: "+cal.get(Calendar.YEAR)); } } Date: 7 Month: 10 Year: 2020 Following example creates GregorianCalander using the getInstance() method and prints the date − Live Demo import java.util.Calendar; import java.util.GregorianCalendar; public class Test { public static void main(String args[]){ //Instantiating the GregorianCalendar GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); System.out.println("Date: "+cal.get(Calendar.DATE)); System.out.println("Month: "+cal.get(Calendar.MONTH)); System.out.println("Year: "+cal.get(Calendar.YEAR)); } } Date: 7 Month: 10 Year: 2020
[ { "code": null, "e": 1320, "s": 1062, "text": "The GregorianCalendar class supports standard calendars it supports Julian and Gregorian calendars you can create an object of GregorianCalendar using one of its constructors. Following are various examples demonstrating how to print date using this class −" }, { "code": null, "e": 1458, "s": 1320, "text": "Following example creates GregorianCalander by passing year, month and date values as parameters to its constructor and prints the date −" }, { "code": null, "e": 1468, "s": 1458, "text": "Live Demo" }, { "code": null, "e": 1921, "s": 1468, "text": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\npublic class Test {\n public static void main(String args[]){\n //Instantiating the GregorianCalendar\n GregorianCalendar cal = new GregorianCalendar(2018, 6, 27);\n System.out.println(cal);\n System.out.println(\"Date: \"+cal.get(Calendar.DATE));\n System.out.println(\"Month: \"+cal.get(Calendar.MONTH));\n System.out.println(\"Year: \"+cal.get(Calendar.YEAR));\n }\n}" }, { "code": null, "e": 2419, "s": 1921, "text": "java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id=\"Asia/Calcutta\",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=?,YEAR=2018,MONTH=6,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=27,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]\nDate: 27\nMonth: 6\nYear: 2018" }, { "code": null, "e": 2548, "s": 2419, "text": "Following example creates GregorianCalander by passing the Locale object as a parameter to its constructor and prints the date −" }, { "code": null, "e": 2558, "s": 2548, "text": "Live Demo" }, { "code": null, "e": 3040, "s": 2558, "text": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.util.Locale;\npublic class Test {\n public static void main(String args[]){ \nLocale locale = new Locale(\"en\", \"IN\");\n //Instantiating the GregorianCalendar \nGregorianCalendar cal = new GregorianCalendar(locale);\n System.out.println(\"Date: \"+cal.get(Calendar.DATE));\n System.out.println(\"Month: \"+cal.get(Calendar.MONTH));\n System.out.println(\"Year: \"+cal.get(Calendar.YEAR));\n }\n}" }, { "code": null, "e": 3069, "s": 3040, "text": "Date: 7\nMonth: 10\nYear: 2020" }, { "code": null, "e": 3200, "s": 3069, "text": "Following example creates GregorianCalander by passing the TimeZone object as a parameter to its constructor and prints the date −" }, { "code": null, "e": 3210, "s": 3200, "text": "Live Demo" }, { "code": null, "e": 3722, "s": 3210, "text": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.util.TimeZone;\npublic class Test {\n public static void main(String args[]){ \n TimeZone timeZone = TimeZone.getTimeZone(\"GMT+5:30\");\n //Instantiating the GregorianCalendar \n GregorianCalendar cal = new GregorianCalendar(timeZone);\n System.out.println(\"Date: \"+cal.get(Calendar.DATE));\n System.out.println(\"Month: \"+cal.get(Calendar.MONTH));\n System.out.println(\"Year: \"+cal.get(Calendar.YEAR));\n }\n}" }, { "code": null, "e": 3751, "s": 3722, "text": "Date: 7\nMonth: 10\nYear: 2020" }, { "code": null, "e": 3848, "s": 3751, "text": "Following example creates GregorianCalander using the getInstance() method and prints the date −" }, { "code": null, "e": 3858, "s": 3848, "text": "Live Demo" }, { "code": null, "e": 4303, "s": 3858, "text": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\npublic class Test {\n public static void main(String args[]){ \n //Instantiating the GregorianCalendar \n GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();\n System.out.println(\"Date: \"+cal.get(Calendar.DATE));\n System.out.println(\"Month: \"+cal.get(Calendar.MONTH));\n System.out.println(\"Year: \"+cal.get(Calendar.YEAR));\n }\n}" }, { "code": null, "e": 4332, "s": 4303, "text": "Date: 7\nMonth: 10\nYear: 2020" } ]
Can interfaces have Static methods in Java?
An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static. A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation. Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class. In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface. Live Demo interface MyInterface{ public void demo(); public static void display() { System.out.println("This is a static method"); } } public class InterfaceExample{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demo(); MyInterface.display(); } } This is the implementation of the demo method This is a static method
[ { "code": null, "e": 1181, "s": 1062, "text": "An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static." }, { "code": null, "e": 1364, "s": 1181, "text": "A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation." }, { "code": null, "e": 1525, "s": 1364, "text": "Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class." }, { "code": null, "e": 1657, "s": 1525, "text": "In the following example, we are defining a static method in an interface and accessing it from a class implementing the interface." }, { "code": null, "e": 1668, "s": 1657, "text": " Live Demo" }, { "code": null, "e": 2094, "s": 1668, "text": "interface MyInterface{\n public void demo();\n public static void display() {\n System.out.println(\"This is a static method\");\n }\n}\npublic class InterfaceExample{\n public void demo() {\n System.out.println(\"This is the implementation of the demo method\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.demo();\n MyInterface.display();\n }\n}" }, { "code": null, "e": 2164, "s": 2094, "text": "This is the implementation of the demo method\nThis is a static method" } ]
MongoEngine - Document Inheritance
It is possible to define an inherited class of any user defined Document class. The inherited class may add extra fields if required. However, since such as a class is not a direct subclass of Document class, it will not create a new collection, instead its objects are stored in a collection used by its parent class. In the parent class, meta attribute ‘allow_inheritance the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection. In the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection. from mongoengine import * con=connect('newdb') class employee (Document): name=StringField(required=True) branch=StringField() meta={'allow_inheritance':True} class salary(employee): dept=StringField() sal=IntField() e1=employee(name='Bharat', branch='Chennai').save() s1=salary(name='Deep', branch='Hyderabad', dept='Accounts', sal=25000).save() We can verify that two documents are stored in employee collection as follows − { "_id":{"$oid":"5ebc34f44baa3752530b278a"}, "_cls":"employee", "name":"Bharat", "branch":"Chennai" } { "_id":{"$oid":"5ebc34f44baa3752530b278b"}, "_cls":"employee.salary", "name":"Deep", "branch":"Hyderabad", "dept":"Accounts", "sal":{"$numberInt":"25000"} } Note that, in order to identify the respective Document class, MongoEngine adds a “_cls” field and sets its value as "employee" and "employee.salary". If you want to provide extra functionality to a group of Document classes, but without overhead of inheritance, you can first create an abstract class and then derive one or more classes from the same. To make a class abstract, meta attribute ‘abstract’ is set to True. from mongoengine import * con=connect('newdb') class shape (Document): meta={'abstract':True} def area(self): pass class rectangle(shape): width=IntField() height=IntField() def area(self): return self.width*self.height r1=rectangle(width=20, height=30).save() Print Add Notes Bookmark this page
[ { "code": null, "e": 2948, "s": 2310, "text": "It is possible to define an inherited class of any user defined Document class. The inherited class may add extra fields if required. However, since such as a class is not a direct subclass of Document class, it will not create a new collection, instead its objects are stored in a collection used by its parent class. In the parent class, meta attribute ‘allow_inheritance the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection." }, { "code": null, "e": 3215, "s": 2948, "text": "In the following example, we first define employee as a document class and set allow_inheritance to true. The salary class is derived from employee, adding two more fields dept and sal. Objects of Employee as well as salary classes are stored in employee collection." }, { "code": null, "e": 3562, "s": 3215, "text": "from mongoengine import *\ncon=connect('newdb')\nclass employee (Document):\nname=StringField(required=True)\nbranch=StringField()\nmeta={'allow_inheritance':True}\nclass salary(employee):\ndept=StringField()\nsal=IntField()\ne1=employee(name='Bharat', branch='Chennai').save()\ns1=salary(name='Deep', branch='Hyderabad', dept='Accounts', sal=25000).save()" }, { "code": null, "e": 3642, "s": 3562, "text": "We can verify that two documents are stored in employee collection as follows −" }, { "code": null, "e": 3902, "s": 3642, "text": "{\n\"_id\":{\"$oid\":\"5ebc34f44baa3752530b278a\"},\n\"_cls\":\"employee\",\n\"name\":\"Bharat\",\n\"branch\":\"Chennai\"\n}\n{\n\"_id\":{\"$oid\":\"5ebc34f44baa3752530b278b\"},\n\"_cls\":\"employee.salary\",\n\"name\":\"Deep\",\n\"branch\":\"Hyderabad\",\n\"dept\":\"Accounts\",\n\"sal\":{\"$numberInt\":\"25000\"}\n}" }, { "code": null, "e": 4053, "s": 3902, "text": "Note that, in order to identify the respective Document class, MongoEngine adds a “_cls” field and sets its value as \"employee\" and \"employee.salary\"." }, { "code": null, "e": 4323, "s": 4053, "text": "If you want to provide extra functionality to a group of Document classes, but without overhead of inheritance, you can first create an abstract class and then derive one or more classes from the same. To make a class abstract, meta attribute ‘abstract’ is set to True." }, { "code": null, "e": 4614, "s": 4323, "text": "from mongoengine import *\ncon=connect('newdb')\n\nclass shape (Document):\n meta={'abstract':True}\n def area(self):\n pass\n\nclass rectangle(shape):\n width=IntField()\n height=IntField()\n def area(self):\n return self.width*self.height\n\nr1=rectangle(width=20, height=30).save()" }, { "code": null, "e": 4621, "s": 4614, "text": " Print" }, { "code": null, "e": 4632, "s": 4621, "text": " Add Notes" } ]
Conversion of four-digit hex to ASCII in 8051
We have already seen how to convert Hexadecimal digit to its ASCII equivalent. In this section, we will see how to convert two-byte (4-digit) Hexadecimal number to ASCII. Each nibble of these numbers is converted to its ASCII value. We are using one subroutine to convert a hexadecimal digit to ASCII. In this program, we are calling the subroutine multiple times. In the memory, we are storing 2-byte Hexadecimal number at location 20H and 21H. After converted ASCII values are stored at location 30H to 33H. The hexadecimal number is 2FA9H. The ASCII equivalent is 32 46 41 39. MOVR0,#20H;set source address 20H to R0 MOVR1,#30H;Set destination address 30H to R1 MOVR5,#02H;Set the counter as 2 for 2-bytes LOOP: MOVA,@R0; Get the first byte from location 20H MOVR4,A; Store the content of A to R4 SWAPA; Swap Nibbles of A ANLA,#0FH; Mask upper nibble of A ACALL HEX2ASC; Call subroutine to convert HEX to ASCII MOV@R1,B; Store the ASCII to destination INCR1; Increment the dest address MOVA,R4; Take the original number again ANLA,#0FH; Mask upper nibble of A ACALL HEX2ASC ; Call subroutine to convert HEX to ASCII MOV@R1,B; Store the ASCII to destination INCR1; Increment the destination address INCR0; Increase R0 for next source address DJNZR5,LOOP ; Decrease the byte count, and iterate HALT: SJMP HALT ;Stop the program ;This is a subroutine to convert Hex to ASCII. It takes A and B registers. A is holding the input, and B is for output HEX2ASC: MOVR2,A; Store the content of A into R2 CLRC;Clear the Carry Flag SUBBA,#0AH;Subtract 0AH from A JCNUM ;When carry is present, A is numeric ADDA,#41H;Add41H for Alphabet SJMP STORE ;Jumpto store the value NUM: MOVA,R2;Copy R2 to A ADDA,#30H;Add 30H with A to get ASCII STORE: MOVB,A;Store A content to B RET In this program, we are taking the number into the accumulator. Then to get the hexadecimal digits individually, we will apply masking logic. Here the HEX2 ASC subroutine is using the register A and B. A is acting like the input argument and B as output.
[ { "code": null, "e": 1295, "s": 1062, "text": "We have already seen how to convert Hexadecimal digit to its ASCII equivalent. In this section, we will see how to convert two-byte (4-digit) Hexadecimal number to ASCII. Each nibble of these numbers is converted to its ASCII value." }, { "code": null, "e": 1427, "s": 1295, "text": "We are using one subroutine to convert a hexadecimal digit to ASCII. In this program, we are calling the subroutine multiple times." }, { "code": null, "e": 1572, "s": 1427, "text": "In the memory, we are storing 2-byte Hexadecimal number at location 20H and 21H. After converted ASCII values are stored at location 30H to 33H." }, { "code": null, "e": 1642, "s": 1572, "text": "The hexadecimal number is 2FA9H. The ASCII equivalent is 32 46 41 39." }, { "code": null, "e": 2967, "s": 1642, "text": " MOVR0,#20H;set source address 20H to R0\n MOVR1,#30H;Set destination address 30H to R1\n MOVR5,#02H;Set the counter as 2 for 2-bytes\n\nLOOP: MOVA,@R0; Get the first byte from location 20H\n MOVR4,A; Store the content of A to R4\n SWAPA; Swap Nibbles of A\n ANLA,#0FH; Mask upper nibble of A\n ACALL HEX2ASC; Call subroutine to convert HEX to ASCII\n MOV@R1,B; Store the ASCII to destination\n INCR1; Increment the dest address\n\n MOVA,R4; Take the original number again\n ANLA,#0FH; Mask upper nibble of A\n ACALL HEX2ASC ; Call subroutine to convert HEX to ASCII\n MOV@R1,B; Store the ASCII to destination\n INCR1; Increment the destination address\n\n INCR0; Increase R0 for next source address\n DJNZR5,LOOP ; Decrease the byte count, and iterate\nHALT: SJMP HALT ;Stop the program\n;This is a subroutine to convert Hex to ASCII. It takes A and B registers. A is holding the input, and B is for output\n\nHEX2ASC: MOVR2,A; Store the content of A into R2\n\nCLRC;Clear the Carry Flag\nSUBBA,#0AH;Subtract 0AH from A\nJCNUM ;When carry is present, A is numeric\nADDA,#41H;Add41H for Alphabet\nSJMP STORE ;Jumpto store the value\nNUM: MOVA,R2;Copy R2 to A\nADDA,#30H;Add 30H with A to get ASCII\nSTORE: MOVB,A;Store A content to B\nRET" }, { "code": null, "e": 3110, "s": 2967, "text": "In this program, we are taking the number into the accumulator. Then to get the hexadecimal digits individually, we will apply masking logic. " }, { "code": null, "e": 3224, "s": 3110, "text": "Here the HEX2 ASC subroutine is using the register A and B. A is acting like the input argument and B as output. " } ]
How to check cursor array list is empty or not in Android sqlite?
Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc. This example demonstrate about How to check cursor array list is empty or not in Android sqlite. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:hint="Enter Name" android:layout_height="wrap_content" /> <EditText android:id="@+id/salary" android:layout_width="match_parent" android:inputType="numberDecimal" android:hint="Enter Salary" android:layout_height="wrap_content" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"><Button android:id="@+id/save" android:text="Save" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/refresh" android:text="Refresh" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/udate" android:text="Update" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/Delete" android:text="DeleteALL" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout> In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button to get the listview. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { Button save, refresh; EditText name, salary; private ListView listView; ArrayAdapter arrayAdapter; @Override protected void onCreate(Bundle readdInstanceState) { super.onCreate(readdInstanceState); setContentView(R.layout.activity_main); final DatabaseHelper helper = new DatabaseHelper(this); final ArrayList array_list = helper.getAllCotacts(); name = findViewById(R.id.name); salary = findViewById(R.id.salary); listView = findViewById(R.id.listView); if(!array_list.isEmpty()) { arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list); listView.setAdapter(arrayAdapter); } findViewById(R.id.Delete).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (helper.delete()) { Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Deleted", Toast.LENGTH_LONG).show(); } } }); findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) { if (helper.update(name.getText().toString(), salary.getText().toString())) { Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Updated", Toast.LENGTH_LONG).show(); } } else { name.setError("Enter NAME"); salary.setError("Enter Salary"); } } }); findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!array_list.isEmpty()) { array_list.clear(); array_list.addAll(helper.getAllCotacts()); arrayAdapter.notifyDataSetChanged(); listView.invalidateViews(); listView.refreshDrawableState(); } } }); findViewById(R.id.save).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) { if (helper.insert(name.getText().toString(), salary.getText().toString())) { Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show(); } } else { name.setError("Enter NAME"); salary.setError("Enter Salary"); } } }); } } Step 4 − Add the following code to src/ DatabaseHelper.java package com.example.andy.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import java.io.IOException; import java.util.ArrayList; class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "salaryDatabase6"; public static final String CONTACTS_TABLE_NAME = "SalaryDetails"; public DatabaseHelper(Context context) { super(context,DATABASE_NAME,null,1); } @Override public void onCreate(SQLiteDatabase db) { try { db.execSQL( "create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary int,datetime default current_timestamp )" ); } catch (SQLiteException e) { try { throw new IOException(e); } catch (IOException e1) { e1.printStackTrace(); } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME); onCreate(db); } public boolean insert(String s, String s1) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", s); contentValues.put("salary", s1); db.replace(CONTACTS_TABLE_NAME, null, contentValues); return true; } public ArrayList getAllCotacts() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList<String> array_list = new ArrayList<String>(); Cursor res = db.rawQuery( "select (id ||' : '||name || ' : ' || salary || ' : '|| datetime) as fullname from "+CONTACTS_TABLE_NAME, null ); res.moveToFirst(); while(res.isAfterLast() == false) { array_list.add(res.getString(res.getColumnIndex("HighestNumber"))); res.moveToNext(); } return array_list; } public boolean update(String s, String s1) { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("UPDATE "+CONTACTS_TABLE_NAME+" SET name = "+"'"+s+"', "+ "salary = "+"'"+s1+"'"); return true; } public boolean delete() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE from "+CONTACTS_TABLE_NAME); return true; } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Click here to download the project code
[ { "code": null, "e": 1457, "s": 1062, "text": "Before getting into example, we should know what sqlite data base in android is. SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC, ODBC etc." }, { "code": null, "e": 1554, "s": 1457, "text": "This example demonstrate about How to check cursor array list is empty or not in Android sqlite." }, { "code": null, "e": 1683, "s": 1554, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1748, "s": 1683, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3384, "s": 1748, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:orientation=\"vertical\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter Name\"\n android:layout_height=\"wrap_content\" />\n <EditText\n android:id=\"@+id/salary\"\n android:layout_width=\"match_parent\"\n android:inputType=\"numberDecimal\"\n android:hint=\"Enter Salary\"\n android:layout_height=\"wrap_content\" />\n <LinearLayout\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"><Button\n android:id=\"@+id/save\"\n android:text=\"Save\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/refresh\"\n android:text=\"Refresh\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/udate\"\n android:text=\"Update\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/Delete\"\n android:text=\"DeleteALL\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n </LinearLayout>\n\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\">\n </ListView>\n</LinearLayout>" }, { "code": null, "e": 3569, "s": 3384, "text": "In the above code, we have taken name and salary as Edit text, when user click on save button it will store the data into sqlite data base. Click on refresh button to get the listview." }, { "code": null, "e": 3626, "s": 3569, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 6988, "s": 3626, "text": "package com.example.andy.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Toast;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n Button save, refresh;\n EditText name, salary;\n private ListView listView;\n ArrayAdapter arrayAdapter;\n\n @Override\n protected void onCreate(Bundle readdInstanceState) {\n super.onCreate(readdInstanceState);\n setContentView(R.layout.activity_main);\n final DatabaseHelper helper = new DatabaseHelper(this);\n final ArrayList array_list = helper.getAllCotacts();\n name = findViewById(R.id.name);\n salary = findViewById(R.id.salary);\n listView = findViewById(R.id.listView);\n if(!array_list.isEmpty()) {\n arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);\n listView.setAdapter(arrayAdapter);\n }\n findViewById(R.id.Delete).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (helper.delete()) {\n Toast.makeText(MainActivity.this, \"Deleted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Deleted\", Toast.LENGTH_LONG).show();\n }\n }\n });\n findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.update(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Updated\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Updated\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if(!array_list.isEmpty()) {\n array_list.clear();\n array_list.addAll(helper.getAllCotacts());\n arrayAdapter.notifyDataSetChanged();\n listView.invalidateViews();\n listView.refreshDrawableState();\n }\n }\n });\n findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {\n if (helper.insert(name.getText().toString(), salary.getText().toString())) {\n Toast.makeText(MainActivity.this, \"Inserted\", Toast.LENGTH_LONG).show();\n } else {\n Toast.makeText(MainActivity.this, \"NOT Inserted\", Toast.LENGTH_LONG).show();\n }\n } else {\n name.setError(\"Enter NAME\");\n salary.setError(\"Enter Salary\");\n }\n }\n });\n }\n}" }, { "code": null, "e": 7048, "s": 6988, "text": "Step 4 − Add the following code to src/ DatabaseHelper.java" }, { "code": null, "e": 9491, "s": 7048, "text": "package com.example.andy.myapplication;\n\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\n\nclass DatabaseHelper extends SQLiteOpenHelper {\n public static final String DATABASE_NAME = \"salaryDatabase6\";\n public static final String CONTACTS_TABLE_NAME = \"SalaryDetails\";\n public DatabaseHelper(Context context) {\n super(context,DATABASE_NAME,null,1);\n }\n\n @Override\n public void onCreate(SQLiteDatabase db) {\n try {\n db.execSQL(\n \"create table \"+ CONTACTS_TABLE_NAME +\"(id INTEGER PRIMARY KEY, name text,salary int,datetime default current_timestamp )\"\n );\n } catch (SQLiteException e) {\n try {\n throw new IOException(e);\n } catch (IOException e1) {\n e1.printStackTrace();\n }\n }\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n db.execSQL(\"DROP TABLE IF EXISTS \"+CONTACTS_TABLE_NAME);\n onCreate(db);\n }\n\n public boolean insert(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n\n ContentValues contentValues = new ContentValues();\n contentValues.put(\"name\", s);\n contentValues.put(\"salary\", s1);\n db.replace(CONTACTS_TABLE_NAME, null, contentValues);\n return true;\n }\n\n public ArrayList getAllCotacts() {\n SQLiteDatabase db = this.getReadableDatabase();\n ArrayList<String> array_list = new ArrayList<String>();\n Cursor res = db.rawQuery( \"select (id ||' : '||name || ' : ' || salary || ' : '|| datetime) as fullname from \"+CONTACTS_TABLE_NAME, null );\n res.moveToFirst();\n\n while(res.isAfterLast() == false) {\n array_list.add(res.getString(res.getColumnIndex(\"HighestNumber\")));\n res.moveToNext();\n }\n return array_list;\n }\n\n public boolean update(String s, String s1) {\n SQLiteDatabase db = this.getWritableDatabase();\n db.execSQL(\"UPDATE \"+CONTACTS_TABLE_NAME+\" SET name = \"+\"'\"+s+\"', \"+ \"salary = \"+\"'\"+s1+\"'\");\n return true;\n }\n\n public boolean delete() {\n SQLiteDatabase db = this.getWritableDatabase();\n db.execSQL(\"DELETE from \"+CONTACTS_TABLE_NAME);\n return true;\n }\n}" }, { "code": null, "e": 9838, "s": 9491, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 9878, "s": 9838, "text": "Click here to download the project code" } ]
SQL | BETWEEN & IN Operator - GeeksforGeeks
11 Jan, 2022 BETWEEN The SQL BETWEEN condition allows you to easily test if an expression is within a range of values (inclusive). The values can be text, date, or numbers. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement. The SQL BETWEEN Condition will return the records where expression is within the range of value1 and value2. Syntax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; Examples: Consider the following Employee Table, Queries Using BETWEEN with Numeric Values: List all the Employee Fname, Lname who is having salary between 30000 and 45000. SELECT Fname, Lname FROM Employee WHERE Salary BETWEEN 30000 AND 45000; Output: Using BETWEEN with Date Values: Find all the Employee having Date of Birth Between 01-01-1985 and 12-12-1990. SELECT Fname, Lname FROM Employee where DOB BETWEEN '1985-01-01' AND '1990-12-30'; Output: Using NOT operator with BETWEEN Find all the Employee name whose salary is not in the range of 30000 and 45000. SELECT Fname, Lname FROM Employee WHERE Salary NOT BETWEEN 30000 AND 45000; Output: IN IN operator allows you to easily test if the expression matches any value in the list of values. It is used to remove the need of multiple OR condition in SELECT, INSERT, UPDATE or DELETE. You can also use NOT IN to exclude the rows in your list. We should note that any kind of duplicate entry will be retained. Syntax: SELECT column_name(s) FROM table_name WHERE column_name IN (list_of_values); Queries Find the Fname, Lname of the Employees who have Salary equal to 30000, 40000 or 25000. SELECT Fname, Lname FROM Employee WHERE Salary IN (30000, 40000, 25000); Output: Find the Fname, Lname of all the Employee who have Salary not equal to 25000 or 30000. SELECT Fname, Lname FROM Employee WHERE Salary NOT IN (25000, 30000); Output: This article is contributed by Anuj Chauhan. 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. parthbanathia rkbhola5 SQL-Clauses-Operators DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction of ER Model Introduction of B-Tree SQL Trigger | Student Database Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 How to find Nth highest salary from a table SQL | ALTER (RENAME) SQL Trigger | Student Database SQL | Views Difference between DDL and DML in DBMS
[ { "code": null, "e": 23852, "s": 23824, "text": "\n11 Jan, 2022" }, { "code": null, "e": 23860, "s": 23852, "text": "BETWEEN" }, { "code": null, "e": 24187, "s": 23860, "text": "The SQL BETWEEN condition allows you to easily test if an expression is within a range of values (inclusive). The values can be text, date, or numbers. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement. The SQL BETWEEN Condition will return the records where expression is within the range of value1 and value2. " }, { "code": null, "e": 24197, "s": 24187, "text": "Syntax: " }, { "code": null, "e": 24280, "s": 24197, "text": "SELECT column_name(s)\nFROM table_name\nWHERE column_name BETWEEN value1 AND value2;" }, { "code": null, "e": 24331, "s": 24280, "text": "Examples: Consider the following Employee Table, " }, { "code": null, "e": 24341, "s": 24333, "text": "Queries" }, { "code": null, "e": 24461, "s": 24343, "text": "Using BETWEEN with Numeric Values: List all the Employee Fname, Lname who is having salary between 30000 and 45000. " }, { "code": null, "e": 24533, "s": 24461, "text": "SELECT Fname, Lname\nFROM Employee\nWHERE Salary\nBETWEEN 30000 AND 45000;" }, { "code": null, "e": 24543, "s": 24533, "text": "Output: " }, { "code": null, "e": 24655, "s": 24543, "text": "Using BETWEEN with Date Values: Find all the Employee having Date of Birth Between 01-01-1985 and 12-12-1990. " }, { "code": null, "e": 24738, "s": 24655, "text": "SELECT Fname, Lname\nFROM Employee\nwhere DOB\nBETWEEN '1985-01-01' AND '1990-12-30';" }, { "code": null, "e": 24748, "s": 24738, "text": "Output: " }, { "code": null, "e": 24862, "s": 24748, "text": "Using NOT operator with BETWEEN Find all the Employee name whose salary is not in the range of 30000 and 45000. " }, { "code": null, "e": 24938, "s": 24862, "text": "SELECT Fname, Lname\nFROM Employee\nWHERE Salary\nNOT BETWEEN 30000 AND 45000;" }, { "code": null, "e": 24948, "s": 24938, "text": "Output: " }, { "code": null, "e": 24953, "s": 24950, "text": "IN" }, { "code": null, "e": 25276, "s": 24953, "text": "IN operator allows you to easily test if the expression matches any value in the list of values. It is used to remove the need of multiple OR condition in SELECT, INSERT, UPDATE or DELETE. You can also use NOT IN to exclude the rows in your list. We should note that any kind of duplicate entry will be retained. Syntax: " }, { "code": null, "e": 25353, "s": 25276, "text": "SELECT column_name(s)\nFROM table_name\nWHERE column_name IN (list_of_values);" }, { "code": null, "e": 25363, "s": 25355, "text": "Queries" }, { "code": null, "e": 25454, "s": 25365, "text": "Find the Fname, Lname of the Employees who have Salary equal to 30000, 40000 or 25000. " }, { "code": null, "e": 25527, "s": 25454, "text": "SELECT Fname, Lname\nFROM Employee\nWHERE Salary IN (30000, 40000, 25000);" }, { "code": null, "e": 25537, "s": 25527, "text": "Output: " }, { "code": null, "e": 25624, "s": 25537, "text": "Find the Fname, Lname of all the Employee who have Salary not equal to 25000 or 30000." }, { "code": null, "e": 25694, "s": 25624, "text": "SELECT Fname, Lname\nFROM Employee\nWHERE Salary NOT IN (25000, 30000);" }, { "code": null, "e": 25704, "s": 25694, "text": "Output: " }, { "code": null, "e": 26001, "s": 25704, "text": "This article is contributed by Anuj Chauhan. 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": 26127, "s": 26001, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 26141, "s": 26127, "text": "parthbanathia" }, { "code": null, "e": 26150, "s": 26141, "text": "rkbhola5" }, { "code": null, "e": 26172, "s": 26150, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 26177, "s": 26172, "text": "DBMS" }, { "code": null, "e": 26181, "s": 26177, "text": "SQL" }, { "code": null, "e": 26186, "s": 26181, "text": "DBMS" }, { "code": null, "e": 26190, "s": 26186, "text": "SQL" }, { "code": null, "e": 26288, "s": 26190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26297, "s": 26288, "text": "Comments" }, { "code": null, "e": 26310, "s": 26297, "text": "Old Comments" }, { "code": null, "e": 26335, "s": 26310, "text": "Introduction of ER Model" }, { "code": null, "e": 26358, "s": 26335, "text": "Introduction of B-Tree" }, { "code": null, "e": 26389, "s": 26358, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 26442, "s": 26389, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 26500, "s": 26442, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 26544, "s": 26500, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 26565, "s": 26544, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 26596, "s": 26565, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 26608, "s": 26596, "text": "SQL | Views" } ]
How to display multiple lines of text in Tkinter Label?
Tkinter Label widgets are created by defining the Label(parent, **options) constructor in the program. We use the Label widget to display Text or Images in any application. If we want to display a text, we have to assign a value to the text attribute in the constructor. You can also add multiple lines of text in the label widget by using \n next line attribute. It will separate the current text to the next line in the Label widget. # Import the tkinter library from tkinter import * # Create an instance of tkinter frame win= Tk() # Set the size of the Tkinter window win.geometry("700x350") # Add a label widget label= Label(win, text= "Hello There!\n How are you?", font= ('Aerial', 17)) label.pack() win.mainloop() Executing the above code will display a multiline Label Widget.
[ { "code": null, "e": 1498, "s": 1062, "text": "Tkinter Label widgets are created by defining the Label(parent, **options) constructor in the program. We use the Label widget to display Text or Images in any application. If we want to display a text, we have to assign a value to the text attribute in the constructor. You can also add multiple lines of text in the label widget by using \\n next line attribute. It will separate the current text to the next line in the Label widget." }, { "code": null, "e": 1788, "s": 1498, "text": "# Import the tkinter library\nfrom tkinter import *\n\n# Create an instance of tkinter frame\nwin= Tk()\n\n# Set the size of the Tkinter window\nwin.geometry(\"700x350\")\n\n# Add a label widget\nlabel= Label(win, text= \"Hello There!\\n How are you?\", font= ('Aerial', 17))\nlabel.pack()\n\nwin.mainloop()" }, { "code": null, "e": 1852, "s": 1788, "text": "Executing the above code will display a multiline Label Widget." } ]
Advanced Image Processing in R. ‘ImageMagick’ is one of the famous open... | by AbdulMajedRaja RS | Towards Data Science
‘ImageMagick’ is one of the famous open source libraries available for editing and manipulating Images of different types (Raster & Vector Images). magick is an R-package binding to ‘ImageMagick’ for Advanced Image-Processing in R, authored by Jeroen Ooms. magick supports many common image formats like png, jpeg, tiff and manipulations like rotate, scale, crop, trim, blur, flip, annotate and much more. This post is to help you get started with magick to process, edit and manipulate images in R that could be anything from just file format conversion (eg. png to jpeg) or annotating R graphics output. magick is available on CRAN and also on ropensci’s github. #installing magick package from CRANinstall.packages('magick') #from Github ropensci library - note: requires RToolsdevtools::install_github('ropensci/magick') Let us load the library and read our first image or images from the internet with image_read() #Loading magick packagelibrary(magick)#reading a png image frink imagefrink <- image_read("https://jeroen.github.io/images/frink.png")#reading a jpg image ex-President Barack Obama from Wikipediaobama <- image_read('https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/President_Barack_Obama.jpg/800px-President_Barack_Obama.jpg') Make sure you have got an updated version of curl package installed for the successfully reading image as mentioned above. We can get basic details of the read images with image_info() #image detailsimage_info(obama)image_info(frink)image_info(obama) format width height colorspace filesize1 JPEG 800 999 sRGB 151770image_info(frink)format width height colorspace filesize1 PNG 220 445 sRGB 73494 Communicating with RStudio, magick lets you print/display image in RStudio Viewer pane. #displaying the imageprint(obama) Whether you are a web developer or you are putting together a powerpoint deck, Image File Format Conversion is one of the operations that we would end up doing and this is literally an one-liner using magick‘s image_write(). #Rendering JPG image into SVGimage_write(obama, path = 'obama.svg', format = 'svg') Below is the PNG format of Obama Image that we read in from Wikipedia: But you might be wondering, “Hey! This is just basic Image processing. Didn’t you tell this is advanced?” And Yes, Here comes the advanced stuff along with a good news that magick supports pipe %>% operator. This is what we are going to do: #Applying Charcoal effect to Obama's image #and compositing it with frink's image#and finally annotating it with a textimage_charcoal(obama) %>% image_composite(frink) %>% image_annotate("CONFIDENTIAL", size = 50, color = "red", boxcolor = "pink", degrees = 30, location = "+100+100") %>% image_rotate(30) %>% image_write('obama_with_frink.png','png') Gives this output: How does the output image look? Artistic isn’t it ;)! But this is not Data Scientists want to do every day, instead, we play with Plots and most of the time want to annotate the R Graphics output and here’s how you can do that with magick‘s image_annotate() library(ggplot2)img <- image_graph(600, 400, res = 96)p <- ggplot(iris) + geom_point(aes(Sepal.Length,Petal.Length))print(p)dev.off()img %>% image_annotate("CONFIDENTIAL", size = 50, color = "red", boxcolor = "pink", degrees = 30, location = "+100+100") %>% image_write('conf_ggplot.png','png') Gives this output image: This is nothing but a glimpse of what magick can do. Literally, there is a lot of magic left in magick. Try it out yourself and share your thoughts in comments. The code used here can be found on my github. If you are interested in building your expertise in Deep Learning with Python, check out this Datacamp course. References: 1. Magick Ropensci 2. Magick CRAN Documentation 3. Obama Image Credit 4. Frink Image Credit
[ { "code": null, "e": 429, "s": 172, "text": "‘ImageMagick’ is one of the famous open source libraries available for editing and manipulating Images of different types (Raster & Vector Images). magick is an R-package binding to ‘ImageMagick’ for Advanced Image-Processing in R, authored by Jeroen Ooms." }, { "code": null, "e": 578, "s": 429, "text": "magick supports many common image formats like png, jpeg, tiff and manipulations like rotate, scale, crop, trim, blur, flip, annotate and much more." }, { "code": null, "e": 778, "s": 578, "text": "This post is to help you get started with magick to process, edit and manipulate images in R that could be anything from just file format conversion (eg. png to jpeg) or annotating R graphics output." }, { "code": null, "e": 837, "s": 778, "text": "magick is available on CRAN and also on ropensci’s github." }, { "code": null, "e": 997, "s": 837, "text": "#installing magick package from CRANinstall.packages('magick') #from Github ropensci library - note: requires RToolsdevtools::install_github('ropensci/magick')" }, { "code": null, "e": 1092, "s": 997, "text": "Let us load the library and read our first image or images from the internet with image_read()" }, { "code": null, "e": 1428, "s": 1092, "text": "#Loading magick packagelibrary(magick)#reading a png image frink imagefrink <- image_read(\"https://jeroen.github.io/images/frink.png\")#reading a jpg image ex-President Barack Obama from Wikipediaobama <- image_read('https://upload.wikimedia.org/wikipedia/commons/thumb/8/8d/President_Barack_Obama.jpg/800px-President_Barack_Obama.jpg')" }, { "code": null, "e": 1551, "s": 1428, "text": "Make sure you have got an updated version of curl package installed for the successfully reading image as mentioned above." }, { "code": null, "e": 1613, "s": 1551, "text": "We can get basic details of the read images with image_info()" }, { "code": null, "e": 1858, "s": 1613, "text": "#image detailsimage_info(obama)image_info(frink)image_info(obama) format width height colorspace filesize1 JPEG 800 999 sRGB 151770image_info(frink)format width height colorspace filesize1 PNG 220 445 sRGB 73494" }, { "code": null, "e": 1946, "s": 1858, "text": "Communicating with RStudio, magick lets you print/display image in RStudio Viewer pane." }, { "code": null, "e": 1980, "s": 1946, "text": "#displaying the imageprint(obama)" }, { "code": null, "e": 2205, "s": 1980, "text": "Whether you are a web developer or you are putting together a powerpoint deck, Image File Format Conversion is one of the operations that we would end up doing and this is literally an one-liner using magick‘s image_write()." }, { "code": null, "e": 2289, "s": 2205, "text": "#Rendering JPG image into SVGimage_write(obama, path = 'obama.svg', format = 'svg')" }, { "code": null, "e": 2360, "s": 2289, "text": "Below is the PNG format of Obama Image that we read in from Wikipedia:" }, { "code": null, "e": 2568, "s": 2360, "text": "But you might be wondering, “Hey! This is just basic Image processing. Didn’t you tell this is advanced?” And Yes, Here comes the advanced stuff along with a good news that magick supports pipe %>% operator." }, { "code": null, "e": 2601, "s": 2568, "text": "This is what we are going to do:" }, { "code": null, "e": 2975, "s": 2601, "text": "#Applying Charcoal effect to Obama's image #and compositing it with frink's image#and finally annotating it with a textimage_charcoal(obama) %>% image_composite(frink) %>% image_annotate(\"CONFIDENTIAL\", size = 50, color = \"red\", boxcolor = \"pink\", degrees = 30, location = \"+100+100\") %>% image_rotate(30) %>% image_write('obama_with_frink.png','png')" }, { "code": null, "e": 2994, "s": 2975, "text": "Gives this output:" }, { "code": null, "e": 3048, "s": 2994, "text": "How does the output image look? Artistic isn’t it ;)!" }, { "code": null, "e": 3252, "s": 3048, "text": "But this is not Data Scientists want to do every day, instead, we play with Plots and most of the time want to annotate the R Graphics output and here’s how you can do that with magick‘s image_annotate()" }, { "code": null, "e": 3571, "s": 3252, "text": "library(ggplot2)img <- image_graph(600, 400, res = 96)p <- ggplot(iris) + geom_point(aes(Sepal.Length,Petal.Length))print(p)dev.off()img %>% image_annotate(\"CONFIDENTIAL\", size = 50, color = \"red\", boxcolor = \"pink\", degrees = 30, location = \"+100+100\") %>% image_write('conf_ggplot.png','png')" }, { "code": null, "e": 3596, "s": 3571, "text": "Gives this output image:" }, { "code": null, "e": 3914, "s": 3596, "text": "This is nothing but a glimpse of what magick can do. Literally, there is a lot of magic left in magick. Try it out yourself and share your thoughts in comments. The code used here can be found on my github. If you are interested in building your expertise in Deep Learning with Python, check out this Datacamp course." }, { "code": null, "e": 3926, "s": 3914, "text": "References:" } ]
Find the frequency of a number in an array - GeeksforGeeks
14 May, 2021 Given an array, a[], and an element x, find a number of occurrences of x in a[].Examples: Input : a[] = {0, 5, 5, 5, 4} x = 5 Output : 3 Input : a[] = {1, 2, 3} x = 4 Output : 0 If array is not sorted The idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element that matches with x, we increment count. Finally, we return count. Below is the implementation of the approach. C++ Java Python3 C# PHP Javascript // CPP program to count occurrences of an// element in an unsorted array#include<iostream>using namespace std; int frequency(int a[], int n, int x){ int count = 0; for (int i=0; i < n; i++) if (a[i] == x) count++; return count;} // Driver programint main() { int a[] = {0, 5, 5, 5, 4}; int x = 5; int n = sizeof(a)/sizeof(a[0]); cout << frequency(a, n, x); return 0;} // Java program to count// occurrences of an// element in an unsorted// array import java.io.*; class GFG { static int frequency(int a[], int n, int x) { int count = 0; for (int i=0; i < n; i++) if (a[i] == x) count++; return count; } // Driver program public static void main (String[] args) { int a[] = {0, 5, 5, 5, 4}; int x = 5; int n = a.length; System.out.println(frequency(a, n, x)); }} // This code is contributed// by Ansu Kumari # Python program to count# occurrences of an# element in an unsorted# arraydef frequency(a, x): count = 0 for i in a: if i == x: count += 1 return count # Driver programa = [0, 5, 5, 5, 4]x = 5print(frequency(a, x)) # This code is contributed by Ansu Kumari // C# program to count// occurrences of an// element in an unsorted// arrayusing System; class GFG { static int frequency(int []a, int n, int x) { int count = 0; for (int i=0; i < n; i++) if (a[i] == x) count++; return count; } // Driver program static public void Main (){ int []a = {0, 5, 5, 5, 4}; int x = 5; int n = a.Length; Console.Write(frequency(a, n, x)); }} // This code is contributed// by Anuj_67 <?php// PHP program to count occurrences of an// element in an unsorted array function frequency($a, $n, $x){ $count = 0; for ($i = 0; $i < $n; $i++) if ($a[$i] == $x) $count++; return $count;} // Driver Code $a = array (0, 5, 5, 5, 4); $x = 5; $n = sizeof($a); echo frequency($a, $n, $x); // This code is contributed by ajit?> <script> // C# program to count occurrences of an element in an unsorted array function frequency(a, n, x) { let count = 0; for (let i=0; i < n; i++) if (a[i] == x) count++; return count; } let a = [0, 5, 5, 5, 4]; let x = 5; let n = a.length; document.write(frequency(a, n, x)); </script> Output: 3 Time Complexity : O(n) Auxiliary Space : O(1) If array is sorted We can apply methods for both sorted and unsorted. But for a sorted array, we can optimize it to work in O(Log n) time using Binary Search. Please refer to below article for details.Count number of occurrences (or frequency) in a sorted array. If there are multiple queries on a single array We can use hashing to store frequencies of all elements. Then we can answer all queries in O(1) time. Please refer Frequency of each element in an unsorted array for details. CPP Java Python3 C# Javascript // CPP program to answer queries for frequencies// in O(1) time.#include <bits/stdc++.h>using namespace std; unordered_map<int, int> hm; void countFreq(int a[], int n){ // Insert elements and their // frequencies in hash map. for (int i=0; i<n; i++) hm[a[i]]++;} // Return frequency of x (Assumes that// countFreq() is called before)int query(int x){ return hm[x];} // Driver programint main(){ int a[] = {1, 3, 2, 4, 2, 1}; int n = sizeof(a)/sizeof(a[0]); countFreq(a, n); cout << query(2) << endl; cout << query(3) << endl; cout << query(5) << endl; return 0;} // Java program to answer// queries for frequencies// in O(1) time. import java.io.*;import java.util.*; class GFG { static HashMap <Integer, Integer> hm = new HashMap<Integer, Integer>(); static void countFreq(int a[], int n) { // Insert elements and their // frequencies in hash map. for (int i=0; i<n; i++) if (hm.containsKey(a[i]) ) hm.put(a[i], hm.get(a[i]) + 1); else hm.put(a[i] , 1); } // Return frequency of x (Assumes that // countFreq() is called before) static int query(int x) { if (hm.containsKey(x)) return hm.get(x); return 0; } // Driver program public static void main (String[] args) { int a[] = {1, 3, 2, 4, 2, 1}; int n = a.length; countFreq(a, n); System.out.println(query(2)); System.out.println(query(3)); System.out.println(query(5)); } } // This code is contributed by Ansu Kumari # Python program to# answer queries for# frequencies# in O(1) time. hm = {} def countFreq(a): global hm # Insert elements and their # frequencies in hash map. for i in a: if i in hm: hm[i] += 1 else: hm[i] = 1 # Return frequency# of x (Assumes that# countFreq() is# called before)def query(x): if x in hm: return hm[x] return 0 # Driver programa = [1, 3, 2, 4, 2, 1]countFreq(a)print(query(2))print(query(3))print(query(5)) # This code is contributed# by Ansu Kumari // C# program to answer// queries for frequencies// in O(1) time.using System;using System.Collections.Generic;class GFG{ static Dictionary <int, int> hm = new Dictionary<int, int>(); static void countFreq(int []a, int n){ // Insert elements and their // frequencies in hash map. for (int i = 0; i < n; i++) if (hm.ContainsKey(a[i]) ) hm[a[i]] = hm[a[i]] + 1; else hm.Add(a[i], 1);} // Return frequency of x (Assumes that// countFreq() is called before)static int query(int x){ if (hm.ContainsKey(x)) return hm[x]; return 0;} // Driver codepublic static void Main(String[] args){ int []a = {1, 3, 2, 4, 2, 1}; int n = a.Length; countFreq(a, n); Console.WriteLine(query(2)); Console.WriteLine(query(3)); Console.WriteLine(query(5));}} // This code is contributed by 29AjayKumar <script> // JavaScript program to answer// queries for frequencies// in O(1) time. var hm = new Map(); function countFreq(a, n){ // Insert elements and their // frequencies in hash map. for (var i=0; i<n; i++) { if(hm.has(a[i])) { hm.set(a[i], hm.get(a[i])+1); } else { hm.set(a[i], 1); } }} // Return frequency of x (Assumes that// countFreq() is called before)function query(x){ if(hm.has(x)) { return hm.get(x); } return 0;} // Driver programvar a = [1, 3, 2, 4, 2, 1];var n = a.length;countFreq(a, n);document.write( query(2) + "<br>");document.write( query(3) + "<br>");document.write( query(5) + "<br>"); </script> Output : 2 1 0 This article is contributed by Sangita Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. jit_t vt_m 29AjayKumar divyesh072019 rutvik_56 Binary Search Arrays Arrays Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Maximum and minimum of an array using minimum number of comparisons Python | Using 2D arrays/lists the right way Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Queue | Set 1 (Introduction and Array Implementation)
[ { "code": null, "e": 25258, "s": 25230, "text": "\n14 May, 2021" }, { "code": null, "e": 25350, "s": 25258, "text": "Given an array, a[], and an element x, find a number of occurrences of x in a[].Examples: " }, { "code": null, "e": 25462, "s": 25350, "text": "Input : a[] = {0, 5, 5, 5, 4}\n x = 5\nOutput : 3\n\nInput : a[] = {1, 2, 3}\n x = 4\nOutput : 0" }, { "code": null, "e": 25489, "s": 25466, "text": "If array is not sorted" }, { "code": null, "e": 25709, "s": 25489, "text": "The idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element that matches with x, we increment count. Finally, we return count. Below is the implementation of the approach. " }, { "code": null, "e": 25713, "s": 25709, "text": "C++" }, { "code": null, "e": 25718, "s": 25713, "text": "Java" }, { "code": null, "e": 25726, "s": 25718, "text": "Python3" }, { "code": null, "e": 25729, "s": 25726, "text": "C#" }, { "code": null, "e": 25733, "s": 25729, "text": "PHP" }, { "code": null, "e": 25744, "s": 25733, "text": "Javascript" }, { "code": "// CPP program to count occurrences of an// element in an unsorted array#include<iostream>using namespace std; int frequency(int a[], int n, int x){ int count = 0; for (int i=0; i < n; i++) if (a[i] == x) count++; return count;} // Driver programint main() { int a[] = {0, 5, 5, 5, 4}; int x = 5; int n = sizeof(a)/sizeof(a[0]); cout << frequency(a, n, x); return 0;}", "e": 26151, "s": 25744, "text": null }, { "code": "// Java program to count// occurrences of an// element in an unsorted// array import java.io.*; class GFG { static int frequency(int a[], int n, int x) { int count = 0; for (int i=0; i < n; i++) if (a[i] == x) count++; return count; } // Driver program public static void main (String[] args) { int a[] = {0, 5, 5, 5, 4}; int x = 5; int n = a.length; System.out.println(frequency(a, n, x)); }} // This code is contributed// by Ansu Kumari", "e": 26709, "s": 26151, "text": null }, { "code": "# Python program to count# occurrences of an# element in an unsorted# arraydef frequency(a, x): count = 0 for i in a: if i == x: count += 1 return count # Driver programa = [0, 5, 5, 5, 4]x = 5print(frequency(a, x)) # This code is contributed by Ansu Kumari", "e": 26988, "s": 26709, "text": null }, { "code": "// C# program to count// occurrences of an// element in an unsorted// arrayusing System; class GFG { static int frequency(int []a, int n, int x) { int count = 0; for (int i=0; i < n; i++) if (a[i] == x) count++; return count; } // Driver program static public void Main (){ int []a = {0, 5, 5, 5, 4}; int x = 5; int n = a.Length; Console.Write(frequency(a, n, x)); }} // This code is contributed// by Anuj_67", "e": 27518, "s": 26988, "text": null }, { "code": "<?php// PHP program to count occurrences of an// element in an unsorted array function frequency($a, $n, $x){ $count = 0; for ($i = 0; $i < $n; $i++) if ($a[$i] == $x) $count++; return $count;} // Driver Code $a = array (0, 5, 5, 5, 4); $x = 5; $n = sizeof($a); echo frequency($a, $n, $x); // This code is contributed by ajit?>", "e": 27881, "s": 27518, "text": null }, { "code": "<script> // C# program to count occurrences of an element in an unsorted array function frequency(a, n, x) { let count = 0; for (let i=0; i < n; i++) if (a[i] == x) count++; return count; } let a = [0, 5, 5, 5, 4]; let x = 5; let n = a.length; document.write(frequency(a, n, x)); </script>", "e": 28274, "s": 27881, "text": null }, { "code": null, "e": 28283, "s": 28274, "text": "Output: " }, { "code": null, "e": 28285, "s": 28283, "text": "3" }, { "code": null, "e": 28332, "s": 28285, "text": "Time Complexity : O(n) Auxiliary Space : O(1) " }, { "code": null, "e": 28351, "s": 28332, "text": "If array is sorted" }, { "code": null, "e": 28596, "s": 28351, "text": "We can apply methods for both sorted and unsorted. But for a sorted array, we can optimize it to work in O(Log n) time using Binary Search. Please refer to below article for details.Count number of occurrences (or frequency) in a sorted array. " }, { "code": null, "e": 28644, "s": 28596, "text": "If there are multiple queries on a single array" }, { "code": null, "e": 28821, "s": 28644, "text": "We can use hashing to store frequencies of all elements. Then we can answer all queries in O(1) time. Please refer Frequency of each element in an unsorted array for details. " }, { "code": null, "e": 28825, "s": 28821, "text": "CPP" }, { "code": null, "e": 28830, "s": 28825, "text": "Java" }, { "code": null, "e": 28838, "s": 28830, "text": "Python3" }, { "code": null, "e": 28841, "s": 28838, "text": "C#" }, { "code": null, "e": 28852, "s": 28841, "text": "Javascript" }, { "code": "// CPP program to answer queries for frequencies// in O(1) time.#include <bits/stdc++.h>using namespace std; unordered_map<int, int> hm; void countFreq(int a[], int n){ // Insert elements and their // frequencies in hash map. for (int i=0; i<n; i++) hm[a[i]]++;} // Return frequency of x (Assumes that// countFreq() is called before)int query(int x){ return hm[x];} // Driver programint main(){ int a[] = {1, 3, 2, 4, 2, 1}; int n = sizeof(a)/sizeof(a[0]); countFreq(a, n); cout << query(2) << endl; cout << query(3) << endl; cout << query(5) << endl; return 0;}", "e": 29457, "s": 28852, "text": null }, { "code": "// Java program to answer// queries for frequencies// in O(1) time. import java.io.*;import java.util.*; class GFG { static HashMap <Integer, Integer> hm = new HashMap<Integer, Integer>(); static void countFreq(int a[], int n) { // Insert elements and their // frequencies in hash map. for (int i=0; i<n; i++) if (hm.containsKey(a[i]) ) hm.put(a[i], hm.get(a[i]) + 1); else hm.put(a[i] , 1); } // Return frequency of x (Assumes that // countFreq() is called before) static int query(int x) { if (hm.containsKey(x)) return hm.get(x); return 0; } // Driver program public static void main (String[] args) { int a[] = {1, 3, 2, 4, 2, 1}; int n = a.length; countFreq(a, n); System.out.println(query(2)); System.out.println(query(3)); System.out.println(query(5)); } } // This code is contributed by Ansu Kumari", "e": 30441, "s": 29457, "text": null }, { "code": "# Python program to# answer queries for# frequencies# in O(1) time. hm = {} def countFreq(a): global hm # Insert elements and their # frequencies in hash map. for i in a: if i in hm: hm[i] += 1 else: hm[i] = 1 # Return frequency# of x (Assumes that# countFreq() is# called before)def query(x): if x in hm: return hm[x] return 0 # Driver programa = [1, 3, 2, 4, 2, 1]countFreq(a)print(query(2))print(query(3))print(query(5)) # This code is contributed# by Ansu Kumari", "e": 30957, "s": 30441, "text": null }, { "code": "// C# program to answer// queries for frequencies// in O(1) time.using System;using System.Collections.Generic;class GFG{ static Dictionary <int, int> hm = new Dictionary<int, int>(); static void countFreq(int []a, int n){ // Insert elements and their // frequencies in hash map. for (int i = 0; i < n; i++) if (hm.ContainsKey(a[i]) ) hm[a[i]] = hm[a[i]] + 1; else hm.Add(a[i], 1);} // Return frequency of x (Assumes that// countFreq() is called before)static int query(int x){ if (hm.ContainsKey(x)) return hm[x]; return 0;} // Driver codepublic static void Main(String[] args){ int []a = {1, 3, 2, 4, 2, 1}; int n = a.Length; countFreq(a, n); Console.WriteLine(query(2)); Console.WriteLine(query(3)); Console.WriteLine(query(5));}} // This code is contributed by 29AjayKumar", "e": 31811, "s": 30957, "text": null }, { "code": "<script> // JavaScript program to answer// queries for frequencies// in O(1) time. var hm = new Map(); function countFreq(a, n){ // Insert elements and their // frequencies in hash map. for (var i=0; i<n; i++) { if(hm.has(a[i])) { hm.set(a[i], hm.get(a[i])+1); } else { hm.set(a[i], 1); } }} // Return frequency of x (Assumes that// countFreq() is called before)function query(x){ if(hm.has(x)) { return hm.get(x); } return 0;} // Driver programvar a = [1, 3, 2, 4, 2, 1];var n = a.length;countFreq(a, n);document.write( query(2) + \"<br>\");document.write( query(3) + \"<br>\");document.write( query(5) + \"<br>\"); </script>", "e": 32532, "s": 31811, "text": null }, { "code": null, "e": 32542, "s": 32532, "text": "Output : " }, { "code": null, "e": 32548, "s": 32542, "text": "2\n1\n0" }, { "code": null, "e": 32967, "s": 32548, "text": "This article is contributed by Sangita Dey. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. " }, { "code": null, "e": 32973, "s": 32967, "text": "jit_t" }, { "code": null, "e": 32978, "s": 32973, "text": "vt_m" }, { "code": null, "e": 32990, "s": 32978, "text": "29AjayKumar" }, { "code": null, "e": 33004, "s": 32990, "text": "divyesh072019" }, { "code": null, "e": 33014, "s": 33004, "text": "rutvik_56" }, { "code": null, "e": 33028, "s": 33014, "text": "Binary Search" }, { "code": null, "e": 33035, "s": 33028, "text": "Arrays" }, { "code": null, "e": 33042, "s": 33035, "text": "Arrays" }, { "code": null, "e": 33056, "s": 33042, "text": "Binary Search" }, { "code": null, "e": 33154, "s": 33056, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33163, "s": 33154, "text": "Comments" }, { "code": null, "e": 33176, "s": 33163, "text": "Old Comments" }, { "code": null, "e": 33224, "s": 33176, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33268, "s": 33224, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33291, "s": 33268, "text": "Introduction to Arrays" }, { "code": null, "e": 33323, "s": 33291, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33337, "s": 33323, "text": "Linear Search" }, { "code": null, "e": 33405, "s": 33337, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33450, "s": 33405, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 33471, "s": 33450, "text": "Linked List vs Array" }, { "code": null, "e": 33556, "s": 33471, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" } ]
vector::at() and vector::swap() in C++ STL
30 Jun, 2022 Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. at() function is used reference the element present at the position given as the parameter to the function. Syntax: vectorname.at(position) Parameters: Position of the element to be fetched. Returns: Direct reference to the element at the given position. Examples: Input: myvector = 1, 2, 3 myvector.at(2); Output: 3 Input: myvector = 3, 4, 1, 7, 3 myvector.at(3); Output: 7 Errors and Exceptions If the position is not present in the vector, it throws out_of_range.It has a strong no exception throw guarantee otherwise. If the position is not present in the vector, it throws out_of_range. It has a strong no exception throw guarantee otherwise. Time Complexity – Constant O(1) C++ // CPP program to illustrate// Implementation of at() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(3); cout << myvector.at(3); return 0;} 7 Applications: Given a vector of integers, print all the integers present at even positions. Input: 1, 2, 3, 4, 5, 6, 7, 8, 9 Output: 1 3 5 7 9 Explanation - 1, 3, 5, 7 and 9 are at position 0, 2, 4, 6 and 8 which are even Algorithm Run a loop till the size of the vector.Check if the position is divisible by 2, if yes, print the element at that position. Run a loop till the size of the vector. Check if the position is divisible by 2, if yes, print the element at that position. C++ // CPP program to illustrate// Application of at() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); myvector.push_back(4); myvector.push_back(5); myvector.push_back(6); myvector.push_back(7); myvector.push_back(8); myvector.push_back(9); // vector becomes 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < myvector.size(); i += 2) { cout << myvector.at(i); cout << " "; } return 0;} 1 3 5 7 9 This function is used to swap the contents of one vector with another vector of same type and sizes of vectors may differ. Syntax: vectorname1.swap(vectorname2) Parameters: The name of the vector with which the contents have to be swapped. Result: All the elements of the 2 vectors are swapped. Examples: Input: myvector1 = {1, 2, 3, 4} myvector2 = {3, 5, 7, 9} myvector1.swap(myvector2); Output: myvector1 = {3, 5, 7, 9} myvector2 = {1, 2, 3, 4} Input: myvector1 = {1, 3, 5, 7} myvector2 = {2, 4, 6, 8} myvector1.swap(myvector2); Output: myvector1 = {2, 4, 6, 8} myvector2 = {1, 3, 5, 7} Errors and Exceptions It throws an error if the vector is not of the same type.It has a basic no exception throw guarantee otherwise. It throws an error if the vector is not of the same type. It has a basic no exception throw guarantee otherwise. Time Complexity – Constant O(1) C++ // CPP program to illustrate// Implementation of swap() function#include <iostream>#include <vector>using namespace std; int main(){ // vector container declaration vector<int> myvector1{ 1, 2, 3, 4 }; vector<int> myvector2{ 3, 5, 7, 9 }; // using swap() function to swap // elements of vector myvector1.swap(myvector2); // printing the first vector cout << "myvector1 = "; for (auto it = myvector1.begin(); it < myvector1.end(); ++it) cout << *it << " "; // printing the second vector cout << endl << "myvector2 = "; for (auto it = myvector2.begin(); it < myvector2.end(); ++it) cout << *it << " "; return 0;} myvector1 = 3 5 7 9 myvector2 = 1 2 3 4 If the size of the vectors differ: C++ // CPP program#include <iostream>#include <vector>using namespace std; int main(){ vector<int> vec1{ 100, 100, 100 }; vector<int> vec2{ 200, 200, 200, 200, 200 }; vec1.swap(vec2); cout << "The vec1 contains:"; for (int i = 0; i < vec1.size(); i++) cout << ' ' << vec1[i]; cout << '\n'; cout << "The vec2 contains:"; for (int i = 0; i < vec2.size(); i++) cout << ' ' << vec2[i]; cout << '\n'; return 0;} The vec1 contains: 200 200 200 200 200 The vec2 contains: 100 100 100 Let us see the differences in a tabular form -: soumya7 devgagrani123 shaista ambreen 7ckngmad sweetyty utkarshgupta110092 mayank007rawa cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Inheritance in C++ Substring in C++ C++ Classes and Objects Priority Queue in C++ Standard Template Library (STL) Object Oriented Programming in C++ Sorting a vector in C++ Virtual Function in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 240, "s": 52, "text": "Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container." }, { "code": null, "e": 357, "s": 240, "text": "at() function is used reference the element present at the position given as the parameter to the function. Syntax: " }, { "code": null, "e": 498, "s": 357, "text": "vectorname.at(position)\nParameters: \nPosition of the element to be fetched.\nReturns: \nDirect reference to the element at the given position." }, { "code": null, "e": 510, "s": 498, "text": "Examples: " }, { "code": null, "e": 639, "s": 510, "text": "Input: myvector = 1, 2, 3\n myvector.at(2);\nOutput: 3\n\nInput: myvector = 3, 4, 1, 7, 3\n myvector.at(3);\nOutput: 7" }, { "code": null, "e": 663, "s": 639, "text": "Errors and Exceptions " }, { "code": null, "e": 788, "s": 663, "text": "If the position is not present in the vector, it throws out_of_range.It has a strong no exception throw guarantee otherwise." }, { "code": null, "e": 858, "s": 788, "text": "If the position is not present in the vector, it throws out_of_range." }, { "code": null, "e": 914, "s": 858, "text": "It has a strong no exception throw guarantee otherwise." }, { "code": null, "e": 946, "s": 914, "text": "Time Complexity – Constant O(1)" }, { "code": null, "e": 950, "s": 946, "text": "C++" }, { "code": "// CPP program to illustrate// Implementation of at() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(3); myvector.push_back(4); myvector.push_back(1); myvector.push_back(7); myvector.push_back(3); cout << myvector.at(3); return 0;}", "e": 1277, "s": 950, "text": null }, { "code": null, "e": 1279, "s": 1277, "text": "7" }, { "code": null, "e": 1373, "s": 1279, "text": "Applications: Given a vector of integers, print all the integers present at even positions. " }, { "code": null, "e": 1503, "s": 1373, "text": "Input: 1, 2, 3, 4, 5, 6, 7, 8, 9\nOutput: 1 3 5 7 9\nExplanation - 1, 3, 5, 7 and 9 are at position 0, 2, 4, 6 and 8 which are even" }, { "code": null, "e": 1515, "s": 1503, "text": "Algorithm " }, { "code": null, "e": 1639, "s": 1515, "text": "Run a loop till the size of the vector.Check if the position is divisible by 2, if yes, print the element at that position." }, { "code": null, "e": 1679, "s": 1639, "text": "Run a loop till the size of the vector." }, { "code": null, "e": 1764, "s": 1679, "text": "Check if the position is divisible by 2, if yes, print the element at that position." }, { "code": null, "e": 1768, "s": 1764, "text": "C++" }, { "code": "// CPP program to illustrate// Application of at() function#include <iostream>#include <vector>using namespace std; int main(){ vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(3); myvector.push_back(4); myvector.push_back(5); myvector.push_back(6); myvector.push_back(7); myvector.push_back(8); myvector.push_back(9); // vector becomes 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < myvector.size(); i += 2) { cout << myvector.at(i); cout << \" \"; } return 0;}", "e": 2325, "s": 1768, "text": null }, { "code": null, "e": 2336, "s": 2325, "text": "1 3 5 7 9 " }, { "code": null, "e": 2459, "s": 2336, "text": "This function is used to swap the contents of one vector with another vector of same type and sizes of vectors may differ." }, { "code": null, "e": 2468, "s": 2459, "text": "Syntax: " }, { "code": null, "e": 2633, "s": 2468, "text": "vectorname1.swap(vectorname2)\nParameters:\nThe name of the vector with which\nthe contents have to be swapped.\nResult: \nAll the elements of the 2 vectors are swapped." }, { "code": null, "e": 2645, "s": 2633, "text": "Examples: " }, { "code": null, "e": 2984, "s": 2645, "text": "Input: myvector1 = {1, 2, 3, 4}\n myvector2 = {3, 5, 7, 9}\n myvector1.swap(myvector2);\nOutput: myvector1 = {3, 5, 7, 9}\n myvector2 = {1, 2, 3, 4}\n\nInput: myvector1 = {1, 3, 5, 7}\n myvector2 = {2, 4, 6, 8}\n myvector1.swap(myvector2);\nOutput: myvector1 = {2, 4, 6, 8}\n myvector2 = {1, 3, 5, 7}" }, { "code": null, "e": 3008, "s": 2984, "text": "Errors and Exceptions " }, { "code": null, "e": 3120, "s": 3008, "text": "It throws an error if the vector is not of the same type.It has a basic no exception throw guarantee otherwise." }, { "code": null, "e": 3178, "s": 3120, "text": "It throws an error if the vector is not of the same type." }, { "code": null, "e": 3233, "s": 3178, "text": "It has a basic no exception throw guarantee otherwise." }, { "code": null, "e": 3265, "s": 3233, "text": "Time Complexity – Constant O(1)" }, { "code": null, "e": 3269, "s": 3265, "text": "C++" }, { "code": "// CPP program to illustrate// Implementation of swap() function#include <iostream>#include <vector>using namespace std; int main(){ // vector container declaration vector<int> myvector1{ 1, 2, 3, 4 }; vector<int> myvector2{ 3, 5, 7, 9 }; // using swap() function to swap // elements of vector myvector1.swap(myvector2); // printing the first vector cout << \"myvector1 = \"; for (auto it = myvector1.begin(); it < myvector1.end(); ++it) cout << *it << \" \"; // printing the second vector cout << endl << \"myvector2 = \"; for (auto it = myvector2.begin(); it < myvector2.end(); ++it) cout << *it << \" \"; return 0;}", "e": 3960, "s": 3269, "text": null }, { "code": null, "e": 4002, "s": 3960, "text": "myvector1 = 3 5 7 9 \nmyvector2 = 1 2 3 4 " }, { "code": null, "e": 4037, "s": 4002, "text": "If the size of the vectors differ:" }, { "code": null, "e": 4041, "s": 4037, "text": "C++" }, { "code": "// CPP program#include <iostream>#include <vector>using namespace std; int main(){ vector<int> vec1{ 100, 100, 100 }; vector<int> vec2{ 200, 200, 200, 200, 200 }; vec1.swap(vec2); cout << \"The vec1 contains:\"; for (int i = 0; i < vec1.size(); i++) cout << ' ' << vec1[i]; cout << '\\n'; cout << \"The vec2 contains:\"; for (int i = 0; i < vec2.size(); i++) cout << ' ' << vec2[i]; cout << '\\n'; return 0;}", "e": 4492, "s": 4041, "text": null }, { "code": null, "e": 4562, "s": 4492, "text": "The vec1 contains: 200 200 200 200 200\nThe vec2 contains: 100 100 100" }, { "code": null, "e": 4611, "s": 4562, "text": "Let us see the differences in a tabular form -: " }, { "code": null, "e": 4619, "s": 4611, "text": "soumya7" }, { "code": null, "e": 4633, "s": 4619, "text": "devgagrani123" }, { "code": null, "e": 4649, "s": 4633, "text": "shaista ambreen" }, { "code": null, "e": 4658, "s": 4649, "text": "7ckngmad" }, { "code": null, "e": 4667, "s": 4658, "text": "sweetyty" }, { "code": null, "e": 4686, "s": 4667, "text": "utkarshgupta110092" }, { "code": null, "e": 4700, "s": 4686, "text": "mayank007rawa" }, { "code": null, "e": 4711, "s": 4700, "text": "cpp-vector" }, { "code": null, "e": 4715, "s": 4711, "text": "STL" }, { "code": null, "e": 4719, "s": 4715, "text": "C++" }, { "code": null, "e": 4723, "s": 4719, "text": "STL" }, { "code": null, "e": 4727, "s": 4723, "text": "CPP" }, { "code": null, "e": 4825, "s": 4727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4868, "s": 4825, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 4902, "s": 4868, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 4927, "s": 4902, "text": "unordered_map in C++ STL" }, { "code": null, "e": 4946, "s": 4927, "text": "Inheritance in C++" }, { "code": null, "e": 4963, "s": 4946, "text": "Substring in C++" }, { "code": null, "e": 4987, "s": 4963, "text": "C++ Classes and Objects" }, { "code": null, "e": 5041, "s": 4987, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 5076, "s": 5041, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 5100, "s": 5076, "text": "Sorting a vector in C++" } ]
Flutter – Magic 8 Ball App
15 Jan, 2021 We will be building a Magic 8 Ball app that will give you the answers to all fun tricky questions (basically it is a fun game app that will change its state of image Flatbutton using Stateful widgets). For this, we will use Stateless and Stateful Flutter widgets, a Flatbutton. We will be using VS Code IDE for this project, you can also use Android Studio or any other IDE. Now, First, create the Flutter project with the initial steps and follow the below steps: Step 1: Create an images folder in the project directory and add the required images. Note: The images used in the article can be download images from here if you want to follow along. Step 2: Now, include the images in pubspec.yaml file to use them in the app. Note: Use proper indentation, otherwise your images will not be included. Step 3: Now, add the following code in main.dart file: Dart // importing flutter and dart packagesimport 'package:flutter/material.dart';import 'dart:math'; // Creates a Material Appvoid main() => runApp( MaterialApp( home: BallPage(), ), ); // Creates a Scaffold with// appbar using Stateless widget class BallPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.green[100], appBar: AppBar( backgroundColor: Colors.green[600], title: Text('GeeksforGeeks'), ), body: Ball(), ); }} // Creates a Stateful widget class Ball extends StatefulWidget { Ball({Key key}) : super(key: key); @override _BallState createState() => _BallState();} class _BallState extends State<Ball> { int ballNumber = 1; @override // Returns app with centered image Flatbutton Widget build(BuildContext context) { return Center( child: FlatButton( onPressed: () { setState(() { // Random.nextInt(n) returns random // integer from 0 to n-1 ballNumber = Random().nextInt(5) + 1; }); }, // Adding images child: Image.asset('images/ball$ballNumber.png'), ), ); }} Output: android Flutter Technical Scripter 2020 Dart Flutter Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - Asset Image Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Stack Widget Flutter - Search Bar
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jan, 2021" }, { "code": null, "e": 333, "s": 54, "text": "We will be building a Magic 8 Ball app that will give you the answers to all fun tricky questions (basically it is a fun game app that will change its state of image Flatbutton using Stateful widgets). For this, we will use Stateless and Stateful Flutter widgets, a Flatbutton. " }, { "code": null, "e": 520, "s": 333, "text": "We will be using VS Code IDE for this project, you can also use Android Studio or any other IDE. Now, First, create the Flutter project with the initial steps and follow the below steps:" }, { "code": null, "e": 606, "s": 520, "text": "Step 1: Create an images folder in the project directory and add the required images." }, { "code": null, "e": 705, "s": 606, "text": "Note: The images used in the article can be download images from here if you want to follow along." }, { "code": null, "e": 782, "s": 705, "text": "Step 2: Now, include the images in pubspec.yaml file to use them in the app." }, { "code": null, "e": 856, "s": 782, "text": "Note: Use proper indentation, otherwise your images will not be included." }, { "code": null, "e": 911, "s": 856, "text": "Step 3: Now, add the following code in main.dart file:" }, { "code": null, "e": 916, "s": 911, "text": "Dart" }, { "code": "// importing flutter and dart packagesimport 'package:flutter/material.dart';import 'dart:math'; // Creates a Material Appvoid main() => runApp( MaterialApp( home: BallPage(), ), ); // Creates a Scaffold with// appbar using Stateless widget class BallPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.green[100], appBar: AppBar( backgroundColor: Colors.green[600], title: Text('GeeksforGeeks'), ), body: Ball(), ); }} // Creates a Stateful widget class Ball extends StatefulWidget { Ball({Key key}) : super(key: key); @override _BallState createState() => _BallState();} class _BallState extends State<Ball> { int ballNumber = 1; @override // Returns app with centered image Flatbutton Widget build(BuildContext context) { return Center( child: FlatButton( onPressed: () { setState(() { // Random.nextInt(n) returns random // integer from 0 to n-1 ballNumber = Random().nextInt(5) + 1; }); }, // Adding images child: Image.asset('images/ball$ballNumber.png'), ), ); }}", "e": 2160, "s": 916, "text": null }, { "code": null, "e": 2169, "s": 2160, "text": "Output: " }, { "code": null, "e": 2177, "s": 2169, "text": "android" }, { "code": null, "e": 2185, "s": 2177, "text": "Flutter" }, { "code": null, "e": 2209, "s": 2185, "text": "Technical Scripter 2020" }, { "code": null, "e": 2214, "s": 2209, "text": "Dart" }, { "code": null, "e": 2222, "s": 2214, "text": "Flutter" }, { "code": null, "e": 2241, "s": 2222, "text": "Technical Scripter" }, { "code": null, "e": 2339, "s": 2241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2371, "s": 2339, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 2399, "s": 2371, "text": "Listview.builder in Flutter" }, { "code": null, "e": 2438, "s": 2399, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2463, "s": 2438, "text": "Splash Screen in Flutter" }, { "code": null, "e": 2485, "s": 2463, "text": "Flutter - Asset Image" }, { "code": null, "e": 2517, "s": 2485, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 2556, "s": 2517, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 2582, "s": 2556, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 2605, "s": 2582, "text": "Flutter - Stack Widget" } ]
SQL - GeeksforGeeks
03 Aug, 2021 CREATE TABLE temp ( id INT, name VARCHAR(100) ); INSERT INTO temp VALUES (1, "abc"); INSERT INTO temp VALUES (2, "abc"); INSERT INTO temp VALUES (3, "bcd"); INSERT INTO temp VALUES (4, "cde"); SELECT Count(*) FROM temp GROUP BY name; count(*) -------- 2 1 1 SELECT 'T' AS result FROM Book HAVING MIN(NumberOfPages) < MAX(NumberOfPages); Table A Id Name Age ---------------- 12 Arun 60 15 Shreya 24 99 Rohit 11 Table B Id Name Age ---------------- 15 Shreya 24 25 Hari 40 98 Rohit 20 99 Rohit 11 Table C Id Phone Area ----------------- 10 2200 02 99 2100 01 SELECT A.id FROM A WHERE A.age > ALL (SELECT B.age FROM B WHERE B. name = "arun") SELECT Y FROM T WHERE X=7; Borrower Bank_Manager Loan_Amount Ramesh Sunderajan 10000.00 Suresh Ramgopal 5000.00 Mahesh Sunderajan 7000.00 SELECT Count(*) FROM ( ( SELECT Borrower, Bank_Manager FROM Loan_Records) AS S NATURAL JOIN ( SELECT Bank_Manager, Loan_Amount FROM Loan_Records) AS T ); See Question 3 of http://www.geeksforgeeks.org/database-management-systems-set-4/ Table: Passenger pid pname age ----------------- 0 Sachin 65 1 Rahul 66 2 Sourav 67 3 Anil 69 Table : Reservation pid class tid --------------- 0 AC 8200 1 AC 8201 2 SC 8201 5 AC 8203 1 SC 8204 3 AC 8202 SLECT pid FROM Reservation , WHERE class ‘AC’ AND EXISTS (SELECT * FROM Passenger WHERE age > 65 AND Passenger. pid = Reservation.pid) IV) SELECT R.a, R.b FROM R,S WHERE R.c=S.c Consider the following relational schema: Suppliers(sid:integer, sname:string, city:string, street:string) Parts(pid:integer, pname:string, color:string) Catalog(sid:integer, pid:integer, cost:real) Consider the following relational query on the above database: SELECT S.sname FROM Suppliers S WHERE S.sid NOT IN (SELECT C.sid FROM Catalog C WHERE C.pid NOT IN (SELECT P.pid FROM Parts P WHERE P.color<> 'blue')) Assume that relations corresponding to the above schema are not empty. Which one of the following is the correct interpretation of the above query? Find the names of all suppliers who have supplied a non-blue part. Find the names of all suppliers who have not supplied a non-blue part. Find the names of all suppliers who have supplied only blue parts. Find the names of all suppliers who have not supplied only blue parts. None (D) option matched because given query returns suppliers who have not supplied any blue parts. That means it can include other than blue parts. (A): False, as this may include blue parts and may not include "null" parts. (B): Obviously false because it returning other than any blue part. (C): Obviously false because it does not return this. (D): Correct. Please try here: http://sqlfiddle.com/#!9/9ae12d/1/0 This explanation is contributed by Archit Garg. Q1 : Select e.empId From employee e Where not exists (Select * From employee s where s.department = “5” and s.salary >=e.salary) Q2 : Select e.empId From employee e Where e.salary > Any (Select distinct salary From employee s Where s.department = “5”) e1 ------- A-------- 1---------10000 e2 -------B ------- 5 ---------5000 e3 -------C ------- 5----------7000 e4 -------D ------- 2----------2000 e5 -------E ------- 3----------6000 Now the actual result should contain empId : e1 , e3 and e5 ( because they have salary greater than anyone employee in the department '5') -------------------------------------------------------- Now Q1 : Note : EXISTS(empty set) gives FALSE, and NOT EXISTS(empty set) gives TRUE. Select e.empId From employee e Where not exists (Select * From employee s where s.department = “5” and s.salary >=e.salary) Q1 will result only empId e1. --------------------------------------------------------- whereas Q2 : Select e.empId From employee e Where e.salary > Any (Select distinct salary From employee s Where s.department = “5”) Q2 will result empId e1, e3 and e5. -------------------------------------------------------- Hence Q1 is the correct query. Note that if we use ALL in place of Any in second query then this will be correct. Option (A) is correct. S1: A foreign key declaration can always be replaced by an equivalent check assertion in SQL. S2: Given the table R(a,b,c) where a and b together form the primary key, the following is a valid table definition. CREATE TABLE S ( a INTEGER, d INTEGER, e INTEGER, PRIMARY KEY (d), FOREIGN KEY (a) references R) Using a check condition we can have the same effect as Foreign key while adding elements to the child table. But when we delete an element from the parent table the referential integrity constraint is no longer valid. So, a check constraint cannot replace a foreign key. So, we cannot replace it with a single check. S2: Given the table R(a,b,c) where a and b together form the primary key, the following is a valid table definition. CREATE TABLE S ( a INTEGER, d INTEGER, e INTEGER, PRIMARY KEY (d), FOREIGN KEY (a) references R) False: Foreign key in one table should uniquely identifies a row of other table. In above table definition, table S has a foreign key that refers to field 'a' of R. The field 'a' in table S doesn't uniquely identify a row in table R. employees(emp-id, first-name, last-name, hire-date, dept-id, salary) departments(dept-id, dept-name, manager-id, location-id) SQL> SELECT last-name, hire-date FROM employees WHERE (dept-id, hire-date) IN ( SELECT dept-id, MAX(hire-date) FROM employees JOIN departments USING(dept-id) WHERE location-id = 1700 GROUP BY dept-id); SELECT dept-id, MAX(hire-date) FROM employees JOIN departments USING(dept-id) WHERE location-id = 1700 GROUP BY dept-id SELECT last-name, hire-date FROM employees WHERE (dept-id, hire-date) IN (Inner-Query); Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... Must Do Coding Questions for Product Based Companies 50 Common Ports You Should Know GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge? How to Find Length of String in Bash Script? Order and Ranking Questions & Answers Spring Boot - Thymeleaf with Example Naming Convention in C++ Floyd’s Cycle Finding Algorithm How to add horizontal line in HTML ?
[ { "code": null, "e": 31567, "s": 31539, "text": "\n03 Aug, 2021" }, { "code": null, "e": 31835, "s": 31567, "text": "CREATE TABLE temp \n ( \n id INT, \n name VARCHAR(100) \n ); \n\nINSERT INTO temp VALUES (1, \"abc\"); \nINSERT INTO temp VALUES (2, \"abc\"); \nINSERT INTO temp VALUES (3, \"bcd\"); \nINSERT INTO temp VALUES (4, \"cde\"); \n\nSELECT Count(*) \nFROM temp \nGROUP BY name; \n" }, { "code": null, "e": 31860, "s": 31835, "text": "count(*)\n--------\n2\n1\n1\n" }, { "code": null, "e": 31945, "s": 31860, "text": " SELECT 'T' AS result\n FROM Book\n HAVING MIN(NumberOfPages) < MAX(NumberOfPages);\n" }, { "code": null, "e": 32219, "s": 31945, "text": "Table A\nId Name Age\n----------------\n12 Arun 60\n15 Shreya 24\n99 Rohit 11\n\n\nTable B\nId Name Age\n----------------\n15 Shreya 24\n25 Hari 40\n98 Rohit 20\n99 Rohit 11\n\n\nTable C\nId Phone Area\n-----------------\n10 2200 02 \n99 2100 01" }, { "code": null, "e": 32353, "s": 32219, "text": "SELECT A.id \nFROM A \nWHERE A.age > ALL (SELECT B.age \n FROM B \n WHERE B. name = \"arun\") \n" }, { "code": null, "e": 32381, "s": 32353, "text": "SELECT Y FROM T WHERE X=7;\n" }, { "code": null, "e": 32529, "s": 32381, "text": "Borrower Bank_Manager Loan_Amount\n Ramesh Sunderajan 10000.00\n Suresh Ramgopal 5000.00\n Mahesh Sunderajan 7000.00" }, { "code": null, "e": 32733, "s": 32529, "text": "SELECT Count(*) \nFROM ( ( SELECT Borrower, Bank_Manager \n FROM Loan_Records) AS S \n NATURAL JOIN ( SELECT Bank_Manager, Loan_Amount \n FROM Loan_Records) AS T );" }, { "code": null, "e": 32815, "s": 32733, "text": "See Question 3 of http://www.geeksforgeeks.org/database-management-systems-set-4/" }, { "code": null, "e": 33089, "s": 32815, "text": "Table: Passenger\npid pname age\n-----------------\n 0 Sachin 65\n 1 Rahul 66\n 2 Sourav 67\n 3 Anil 69\n\nTable : Reservation\npid class tid\n---------------\n 0 AC 8200\n 1 AC 8201\n 2 SC 8201\n 5 AC 8203\n 1 SC 8204\n 3 AC 8202" }, { "code": null, "e": 33249, "s": 33089, "text": "SLECT pid\nFROM Reservation ,\nWHERE class ‘AC’ AND\n EXISTS (SELECT *\n FROM Passenger\n WHERE age > 65 AND\n Passenger. pid = Reservation.pid)" }, { "code": null, "e": 33311, "s": 33249, "text": "IV) SELECT R.a, R.b\n FROM R,S\n WHERE R.c=S.c" }, { "code": null, "e": 33355, "s": 33311, "text": "Consider the following relational schema: " }, { "code": null, "e": 33512, "s": 33355, "text": "Suppliers(sid:integer, sname:string, city:string, street:string)\nParts(pid:integer, pname:string, color:string)\nCatalog(sid:integer, pid:integer, cost:real)" }, { "code": null, "e": 33577, "s": 33512, "text": "Consider the following relational query on the above database: " }, { "code": null, "e": 33894, "s": 33577, "text": "SELECT S.sname\n FROM Suppliers S\n WHERE S.sid NOT IN (SELECT C.sid\n FROM Catalog C\n WHERE C.pid NOT IN (SELECT P.pid \n FROM Parts P\n WHERE P.color<> 'blue'))" }, { "code": null, "e": 34043, "s": 33894, "text": "Assume that relations corresponding to the above schema are not empty. Which one of the following is the correct interpretation of the above query? " }, { "code": null, "e": 34111, "s": 34043, "text": "Find the names of all suppliers who have supplied a non-blue part. " }, { "code": null, "e": 34183, "s": 34111, "text": "Find the names of all suppliers who have not supplied a non-blue part. " }, { "code": null, "e": 34251, "s": 34183, "text": "Find the names of all suppliers who have supplied only blue parts. " }, { "code": null, "e": 34323, "s": 34251, "text": "Find the names of all suppliers who have not supplied only blue parts. " }, { "code": null, "e": 34329, "s": 34323, "text": "None " }, { "code": null, "e": 34788, "s": 34329, "text": "(D) option matched because given query returns suppliers who have not supplied any blue parts. That means it can include other than blue parts. (A): False, as this may include blue parts and may not include \"null\" parts. (B): Obviously false because it returning other than any blue part. (C): Obviously false because it does not return this. (D): Correct. Please try here: http://sqlfiddle.com/#!9/9ae12d/1/0 This explanation is contributed by Archit Garg. " }, { "code": null, "e": 35114, "s": 34788, "text": "Q1 : Select e.empId\n From employee e\n Where not exists\n (Select * From employee s where s.department = “5” and \n s.salary >=e.salary)\nQ2 : Select e.empId\n From employee e\n Where e.salary > Any\n (Select distinct salary From employee s Where s.department = “5”)\n" }, { "code": null, "e": 35296, "s": 35114, "text": "e1 ------- A-------- 1---------10000\ne2 -------B ------- 5 ---------5000\ne3 -------C ------- 5----------7000\ne4 -------D ------- 2----------2000\ne5 -------E ------- 3----------6000\n" }, { "code": null, "e": 35579, "s": 35296, "text": "Now the actual result should contain empId : e1 , e3 and e5 ( because they have salary greater than anyone employee in the department '5') -------------------------------------------------------- Now Q1 : Note : EXISTS(empty set) gives FALSE, and NOT EXISTS(empty set) gives TRUE. " }, { "code": null, "e": 35705, "s": 35579, "text": "Select e.empId\nFrom employee e\nWhere not exists\n(Select * From employee s where s.department = “5” and\ns.salary >=e.salary)\n\n" }, { "code": null, "e": 35808, "s": 35705, "text": "Q1 will result only empId e1. --------------------------------------------------------- whereas Q2 : " }, { "code": null, "e": 35928, "s": 35808, "text": "Select e.empId\nFrom employee e\nWhere e.salary > Any\n(Select distinct salary From employee s Where s.department = “5”)\n\n" }, { "code": null, "e": 36158, "s": 35928, "text": "Q2 will result empId e1, e3 and e5. -------------------------------------------------------- Hence Q1 is the correct query. Note that if we use ALL in place of Any in second query then this will be correct. Option (A) is correct." }, { "code": null, "e": 36577, "s": 36158, "text": " S1: A foreign key declaration can always \n be replaced by an equivalent check\n assertion in SQL.\n S2: Given the table R(a,b,c) where a and\n b together form the primary key, the \n following is a valid table definition.\n CREATE TABLE S (\n a INTEGER,\n d INTEGER,\n e INTEGER,\n PRIMARY KEY (d),\n FOREIGN KEY (a) references R) " }, { "code": null, "e": 36848, "s": 36577, "text": "Using a check condition we can have the same effect as Foreign key while adding elements to the child table. But when we delete an element from the parent table the referential integrity constraint is no longer valid. So, a check constraint cannot replace a foreign key." }, { "code": null, "e": 36895, "s": 36848, "text": "So, we cannot replace it with a single check. " }, { "code": null, "e": 37201, "s": 36895, "text": " S2: Given the table R(a,b,c) where a and\n b together form the primary key, the\n following is a valid table definition.\n CREATE TABLE S (\n a INTEGER,\n d INTEGER,\n e INTEGER,\n PRIMARY KEY (d),\n FOREIGN KEY (a) references R) \n\n\n" }, { "code": null, "e": 37435, "s": 37201, "text": "False: Foreign key in one table should uniquely identifies a row of other table. In above table definition, table S has a foreign key that refers to field 'a' of R. The field 'a' in table S doesn't uniquely identify a row in table R." }, { "code": null, "e": 37572, "s": 37435, "text": " employees(emp-id, first-name, last-name, hire-date, dept-id, salary)\n departments(dept-id, dept-name, manager-id, location-id) " }, { "code": null, "e": 37896, "s": 37572, "text": "SQL> SELECT last-name, hire-date\n FROM employees\n WHERE (dept-id, hire-date) IN ( SELECT dept-id, MAX(hire-date)\n FROM employees JOIN departments USING(dept-id)\n WHERE location-id = 1700\n GROUP BY dept-id); " }, { "code": null, "e": 38032, "s": 37896, "text": "SELECT dept-id, MAX(hire-date)\n FROM employees JOIN departments USING(dept-id)\n WHERE location-id = 1700\n GROUP BY dept-id\n" }, { "code": null, "e": 38137, "s": 38032, "text": "SELECT last-name, hire-date\n FROM employees\n WHERE (dept-id, hire-date) IN\n (Inner-Query); \n" }, { "code": null, "e": 38235, "s": 38137, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 38309, "s": 38235, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 38362, "s": 38309, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 38394, "s": 38362, "text": "50 Common Ports You Should Know" }, { "code": null, "e": 38460, "s": 38394, "text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?" }, { "code": null, "e": 38505, "s": 38460, "text": "How to Find Length of String in Bash Script?" }, { "code": null, "e": 38543, "s": 38505, "text": "Order and Ranking Questions & Answers" }, { "code": null, "e": 38580, "s": 38543, "text": "Spring Boot - Thymeleaf with Example" }, { "code": null, "e": 38605, "s": 38580, "text": "Naming Convention in C++" }, { "code": null, "e": 38637, "s": 38605, "text": "Floyd’s Cycle Finding Algorithm" } ]
Why to use char[] array over a string for storing passwords in Java?
20 Jun, 2022 1. Strings are immutable: Strings are immutable in Java and therefore if a password is stored as plain text it will be available in memory until Garbage collector clears it and as Strings are used in the String pool for re-usability there are high chances that it will remain in memory for long duration, which is a security threat. Strings are immutable and there is no way that the content of Strings can be changed because any change will produce new String. Within an array, the data can be wiped explicitly after its work is completed. The array can be overwritten and the password won’t be present anywhere in the system, even before garbage collection. 2. Security: Any one who has access to memory dump can find the password in clear text and that’s another reason to use encrypted password than plain text. So Storing password in character array clearly mitigates security risk of stealing password. 3. Log file safety: With an array, one can explicitly wipe the data , overwrite the array and the password won’t be present anywhere in the system. With plain String, there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable. Java //Java program to illustrate preferring char[] arrays//over strings for passwords in Javapublic class PasswordPreference{ public static void main(String[] args) { String strPwd = "password"; char[] charPwd = new char[] {'p','a','s','s','w','o','r','d'}; System.out.println("String password: " + strPwd ); System.out.println("Character password: " + charPwd ); }} Output: String password: password Character password: [C@15db9742 4. Java Recommendation: Java has methods like JPasswordField of javax.swing as the method public String getText() which returns String is Deprecated from Java 2 and is replaced by public char[] getPassword() which returns Char Array. This article is contributed by Kanika Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and 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 if you want to share more information about the topic discussed above. sagar0719kumar kashishsoda ankur035 Java-Array-Programs Java-String-Programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jun, 2022" }, { "code": null, "e": 715, "s": 54, "text": "1. Strings are immutable: Strings are immutable in Java and therefore if a password is stored as plain text it will be available in memory until Garbage collector clears it and as Strings are used in the String pool for re-usability there are high chances that it will remain in memory for long duration, which is a security threat. Strings are immutable and there is no way that the content of Strings can be changed because any change will produce new String. Within an array, the data can be wiped explicitly after its work is completed. The array can be overwritten and the password won’t be present anywhere in the system, even before garbage collection." }, { "code": null, "e": 966, "s": 715, "text": "2. Security: Any one who has access to memory dump can find the password in clear text and that’s another reason to use encrypted password than plain text. So Storing password in character array clearly mitigates security risk of stealing password. " }, { "code": null, "e": 1276, "s": 966, "text": "3. Log file safety: With an array, one can explicitly wipe the data , overwrite the array and the password won’t be present anywhere in the system. With plain String, there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable." }, { "code": null, "e": 1281, "s": 1276, "text": "Java" }, { "code": "//Java program to illustrate preferring char[] arrays//over strings for passwords in Javapublic class PasswordPreference{ public static void main(String[] args) { String strPwd = \"password\"; char[] charPwd = new char[] {'p','a','s','s','w','o','r','d'}; System.out.println(\"String password: \" + strPwd ); System.out.println(\"Character password: \" + charPwd ); }}", "e": 1694, "s": 1281, "text": null }, { "code": null, "e": 1703, "s": 1694, "text": "Output: " }, { "code": null, "e": 1761, "s": 1703, "text": "String password: password\nCharacter password: [C@15db9742" }, { "code": null, "e": 1995, "s": 1761, "text": "4. Java Recommendation: Java has methods like JPasswordField of javax.swing as the method public String getText() which returns String is Deprecated from Java 2 and is replaced by public char[] getPassword() which returns Char Array." }, { "code": null, "e": 2262, "s": 1995, "text": "This article is contributed by Kanika Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2390, "s": 2262, "text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 2405, "s": 2390, "text": "sagar0719kumar" }, { "code": null, "e": 2417, "s": 2405, "text": "kashishsoda" }, { "code": null, "e": 2426, "s": 2417, "text": "ankur035" }, { "code": null, "e": 2446, "s": 2426, "text": "Java-Array-Programs" }, { "code": null, "e": 2467, "s": 2446, "text": "Java-String-Programs" }, { "code": null, "e": 2472, "s": 2467, "text": "Java" }, { "code": null, "e": 2477, "s": 2472, "text": "Java" } ]
Ways to apply LEFT, RIGHT, MID in Pandas
28 Jul, 2020 Many times we need to extract specific characters present within a string in Pandas data frame. In order to solve this issue, we have concept of Left, Right, and Mid in pandas. Example 1: Extract Characters From the Left Python3 # importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['1000-BMW','2000-Audi','3000-Volkswagen', '4000-Datsun','5000-Toyota','6000-Maruti Suzuki'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters from right side# using slicing and storing result in # 'Left'Left = df['Model_name'].str[:4] print(Left) Output : 0 1000 1 2000 2 3000 3 4000 4 5000 5 6000 Name: Model_name, dtype: object Example 2: Extract Characters From the Right Python3 # importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['ID-11111-BMW','ID-22222-Volkswagen', 'ID-33333-Toyota','ID-44444-Hyundai ', 'ID-55555-Datsun','ID-66666-Mercedes'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters from left side using# slicing and storing result in 'Right'Right = df['Model_name'].str[4:8] print (Right) Output : 0 11111 1 22222 2 33333 3 44444 4 55555 5 66666 Name: Model_name, dtype: object Example 3: Extract Characters From the Middle Python3 # importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['ID-11111-BMW','ID-22222-Volkswagen', 'ID-33333-Toyota','ID-44444-Hyundai ', 'ID-55555-Datsun','ID-66666-Mercedes'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters from Middle using # slicing and storing result in 'Mid'Mid = df['Model_name'].str[4:8] print (Mid) Output : 0 1111 1 2222 2 3333 3 4444 4 5555 5 6666 Name: Model_name, dtype: object Example 4 : Before a symbol using str.split() function Python3 # importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['1000-BMW','2000-Audi', '3000-Volkswagen','4000-Datsun', '5000-Toyota','6000-Maruti Suzuki'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters before symbol "-"# using srt.strip() and str[0]# and storing result to 'Before_symbol'Before_symbol = df['Model_name'].str.split('-').str[0] print (Before_symbol) Output : 0 1000 1 2000 2 3000 3 4000 4 5000 5 6000 Name: Model_name, dtype: object Example 5 : Between identical symbols using str.split() function Python3 # importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['M3-1906-BMW','M5-2096-Audi', 'M11-3096-Volkswagen','M9-4096-Datsun', 'M8-5096-Toyota','M23-6096-Maruti Suzuki'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters between symbol "-"# using srt.strip() and str[1]# and storing result to 'Before_symbol'BetweenTwoSymbols = df['Model_name'].str.split('-').str[1] print (BetweenTwoSymbols) Output : 0 1906 1 2096 2 3096 3 4096 4 5096 5 6096 Name: Model_name, dtype: object Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 205, "s": 28, "text": "Many times we need to extract specific characters present within a string in Pandas data frame. In order to solve this issue, we have concept of Left, Right, and Mid in pandas." }, { "code": null, "e": 249, "s": 205, "text": "Example 1: Extract Characters From the Left" }, { "code": null, "e": 257, "s": 249, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['1000-BMW','2000-Audi','3000-Volkswagen', '4000-Datsun','5000-Toyota','6000-Maruti Suzuki'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters from right side# using slicing and storing result in # 'Left'Left = df['Model_name'].str[:4] print(Left)", "e": 656, "s": 257, "text": null }, { "code": null, "e": 665, "s": 656, "text": "Output :" }, { "code": null, "e": 758, "s": 665, "text": "0 1000\n1 2000\n2 3000\n3 4000\n4 5000\n5 6000\nName: Model_name, dtype: object\n" }, { "code": null, "e": 803, "s": 758, "text": "Example 2: Extract Characters From the Right" }, { "code": null, "e": 811, "s": 803, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['ID-11111-BMW','ID-22222-Volkswagen', 'ID-33333-Toyota','ID-44444-Hyundai ', 'ID-55555-Datsun','ID-66666-Mercedes'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters from left side using# slicing and storing result in 'Right'Right = df['Model_name'].str[4:8] print (Right)", "e": 1243, "s": 811, "text": null }, { "code": null, "e": 1252, "s": 1243, "text": "Output :" }, { "code": null, "e": 1351, "s": 1252, "text": "0 11111\n1 22222\n2 33333\n3 44444\n4 55555\n5 66666\nName: Model_name, dtype: object\n" }, { "code": null, "e": 1397, "s": 1351, "text": "Example 3: Extract Characters From the Middle" }, { "code": null, "e": 1405, "s": 1397, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['ID-11111-BMW','ID-22222-Volkswagen', 'ID-33333-Toyota','ID-44444-Hyundai ', 'ID-55555-Datsun','ID-66666-Mercedes'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters from Middle using # slicing and storing result in 'Mid'Mid = df['Model_name'].str[4:8] print (Mid)", "e": 1829, "s": 1405, "text": null }, { "code": null, "e": 1838, "s": 1829, "text": "Output :" }, { "code": null, "e": 1931, "s": 1838, "text": "0 1111\n1 2222\n2 3333\n3 4444\n4 5555\n5 6666\nName: Model_name, dtype: object\n" }, { "code": null, "e": 1986, "s": 1931, "text": "Example 4 : Before a symbol using str.split() function" }, { "code": null, "e": 1994, "s": 1986, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['1000-BMW','2000-Audi', '3000-Volkswagen','4000-Datsun', '5000-Toyota','6000-Maruti Suzuki'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters before symbol \"-\"# using srt.strip() and str[0]# and storing result to 'Before_symbol'Before_symbol = df['Model_name'].str.split('-').str[0] print (Before_symbol)", "e": 2459, "s": 1994, "text": null }, { "code": null, "e": 2468, "s": 2459, "text": "Output :" }, { "code": null, "e": 2561, "s": 2468, "text": "0 1000\n1 2000\n2 3000\n3 4000\n4 5000\n5 6000\nName: Model_name, dtype: object\n" }, { "code": null, "e": 2627, "s": 2561, "text": "Example 5 : Between identical symbols using str.split() function" }, { "code": null, "e": 2635, "s": 2627, "text": "Python3" }, { "code": "# importing pandas libraryimport pandas as pd # creating and initializing a list Cars = ['M3-1906-BMW','M5-2096-Audi', 'M11-3096-Volkswagen','M9-4096-Datsun', 'M8-5096-Toyota','M23-6096-Maruti Suzuki'] # creating a pandas dataframedf = pd.DataFrame(Cars, columns= ['Model_name']) # Extracting characters between symbol \"-\"# using srt.strip() and str[1]# and storing result to 'Before_symbol'BetweenTwoSymbols = df['Model_name'].str.split('-').str[1] print (BetweenTwoSymbols)", "e": 3129, "s": 2635, "text": null }, { "code": null, "e": 3138, "s": 3129, "text": "Output :" }, { "code": null, "e": 3231, "s": 3138, "text": "0 1906\n1 2096\n2 3096\n3 4096\n4 5096\n5 6096\nName: Model_name, dtype: object\n" }, { "code": null, "e": 3255, "s": 3231, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3269, "s": 3255, "text": "Python-pandas" }, { "code": null, "e": 3276, "s": 3269, "text": "Python" } ]
How to use bcrypt for hashing passwords in PHP?
04 Jul, 2019 Everyone knows and understands that storing the password in a clear text in the database is a quite rude thing and not secure. Yet, several do it because it makes an internet site quite easy for password recovery or testing.The bcrypt is a password hashing technique used to build password security. It is used to protect the password from hacking attacks because of the password is stored in bcrypted format. The password_hash() function in PHP is an inbuilt function which is used to create a new password hash. It uses a strong & robust hashing algorithm. The password_hash() function is very much compatible with the crypt() function. Therefore, password hashes created by crypt() may be used with password_hash() and vice-versa. The functions password_verify() and password_hash() just the wrappers around the function crypt(), and they make it much easier to use it accurately. Syntax: string password_hash( $password, $algo, $options ) The following algorithms are currently supported by password_hash() function: PASSWORD_DEFAULT PASSWORD_BCRYPT PASSWORD_ARGON2I PASSWORD_ARGON2ID Parameters: This function accepts three parameters as mentioned above and described below: password: It stores the password of the user. algo: It is the password algorithm constant that is used continuously while denoting the algorithm which is to be used when the hashing of password takes place. options: It is an associative array, which contains the options. If this is removed and doesn’t include, a random salt is going to be used, and the utilization of a default cost will happen. Return Value: It returns the hashed password on success or False on failure. Example: Input : echo password_hash("GFG@123", PASSWORD_DEFAULT); Output : $2y$10$.vGA19Jh8YrwSJFDodbfoHJIOFH)DfhuofGv3Fykk1a Below programs illustrate the passwor_hash() function in PHP: Program 1: <?php echo password_hash("GFG@123", PASSWORD_DEFAULT);?> $2y$10$Z166W1fBdsLcXPVQVfPw/uRq1ueWMA6sLt9bmdUFz9AmOGLdM393G Program 2: <?php $options = [ 'cost' => 12,]; echo password_hash("GFG@123", PASSWORD_BCRYPT, $options);?> $2y$12$jgzGJmLsUHGNjmDK98MbWe82e3CIJZuflAj6lE1I.dlyhSVfz42oq Program 3: <?php $timeTarget = 0.069; // 69 milliseconds $cost = 8;do { $cost++; $start = microtime(true); password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]); $end = microtime(true);} while (($end - $start) < $timeTarget); echo "The appropriate cost is: " . $cost;?> The appropriate cost is: 10 Program 4: <?phpecho 'Argon2i hash: ' . password_hash('GFG@123', PASSWORD_ARGON2I);?> Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YUNvTkJBT2dEejQuUVQvRQ$+96jm/eISqZ7+P9n0DrsBf25piwfnLRy2Yy1VYmb9iI Reference: https://www.php.net/manual/en/function.password-hash.php Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2019" }, { "code": null, "e": 438, "s": 28, "text": "Everyone knows and understands that storing the password in a clear text in the database is a quite rude thing and not secure. Yet, several do it because it makes an internet site quite easy for password recovery or testing.The bcrypt is a password hashing technique used to build password security. It is used to protect the password from hacking attacks because of the password is stored in bcrypted format." }, { "code": null, "e": 912, "s": 438, "text": "The password_hash() function in PHP is an inbuilt function which is used to create a new password hash. It uses a strong & robust hashing algorithm. The password_hash() function is very much compatible with the crypt() function. Therefore, password hashes created by crypt() may be used with password_hash() and vice-versa. The functions password_verify() and password_hash() just the wrappers around the function crypt(), and they make it much easier to use it accurately." }, { "code": null, "e": 920, "s": 912, "text": "Syntax:" }, { "code": null, "e": 971, "s": 920, "text": "string password_hash( $password, $algo, $options )" }, { "code": null, "e": 1049, "s": 971, "text": "The following algorithms are currently supported by password_hash() function:" }, { "code": null, "e": 1066, "s": 1049, "text": "PASSWORD_DEFAULT" }, { "code": null, "e": 1082, "s": 1066, "text": "PASSWORD_BCRYPT" }, { "code": null, "e": 1099, "s": 1082, "text": "PASSWORD_ARGON2I" }, { "code": null, "e": 1117, "s": 1099, "text": "PASSWORD_ARGON2ID" }, { "code": null, "e": 1208, "s": 1117, "text": "Parameters: This function accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 1254, "s": 1208, "text": "password: It stores the password of the user." }, { "code": null, "e": 1415, "s": 1254, "text": "algo: It is the password algorithm constant that is used continuously while denoting the algorithm which is to be used when the hashing of password takes place." }, { "code": null, "e": 1606, "s": 1415, "text": "options: It is an associative array, which contains the options. If this is removed and doesn’t include, a random salt is going to be used, and the utilization of a default cost will happen." }, { "code": null, "e": 1683, "s": 1606, "text": "Return Value: It returns the hashed password on success or False on failure." }, { "code": null, "e": 1692, "s": 1683, "text": "Example:" }, { "code": null, "e": 1810, "s": 1692, "text": "Input : echo password_hash(\"GFG@123\", PASSWORD_DEFAULT);\nOutput : $2y$10$.vGA19Jh8YrwSJFDodbfoHJIOFH)DfhuofGv3Fykk1a\n" }, { "code": null, "e": 1872, "s": 1810, "text": "Below programs illustrate the passwor_hash() function in PHP:" }, { "code": null, "e": 1883, "s": 1872, "text": "Program 1:" }, { "code": "<?php echo password_hash(\"GFG@123\", PASSWORD_DEFAULT);?>", "e": 1941, "s": 1883, "text": null }, { "code": null, "e": 2003, "s": 1941, "text": "$2y$10$Z166W1fBdsLcXPVQVfPw/uRq1ueWMA6sLt9bmdUFz9AmOGLdM393G\n" }, { "code": null, "e": 2014, "s": 2003, "text": "Program 2:" }, { "code": "<?php $options = [ 'cost' => 12,]; echo password_hash(\"GFG@123\", PASSWORD_BCRYPT, $options);?>", "e": 2114, "s": 2014, "text": null }, { "code": null, "e": 2176, "s": 2114, "text": "$2y$12$jgzGJmLsUHGNjmDK98MbWe82e3CIJZuflAj6lE1I.dlyhSVfz42oq\n" }, { "code": null, "e": 2187, "s": 2176, "text": "Program 3:" }, { "code": "<?php $timeTarget = 0.069; // 69 milliseconds $cost = 8;do { $cost++; $start = microtime(true); password_hash(\"test\", PASSWORD_BCRYPT, [\"cost\" => $cost]); $end = microtime(true);} while (($end - $start) < $timeTarget); echo \"The appropriate cost is: \" . $cost;?>", "e": 2466, "s": 2187, "text": null }, { "code": null, "e": 2495, "s": 2466, "text": "The appropriate cost is: 10\n" }, { "code": null, "e": 2506, "s": 2495, "text": "Program 4:" }, { "code": "<?phpecho 'Argon2i hash: ' . password_hash('GFG@123', PASSWORD_ARGON2I);?>", "e": 2581, "s": 2506, "text": null }, { "code": null, "e": 2692, "s": 2581, "text": "Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YUNvTkJBT2dEejQuUVQvRQ$+96jm/eISqZ7+P9n0DrsBf25piwfnLRy2Yy1VYmb9iI\n" }, { "code": null, "e": 2760, "s": 2692, "text": "Reference: https://www.php.net/manual/en/function.password-hash.php" }, { "code": null, "e": 2767, "s": 2760, "text": "Picked" }, { "code": null, "e": 2771, "s": 2767, "text": "PHP" }, { "code": null, "e": 2784, "s": 2771, "text": "PHP Programs" }, { "code": null, "e": 2801, "s": 2784, "text": "Web Technologies" }, { "code": null, "e": 2828, "s": 2801, "text": "Web technologies Questions" }, { "code": null, "e": 2832, "s": 2828, "text": "PHP" } ]
Python User defined functions
26 Jul, 2021 A function is a set of statements that take inputs, do some specific computation and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function.Functions that readily comes with Python are called built-in functions. Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are known as user defines functions. Table of Content User defined functions Parameterized functions Default arguments Keyword arguments Variable length arguments Pass by Reference or pass by value? Default arguments Keyword arguments Variable length arguments Pass by Reference or pass by value? Function with return value All the functions that are written by any us comes under the category of user defined functions. Below are the steps for writing user defined functions in Python. In Python, def keyword is used to declare user defined functions. An indented block of statements follows the function name and arguments which contains the body of the function. Syntax: def function_name(): statements . . Example: Python3 # Python program to# demonstrate functions # Declaring a functiondef fun(): print("Inside function") # Driver's code# Calling functionfun() Output: Inside function The function may take arguments(s) also called parameters as input within the opening and closing parentheses, just after the function name followed by a colon.Syntax: def function_name(argument1, argument2, ...): statements . . Example: Python3 # Python program to# demonstrate functions # A simple Python function to check# whether x is even or odddef evenOdd( x ): if (x % 2 == 0): print("even") else: print("odd") # Driver codeevenOdd(2)evenOdd(3) Output: even odd A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.The following example illustrates Default arguments.Example: Python3 # Python program to demonstrate# default argumentsdef myFun(x, y = 50): print("x: ", x) print("y: ", y) # Driver code (We call myFun() with only# argument)myFun(10) Output: x: 10 y: 50 Note: To know more about default arguments click here. The idea is to allow caller to specify argument name with values so that caller does not need to remember order of parameters.Example: Python3 # Python program to demonstrate Keyword Argumentsdef student(firstname, lastname): print(firstname, lastname) # Keyword arguments student(firstname ='Geeks', lastname ='Practice') student(lastname ='Practice', firstname ='Geeks') Output: Geeks Practice Geeks Practice We can have both normal and keyword variable number of arguments. The special syntax *args in function definitions in Python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them). Example: Python3 # Python program to illustrate # *args and **kwargsdef myFun1(*argv): for arg in argv: print (arg) def myFun2(**kwargs): for key, value in kwargs.items(): print ("% s == % s" %(key, value)) # Driver codeprint("Result of * args: ")myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks') print("\nResult of **kwargs")myFun2(first ='Geeks', mid ='for', last ='Geeks') Output: Result of *args: Hello Welcome to GeeksforGeeks Result of **kwargs mid == for first == Geeks last == Geeks Note: To know more about variable length arguments click here. One important thing to note is, in Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. Parameter passing in Python is same as reference passing in Java. To confirm this Python’s built-in id() function is used in below example.Example: Python3 # Python program to# verify pass by reference def myFun(x): print("Value received:", x, "id:", id(x)) # Driver's codex = 12print("Value passed:", x, "id:", id(x))myFun(x) Value passed: 12 id: 11094656 Value received: 12 id: 11094656 Output: Value passed: 12 id: 10853984 Value received: 12 id: 10853984 If the value of the above variable is changed inside a function, then it will create a different variable as a number which is immutable. However, if a mutable list object is modified inside the function, the changes are reflected outside the function also.Example: Python3 def myFun(x, arr): print("Inside function") # changing integer will # Also change the reference # to the variable x += 10 print("Value received", x, "Id", id(x)) # Modifying mutable objects # will also be reflected outside # the function arr[0] = 0 print("List received", arr, "Id", id(arr)) # Driver's codex = 10arr = [1, 2, 3] print("Before calling function")print("Value passed", x, "Id", id(x))print("Array passed", arr, "Id", id(arr))print() myFun(x, arr) print("\nAfter calling function")print("Value passed", x, "Id", id(x))print("Array passed", arr, "Id", id(arr)) Output: Before calling function Value passed 10 Id 10853920 Array passed [1, 2, 3] Id 139773681420488 Inside function Value received 20 Id 10854240 List received [0, 2, 3] Id 139773681420488 After calling function Value passed 10 Id 10853920 Array passed [0, 2, 3] Id 139773681420488 Sometimes we might need the result of the function to be used in further process. Hence, a function should also returns a value when it finishes it’s execution. This can be achieved by return statement. A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.Syntax: def fun(): statements . . return [expression] Example: Python3 # Python program to# demonstrate return statement def add(a, b): # returning sum of a and b return a + b def is_true(a): # returning boolean of a return bool(a) # calling functionres = add(2, 3)print("Result of add function is {}".format(res)) res = is_true(2<5)print("\nResult of is_true function is {}".format(res)) Output: Result of add function is 5 Result of is_true function is True abhishek0719kadiyan anikakapoor Python-Functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n26 Jul, 2021" }, { "code": null, "e": 568, "s": 53, "text": "A function is a set of statements that take inputs, do some specific computation and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function.Functions that readily comes with Python are called built-in functions. Python provides built-in functions like print(), etc. but we can also create your own functions. These functions are known as user defines functions. " }, { "code": null, "e": 587, "s": 568, "text": "Table of Content " }, { "code": null, "e": 612, "s": 587, "text": "User defined functions " }, { "code": null, "e": 739, "s": 612, "text": "Parameterized functions Default arguments Keyword arguments Variable length arguments Pass by Reference or pass by value? " }, { "code": null, "e": 759, "s": 739, "text": "Default arguments " }, { "code": null, "e": 779, "s": 759, "text": "Keyword arguments " }, { "code": null, "e": 807, "s": 779, "text": "Variable length arguments " }, { "code": null, "e": 845, "s": 807, "text": "Pass by Reference or pass by value? " }, { "code": null, "e": 874, "s": 845, "text": "Function with return value " }, { "code": null, "e": 1042, "s": 878, "text": "All the functions that are written by any us comes under the category of user defined functions. Below are the steps for writing user defined functions in Python. " }, { "code": null, "e": 1110, "s": 1042, "text": "In Python, def keyword is used to declare user defined functions. " }, { "code": null, "e": 1225, "s": 1110, "text": "An indented block of statements follows the function name and arguments which contains the body of the function. " }, { "code": null, "e": 1235, "s": 1225, "text": "Syntax: " }, { "code": null, "e": 1283, "s": 1235, "text": "def function_name():\n statements\n .\n ." }, { "code": null, "e": 1293, "s": 1283, "text": "Example: " }, { "code": null, "e": 1301, "s": 1293, "text": "Python3" }, { "code": "# Python program to# demonstrate functions # Declaring a functiondef fun(): print(\"Inside function\") # Driver's code# Calling functionfun()", "e": 1444, "s": 1301, "text": null }, { "code": null, "e": 1454, "s": 1444, "text": "Output: " }, { "code": null, "e": 1470, "s": 1454, "text": "Inside function" }, { "code": null, "e": 1642, "s": 1472, "text": "The function may take arguments(s) also called parameters as input within the opening and closing parentheses, just after the function name followed by a colon.Syntax: " }, { "code": null, "e": 1715, "s": 1642, "text": "def function_name(argument1, argument2, ...):\n statements\n .\n ." }, { "code": null, "e": 1725, "s": 1715, "text": "Example: " }, { "code": null, "e": 1733, "s": 1725, "text": "Python3" }, { "code": "# Python program to# demonstrate functions # A simple Python function to check# whether x is even or odddef evenOdd( x ): if (x % 2 == 0): print(\"even\") else: print(\"odd\") # Driver codeevenOdd(2)evenOdd(3)", "e": 1961, "s": 1733, "text": null }, { "code": null, "e": 1971, "s": 1961, "text": "Output: " }, { "code": null, "e": 1980, "s": 1971, "text": "even\nodd" }, { "code": null, "e": 2173, "s": 1982, "text": "A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.The following example illustrates Default arguments.Example: " }, { "code": null, "e": 2181, "s": 2173, "text": "Python3" }, { "code": "# Python program to demonstrate# default argumentsdef myFun(x, y = 50): print(\"x: \", x) print(\"y: \", y) # Driver code (We call myFun() with only# argument)myFun(10)", "e": 2354, "s": 2181, "text": null }, { "code": null, "e": 2364, "s": 2354, "text": "Output: " }, { "code": null, "e": 2378, "s": 2364, "text": "x: 10\ny: 50" }, { "code": null, "e": 2434, "s": 2378, "text": "Note: To know more about default arguments click here. " }, { "code": null, "e": 2570, "s": 2434, "text": "The idea is to allow caller to specify argument name with values so that caller does not need to remember order of parameters.Example: " }, { "code": null, "e": 2578, "s": 2570, "text": "Python3" }, { "code": "# Python program to demonstrate Keyword Argumentsdef student(firstname, lastname): print(firstname, lastname) # Keyword arguments student(firstname ='Geeks', lastname ='Practice') student(lastname ='Practice', firstname ='Geeks')", "e": 2843, "s": 2578, "text": null }, { "code": null, "e": 2852, "s": 2843, "text": "Output: " }, { "code": null, "e": 2882, "s": 2852, "text": "Geeks Practice\nGeeks Practice" }, { "code": null, "e": 2952, "s": 2884, "text": "We can have both normal and keyword variable number of arguments. " }, { "code": null, "e": 3142, "s": 2952, "text": "The special syntax *args in function definitions in Python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. " }, { "code": null, "e": 3419, "s": 3142, "text": "The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. We use the name kwargs with the double star. The reason is because the double star allows us to pass through keyword arguments (and any number of them). " }, { "code": null, "e": 3429, "s": 3419, "text": "Example: " }, { "code": null, "e": 3437, "s": 3429, "text": "Python3" }, { "code": "# Python program to illustrate # *args and **kwargsdef myFun1(*argv): for arg in argv: print (arg) def myFun2(**kwargs): for key, value in kwargs.items(): print (\"% s == % s\" %(key, value)) # Driver codeprint(\"Result of * args: \")myFun1('Hello', 'Welcome', 'to', 'GeeksforGeeks') print(\"\\nResult of **kwargs\")myFun2(first ='Geeks', mid ='for', last ='Geeks') ", "e": 3823, "s": 3437, "text": null }, { "code": null, "e": 3832, "s": 3823, "text": "Output: " }, { "code": null, "e": 3941, "s": 3832, "text": "Result of *args: \nHello\nWelcome\nto\nGeeksforGeeks\n\nResult of **kwargs\nmid == for\nfirst == Geeks\nlast == Geeks" }, { "code": null, "e": 4005, "s": 3941, "text": "Note: To know more about variable length arguments click here. " }, { "code": null, "e": 4313, "s": 4005, "text": "One important thing to note is, in Python every variable name is a reference. When we pass a variable to a function, a new reference to the object is created. Parameter passing in Python is same as reference passing in Java. To confirm this Python’s built-in id() function is used in below example.Example: " }, { "code": null, "e": 4321, "s": 4313, "text": "Python3" }, { "code": "# Python program to# verify pass by reference def myFun(x): print(\"Value received:\", x, \"id:\", id(x)) # Driver's codex = 12print(\"Value passed:\", x, \"id:\", id(x))myFun(x)", "e": 4495, "s": 4321, "text": null }, { "code": null, "e": 4557, "s": 4495, "text": "Value passed: 12 id: 11094656\nValue received: 12 id: 11094656" }, { "code": null, "e": 4567, "s": 4557, "text": "Output: " }, { "code": null, "e": 4629, "s": 4567, "text": "Value passed: 12 id: 10853984\nValue received: 12 id: 10853984" }, { "code": null, "e": 4896, "s": 4629, "text": "If the value of the above variable is changed inside a function, then it will create a different variable as a number which is immutable. However, if a mutable list object is modified inside the function, the changes are reflected outside the function also.Example: " }, { "code": null, "e": 4904, "s": 4896, "text": "Python3" }, { "code": "def myFun(x, arr): print(\"Inside function\") # changing integer will # Also change the reference # to the variable x += 10 print(\"Value received\", x, \"Id\", id(x)) # Modifying mutable objects # will also be reflected outside # the function arr[0] = 0 print(\"List received\", arr, \"Id\", id(arr)) # Driver's codex = 10arr = [1, 2, 3] print(\"Before calling function\")print(\"Value passed\", x, \"Id\", id(x))print(\"Array passed\", arr, \"Id\", id(arr))print() myFun(x, arr) print(\"\\nAfter calling function\")print(\"Value passed\", x, \"Id\", id(x))print(\"Array passed\", arr, \"Id\", id(arr))", "e": 5512, "s": 4904, "text": null }, { "code": null, "e": 5522, "s": 5512, "text": "Output: " }, { "code": null, "e": 5800, "s": 5522, "text": "Before calling function\nValue passed 10 Id 10853920\nArray passed [1, 2, 3] Id 139773681420488\n\nInside function\nValue received 20 Id 10854240\nList received [0, 2, 3] Id 139773681420488\n\nAfter calling function\nValue passed 10 Id 10853920\nArray passed [0, 2, 3] Id 139773681420488" }, { "code": null, "e": 6331, "s": 5802, "text": "Sometimes we might need the result of the function to be used in further process. Hence, a function should also returns a value when it finishes it’s execution. This can be achieved by return statement. A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.Syntax: " }, { "code": null, "e": 6393, "s": 6331, "text": "def fun():\n statements\n .\n .\n return [expression]" }, { "code": null, "e": 6404, "s": 6393, "text": "Example: " }, { "code": null, "e": 6412, "s": 6404, "text": "Python3" }, { "code": "# Python program to# demonstrate return statement def add(a, b): # returning sum of a and b return a + b def is_true(a): # returning boolean of a return bool(a) # calling functionres = add(2, 3)print(\"Result of add function is {}\".format(res)) res = is_true(2<5)print(\"\\nResult of is_true function is {}\".format(res))", "e": 6750, "s": 6412, "text": null }, { "code": null, "e": 6760, "s": 6750, "text": "Output: " }, { "code": null, "e": 6824, "s": 6760, "text": "Result of add function is 5\n\nResult of is_true function is True" }, { "code": null, "e": 6846, "s": 6826, "text": "abhishek0719kadiyan" }, { "code": null, "e": 6858, "s": 6846, "text": "anikakapoor" }, { "code": null, "e": 6875, "s": 6858, "text": "Python-Functions" }, { "code": null, "e": 6882, "s": 6875, "text": "Python" } ]
Angular PrimeNG Chips Component
25 Aug, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Chips component in Angular PrimeNG. Chips component: It is used to set multiple values to enter for an input field. Properties: field: It is used to set the name of the property to display on a chip. It is of string data type, the default value is null. max: It is used to set the maximum number of entries allowed. It is of number datatype, the default value is null. disabled: It is used to disable the checkbox. It is of the boolean data type, the default value is false. style: It is used to give the inline style of the component. It is of string data type, the default value is null. styleClass: It is the style class of the component. It is of string data type, the default value is null. placeholder: It is used to set the placeholder text for the input. It is of string data type, the default value is null. tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null. inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null. ariaLabelledBy: This property establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null. allowDuplicate: It is used to set whether to allow duplicate values or not. It is of the boolean data type, the default value is true. inputStyle: It is used to set the inline style of the input field. It is of string data type, the default value is null. inputStyleClass: It is used to set the style class of the input field. It is of string data type, the default value is null. addOnTab: It is used to set whether to add an item on tab keypress. It is of the boolean data type, the default value is false. addOnBlur: It is used to set whether to add an item when the input loses focus. It is of the boolean data type, the default value is false. separator: It is used to set the separator char to add an item when pressed in addition to the enter key. It is of string data type, the default value is null. Events: onAdd: It is a callback that is fired when a value is added. onRemove: It is a callback that is fired when a value is removed. onChipClick: It is a callback that is fired when a chip is clicked. onFocus: It is a callback that is fired when an input is focused. onBlur: It is a callback that is fired when an input loses focus. Styling: p-chips: It is a container element. p-chips-token: It is a chip element container. p-chips-token-icon: It is an icon of a chip. p-chips-token-label: It is a label of a chip. p-chips-input-token: It is a container of input elements. Creating Angular Application & module installation: Step 1: Create an Angular application using the following command.ng new appname Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory.npm install primeng --save npm install primeicons --save Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: It will look like the following: Example 1: This is the basic example that shows how to use the Chips component. app.component.html <div> <h2>GeeksforGeeks</h2> <h4>PrimeNG chips component</h4> <p-chips></p-chips></div> app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { HttpClientModule } from "@angular/common/http";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { ChipsModule } from "primeng/chips";import { ButtonModule } from "primeng/button"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ChipsModule, ButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Example 2: In this example, we have a template for the Chips component. app.component.html <h5>PrimeNG Chips Component</h5><p-chips [(ngModel)]="geeks"> <ng-template let-gfg pTemplate="gfg"> {{gfg}}<i class="pi pi-user p-ml-2"></i> </ng-template></p-chips> app.component.ts import { Component } from "@angular/core";import { MenuItem } from "primeng/api"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent { geeks: string[];} app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { HttpClientModule } from "@angular/common/http";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component";import { ChipsModule } from "primeng/chips";import { ButtonModule } from "primeng/button"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ChipsModule, ButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} Output: Reference: https://primefaces.org/primeng/showcase/#/chips Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Aug, 2021" }, { "code": null, "e": 309, "s": 28, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Chips component in Angular PrimeNG." }, { "code": null, "e": 389, "s": 309, "text": "Chips component: It is used to set multiple values to enter for an input field." }, { "code": null, "e": 401, "s": 389, "text": "Properties:" }, { "code": null, "e": 527, "s": 401, "text": "field: It is used to set the name of the property to display on a chip. It is of string data type, the default value is null." }, { "code": null, "e": 642, "s": 527, "text": "max: It is used to set the maximum number of entries allowed. It is of number datatype, the default value is null." }, { "code": null, "e": 748, "s": 642, "text": "disabled: It is used to disable the checkbox. It is of the boolean data type, the default value is false." }, { "code": null, "e": 863, "s": 748, "text": "style: It is used to give the inline style of the component. It is of string data type, the default value is null." }, { "code": null, "e": 969, "s": 863, "text": "styleClass: It is the style class of the component. It is of string data type, the default value is null." }, { "code": null, "e": 1090, "s": 969, "text": "placeholder: It is used to set the placeholder text for the input. It is of string data type, the default value is null." }, { "code": null, "e": 1214, "s": 1090, "text": "tabindex: It is used to set the index of the element in tabbing order. It is of number datatype, the default value is null." }, { "code": null, "e": 1333, "s": 1214, "text": "inputId: It is an ID identifier of the underlying input element. It is of string data type, the default value is null." }, { "code": null, "e": 1529, "s": 1333, "text": "ariaLabelledBy: This property establishes relationships between the component and label(s) where its value should be one or more element IDs. It is of string data type, the default value is null." }, { "code": null, "e": 1664, "s": 1529, "text": "allowDuplicate: It is used to set whether to allow duplicate values or not. It is of the boolean data type, the default value is true." }, { "code": null, "e": 1785, "s": 1664, "text": "inputStyle: It is used to set the inline style of the input field. It is of string data type, the default value is null." }, { "code": null, "e": 1910, "s": 1785, "text": "inputStyleClass: It is used to set the style class of the input field. It is of string data type, the default value is null." }, { "code": null, "e": 2038, "s": 1910, "text": "addOnTab: It is used to set whether to add an item on tab keypress. It is of the boolean data type, the default value is false." }, { "code": null, "e": 2178, "s": 2038, "text": "addOnBlur: It is used to set whether to add an item when the input loses focus. It is of the boolean data type, the default value is false." }, { "code": null, "e": 2338, "s": 2178, "text": "separator: It is used to set the separator char to add an item when pressed in addition to the enter key. It is of string data type, the default value is null." }, { "code": null, "e": 2346, "s": 2338, "text": "Events:" }, { "code": null, "e": 2407, "s": 2346, "text": "onAdd: It is a callback that is fired when a value is added." }, { "code": null, "e": 2473, "s": 2407, "text": "onRemove: It is a callback that is fired when a value is removed." }, { "code": null, "e": 2541, "s": 2473, "text": "onChipClick: It is a callback that is fired when a chip is clicked." }, { "code": null, "e": 2607, "s": 2541, "text": "onFocus: It is a callback that is fired when an input is focused." }, { "code": null, "e": 2673, "s": 2607, "text": "onBlur: It is a callback that is fired when an input loses focus." }, { "code": null, "e": 2684, "s": 2675, "text": "Styling:" }, { "code": null, "e": 2720, "s": 2684, "text": "p-chips: It is a container element." }, { "code": null, "e": 2767, "s": 2720, "text": "p-chips-token: It is a chip element container." }, { "code": null, "e": 2812, "s": 2767, "text": "p-chips-token-icon: It is an icon of a chip." }, { "code": null, "e": 2858, "s": 2812, "text": "p-chips-token-label: It is a label of a chip." }, { "code": null, "e": 2916, "s": 2858, "text": "p-chips-input-token: It is a container of input elements." }, { "code": null, "e": 2968, "s": 2916, "text": "Creating Angular Application & module installation:" }, { "code": null, "e": 3049, "s": 2968, "text": "Step 1: Create an Angular application using the following command.ng new appname" }, { "code": null, "e": 3116, "s": 3049, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 3131, "s": 3116, "text": "ng new appname" }, { "code": null, "e": 3238, "s": 3131, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname" }, { "code": null, "e": 3335, "s": 3238, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 3346, "s": 3335, "text": "cd appname" }, { "code": null, "e": 3451, "s": 3346, "text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 3500, "s": 3451, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 3557, "s": 3500, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 3609, "s": 3557, "text": "Project Structure: It will look like the following:" }, { "code": null, "e": 3691, "s": 3611, "text": "Example 1: This is the basic example that shows how to use the Chips component." }, { "code": null, "e": 3710, "s": 3691, "text": "app.component.html" }, { "code": "<div> <h2>GeeksforGeeks</h2> <h4>PrimeNG chips component</h4> <p-chips></p-chips></div>", "e": 3801, "s": 3710, "text": null }, { "code": null, "e": 3818, "s": 3801, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}", "e": 3963, "s": 3818, "text": null }, { "code": null, "e": 3977, "s": 3963, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { HttpClientModule } from \"@angular/common/http\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { ChipsModule } from \"primeng/chips\";import { ButtonModule } from \"primeng/button\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ChipsModule, ButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 4610, "s": 3977, "text": null }, { "code": null, "e": 4618, "s": 4610, "text": "Output:" }, { "code": null, "e": 4691, "s": 4618, "text": "Example 2: In this example, we have a template for the Chips component. " }, { "code": null, "e": 4710, "s": 4691, "text": "app.component.html" }, { "code": "<h5>PrimeNG Chips Component</h5><p-chips [(ngModel)]=\"geeks\"> <ng-template let-gfg pTemplate=\"gfg\"> {{gfg}}<i class=\"pi pi-user p-ml-2\"></i> </ng-template></p-chips>", "e": 4881, "s": 4710, "text": null }, { "code": null, "e": 4898, "s": 4881, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { MenuItem } from \"primeng/api\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent { geeks: string[];}", "e": 5101, "s": 4898, "text": null }, { "code": null, "e": 5115, "s": 5101, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { HttpClientModule } from \"@angular/common/http\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\";import { ChipsModule } from \"primeng/chips\";import { ButtonModule } from \"primeng/button\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, ChipsModule, ButtonModule, FormsModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 5748, "s": 5115, "text": null }, { "code": null, "e": 5756, "s": 5748, "text": "Output:" }, { "code": null, "e": 5815, "s": 5756, "text": "Reference: https://primefaces.org/primeng/showcase/#/chips" }, { "code": null, "e": 5831, "s": 5815, "text": "Angular-PrimeNG" }, { "code": null, "e": 5841, "s": 5831, "text": "AngularJS" }, { "code": null, "e": 5858, "s": 5841, "text": "Web Technologies" }, { "code": null, "e": 5956, "s": 5858, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5980, "s": 5956, "text": "Routing in Angular 9/10" }, { "code": null, "e": 6015, "s": 5980, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 6039, "s": 6015, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 6092, "s": 6039, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 6141, "s": 6092, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 6203, "s": 6141, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6236, "s": 6203, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6297, "s": 6236, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6347, "s": 6297, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Introduction of Statistics and its Types
29 Jun, 2020 Statistics simply means numerical data, and is field of math that generally deals with collection of data, tabulation, and interpretation of numerical data. It is actually a form of mathematical analysis that uses different quantitative models to produce a set of experimental data or studies of real life. It is an area of applied mathematics concern with data collection analysis, interpretation, and presentation. Statistics deals with how data can be used to solve complex problems. Some people consider statistics to be a distinct mathematical science rather than a branch of mathematics. Statistics makes work easy and simple and provides a clear and clean picture of work you do on a regular basis. Basic terminology of Statistics : Population –It is actually a collection of set of individuals or objects or events whose properties are to be analyzed. Sample –It is the subset of a population. Types of Statistics : 1. Descriptive Statistics :Descriptive statistics uses data that provides a description of the population either through numerical calculation or graph or table. It provides a graphical summary of data. It is simply used for summarizing objects, etc. There are two categories in this as following below. (a). Measure of central tendency –Measure of central tendency is also known as summary statistics that is used to represents the center point or a particular value of a data set or sample set.In statistics, there are three common measures of central tendency as shown below:(i) Mean :It is measure of average of all value in a sample set.For example,(ii) Median :It is measure of central value of a sample set. In these, data set is ordered from lowest to highest value and then finds exact middle.For example,(iii) Mode :It is value most frequently arrived in sample set. The value repeated most of time in central set is actually mode.For example, (i) Mean :It is measure of average of all value in a sample set.For example, (ii) Median :It is measure of central value of a sample set. In these, data set is ordered from lowest to highest value and then finds exact middle.For example, (iii) Mode :It is value most frequently arrived in sample set. The value repeated most of time in central set is actually mode.For example, (b). Measure of Variability –Measure of Variability is also known as measure of dispersion and used to describe variability in a sample or population. In statistics, there are three common measures of variability as shown below:(i) Range :It is given measure of how to spread apart values in sample set or data set.Range = Maximum value - Minimum value (ii) Variance :It simply describes how much a random variable defers from expected value and it is also computed as square of deviation.S2= ∑ni=1 [(xi - ͞x)2 ÷ n] In these formula, n represent total data points, ͞x represent mean of data points and xi represent individual data points.(iii) Dispersion :It is measure of dispersion of set of data from its mean.σ= √ (1÷n) ∑ni=1 (xi - μ)2 (i) Range :It is given measure of how to spread apart values in sample set or data set.Range = Maximum value - Minimum value Range = Maximum value - Minimum value (ii) Variance :It simply describes how much a random variable defers from expected value and it is also computed as square of deviation.S2= ∑ni=1 [(xi - ͞x)2 ÷ n] In these formula, n represent total data points, ͞x represent mean of data points and xi represent individual data points. S2= ∑ni=1 [(xi - ͞x)2 ÷ n] In these formula, n represent total data points, ͞x represent mean of data points and xi represent individual data points. (iii) Dispersion :It is measure of dispersion of set of data from its mean.σ= √ (1÷n) ∑ni=1 (xi - μ)2 σ= √ (1÷n) ∑ni=1 (xi - μ)2 2. Inferential Statistics :Inferential Statistics makes inference and prediction about population based on a sample of data taken from population. It generalizes a large dataset and applies probabilities to draw a conclusion. It is simply used for explaining meaning of descriptive stats. It is simply used to analyze, interpret result, and draw conclusion. Inferential Statistics is mainly related to and associated with hypothesis testing whose main target is to reject null hypothesis. Hypothesis testing is a type of inferential procedure that takes help of sample data to evaluate and assess credibility of a hypothesis about a population. Inferential statistics are generally used to determine how strong relationship is within sample. But it is very difficult to obtain a population list and draw a random sample. Inferential statistics can be done with help of various steps as given below: Obtain and start with a theory.Generate a research hypothesis.Operationalize or use variablesIdentify or find out population to which we can apply study material.Generate or form a null hypothesis for these population.Collect and gather a sample of children from population and simply run study.Then, perform all tests of statistical to clarify if obtained characteristics of sample are sufficiently different from what would be expected under null hypothesis so that we can be able to find and reject null hypothesis. Obtain and start with a theory. Generate a research hypothesis. Operationalize or use variables Identify or find out population to which we can apply study material. Generate or form a null hypothesis for these population. Collect and gather a sample of children from population and simply run study. Then, perform all tests of statistical to clarify if obtained characteristics of sample are sufficiently different from what would be expected under null hypothesis so that we can be able to find and reject null hypothesis. Types of inferential statistics –Various types of inferential statistics are used widely nowadays and are very easy to interpret. These are given below: One sample test of difference/One sample hypothesis test Confidence Interval Contingency Tables and Chi-Square Statistic T-test or Anova Pearson Correlation Bi-variate Regression Multi-variate Regression median-finding Engineering Mathematics Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph Univariate, Bivariate and Multivariate data and its analysis Logic Notations in LaTeX Properties of Boolean Algebra Number of Possible Super Keys in DBMS Discrete Mathematics | Hasse Diagrams
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jun, 2020" }, { "code": null, "e": 646, "s": 52, "text": "Statistics simply means numerical data, and is field of math that generally deals with collection of data, tabulation, and interpretation of numerical data. It is actually a form of mathematical analysis that uses different quantitative models to produce a set of experimental data or studies of real life. It is an area of applied mathematics concern with data collection analysis, interpretation, and presentation. Statistics deals with how data can be used to solve complex problems. Some people consider statistics to be a distinct mathematical science rather than a branch of mathematics." }, { "code": null, "e": 758, "s": 646, "text": "Statistics makes work easy and simple and provides a clear and clean picture of work you do on a regular basis." }, { "code": null, "e": 792, "s": 758, "text": "Basic terminology of Statistics :" }, { "code": null, "e": 912, "s": 792, "text": "Population –It is actually a collection of set of individuals or objects or events whose properties are to be analyzed." }, { "code": null, "e": 954, "s": 912, "text": "Sample –It is the subset of a population." }, { "code": null, "e": 976, "s": 954, "text": "Types of Statistics :" }, { "code": null, "e": 1280, "s": 976, "text": "1. Descriptive Statistics :Descriptive statistics uses data that provides a description of the population either through numerical calculation or graph or table. It provides a graphical summary of data. It is simply used for summarizing objects, etc. There are two categories in this as following below." }, { "code": null, "e": 1930, "s": 1280, "text": "(a). Measure of central tendency –Measure of central tendency is also known as summary statistics that is used to represents the center point or a particular value of a data set or sample set.In statistics, there are three common measures of central tendency as shown below:(i) Mean :It is measure of average of all value in a sample set.For example,(ii) Median :It is measure of central value of a sample set. In these, data set is ordered from lowest to highest value and then finds exact middle.For example,(iii) Mode :It is value most frequently arrived in sample set. The value repeated most of time in central set is actually mode.For example," }, { "code": null, "e": 2007, "s": 1930, "text": "(i) Mean :It is measure of average of all value in a sample set.For example," }, { "code": null, "e": 2168, "s": 2007, "text": "(ii) Median :It is measure of central value of a sample set. In these, data set is ordered from lowest to highest value and then finds exact middle.For example," }, { "code": null, "e": 2308, "s": 2168, "text": "(iii) Mode :It is value most frequently arrived in sample set. The value repeated most of time in central set is actually mode.For example," }, { "code": null, "e": 3053, "s": 2308, "text": "(b). Measure of Variability –Measure of Variability is also known as measure of dispersion and used to describe variability in a sample or population. In statistics, there are three common measures of variability as shown below:(i) Range :It is given measure of how to spread apart values in sample set or data set.Range = Maximum value - Minimum value (ii) Variance :It simply describes how much a random variable defers from expected value and it is also computed as square of deviation.S2= ∑ni=1 [(xi - ͞x)2 ÷ n] In these formula, n represent total data points, ͞x represent mean of data points and xi represent individual data points.(iii) Dispersion :It is measure of dispersion of set of data from its mean.σ= √ (1÷n) ∑ni=1 (xi - μ)2 " }, { "code": null, "e": 3179, "s": 3053, "text": "(i) Range :It is given measure of how to spread apart values in sample set or data set.Range = Maximum value - Minimum value " }, { "code": null, "e": 3218, "s": 3179, "text": "Range = Maximum value - Minimum value " }, { "code": null, "e": 3507, "s": 3218, "text": "(ii) Variance :It simply describes how much a random variable defers from expected value and it is also computed as square of deviation.S2= ∑ni=1 [(xi - ͞x)2 ÷ n] In these formula, n represent total data points, ͞x represent mean of data points and xi represent individual data points." }, { "code": null, "e": 3538, "s": 3507, "text": "S2= ∑ni=1 [(xi - ͞x)2 ÷ n] " }, { "code": null, "e": 3661, "s": 3538, "text": "In these formula, n represent total data points, ͞x represent mean of data points and xi represent individual data points." }, { "code": null, "e": 3765, "s": 3661, "text": "(iii) Dispersion :It is measure of dispersion of set of data from its mean.σ= √ (1÷n) ∑ni=1 (xi - μ)2 " }, { "code": null, "e": 3794, "s": 3765, "text": "σ= √ (1÷n) ∑ni=1 (xi - μ)2 " }, { "code": null, "e": 4283, "s": 3794, "text": "2. Inferential Statistics :Inferential Statistics makes inference and prediction about population based on a sample of data taken from population. It generalizes a large dataset and applies probabilities to draw a conclusion. It is simply used for explaining meaning of descriptive stats. It is simply used to analyze, interpret result, and draw conclusion. Inferential Statistics is mainly related to and associated with hypothesis testing whose main target is to reject null hypothesis." }, { "code": null, "e": 4615, "s": 4283, "text": "Hypothesis testing is a type of inferential procedure that takes help of sample data to evaluate and assess credibility of a hypothesis about a population. Inferential statistics are generally used to determine how strong relationship is within sample. But it is very difficult to obtain a population list and draw a random sample." }, { "code": null, "e": 4693, "s": 4615, "text": "Inferential statistics can be done with help of various steps as given below:" }, { "code": null, "e": 5212, "s": 4693, "text": "Obtain and start with a theory.Generate a research hypothesis.Operationalize or use variablesIdentify or find out population to which we can apply study material.Generate or form a null hypothesis for these population.Collect and gather a sample of children from population and simply run study.Then, perform all tests of statistical to clarify if obtained characteristics of sample are sufficiently different from what would be expected under null hypothesis so that we can be able to find and reject null hypothesis." }, { "code": null, "e": 5244, "s": 5212, "text": "Obtain and start with a theory." }, { "code": null, "e": 5276, "s": 5244, "text": "Generate a research hypothesis." }, { "code": null, "e": 5308, "s": 5276, "text": "Operationalize or use variables" }, { "code": null, "e": 5378, "s": 5308, "text": "Identify or find out population to which we can apply study material." }, { "code": null, "e": 5435, "s": 5378, "text": "Generate or form a null hypothesis for these population." }, { "code": null, "e": 5513, "s": 5435, "text": "Collect and gather a sample of children from population and simply run study." }, { "code": null, "e": 5737, "s": 5513, "text": "Then, perform all tests of statistical to clarify if obtained characteristics of sample are sufficiently different from what would be expected under null hypothesis so that we can be able to find and reject null hypothesis." }, { "code": null, "e": 5890, "s": 5737, "text": "Types of inferential statistics –Various types of inferential statistics are used widely nowadays and are very easy to interpret. These are given below:" }, { "code": null, "e": 5947, "s": 5890, "text": "One sample test of difference/One sample hypothesis test" }, { "code": null, "e": 5967, "s": 5947, "text": "Confidence Interval" }, { "code": null, "e": 6011, "s": 5967, "text": "Contingency Tables and Chi-Square Statistic" }, { "code": null, "e": 6027, "s": 6011, "text": "T-test or Anova" }, { "code": null, "e": 6047, "s": 6027, "text": "Pearson Correlation" }, { "code": null, "e": 6069, "s": 6047, "text": "Bi-variate Regression" }, { "code": null, "e": 6094, "s": 6069, "text": "Multi-variate Regression" }, { "code": null, "e": 6109, "s": 6094, "text": "median-finding" }, { "code": null, "e": 6133, "s": 6109, "text": "Engineering Mathematics" }, { "code": null, "e": 6231, "s": 6133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6290, "s": 6231, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 6313, "s": 6290, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 6336, "s": 6313, "text": "Set Notations in LaTeX" }, { "code": null, "e": 6357, "s": 6336, "text": "Activation Functions" }, { "code": null, "e": 6422, "s": 6357, "text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph" }, { "code": null, "e": 6483, "s": 6422, "text": "Univariate, Bivariate and Multivariate data and its analysis" }, { "code": null, "e": 6508, "s": 6483, "text": "Logic Notations in LaTeX" }, { "code": null, "e": 6538, "s": 6508, "text": "Properties of Boolean Algebra" }, { "code": null, "e": 6576, "s": 6538, "text": "Number of Possible Super Keys in DBMS" } ]
Python | Numbers in a list within a given range
30 Jun, 2022 Given a list, print the number of numbers in the given range. Examples: Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80 Output : 6 Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40 Output : 4 Multiple Line Approach:Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter. At the end of traversal, the value of the counter will be the answer for the number of numbers in specified range.Below is the Python implementation of the above approach Python # Python program to count the# number of numbers in a given range# using traversal and multiple line code def count(list1, l, r): c = 0 # traverse in the list1 for x in list1: # condition check if x>= l and x<= r: c+= 1 return c # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print count(list1, l, r) Output: 6 Single Line Approach:We can write a single line for traversal and checking condition together: x for x in list1 if l <= x <= r The return value(true) of the condition check is stored in a list, and at the end the length of the list returns the answer.Below is the Python implementation of the above approach Python # Python program to count the# number of numbers in a given range def count(list1, l, r): # x for x in list1 is same as traversal in the list # the if condition checks for the number of numbers in the range # l to r # the return is stored in a list # whose length is the answer return len(list(x for x in list1 if l <= x <= r)) # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print count(list1, l, r) Output: 6 Approach#3 : Using sum We can use sum in this problem. We use list comprehension to iterate over the list and check number is in range or not if it is present comparison will have 1 as have else 0 as value. Sum function return the sum of total of parameters. Python3 # Python program to count the# number of numbers in a given range def count(list1, l, r): # Traversing the list with on line for loop # check if number is in range of not return sum( l <= x <= r for x in list1) # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print( count( list1, l, r ) ) Output: 6 gulshankumarar231 satyam00so Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python Python | os.path.join() method
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 116, "s": 52, "text": "Given a list, print the number of numbers in the given range. " }, { "code": null, "e": 127, "s": 116, "text": "Examples: " }, { "code": null, "e": 267, "s": 127, "text": "Input : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 40-80\nOutput : 6\n\nInput : [10, 20, 30, 40, 50, 40, 40, 60, 70] range: 10-40\nOutput : 4 " }, { "code": null, "e": 582, "s": 269, "text": "Multiple Line Approach:Traverse in the list and check for every number. If the number lies in the specified range, then increase the counter. At the end of traversal, the value of the counter will be the answer for the number of numbers in specified range.Below is the Python implementation of the above approach" }, { "code": null, "e": 589, "s": 582, "text": "Python" }, { "code": "# Python program to count the# number of numbers in a given range# using traversal and multiple line code def count(list1, l, r): c = 0 # traverse in the list1 for x in list1: # condition check if x>= l and x<= r: c+= 1 return c # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print count(list1, l, r)", "e": 953, "s": 589, "text": null }, { "code": null, "e": 963, "s": 953, "text": "Output: " }, { "code": null, "e": 965, "s": 963, "text": "6" }, { "code": null, "e": 1062, "s": 965, "text": "Single Line Approach:We can write a single line for traversal and checking condition together: " }, { "code": null, "e": 1094, "s": 1062, "text": "x for x in list1 if l <= x <= r" }, { "code": null, "e": 1277, "s": 1094, "text": "The return value(true) of the condition check is stored in a list, and at the end the length of the list returns the answer.Below is the Python implementation of the above approach " }, { "code": null, "e": 1284, "s": 1277, "text": "Python" }, { "code": "# Python program to count the# number of numbers in a given range def count(list1, l, r): # x for x in list1 is same as traversal in the list # the if condition checks for the number of numbers in the range # l to r # the return is stored in a list # whose length is the answer return len(list(x for x in list1 if l <= x <= r)) # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print count(list1, l, r)", "e": 1729, "s": 1284, "text": null }, { "code": null, "e": 1738, "s": 1729, "text": "Output: " }, { "code": null, "e": 1741, "s": 1738, "text": "6 " }, { "code": null, "e": 2001, "s": 1741, "text": "Approach#3 : Using sum We can use sum in this problem. We use list comprehension to iterate over the list and check number is in range or not if it is present comparison will have 1 as have else 0 as value. Sum function return the sum of total of parameters." }, { "code": null, "e": 2009, "s": 2001, "text": "Python3" }, { "code": "# Python program to count the# number of numbers in a given range def count(list1, l, r): # Traversing the list with on line for loop # check if number is in range of not return sum( l <= x <= r for x in list1) # driver codelist1 = [10, 20, 30, 40, 50, 40, 40, 60, 70]l = 40r = 80print( count( list1, l, r ) )", "e": 2333, "s": 2009, "text": null }, { "code": null, "e": 2341, "s": 2333, "text": "Output:" }, { "code": null, "e": 2343, "s": 2341, "text": "6" }, { "code": null, "e": 2361, "s": 2343, "text": "gulshankumarar231" }, { "code": null, "e": 2372, "s": 2361, "text": "satyam00so" }, { "code": null, "e": 2393, "s": 2372, "text": "Python list-programs" }, { "code": null, "e": 2405, "s": 2393, "text": "python-list" }, { "code": null, "e": 2412, "s": 2405, "text": "Python" }, { "code": null, "e": 2424, "s": 2412, "text": "python-list" }, { "code": null, "e": 2522, "s": 2424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2564, "s": 2522, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2586, "s": 2564, "text": "Enumerate() in Python" }, { "code": null, "e": 2621, "s": 2586, "text": "Read a file line by line in Python" }, { "code": null, "e": 2647, "s": 2621, "text": "Python String | replace()" }, { "code": null, "e": 2679, "s": 2647, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2708, "s": 2679, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2738, "s": 2708, "text": "Iterate over a list in Python" }, { "code": null, "e": 2765, "s": 2738, "text": "Python Classes and Objects" }, { "code": null, "e": 2801, "s": 2765, "text": "Convert integer to string in Python" } ]
Global and Local variables in JavaScript
28 Jun, 2019 Variables: It holds the data or information which can be changed anytime. JavaScript use reserved keyword var to declare variables. In JavaScript, there are two types of variable and also it tells you where in your program you are allowed to use the variables and functions that you’ve defined. Local Variable:When you use JavaScript, local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them. When you use JavaScript, local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them. Global Variable:In contrast, global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters. In contrast, global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters. Local Variable: Since local variables are defined inside the function so variables with the same name can be used in different functions. Example: <!DOCTYPE html><html> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <p>Outside myfunction() petName is not defined.</p> <p id="Geeks"></p> <p id="geeks"></p> <script> myfunction(); function myfunction() { var petName = "Sizzer"; // local variabl document.getElementById("Geeks").innerHTML = typeof petName + " " + petName; } document.getElementById("geeks").innerHTML = typeof petName; </script> </center> </body> </html> Output: The above example illustrates the use of a local variable. However, that a statement outside of the function can’t refer to the variable named petName without causing an error. That’s because it has local scope. Global Variable: Since global variables are defined outside there function so variables with the same name can not be used in different functions. All the scripts and functions on a web page can access it. Example: <!DOCTYPE html><html> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <p>A GLOBAL variable can be accessed from any script or function.</p> <p id="geeks"></p> <p id="Geeks"></p> <script> var petName = "Rocky";//global variable myFunction(); function myFunction() { document.getElementById("geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; } document.getElementById("Geeks").innerHTML = typeof petName + "- " + "My pet name is " + petName; </script> </center> </body> </html> Output: Although it may seem easier to use global variables than to pass data to a function and return data from it, global variables often create problems. That’s because any function can modify a global variable, and it’s all too easy to misspell a variable name or modify the wrong variable, especially in large applications. That, in turn, can create debugging problems. In contrast, the use of local variables reduces the likelihood of naming conflicts. For instance, two different functions can use the same names for local variables without causing conflicts. That of course, means fewer errors and debugging problems. With just a few exceptions, then, all of the code in your applications should be in functions so all of the variables are local. If you misspell the name of a variable that you’ve already declared, it will be treated as a new global variable. With this in mind, be sure to include the keyword when you declare new variables and always declare a variable before you refer to it in your code. Note: Use local variables whenever possible.Always use the var keyword to declare a new variable before the variable is referred to by other statements. The scope of a variable or function determines what code has access to it. Variables that are created inside a function are local variables, and local variables, and local variables can only be referred to by the code within the function. Variables created outside of functions are global variables, and the code in all functions have access to all global variables. If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes that the variable is global. This can cause debugging problems. In general, it’s better to pass local variables from one function to another as parameters than it is to use global variables. That will make your code easier to understand with less chance for errors. javascript-basics JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2019" }, { "code": null, "e": 349, "s": 54, "text": "Variables: It holds the data or information which can be changed anytime. JavaScript use reserved keyword var to declare variables. In JavaScript, there are two types of variable and also it tells you where in your program you are allowed to use the variables and functions that you’ve defined." }, { "code": null, "e": 555, "s": 349, "text": "Local Variable:When you use JavaScript, local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them." }, { "code": null, "e": 746, "s": 555, "text": "When you use JavaScript, local variables are variables that are defined within functions. They have local scope, which means that they can only be used within the functions that define them." }, { "code": null, "e": 968, "s": 746, "text": "Global Variable:In contrast, global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters." }, { "code": null, "e": 1174, "s": 968, "text": "In contrast, global variables are variables that are defined outside of functions. These variables have global scope, so they can be used by any function without passing them to the function as parameters." }, { "code": null, "e": 1312, "s": 1174, "text": "Local Variable: Since local variables are defined inside the function so variables with the same name can be used in different functions." }, { "code": null, "e": 1321, "s": 1312, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <p>Outside myfunction() petName is not defined.</p> <p id=\"Geeks\"></p> <p id=\"geeks\"></p> <script> myfunction(); function myfunction() { var petName = \"Sizzer\"; // local variabl document.getElementById(\"Geeks\").innerHTML = typeof petName + \" \" + petName; } document.getElementById(\"geeks\").innerHTML = typeof petName; </script> </center> </body> </html>", "e": 1926, "s": 1321, "text": null }, { "code": null, "e": 1934, "s": 1926, "text": "Output:" }, { "code": null, "e": 2146, "s": 1934, "text": "The above example illustrates the use of a local variable. However, that a statement outside of the function can’t refer to the variable named petName without causing an error. That’s because it has local scope." }, { "code": null, "e": 2352, "s": 2146, "text": "Global Variable: Since global variables are defined outside there function so variables with the same name can not be used in different functions. All the scripts and functions on a web page can access it." }, { "code": null, "e": 2361, "s": 2352, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <p>A GLOBAL variable can be accessed from any script or function.</p> <p id=\"geeks\"></p> <p id=\"Geeks\"></p> <script> var petName = \"Rocky\";//global variable myFunction(); function myFunction() { document.getElementById(\"geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; } document.getElementById(\"Geeks\").innerHTML = typeof petName + \"- \" + \"My pet name is \" + petName; </script> </center> </body> </html>", "e": 3058, "s": 2361, "text": null }, { "code": null, "e": 3066, "s": 3058, "text": "Output:" }, { "code": null, "e": 3433, "s": 3066, "text": "Although it may seem easier to use global variables than to pass data to a function and return data from it, global variables often create problems. That’s because any function can modify a global variable, and it’s all too easy to misspell a variable name or modify the wrong variable, especially in large applications. That, in turn, can create debugging problems." }, { "code": null, "e": 3813, "s": 3433, "text": "In contrast, the use of local variables reduces the likelihood of naming conflicts. For instance, two different functions can use the same names for local variables without causing conflicts. That of course, means fewer errors and debugging problems. With just a few exceptions, then, all of the code in your applications should be in functions so all of the variables are local." }, { "code": null, "e": 4075, "s": 3813, "text": "If you misspell the name of a variable that you’ve already declared, it will be treated as a new global variable. With this in mind, be sure to include the keyword when you declare new variables and always declare a variable before you refer to it in your code." }, { "code": null, "e": 4228, "s": 4075, "text": "Note: Use local variables whenever possible.Always use the var keyword to declare a new variable before the variable is referred to by other statements." }, { "code": null, "e": 4303, "s": 4228, "text": "The scope of a variable or function determines what code has access to it." }, { "code": null, "e": 4467, "s": 4303, "text": "Variables that are created inside a function are local variables, and local variables, and local variables can only be referred to by the code within the function." }, { "code": null, "e": 4595, "s": 4467, "text": "Variables created outside of functions are global variables, and the code in all functions have access to all global variables." }, { "code": null, "e": 4754, "s": 4595, "text": "If you forget to code the var keyword in a variable declaration, the JavaScript engine assumes that the variable is global. This can cause debugging problems." }, { "code": null, "e": 4956, "s": 4754, "text": "In general, it’s better to pass local variables from one function to another as parameters than it is to use global variables. That will make your code easier to understand with less chance for errors." }, { "code": null, "e": 4974, "s": 4956, "text": "javascript-basics" }, { "code": null, "e": 4985, "s": 4974, "text": "JavaScript" }, { "code": null, "e": 5002, "s": 4985, "text": "Web Technologies" }, { "code": null, "e": 5100, "s": 5002, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5161, "s": 5100, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5233, "s": 5161, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5273, "s": 5233, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5326, "s": 5273, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 5367, "s": 5326, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5400, "s": 5367, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5462, "s": 5400, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5523, "s": 5462, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5573, "s": 5523, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Scanner nextBoolean() method in Java with Examples
12 Oct, 2018 The nextBoolean() method of java.util.Scanner class scans the next token of the input as a Boolean. If the translation is successful, the scanner advances past the input that matched. Syntax: public boolean nextBoolean() Parameters: The function does not accepts any parameter. Return Value: This function returns the Boolean scanned from the input. Exceptions: The function throws three exceptions as described below: InputMismatchException: if the next token is not a valid boolean NoSuchElementException: throws if input is exhausted IllegalStateException: throws if this scanner is closed Below programs illustrate the above function: Program 1: // Java program to illustrate the// nextBoolean() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = "Gfg true 9 + 6 = 12.0 false"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Boolean, // print found and the Boolean if (scanner.hasNextBoolean()) { System.out.println("Found Boolean value :" + scanner.nextBoolean()); } // if no Boolean is foucnd, // print "Not Found:" and the token else { System.out.println("Not found Boolean() value :" + scanner.next()); } } scanner.close(); }} Not found Boolean() value :Gfg Found Boolean value :true Not found Boolean() value :9 Not found Boolean() value :+ Not found Boolean() value :6 Not found Boolean() value := Not found Boolean() value :12.0 Found Boolean value :false Program 2: To demonstrate InputMismatchException // Java program to illustrate the// nextBoolean() method of Scanner class in Java// InputMismatchException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Boolean // print found and the Boolean // since the value 60 is out of range // it throws an exception System.out.println("Next Boolean value :" + scanner.nextBoolean()); } scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Exception thrown: java.util.InputMismatchException Program 3: To demonstrate NoSuchElementException // Java program to illustrate the// nextBoolean() method of Scanner class in Java// NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // Trying to get the next Boolean value // more times than the scanner // Hence it will throw exception for (int i = 0; i < 5; i++) { // if the next is a Boolean, // print found and the Boolean if (scanner.hasNextBoolean()) { System.out.println("Found Boolean value :" + scanner.nextBoolean()); } // if no Boolean is found, // print "Not Found:" and the token else { System.out.println("Not found Boolean value :" + scanner.next()); } } scanner.close(); } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Not found Boolean value :Gfg Exception thrown: java.util.NoSuchElementException Program 4: To demonstrate IllegalStateException // Java program to illustrate the// nextBoolean() method of Scanner class in Java// IllegalStateException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = "Gfg 9 + 6 = 12.0"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); System.out.println("Scanner Closed"); System.out.println("Trying to get " + "next Boolean value"); while (scanner.hasNext()) { // if the next is a Boolean, // print found and the Boolean if (scanner.hasNextBoolean()) { System.out.println("Found Boolean value :" + scanner.nextBoolean()); } // if no Boolean is found, // print "Not Found:" and the token else { System.out.println("Not found Boolean value :" + scanner.next()); } } } catch (Exception e) { System.out.println("Exception thrown: " + e); } }} Scanner Closed Trying to get next Boolean value Exception thrown: java.lang.IllegalStateException: Scanner closed Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextBoolean() Java - util package Java-Functions Java-Library Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Oct, 2018" }, { "code": null, "e": 212, "s": 28, "text": "The nextBoolean() method of java.util.Scanner class scans the next token of the input as a Boolean. If the translation is successful, the scanner advances past the input that matched." }, { "code": null, "e": 220, "s": 212, "text": "Syntax:" }, { "code": null, "e": 249, "s": 220, "text": "public boolean nextBoolean()" }, { "code": null, "e": 306, "s": 249, "text": "Parameters: The function does not accepts any parameter." }, { "code": null, "e": 378, "s": 306, "text": "Return Value: This function returns the Boolean scanned from the input." }, { "code": null, "e": 447, "s": 378, "text": "Exceptions: The function throws three exceptions as described below:" }, { "code": null, "e": 512, "s": 447, "text": "InputMismatchException: if the next token is not a valid boolean" }, { "code": null, "e": 565, "s": 512, "text": "NoSuchElementException: throws if input is exhausted" }, { "code": null, "e": 621, "s": 565, "text": "IllegalStateException: throws if this scanner is closed" }, { "code": null, "e": 667, "s": 621, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 678, "s": 667, "text": "Program 1:" }, { "code": "// Java program to illustrate the// nextBoolean() method of Scanner class in Java// without parameter import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { String s = \"Gfg true 9 + 6 = 12.0 false\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Boolean, // print found and the Boolean if (scanner.hasNextBoolean()) { System.out.println(\"Found Boolean value :\" + scanner.nextBoolean()); } // if no Boolean is foucnd, // print \"Not Found:\" and the token else { System.out.println(\"Not found Boolean() value :\" + scanner.next()); } } scanner.close(); }}", "e": 1631, "s": 678, "text": null }, { "code": null, "e": 1864, "s": 1631, "text": "Not found Boolean() value :Gfg\nFound Boolean value :true\nNot found Boolean() value :9\nNot found Boolean() value :+\nNot found Boolean() value :6\nNot found Boolean() value :=\nNot found Boolean() value :12.0\nFound Boolean value :false\n" }, { "code": null, "e": 1913, "s": 1864, "text": "Program 2: To demonstrate InputMismatchException" }, { "code": "// Java program to illustrate the// nextBoolean() method of Scanner class in Java// InputMismatchException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); while (scanner.hasNext()) { // if the next is a Boolean // print found and the Boolean // since the value 60 is out of range // it throws an exception System.out.println(\"Next Boolean value :\" + scanner.nextBoolean()); } scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 2817, "s": 1913, "text": null }, { "code": null, "e": 2869, "s": 2817, "text": "Exception thrown: java.util.InputMismatchException\n" }, { "code": null, "e": 2918, "s": 2869, "text": "Program 3: To demonstrate NoSuchElementException" }, { "code": "// Java program to illustrate the// nextBoolean() method of Scanner class in Java// NoSuchElementException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // Trying to get the next Boolean value // more times than the scanner // Hence it will throw exception for (int i = 0; i < 5; i++) { // if the next is a Boolean, // print found and the Boolean if (scanner.hasNextBoolean()) { System.out.println(\"Found Boolean value :\" + scanner.nextBoolean()); } // if no Boolean is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Boolean value :\" + scanner.next()); } } scanner.close(); } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 4183, "s": 2918, "text": null }, { "code": null, "e": 4264, "s": 4183, "text": "Not found Boolean value :Gfg\nException thrown: java.util.NoSuchElementException\n" }, { "code": null, "e": 4312, "s": 4264, "text": "Program 4: To demonstrate IllegalStateException" }, { "code": "// Java program to illustrate the// nextBoolean() method of Scanner class in Java// IllegalStateException import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { String s = \"Gfg 9 + 6 = 12.0\"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // close the scanner scanner.close(); System.out.println(\"Scanner Closed\"); System.out.println(\"Trying to get \" + \"next Boolean value\"); while (scanner.hasNext()) { // if the next is a Boolean, // print found and the Boolean if (scanner.hasNextBoolean()) { System.out.println(\"Found Boolean value :\" + scanner.nextBoolean()); } // if no Boolean is found, // print \"Not Found:\" and the token else { System.out.println(\"Not found Boolean value :\" + scanner.next()); } } } catch (Exception e) { System.out.println(\"Exception thrown: \" + e); } }}", "e": 5637, "s": 4312, "text": null }, { "code": null, "e": 5752, "s": 5637, "text": "Scanner Closed\nTrying to get next Boolean value\nException thrown: java.lang.IllegalStateException: Scanner closed\n" }, { "code": null, "e": 5842, "s": 5752, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextBoolean()" }, { "code": null, "e": 5862, "s": 5842, "text": "Java - util package" }, { "code": null, "e": 5877, "s": 5862, "text": "Java-Functions" }, { "code": null, "e": 5890, "s": 5877, "text": "Java-Library" }, { "code": null, "e": 5895, "s": 5890, "text": "Java" }, { "code": null, "e": 5900, "s": 5895, "text": "Java" } ]
GCD of two numbers in PL/SQL
12 Jul, 2018 Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given two numbers and task is to find the GCD (Greatest Common Divisor) or HCF (Highest Common Factor) value of the numbers.Examples: Input: num1 = 4, num2 = 6 Output: gcd of (num1, num2) = 2 Input: num1 = 8, num2 = 48 Output: gcd of (num1, num2) = 8 Approach is to take two numbers and find their GCD value using Euclidean algorithm. Below is the required implementation: DECLARE -- declare variable num1, num2 and t -- and these three variables datatype are integer num1 INTEGER; num2 INTEGER; t INTEGER; BEGIN num1 := 8; num2 := 48; WHILE MOD(num2, num1) != 0 LOOP t := MOD(num2, num1); num2 := num1; num1 := t; END LOOP; dbms_output.Put_line('GCD of ' ||num1 ||' and ' ||num2 ||' is ' ||num1); END; -- Program End Output : GCD of 8 and 48 is 8 SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions Difference between DELETE, DROP and TRUNCATE Difference between SQL and NoSQL Window functions in SQL MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE SQL Correlated Subqueries MySQL | Regular expressions (Regexp)
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jul, 2018" }, { "code": null, "e": 272, "s": 28, "text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations." }, { "code": null, "e": 406, "s": 272, "text": "Given two numbers and task is to find the GCD (Greatest Common Divisor) or HCF (Highest Common Factor) value of the numbers.Examples:" }, { "code": null, "e": 526, "s": 406, "text": "Input: num1 = 4, num2 = 6\nOutput: gcd of (num1, num2) = 2\n\nInput: num1 = 8, num2 = 48\nOutput: gcd of (num1, num2) = 8\n" }, { "code": null, "e": 610, "s": 526, "text": "Approach is to take two numbers and find their GCD value using Euclidean algorithm." }, { "code": null, "e": 648, "s": 610, "text": "Below is the required implementation:" }, { "code": "DECLARE -- declare variable num1, num2 and t -- and these three variables datatype are integer num1 INTEGER; num2 INTEGER; t INTEGER; BEGIN num1 := 8; num2 := 48; WHILE MOD(num2, num1) != 0 LOOP t := MOD(num2, num1); num2 := num1; num1 := t; END LOOP; dbms_output.Put_line('GCD of ' ||num1 ||' and ' ||num2 ||' is ' ||num1); END; -- Program End ", "e": 1201, "s": 648, "text": null }, { "code": null, "e": 1210, "s": 1201, "text": "Output :" }, { "code": null, "e": 1232, "s": 1210, "text": "GCD of 8 and 48 is 8\n" }, { "code": null, "e": 1243, "s": 1232, "text": "SQL-PL/SQL" }, { "code": null, "e": 1247, "s": 1243, "text": "SQL" }, { "code": null, "e": 1251, "s": 1247, "text": "SQL" }, { "code": null, "e": 1349, "s": 1251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1360, "s": 1349, "text": "CTE in SQL" }, { "code": null, "e": 1426, "s": 1360, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1450, "s": 1426, "text": "SQL Interview Questions" }, { "code": null, "e": 1495, "s": 1450, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 1528, "s": 1495, "text": "Difference between SQL and NoSQL" }, { "code": null, "e": 1552, "s": 1528, "text": "Window functions in SQL" }, { "code": null, "e": 1584, "s": 1552, "text": "MySQL | Group_CONCAT() Function" }, { "code": null, "e": 1623, "s": 1584, "text": "Difference between DELETE and TRUNCATE" }, { "code": null, "e": 1649, "s": 1623, "text": "SQL Correlated Subqueries" } ]
Parameterless Method in Scala
12 Jun, 2019 Prerequisites – Scala | Functions A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle. Example: // Scala program to illustrate// Parameterless method invocationclass GeeksforGeeks(name: String, ar: Int){ // A parameterless method def author = println(name) def article = println(ar) // An empty-parenthesis method def printInformation() = { println("User -> " + name + ", Articles -> " + ar) }} // Creating object object Main { // Main method def main(args: Array[String]) { // Creating object of Class 'Geeksforgeeks' val GFG = new GeeksforGeeks("John", 50) GFG.author // calling method without parenthesis } } Output: John There are generally two conventions for using parameter less method. One is when there are not any parameters. Second one is when method does not change the mutable state. One must avoid the invocations of parameterless methods which look like field selections by defining methods that have side-effects with parenthesis.An example of calling a parameterless method with a parenthesis giving a Compilation error. Example: // Scala program to illustrate// Parameterless method invocationclass GeeksforGeeks(name: String, ar: Int){ // A parameterless method def author = println(name) def article = println(ar) // An empty-parenthesis method def printInformation() = { println("User -> " + name + ", Articles -> " + ar) }} // Creating objectobject Main { // Main method def main(args: Array[String]) { // Creating object of Class 'Geeksforgeeks' val GFG = new GeeksforGeeks("John", 50) GFG.author() //calling method without parenthesis } } Output: prog.scala:23: error: Unit does not take parametersGFG.author() //calling method without parenthesis^one error found Note: An empty parenthesis method can be called without parenthesis but it is always recommended and accepted as convention to call empty-paren methods with parenthesis. Picked Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Scala List filter() method with example Class and Object in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala Map Scala Lists Scala | Arrays Operators in Scala Scala Constructors Enumeration in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2019" }, { "code": null, "e": 62, "s": 28, "text": "Prerequisites – Scala | Functions" }, { "code": null, "e": 375, "s": 62, "text": "A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client code which is a part of uniform access principle." }, { "code": null, "e": 384, "s": 375, "text": "Example:" }, { "code": "// Scala program to illustrate// Parameterless method invocationclass GeeksforGeeks(name: String, ar: Int){ // A parameterless method def author = println(name) def article = println(ar) // An empty-parenthesis method def printInformation() = { println(\"User -> \" + name + \", Articles -> \" + ar) }} // Creating object object Main { // Main method def main(args: Array[String]) { // Creating object of Class 'Geeksforgeeks' val GFG = new GeeksforGeeks(\"John\", 50) GFG.author // calling method without parenthesis } } ", "e": 987, "s": 384, "text": null }, { "code": null, "e": 995, "s": 987, "text": "Output:" }, { "code": null, "e": 1000, "s": 995, "text": "John" }, { "code": null, "e": 1413, "s": 1000, "text": "There are generally two conventions for using parameter less method. One is when there are not any parameters. Second one is when method does not change the mutable state. One must avoid the invocations of parameterless methods which look like field selections by defining methods that have side-effects with parenthesis.An example of calling a parameterless method with a parenthesis giving a Compilation error." }, { "code": null, "e": 1422, "s": 1413, "text": "Example:" }, { "code": "// Scala program to illustrate// Parameterless method invocationclass GeeksforGeeks(name: String, ar: Int){ // A parameterless method def author = println(name) def article = println(ar) // An empty-parenthesis method def printInformation() = { println(\"User -> \" + name + \", Articles -> \" + ar) }} // Creating objectobject Main { // Main method def main(args: Array[String]) { // Creating object of Class 'Geeksforgeeks' val GFG = new GeeksforGeeks(\"John\", 50) GFG.author() //calling method without parenthesis } } ", "e": 2025, "s": 1422, "text": null }, { "code": null, "e": 2033, "s": 2025, "text": "Output:" }, { "code": null, "e": 2150, "s": 2033, "text": "prog.scala:23: error: Unit does not take parametersGFG.author() //calling method without parenthesis^one error found" }, { "code": null, "e": 2320, "s": 2150, "text": "Note: An empty parenthesis method can be called without parenthesis but it is always recommended and accepted as convention to call empty-paren methods with parenthesis." }, { "code": null, "e": 2327, "s": 2320, "text": "Picked" }, { "code": null, "e": 2333, "s": 2327, "text": "Scala" }, { "code": null, "e": 2346, "s": 2333, "text": "Scala-Method" }, { "code": null, "e": 2352, "s": 2346, "text": "Scala" }, { "code": null, "e": 2450, "s": 2352, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2472, "s": 2450, "text": "Type Casting in Scala" }, { "code": null, "e": 2512, "s": 2472, "text": "Scala List filter() method with example" }, { "code": null, "e": 2538, "s": 2512, "text": "Class and Object in Scala" }, { "code": null, "e": 2591, "s": 2538, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 2601, "s": 2591, "text": "Scala Map" }, { "code": null, "e": 2613, "s": 2601, "text": "Scala Lists" }, { "code": null, "e": 2628, "s": 2613, "text": "Scala | Arrays" }, { "code": null, "e": 2647, "s": 2628, "text": "Operators in Scala" }, { "code": null, "e": 2666, "s": 2647, "text": "Scala Constructors" } ]
Python | Pandas Dataframe.sort_values() | Set-1
20 Oct, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier.Pandas sort_values() function sorts a data frame in Ascending or Descending order of passed Column. It’s different than the sorted Python function since it cannot sort a data frame and particular column cannot be selected.Let’s discuss Dataframe.sort_values() Single Parameter Sorting:Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’) Every parameter has some default values except the ‘by’ parameter.Parameters: by: Single/List of column names to sort Data Frame by. axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column. ascending: Boolean value which sorts Data frame in ascending order if True. inplace: Boolean value. Makes the changes in passed data frame itself if True. kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame. na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’. Return Type: Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame. For link to CSV file Used in Code, click here.Example #1: Sorting by Name In the following example, A data frame is made from the csv file and the data frame is sorted in ascending order of Names of Players.Before Sorting- Python # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # displaydata Output: After Sorting- Python # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # sorting data frame by namedata.sort_values("Name", axis = 0, ascending = True, inplace = True, na_position ='last') # displaydata As shown in the image, index column is now jumbled since the data frame is sorted by Name.Output: Example #2: Changing position of Null valuesIn the give data, there are many null values in different columns which are put in the last by default. In this example, the Data Frame is sorted with respect to Salary column and Null values are kept at the top. Python # importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv("nba.csv") # sorting data frame by namedata.sort_values("Salary", axis = 0, ascending = True, inplace = True, na_position ='first') data# display As shown in output image, The NaN values are at the top and after that comes the sorted value of Salary.Output: prachisoda1234 Python pandas-dataFrame Python pandas-dataFrame-methods python-modules Python-pandas 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 Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Oct, 2021" }, { "code": null, "e": 562, "s": 53, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier.Pandas sort_values() function sorts a data frame in Ascending or Descending order of passed Column. It’s different than the sorted Python function since it cannot sort a data frame and particular column cannot be selected.Let’s discuss Dataframe.sort_values() Single Parameter Sorting:Syntax: " }, { "code": null, "e": 665, "s": 562, "text": "DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’)" }, { "code": null, "e": 746, "s": 665, "text": " Every parameter has some default values except the ‘by’ parameter.Parameters: " }, { "code": null, "e": 1239, "s": 746, "text": "by: Single/List of column names to sort Data Frame by. axis: 0 or ‘index’ for rows and 1 or ‘columns’ for Column. ascending: Boolean value which sorts Data frame in ascending order if True. inplace: Boolean value. Makes the changes in passed data frame itself if True. kind: String which can have three inputs(‘quicksort’, ‘mergesort’ or ‘heapsort’) of algorithm used to sort data frame. na_position: Takes two string input ‘last’ or ‘first’ to set position of Null values. Default is ‘last’." }, { "code": null, "e": 1254, "s": 1239, "text": "Return Type: " }, { "code": null, "e": 1341, "s": 1254, "text": "Returns a sorted Data Frame with Same dimensions as of the function caller Data Frame." }, { "code": null, "e": 1565, "s": 1341, "text": "For link to CSV file Used in Code, click here.Example #1: Sorting by Name In the following example, A data frame is made from the csv file and the data frame is sorted in ascending order of Names of Players.Before Sorting- " }, { "code": null, "e": 1572, "s": 1565, "text": "Python" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # displaydata", "e": 1695, "s": 1572, "text": null }, { "code": null, "e": 1705, "s": 1695, "text": "Output: " }, { "code": null, "e": 1721, "s": 1705, "text": "After Sorting- " }, { "code": null, "e": 1728, "s": 1721, "text": "Python" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # sorting data frame by namedata.sort_values(\"Name\", axis = 0, ascending = True, inplace = True, na_position ='last') # displaydata", "e": 1985, "s": 1728, "text": null }, { "code": null, "e": 2085, "s": 1985, "text": "As shown in the image, index column is now jumbled since the data frame is sorted by Name.Output: " }, { "code": null, "e": 2345, "s": 2085, "text": " Example #2: Changing position of Null valuesIn the give data, there are many null values in different columns which are put in the last by default. In this example, the Data Frame is sorted with respect to Salary column and Null values are kept at the top. " }, { "code": null, "e": 2352, "s": 2345, "text": "Python" }, { "code": "# importing pandas packageimport pandas as pd # making data frame from csv filedata = pd.read_csv(\"nba.csv\") # sorting data frame by namedata.sort_values(\"Salary\", axis = 0, ascending = True, inplace = True, na_position ='first') data# display", "e": 2612, "s": 2352, "text": null }, { "code": null, "e": 2726, "s": 2612, "text": "As shown in output image, The NaN values are at the top and after that comes the sorted value of Salary.Output: " }, { "code": null, "e": 2743, "s": 2728, "text": "prachisoda1234" }, { "code": null, "e": 2767, "s": 2743, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2799, "s": 2767, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 2814, "s": 2799, "text": "python-modules" }, { "code": null, "e": 2828, "s": 2814, "text": "Python-pandas" }, { "code": null, "e": 2835, "s": 2828, "text": "Python" }, { "code": null, "e": 2933, "s": 2835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2951, "s": 2933, "text": "Python Dictionary" }, { "code": null, "e": 2993, "s": 2951, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3015, "s": 2993, "text": "Enumerate() in Python" }, { "code": null, "e": 3047, "s": 3015, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3076, "s": 3047, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3103, "s": 3076, "text": "Python Classes and Objects" }, { "code": null, "e": 3124, "s": 3103, "text": "Python OOPs Concepts" }, { "code": null, "e": 3147, "s": 3124, "text": "Introduction To PYTHON" }, { "code": null, "e": 3183, "s": 3147, "text": "Convert integer to string in Python" } ]
Total number of non-decreasing numbers with n digits
17 Feb, 2022 A number is non-decreasing if every digit (except the first one) is greater than or equal to previous digit. For example, 223, 4455567, 899, are non-decreasing numbers.So, given the number of digits n, you are required to find the count of total non-decreasing numbers with n digits.Examples: Input: n = 1 Output: count = 10 Input: n = 2 Output: count = 55 Input: n = 3 Output: count = 220 We strongly recommend you to minimize your browser and try this yourself first.One way to look at the problem is, count of numbers is equal to count n digit number ending with 9 plus count of ending with digit 8 plus count for 7 and so on. How to get count ending with a particular digit? We can recur for n-1 length and digits smaller than or equal to the last digit. So below is recursive formula. Count of n digit numbers = (Count of (n-1) digit numbers Ending with digit 9) + (Count of (n-1) digit numbers Ending with digit 8) + .............................................+ .............................................+ (Count of (n-1) digit numbers Ending with digit 0) Let count ending with digit ‘d’ and length n be count(n, d) count(n, d) = ∑(count(n-1, i)) where i varies from 0 to d Total count = ∑count(n-1, d) where d varies from 0 to n-1 The above recursive solution is going to have many overlapping subproblems. Therefore, we can use Dynamic Programming to build a table in bottom up manner. Below is the implementation of above idea : C++ Java Python3 C# PHP Javascript // C++ program to count non-decreasing number with n digits#include<bits/stdc++.h>using namespace std; long long int countNonDecreasing(int n){ // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j long long int dp[10][n+1]; memset(dp, 0, sizeof dp); // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < 10; i++) dp[i][1] = 1; // Fill the table in bottom-up manner for (int digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (int len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (int x = 0; x <= digit; x++) dp[digit][len] += dp[x][len-1]; } } long long int count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for (int i = 0; i < 10; i++) count += dp[i][n]; return count;} // Driver programint main(){ int n = 3; cout << countNonDecreasing(n); return 0;} class NDN{ static int countNonDecreasing(int n) { // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j int dp[][] = new int[10][n+1]; // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < 10; i++) dp[i][1] = 1; // Fill the table in bottom-up manner for (int digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (int len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (int x = 0; x <= digit; x++) dp[digit][len] += dp[x][len-1]; } } int count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for (int i = 0; i < 10; i++) count += dp[i][n]; return count; } public static void main(String args[]) { int n = 3; System.out.println(countNonDecreasing(n)); }}/* This code is contributed by Rajat Mishra */ # Python3 program to count# non-decreasing number with n digitsdef countNonDecreasing(n): # dp[i][j] contains total count # of non decreasing numbers ending # with digit i and of length j dp = [[0 for i in range(n + 1)] for i in range(10)] # Fill table for non decreasing # numbers of length 1. # Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for i in range(10): dp[i][1] = 1 # Fill the table in bottom-up manner for digit in range(10): # Compute total numbers of non # decreasing numbers of length 'len' for len in range(2, n + 1): # sum of all numbers of length # of len-1 in which last # digit x is <= 'digit' for x in range(digit + 1): dp[digit][len] += dp[x][len - 1] count = 0 # There total nondecreasing numbers # of length n won't be dp[0][n] + # dp[1][n] ..+ dp[9][n] for i in range(10): count += dp[i][n] return count # Driver Coden = 3print(countNonDecreasing(n)) # This code is contributed# by sahilshelangia // C# program to print sum// triangle for a given arrayusing System; class GFG { static int countNonDecreasing(int n) { // dp[i][j] contains total count // of non decreasing numbers ending // with digit i and of length j int [,]dp = new int[10,n + 1]; // Fill table for non decreasing // numbers of length 1 Base cases // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < 10; i++) dp[i, 1] = 1; // Fill the table in bottom-up manner for (int digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (int len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (int x = 0; x <= digit; x++) dp[digit, len] += dp[x, len - 1]; } } int count = 0; // There total nondecreasing numbers // of length n won't be dp[0][n] // + dp[1][n] ..+ dp[9][n] for (int i = 0; i < 10; i++) count += dp[i, n]; return count; } // Driver code public static void Main() { int n = 3; Console.WriteLine(countNonDecreasing(n)); }} // This code is contributed by Sam007. <?php // PHP program to count non-decreasing number with n digits function countNonDecreasing($n){ // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j $dp = array_fill(0,10,array_fill(0,$n+1,NULL)); // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for ($i = 0; $i < 10; $i++) $dp[$i][1] = 1; // Fill the table in bottom-up manner for ($digit = 0; $digit <= 9; $digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for ($len = 2; $len <= $n; $len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for ($x = 0; $x <= $digit; $x++) $dp[$digit][$len] += $dp[$x][$len-1]; } } $count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for ($i = 0; $i < 10; $i++) $count += $dp[$i][$n]; return $count;} // Driver program $n = 3;echo countNonDecreasing($n);return 0;?> <script> function countNonDecreasing(n) { // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j let dp=new Array(10); for(let i=0;i<10;i++) { dp[i]=new Array(n+1); } for(let i=0;i<10;i++) { for(let j=0;j<n+1;j++) { dp[i][j]=0; } } // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (let i = 0; i < 10; i++) dp[i][1] = 1; // Fill the table in bottom-up manner for (let digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (let len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (let x = 0; x <= digit; x++) dp[digit][len] += dp[x][len-1]; } } let count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for (let i = 0; i < 10; i++) count += dp[i][n]; return count; } let n = 3; document.write(countNonDecreasing(n)); // This code is contributed by avanitrachhadiya2155 </script> Output: 220 Thanks to Gaurav Ahirwar for suggesting above method.Another method is based on below direct formula Count of non-decreasing numbers with n digits = N*(N+1)/2*(N+2)/3* ....*(N+n-1)/n Where N = 10 Below is the program to compute count using above formula. C++ Java Python3 C# PHP Javascript // C++ program to count non-decreasing number with n digits#include<bits/stdc++.h>using namespace std; long long int countNonDecreasing(int n){ int N = 10; // Compute value of N*(N+1)/2*(N+2)/3* ....*(N+n-1)/n long long count = 1; for (int i=1; i<=n; i++) { count *= (N+i-1); count /= i; } return count;} // Driver programint main(){ int n = 3; cout << countNonDecreasing(n); return 0;} // java program to count non-decreasing// number with n digitspublic class GFG { static long countNonDecreasing(int n) { int N = 10; // Compute value of N * (N+1)/2 * // (N+2)/3 * ....* (N+n-1)/n long count = 1; for (int i = 1; i <= n; i++) { count *= (N + i - 1); count /= i; } return count; } // Driver code public static void main(String args[]) { int n = 3; System.out.print(countNonDecreasing(n)); } } // This code is contributed by Sam007. # python program to count non-decreasing# number with n digits def countNonDecreasing(n): N = 10 # Compute value of N*(N+1)/2*(N+2)/3 # * ....*(N+n-1)/n count = 1 for i in range(1, n+1): count = int(count * (N+i-1)) count = int(count / i ) return count # Driver programn = 3;print(countNonDecreasing(n)) # This code is contributed by Sam007 // C# program to count non-decreasing// number with n digitsusing System; class GFG { static long countNonDecreasing(int n) { int N = 10; // Compute value of N * (N+1)/2 * // (N+2)/3 * ....* (N+n-1)/n long count = 1; for (int i = 1; i <= n; i++) { count *= (N + i - 1); count /= i; } return count; } public static void Main() { int n = 3; Console.WriteLine(countNonDecreasing(n)); }} // This code is contributed by Sam007. <?php// PHP program to count non-decreasing// number with n digits function countNonDecreasing($n){ $N = 10; // Compute value of N*(N+1)/2*(N+2)/3* ... // ....*(N+n-1)/n $count = 1; for ($i = 1; $i <= $n; $i++) { $count *= ($N + $i - 1); $count /= $i; } return $count;} // Driver Code $n = 3; echo countNonDecreasing($n); // This code is contributed by Sam007?> <script> // javascript program to count non-decreasing// number with n digits function countNonDecreasing(n) { let N = 10; // Compute value of N * (N+1)/2 * // (N+2)/3 * ....* (N+n-1)/n let count = 1; for (let i = 1; i <= n; i++) { count *= (N + i - 1); count = Math.floor(count/ i); } return count; } // Driver code let n = 3; document.write(countNonDecreasing(n)); // This code is contributed by rag2127.</script> Output: 220 Thanks to Abhishek Somani for suggesting this method.How does this formula work? N * (N+1)/2 * (N+2)/3 * .... * (N+n-1)/n Where N = 10 Let us try for different values of n. For n = 1, the value is N from formula. Which is true as for n = 1, we have all single digit numbers, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. For n = 2, the value is N(N+1)/2 from formula We can have N numbers beginning with 0, (N-1) numbers beginning with 1, and so on. So sum is N + (N-1) + .... + 1 = N(N+1)/2 For n = 3, the value is N(N+1)/2(N+2)/3 from formula We can have N(N+1)/2 numbers beginning with 0, (N-1)N/2 numbers beginning with 1 (Note that when we begin with 1, we have N-1 digits left to consider for remaining places), (N-2)(N-1)/2 beginning with 2, and so on. Count = N(N+1)/2 + (N-1)N/2 + (N-2)(N-1)/2 + (N-3)(N-2)/2 .... 3 + 1 [Combining first 2 terms, next 2 terms and so on] = 1/2[N2 + (N-2)2 + .... 4] = N*(N+1)*(N+2)/6 [Refer this , putting n=N/2 in the even sum formula] For general n digit case, we can apply Mathematical Induction. The count would be equal to count n-1 digit beginning with 0, i.e., N*(N+1)/2*(N+2)/3* ....*(N+n-1-1)/(n-1). Plus count of n-1 digit numbers beginning with 1, i.e., (N-1)*(N)/2*(N+1)/3* ....*(N-1+n-1-1)/(n-1) (Note that N is replaced by N-1) and so on.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 sahilshelangia ukasp avanitrachhadiya2155 rag2127 sumitgumber28 simmytarika5 number-digits Dynamic Programming Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Floyd Warshall Algorithm | DP-16 Find if there is a path between two vertices in an undirected graph Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays Operators in C / C++
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Feb, 2022" }, { "code": null, "e": 349, "s": 54, "text": "A number is non-decreasing if every digit (except the first one) is greater than or equal to previous digit. For example, 223, 4455567, 899, are non-decreasing numbers.So, given the number of digits n, you are required to find the count of total non-decreasing numbers with n digits.Examples: " }, { "code": null, "e": 454, "s": 349, "text": "Input: n = 1\nOutput: count = 10\n\nInput: n = 2\nOutput: count = 55\n\nInput: n = 3\nOutput: count = 220" }, { "code": null, "e": 854, "s": 454, "text": "We strongly recommend you to minimize your browser and try this yourself first.One way to look at the problem is, count of numbers is equal to count n digit number ending with 9 plus count of ending with digit 8 plus count for 7 and so on. How to get count ending with a particular digit? We can recur for n-1 length and digits smaller than or equal to the last digit. So below is recursive formula." }, { "code": null, "e": 1242, "s": 854, "text": "Count of n digit numbers = (Count of (n-1) digit numbers Ending with digit 9) +\n (Count of (n-1) digit numbers Ending with digit 8) +\n .............................................+ \n .............................................+\n (Count of (n-1) digit numbers Ending with digit 0) " }, { "code": null, "e": 1304, "s": 1242, "text": "Let count ending with digit ‘d’ and length n be count(n, d) " }, { "code": null, "e": 1421, "s": 1304, "text": "count(n, d) = ∑(count(n-1, i)) where i varies from 0 to d\n\nTotal count = ∑count(n-1, d) where d varies from 0 to n-1" }, { "code": null, "e": 1622, "s": 1421, "text": "The above recursive solution is going to have many overlapping subproblems. Therefore, we can use Dynamic Programming to build a table in bottom up manner. Below is the implementation of above idea : " }, { "code": null, "e": 1626, "s": 1622, "text": "C++" }, { "code": null, "e": 1631, "s": 1626, "text": "Java" }, { "code": null, "e": 1639, "s": 1631, "text": "Python3" }, { "code": null, "e": 1642, "s": 1639, "text": "C#" }, { "code": null, "e": 1646, "s": 1642, "text": "PHP" }, { "code": null, "e": 1657, "s": 1646, "text": "Javascript" }, { "code": "// C++ program to count non-decreasing number with n digits#include<bits/stdc++.h>using namespace std; long long int countNonDecreasing(int n){ // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j long long int dp[10][n+1]; memset(dp, 0, sizeof dp); // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < 10; i++) dp[i][1] = 1; // Fill the table in bottom-up manner for (int digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (int len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (int x = 0; x <= digit; x++) dp[digit][len] += dp[x][len-1]; } } long long int count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for (int i = 0; i < 10; i++) count += dp[i][n]; return count;} // Driver programint main(){ int n = 3; cout << countNonDecreasing(n); return 0;}", "e": 2852, "s": 1657, "text": null }, { "code": "class NDN{ static int countNonDecreasing(int n) { // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j int dp[][] = new int[10][n+1]; // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < 10; i++) dp[i][1] = 1; // Fill the table in bottom-up manner for (int digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (int len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (int x = 0; x <= digit; x++) dp[digit][len] += dp[x][len-1]; } } int count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for (int i = 0; i < 10; i++) count += dp[i][n]; return count; } public static void main(String args[]) { int n = 3; System.out.println(countNonDecreasing(n)); }}/* This code is contributed by Rajat Mishra */", "e": 4131, "s": 2852, "text": null }, { "code": "# Python3 program to count# non-decreasing number with n digitsdef countNonDecreasing(n): # dp[i][j] contains total count # of non decreasing numbers ending # with digit i and of length j dp = [[0 for i in range(n + 1)] for i in range(10)] # Fill table for non decreasing # numbers of length 1. # Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for i in range(10): dp[i][1] = 1 # Fill the table in bottom-up manner for digit in range(10): # Compute total numbers of non # decreasing numbers of length 'len' for len in range(2, n + 1): # sum of all numbers of length # of len-1 in which last # digit x is <= 'digit' for x in range(digit + 1): dp[digit][len] += dp[x][len - 1] count = 0 # There total nondecreasing numbers # of length n won't be dp[0][n] + # dp[1][n] ..+ dp[9][n] for i in range(10): count += dp[i][n] return count # Driver Coden = 3print(countNonDecreasing(n)) # This code is contributed# by sahilshelangia", "e": 5252, "s": 4131, "text": null }, { "code": "// C# program to print sum// triangle for a given arrayusing System; class GFG { static int countNonDecreasing(int n) { // dp[i][j] contains total count // of non decreasing numbers ending // with digit i and of length j int [,]dp = new int[10,n + 1]; // Fill table for non decreasing // numbers of length 1 Base cases // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (int i = 0; i < 10; i++) dp[i, 1] = 1; // Fill the table in bottom-up manner for (int digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (int len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (int x = 0; x <= digit; x++) dp[digit, len] += dp[x, len - 1]; } } int count = 0; // There total nondecreasing numbers // of length n won't be dp[0][n] // + dp[1][n] ..+ dp[9][n] for (int i = 0; i < 10; i++) count += dp[i, n]; return count; } // Driver code public static void Main() { int n = 3; Console.WriteLine(countNonDecreasing(n)); }} // This code is contributed by Sam007.", "e": 6666, "s": 5252, "text": null }, { "code": "<?php // PHP program to count non-decreasing number with n digits function countNonDecreasing($n){ // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j $dp = array_fill(0,10,array_fill(0,$n+1,NULL)); // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for ($i = 0; $i < 10; $i++) $dp[$i][1] = 1; // Fill the table in bottom-up manner for ($digit = 0; $digit <= 9; $digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for ($len = 2; $len <= $n; $len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for ($x = 0; $x <= $digit; $x++) $dp[$digit][$len] += $dp[$x][$len-1]; } } $count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for ($i = 0; $i < 10; $i++) $count += $dp[$i][$n]; return $count;} // Driver program $n = 3;echo countNonDecreasing($n);return 0;?>", "e": 7787, "s": 6666, "text": null }, { "code": "<script> function countNonDecreasing(n) { // dp[i][j] contains total count of non decreasing // numbers ending with digit i and of length j let dp=new Array(10); for(let i=0;i<10;i++) { dp[i]=new Array(n+1); } for(let i=0;i<10;i++) { for(let j=0;j<n+1;j++) { dp[i][j]=0; } } // Fill table for non decreasing numbers of length 1 // Base cases 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 for (let i = 0; i < 10; i++) dp[i][1] = 1; // Fill the table in bottom-up manner for (let digit = 0; digit <= 9; digit++) { // Compute total numbers of non decreasing // numbers of length 'len' for (let len = 2; len <= n; len++) { // sum of all numbers of length of len-1 // in which last digit x is <= 'digit' for (let x = 0; x <= digit; x++) dp[digit][len] += dp[x][len-1]; } } let count = 0; // There total nondecreasing numbers of length n // won't be dp[0][n] + dp[1][n] ..+ dp[9][n] for (let i = 0; i < 10; i++) count += dp[i][n]; return count; } let n = 3; document.write(countNonDecreasing(n)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 9266, "s": 7787, "text": null }, { "code": null, "e": 9275, "s": 9266, "text": "Output: " }, { "code": null, "e": 9279, "s": 9275, "text": "220" }, { "code": null, "e": 9382, "s": 9279, "text": "Thanks to Gaurav Ahirwar for suggesting above method.Another method is based on below direct formula " }, { "code": null, "e": 9510, "s": 9382, "text": "Count of non-decreasing numbers with n digits = \n N*(N+1)/2*(N+2)/3* ....*(N+n-1)/n\nWhere N = 10" }, { "code": null, "e": 9571, "s": 9510, "text": "Below is the program to compute count using above formula. " }, { "code": null, "e": 9575, "s": 9571, "text": "C++" }, { "code": null, "e": 9580, "s": 9575, "text": "Java" }, { "code": null, "e": 9588, "s": 9580, "text": "Python3" }, { "code": null, "e": 9591, "s": 9588, "text": "C#" }, { "code": null, "e": 9595, "s": 9591, "text": "PHP" }, { "code": null, "e": 9606, "s": 9595, "text": "Javascript" }, { "code": "// C++ program to count non-decreasing number with n digits#include<bits/stdc++.h>using namespace std; long long int countNonDecreasing(int n){ int N = 10; // Compute value of N*(N+1)/2*(N+2)/3* ....*(N+n-1)/n long long count = 1; for (int i=1; i<=n; i++) { count *= (N+i-1); count /= i; } return count;} // Driver programint main(){ int n = 3; cout << countNonDecreasing(n); return 0;}", "e": 10039, "s": 9606, "text": null }, { "code": "// java program to count non-decreasing// number with n digitspublic class GFG { static long countNonDecreasing(int n) { int N = 10; // Compute value of N * (N+1)/2 * // (N+2)/3 * ....* (N+n-1)/n long count = 1; for (int i = 1; i <= n; i++) { count *= (N + i - 1); count /= i; } return count; } // Driver code public static void main(String args[]) { int n = 3; System.out.print(countNonDecreasing(n)); } } // This code is contributed by Sam007.", "e": 10633, "s": 10039, "text": null }, { "code": "# python program to count non-decreasing# number with n digits def countNonDecreasing(n): N = 10 # Compute value of N*(N+1)/2*(N+2)/3 # * ....*(N+n-1)/n count = 1 for i in range(1, n+1): count = int(count * (N+i-1)) count = int(count / i ) return count # Driver programn = 3;print(countNonDecreasing(n)) # This code is contributed by Sam007", "e": 11020, "s": 10633, "text": null }, { "code": "// C# program to count non-decreasing// number with n digitsusing System; class GFG { static long countNonDecreasing(int n) { int N = 10; // Compute value of N * (N+1)/2 * // (N+2)/3 * ....* (N+n-1)/n long count = 1; for (int i = 1; i <= n; i++) { count *= (N + i - 1); count /= i; } return count; } public static void Main() { int n = 3; Console.WriteLine(countNonDecreasing(n)); }} // This code is contributed by Sam007.", "e": 11592, "s": 11020, "text": null }, { "code": "<?php// PHP program to count non-decreasing// number with n digits function countNonDecreasing($n){ $N = 10; // Compute value of N*(N+1)/2*(N+2)/3* ... // ....*(N+n-1)/n $count = 1; for ($i = 1; $i <= $n; $i++) { $count *= ($N + $i - 1); $count /= $i; } return $count;} // Driver Code $n = 3; echo countNonDecreasing($n); // This code is contributed by Sam007?>", "e": 12008, "s": 11592, "text": null }, { "code": "<script> // javascript program to count non-decreasing// number with n digits function countNonDecreasing(n) { let N = 10; // Compute value of N * (N+1)/2 * // (N+2)/3 * ....* (N+n-1)/n let count = 1; for (let i = 1; i <= n; i++) { count *= (N + i - 1); count = Math.floor(count/ i); } return count; } // Driver code let n = 3; document.write(countNonDecreasing(n)); // This code is contributed by rag2127.</script>", "e": 12564, "s": 12008, "text": null }, { "code": null, "e": 12573, "s": 12564, "text": "Output: " }, { "code": null, "e": 12577, "s": 12573, "text": "220" }, { "code": null, "e": 12660, "s": 12577, "text": "Thanks to Abhishek Somani for suggesting this method.How does this formula work? " }, { "code": null, "e": 12715, "s": 12660, "text": "N * (N+1)/2 * (N+2)/3 * .... * (N+n-1)/n\nWhere N = 10 " }, { "code": null, "e": 12755, "s": 12715, "text": "Let us try for different values of n. " }, { "code": null, "e": 13624, "s": 12755, "text": "For n = 1, the value is N from formula.\nWhich is true as for n = 1, we have all single digit\nnumbers, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.\n\nFor n = 2, the value is N(N+1)/2 from formula\nWe can have N numbers beginning with 0, (N-1) numbers \nbeginning with 1, and so on.\nSo sum is N + (N-1) + .... + 1 = N(N+1)/2\n\nFor n = 3, the value is N(N+1)/2(N+2)/3 from formula\nWe can have N(N+1)/2 numbers beginning with 0, (N-1)N/2 \nnumbers beginning with 1 (Note that when we begin with 1, \nwe have N-1 digits left to consider for remaining places),\n(N-2)(N-1)/2 beginning with 2, and so on.\nCount = N(N+1)/2 + (N-1)N/2 + (N-2)(N-1)/2 + \n (N-3)(N-2)/2 .... 3 + 1 \n [Combining first 2 terms, next 2 terms and so on]\n = 1/2[N2 + (N-2)2 + .... 4]\n = N*(N+1)*(N+2)/6 [Refer this , putting n=N/2 in the \n even sum formula]" }, { "code": null, "e": 14064, "s": 13624, "text": "For general n digit case, we can apply Mathematical Induction. The count would be equal to count n-1 digit beginning with 0, i.e., N*(N+1)/2*(N+2)/3* ....*(N+n-1-1)/(n-1). Plus count of n-1 digit numbers beginning with 1, i.e., (N-1)*(N)/2*(N+1)/3* ....*(N-1+n-1-1)/(n-1) (Note that N is replaced by N-1) and so on.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 14071, "s": 14064, "text": "Sam007" }, { "code": null, "e": 14086, "s": 14071, "text": "sahilshelangia" }, { "code": null, "e": 14092, "s": 14086, "text": "ukasp" }, { "code": null, "e": 14113, "s": 14092, "text": "avanitrachhadiya2155" }, { "code": null, "e": 14121, "s": 14113, "text": "rag2127" }, { "code": null, "e": 14135, "s": 14121, "text": "sumitgumber28" }, { "code": null, "e": 14148, "s": 14135, "text": "simmytarika5" }, { "code": null, "e": 14162, "s": 14148, "text": "number-digits" }, { "code": null, "e": 14182, "s": 14162, "text": "Dynamic Programming" }, { "code": null, "e": 14195, "s": 14182, "text": "Mathematical" }, { "code": null, "e": 14215, "s": 14195, "text": "Dynamic Programming" }, { "code": null, "e": 14228, "s": 14215, "text": "Mathematical" }, { "code": null, "e": 14326, "s": 14228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14359, "s": 14326, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 14427, "s": 14359, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 14462, "s": 14427, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 14493, "s": 14462, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 14561, "s": 14493, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 14604, "s": 14561, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 14664, "s": 14604, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 14679, "s": 14664, "text": "C++ Data Types" }, { "code": null, "e": 14703, "s": 14679, "text": "Merge two sorted arrays" } ]
Maximum games played by winner
30 Apr, 2021 There are N players which are playing a tournament. We need to find the maximum number of games the winner can play. In this tournament, two players are allowed to play against each other only if the difference between games played by them is not more than one.Examples: Input : N = 3 Output : 2 Maximum games winner can play = 2 Assume that player are P1, P2 and P3 First, two players will play let (P1, P2) Now winner will play against P3, making total games played by winner = 2 Input : N = 4 Output : 2 Maximum games winner can play = 2 Assume that player are P1, P2, P3 and P4 First two pairs will play lets (P1, P2) and (P3, P4). Now winner of these two games will play against each other, making total games played by winner = 2 We can solve this problem by first computing minimum number of players required such that the winner will play x games. Once this is computed actual problem is just inverse of this. Now assume that dp[i] denotes minimum number of players required so that winner plays i games. We can write a recursive relation among dp values as, dp[i + 1] = dp[i] + dp[i – 1] because if runner up has played (i – 1) games and winner has played i games and all players against which they have played the match are disjoint, total games played by winner will be addition of those two sets of players. Above recursive relation can be written as dp[i] = dp[i – 1] + dp[i – 2] Which is same as the Fibonacci series relation, so our final answer will be the index of the maximal Fibonacci number which is less than or equal to given number of players in the input. C++ Java Python3 C# PHP Javascript // C/C++ program to find maximum number of// games played by winner#include <bits/stdc++.h>using namespace std; // method returns maximum games a winner needs// to play in N-player tournamentint maxGameByWinner(int N){ int dp[N]; // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N int i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2);} // Driver code to test above methodsint main(){ int N = 10; cout << maxGameByWinner(N) << endl; return 0;} // Java program to find maximum number of// games played by winnerclass Max_game_winner { // method returns maximum games a winner needs // to play in N-player tournament static int maxGameByWinner(int N) { int[] dp = new int[N]; // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N int i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2); } // Driver code to test above methods public static void main(String args[]) { int N = 10; System.out.println(maxGameByWinner(N)); }}//This code is contributed by Sumit Ghosh # Python3 program to find maximum# number of games played by winner # method returns maximum games# a winner needs to play in# N-player tournament def maxGameByWinner(N): dp = [0 for i in range(N)] # for 0 games, 1 player is needed # for 1 game, 2 players are required dp[0] = 1 dp[1] = 2 # loop until i-th Fibonacci # number is less than or # equal to N i = 1 while dp[i] <= N: i = i + 1 dp[i] = dp[i - 1] + dp[i - 2] # result is (i - 1) because i will be # incremented one extra in while loop # and we want the last value which is # smaller than N, so return (i - 1) # Driver codeN = 10print(maxGameByWinner(N)) # This code is contributed# by sahilshelangia // C# program to find maximum number// of games played by winnerusing System; class GFG { // method returns maximum games a // winner needs to play in N-player // tournament static int maxGameByWinner(int N) { int[] dp = new int[N]; // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number // is less than or equal to N int i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2); } // Driver code public static void Main() { int N = 10; Console.Write(maxGameByWinner(N)); }} // This code is contributed by Nitin Mittal. <?php// PHP program to find maximum number// of games played by winner // Method returns maximum games// a winner needs to play in// N-player tournamentfunction maxGameByWinner($N){ $dp[$N]=0; // for 0 games, 1 player is needed // for 1 game, 2 players are required $dp[0] = 1; $dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N $i = 2; do { $dp[$i] = $dp[$i - 1] + $dp[$i - 2]; } while ($dp[$i++] <= $N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return ($i - 2);} // Driver Code $N = 10; echo maxGameByWinner($N); // This code is contributed by nitin mittal?> <script> // Javascript program to find maximum number of// games played by winner // method returns maximum games a winner needs // to play in N-player tournament function maxGameByWinner(N) { let dp = new Array(N).fill(0); // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N let i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2); } // driver program let N = 10; document.write(maxGameByWinner(N)); // This code is contributed by code_hunt.</script> Output : 4 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. nitin mittal sahilshelangia code_hunt Fibonacci Dynamic Programming Dynamic Programming Fibonacci Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Floyd Warshall Algorithm | DP-16 Find if there is a path between two vertices in an undirected graph Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Sieve of Eratosthenes Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Find minimum number of coins that make a given value Minimum number of jumps to reach end Tabulation vs Memoization Longest Common Substring | DP-29
[ { "code": null, "e": 54, "s": 26, "text": "\n30 Apr, 2021" }, { "code": null, "e": 327, "s": 54, "text": "There are N players which are playing a tournament. We need to find the maximum number of games the winner can play. In this tournament, two players are allowed to play against each other only if the difference between games played by them is not more than one.Examples: " }, { "code": null, "e": 798, "s": 327, "text": "Input : N = 3\nOutput : 2\nMaximum games winner can play = 2\nAssume that player are P1, P2 and P3\nFirst, two players will play let (P1, P2)\nNow winner will play against P3, \nmaking total games played by winner = 2\n\nInput : N = 4\nOutput : 2\nMaximum games winner can play = 2\nAssume that player are P1, P2, P3 and P4\nFirst two pairs will play lets (P1, P2) and \n(P3, P4). Now winner of these two games will \nplay against each other, making total games\nplayed by winner = 2" }, { "code": null, "e": 1645, "s": 800, "text": "We can solve this problem by first computing minimum number of players required such that the winner will play x games. Once this is computed actual problem is just inverse of this. Now assume that dp[i] denotes minimum number of players required so that winner plays i games. We can write a recursive relation among dp values as, dp[i + 1] = dp[i] + dp[i – 1] because if runner up has played (i – 1) games and winner has played i games and all players against which they have played the match are disjoint, total games played by winner will be addition of those two sets of players. Above recursive relation can be written as dp[i] = dp[i – 1] + dp[i – 2] Which is same as the Fibonacci series relation, so our final answer will be the index of the maximal Fibonacci number which is less than or equal to given number of players in the input. " }, { "code": null, "e": 1649, "s": 1645, "text": "C++" }, { "code": null, "e": 1654, "s": 1649, "text": "Java" }, { "code": null, "e": 1662, "s": 1654, "text": "Python3" }, { "code": null, "e": 1665, "s": 1662, "text": "C#" }, { "code": null, "e": 1669, "s": 1665, "text": "PHP" }, { "code": null, "e": 1680, "s": 1669, "text": "Javascript" }, { "code": "// C/C++ program to find maximum number of// games played by winner#include <bits/stdc++.h>using namespace std; // method returns maximum games a winner needs// to play in N-player tournamentint maxGameByWinner(int N){ int dp[N]; // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N int i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2);} // Driver code to test above methodsint main(){ int N = 10; cout << maxGameByWinner(N) << endl; return 0;}", "e": 2496, "s": 1680, "text": null }, { "code": "// Java program to find maximum number of// games played by winnerclass Max_game_winner { // method returns maximum games a winner needs // to play in N-player tournament static int maxGameByWinner(int N) { int[] dp = new int[N]; // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N int i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2); } // Driver code to test above methods public static void main(String args[]) { int N = 10; System.out.println(maxGameByWinner(N)); }}//This code is contributed by Sumit Ghosh", "e": 3498, "s": 2496, "text": null }, { "code": "# Python3 program to find maximum# number of games played by winner # method returns maximum games# a winner needs to play in# N-player tournament def maxGameByWinner(N): dp = [0 for i in range(N)] # for 0 games, 1 player is needed # for 1 game, 2 players are required dp[0] = 1 dp[1] = 2 # loop until i-th Fibonacci # number is less than or # equal to N i = 1 while dp[i] <= N: i = i + 1 dp[i] = dp[i - 1] + dp[i - 2] # result is (i - 1) because i will be # incremented one extra in while loop # and we want the last value which is # smaller than N, so return (i - 1) # Driver codeN = 10print(maxGameByWinner(N)) # This code is contributed# by sahilshelangia", "e": 4236, "s": 3498, "text": null }, { "code": "// C# program to find maximum number// of games played by winnerusing System; class GFG { // method returns maximum games a // winner needs to play in N-player // tournament static int maxGameByWinner(int N) { int[] dp = new int[N]; // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number // is less than or equal to N int i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2); } // Driver code public static void Main() { int N = 10; Console.Write(maxGameByWinner(N)); }} // This code is contributed by Nitin Mittal.", "e": 5213, "s": 4236, "text": null }, { "code": "<?php// PHP program to find maximum number// of games played by winner // Method returns maximum games// a winner needs to play in// N-player tournamentfunction maxGameByWinner($N){ $dp[$N]=0; // for 0 games, 1 player is needed // for 1 game, 2 players are required $dp[0] = 1; $dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N $i = 2; do { $dp[$i] = $dp[$i - 1] + $dp[$i - 2]; } while ($dp[$i++] <= $N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return ($i - 2);} // Driver Code $N = 10; echo maxGameByWinner($N); // This code is contributed by nitin mittal?>", "e": 5990, "s": 5213, "text": null }, { "code": "<script> // Javascript program to find maximum number of// games played by winner // method returns maximum games a winner needs // to play in N-player tournament function maxGameByWinner(N) { let dp = new Array(N).fill(0); // for 0 games, 1 player is needed // for 1 game, 2 players are required dp[0] = 1; dp[1] = 2; // loop until i-th Fibonacci number is // less than or equal to N let i = 2; do { dp[i] = dp[i - 1] + dp[i - 2]; } while (dp[i++] <= N); // result is (i - 2) because i will be // incremented one extra in while loop // and we want the last value which is // smaller than N, so one more decrement return (i - 2); } // driver program let N = 10; document.write(maxGameByWinner(N)); // This code is contributed by code_hunt.</script>", "e": 6922, "s": 5990, "text": null }, { "code": null, "e": 6933, "s": 6922, "text": "Output : " }, { "code": null, "e": 6935, "s": 6933, "text": "4" }, { "code": null, "e": 7358, "s": 6935, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. " }, { "code": null, "e": 7371, "s": 7358, "text": "nitin mittal" }, { "code": null, "e": 7386, "s": 7371, "text": "sahilshelangia" }, { "code": null, "e": 7396, "s": 7386, "text": "code_hunt" }, { "code": null, "e": 7406, "s": 7396, "text": "Fibonacci" }, { "code": null, "e": 7426, "s": 7406, "text": "Dynamic Programming" }, { "code": null, "e": 7446, "s": 7426, "text": "Dynamic Programming" }, { "code": null, "e": 7456, "s": 7446, "text": "Fibonacci" }, { "code": null, "e": 7554, "s": 7456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7587, "s": 7554, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 7655, "s": 7587, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 7690, "s": 7655, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 7721, "s": 7690, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 7743, "s": 7721, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 7811, "s": 7743, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 7864, "s": 7811, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7901, "s": 7864, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7927, "s": 7901, "text": "Tabulation vs Memoization" } ]
Public vs Protected Access Modifier in Java
08 Oct, 2021 Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members. Public Access Modifiers: If a class is declared as public then we can access that class from anywhere. In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B’s main method we create an object of type class A and trying to access the data of method m1. Java // creating a packagepackage pack1; // import required packagesimport java.io.*;import java.util.*; // declaring a public classpublic class A { // declaring method m1 public void m1() { System.out.println("GFG"); }} Compiling and saving the above code by using the below command line: Java // creating a packagepackage pack2; // import required packagesimport java.io.*;import java.util.*; // importing package pack1import pack1.A; // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }} If class A is not public while compiling B class we will get a compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package. Similarly, a member or method, or interface is declared as public as we can access that member from anywhere. Protected Access Modifier: This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface. A member is declared as protected as we can access that member only within the current package but only in the child class of the outside package. Java // import required packagesimport java.io.*;import java.util.*; // declaring a parent class Aclass A { // declaring a protected method m1() protected void m1() { System.out.println("GFG"); }} // creating a child class by extending the class Aclass B extends A { // main method public static void main(String[] args) { // creating an object of parent class // using parent reference A a = new A(); /// calling method m1 a.m1(); // creating an object of child class // using child reference B b = new B(); // calling method m1 b.m1(); // creating an object of child class // using parent reference A a1 = new B(); // calling m1 method a1.m1(); }} In the above example, we create three objects using parent reference and child reference and call m1() method on it, and it successfully executed so from the above example we can say that we can access the protected method within the current package anywhere either by using parent reference or by child reference. mroshanmishra0072 adnanirshad158 prachisoda1234 Java-Modifier Picked Technical Scripter 2020 Difference Between Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Similarities and Difference between Java and C++ Difference between Compile-time and Run-time Polymorphism in Java Differences and Applications of List, Tuple, Set and Dictionary in Python Arrays in Java Arrays.sort() in Java with examples Split() String method in Java with examples Reverse a string in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Oct, 2021" }, { "code": null, "e": 502, "s": 53, "text": "Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members." }, { "code": null, "e": 605, "s": 502, "text": "Public Access Modifiers: If a class is declared as public then we can access that class from anywhere." }, { "code": null, "e": 988, "s": 605, "text": "In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B’s main method we create an object of type class A and trying to access the data of method m1." }, { "code": null, "e": 993, "s": 988, "text": "Java" }, { "code": "// creating a packagepackage pack1; // import required packagesimport java.io.*;import java.util.*; // declaring a public classpublic class A { // declaring method m1 public void m1() { System.out.println(\"GFG\"); }}", "e": 1218, "s": 993, "text": null }, { "code": null, "e": 1288, "s": 1218, "text": "Compiling and saving the above code by using the below command line: " }, { "code": null, "e": 1293, "s": 1288, "text": "Java" }, { "code": "// creating a packagepackage pack2; // import required packagesimport java.io.*;import java.util.*; // importing package pack1import pack1.A; // driver classclass B { // main method public static void main(String[] args) { // creating an object of type class A A a = new A(); // accessing the method m1() a.m1(); }}", "e": 1659, "s": 1293, "text": null }, { "code": null, "e": 1828, "s": 1659, "text": "If class A is not public while compiling B class we will get a compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package." }, { "code": null, "e": 1938, "s": 1828, "text": "Similarly, a member or method, or interface is declared as public as we can access that member from anywhere." }, { "code": null, "e": 2114, "s": 1938, "text": "Protected Access Modifier: This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface." }, { "code": null, "e": 2262, "s": 2114, "text": "A member is declared as protected as we can access that member only within the current package but only in the child class of the outside package. " }, { "code": null, "e": 2267, "s": 2262, "text": "Java" }, { "code": "// import required packagesimport java.io.*;import java.util.*; // declaring a parent class Aclass A { // declaring a protected method m1() protected void m1() { System.out.println(\"GFG\"); }} // creating a child class by extending the class Aclass B extends A { // main method public static void main(String[] args) { // creating an object of parent class // using parent reference A a = new A(); /// calling method m1 a.m1(); // creating an object of child class // using child reference B b = new B(); // calling method m1 b.m1(); // creating an object of child class // using parent reference A a1 = new B(); // calling m1 method a1.m1(); }}", "e": 3076, "s": 2267, "text": null }, { "code": null, "e": 3392, "s": 3076, "text": "In the above example, we create three objects using parent reference and child reference and call m1() method on it, and it successfully executed so from the above example we can say that we can access the protected method within the current package anywhere either by using parent reference or by child reference. " }, { "code": null, "e": 3412, "s": 3394, "text": "mroshanmishra0072" }, { "code": null, "e": 3427, "s": 3412, "text": "adnanirshad158" }, { "code": null, "e": 3442, "s": 3427, "text": "prachisoda1234" }, { "code": null, "e": 3456, "s": 3442, "text": "Java-Modifier" }, { "code": null, "e": 3463, "s": 3456, "text": "Picked" }, { "code": null, "e": 3487, "s": 3463, "text": "Technical Scripter 2020" }, { "code": null, "e": 3506, "s": 3487, "text": "Difference Between" }, { "code": null, "e": 3511, "s": 3506, "text": "Java" }, { "code": null, "e": 3530, "s": 3511, "text": "Technical Scripter" }, { "code": null, "e": 3535, "s": 3530, "text": "Java" }, { "code": null, "e": 3633, "s": 3535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3694, "s": 3633, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3762, "s": 3694, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 3811, "s": 3762, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 3877, "s": 3811, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 3951, "s": 3877, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 3966, "s": 3951, "text": "Arrays in Java" }, { "code": null, "e": 4002, "s": 3966, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 4046, "s": 4002, "text": "Split() String method in Java with examples" }, { "code": null, "e": 4071, "s": 4046, "text": "Reverse a string in Java" } ]
Dart - Static Keyword - GeeksforGeeks
25 Jul, 2021 The static keyword is used for memory management of global data members. The static keyword can be applied to the fields and methods of a class. The static variables and methods are part of the class instead of a specific instance. The static keyword is used for a class-level variable and method that is the same for every instance of a class, this means if a data member is static, it can be accessed without creating an object. The static keyword allows data members to persist Values between different instances of a class. There is no need to create a class object to access a static variable or call a static method: simply put the class name before the static variable or method name to use them. The static variables belong to the class instead of a specific instance. A static variable is common to all instances of a class: this means only a single copy of the static variable is shared among all the instances of a class. The memory allocation for static variables happens only once in the class area at the time of class loading. Static variables can be declared using the static keyword followed by data type then the variable name Syntax: static [date_type] [variable_name]; The static variable can be accessed directly from the class name itself rather than creating an instance of it. Syntax: Classname.staticVariable; The static method belongs to ta class instead of class instances. A static method is only allowed to access the static variables of class and can invoke only static methods of the class. Usually, utility methods are created as static methods when we want it to be used by other classes without the need of creating an instance. A static method can be declared using static keyword followed by return type, followed by method name Syntax: static return_type method_name() { // Statement(s) } Static methods can be invoked directly from the class name itself rather than creating an instance of it. Syntax: ClassName.staticMethod(); Example 1: Dart // Dart Program to show// Static methods in Dartclass Employee { static var emp_dept; var emp_name; int emp_salary; // Function to show details // of the Employee showDetails() { print("Name of the Employee is: ${emp_name}"); print("Salary of the Employee is: ${emp_salary}"); print("Dept. of the Employee is: ${emp_dept}"); }} // Main functionvoid main() { Employee e1 = new Employee(); Employee e2 = new Employee(); Employee.emp_dept = "MIS"; print("GeeksforGeeks Dart static Keyword Example"); e1.emp_name = 'Rahul'; e1.emp_salary = 50000; e1.showDetails(); e2.emp_name = 'Tina'; e2.emp_salary = 55000; e2.showDetails();} Output: GeeksforGeeks Dart static Keyword Example Name of the Employee is: Rahul Salary of the Employee is: 50000 Dept. of the Employee is: MIS Name of the Employee is: Tina Salary of the Employee is: 55000 Dept. of the Employee is: MIS Example 2: Dart // Dart program in dart to// illustrate static methodclass StaticMem { static int num; static disp() { print("#GFG the value of num is ${StaticMem.num}") ; } } void main() { StaticMem.num = 75; // initialize the static variable } StaticMem.disp(); // invoke the static method } Output: #GFG the value of num is 75 Dart-Keywords Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Row and Column Widgets Flutter - BoxShadow Widget Dart Tutorial How to Append or Concatenate Strings in Dart? ListView Class in Flutter Flutter - Flexible Widget Flutter - Stack Widget
[ { "code": null, "e": 23969, "s": 23941, "text": "\n25 Jul, 2021" }, { "code": null, "e": 24202, "s": 23969, "text": "The static keyword is used for memory management of global data members. The static keyword can be applied to the fields and methods of a class. The static variables and methods are part of the class instead of a specific instance. " }, { "code": null, "e": 24401, "s": 24202, "text": "The static keyword is used for a class-level variable and method that is the same for every instance of a class, this means if a data member is static, it can be accessed without creating an object." }, { "code": null, "e": 24498, "s": 24401, "text": "The static keyword allows data members to persist Values between different instances of a class." }, { "code": null, "e": 24674, "s": 24498, "text": "There is no need to create a class object to access a static variable or call a static method: simply put the class name before the static variable or method name to use them." }, { "code": null, "e": 25012, "s": 24674, "text": "The static variables belong to the class instead of a specific instance. A static variable is common to all instances of a class: this means only a single copy of the static variable is shared among all the instances of a class. The memory allocation for static variables happens only once in the class area at the time of class loading." }, { "code": null, "e": 25115, "s": 25012, "text": "Static variables can be declared using the static keyword followed by data type then the variable name" }, { "code": null, "e": 25160, "s": 25115, "text": "Syntax: static [date_type] [variable_name];\n" }, { "code": null, "e": 25273, "s": 25160, "text": " The static variable can be accessed directly from the class name itself rather than creating an instance of it." }, { "code": null, "e": 25308, "s": 25273, "text": "Syntax: Classname.staticVariable;\n" }, { "code": null, "e": 25636, "s": 25308, "text": "The static method belongs to ta class instead of class instances. A static method is only allowed to access the static variables of class and can invoke only static methods of the class. Usually, utility methods are created as static methods when we want it to be used by other classes without the need of creating an instance." }, { "code": null, "e": 25738, "s": 25636, "text": "A static method can be declared using static keyword followed by return type, followed by method name" }, { "code": null, "e": 25805, "s": 25738, "text": "Syntax:\n\nstatic return_type method_name()\n{\n // Statement(s)\n}\n" }, { "code": null, "e": 25911, "s": 25805, "text": "Static methods can be invoked directly from the class name itself rather than creating an instance of it." }, { "code": null, "e": 25946, "s": 25911, "text": "Syntax: ClassName.staticMethod();\n" }, { "code": null, "e": 25957, "s": 25946, "text": "Example 1:" }, { "code": null, "e": 25962, "s": 25957, "text": "Dart" }, { "code": "// Dart Program to show// Static methods in Dartclass Employee { static var emp_dept; var emp_name; int emp_salary; // Function to show details // of the Employee showDetails() { print(\"Name of the Employee is: ${emp_name}\"); print(\"Salary of the Employee is: ${emp_salary}\"); print(\"Dept. of the Employee is: ${emp_dept}\"); }} // Main functionvoid main() { Employee e1 = new Employee(); Employee e2 = new Employee(); Employee.emp_dept = \"MIS\"; print(\"GeeksforGeeks Dart static Keyword Example\"); e1.emp_name = 'Rahul'; e1.emp_salary = 50000; e1.showDetails(); e2.emp_name = 'Tina'; e2.emp_salary = 55000; e2.showDetails();}", "e": 26620, "s": 25962, "text": null }, { "code": null, "e": 26628, "s": 26620, "text": "Output:" }, { "code": null, "e": 26858, "s": 26628, "text": "GeeksforGeeks Dart static Keyword Example\nName of the Employee is: Rahul\nSalary of the Employee is: 50000\nDept. of the Employee is: MIS\nName of the Employee is: Tina\nSalary of the Employee is: 55000\nDept. of the Employee is: MIS\n" }, { "code": null, "e": 26869, "s": 26858, "text": "Example 2:" }, { "code": null, "e": 26874, "s": 26869, "text": "Dart" }, { "code": "// Dart program in dart to// illustrate static methodclass StaticMem { static int num; static disp() { print(\"#GFG the value of num is ${StaticMem.num}\") ; } } void main() { StaticMem.num = 75; // initialize the static variable } StaticMem.disp(); // invoke the static method }", "e": 27193, "s": 26874, "text": null }, { "code": null, "e": 27201, "s": 27193, "text": "Output:" }, { "code": null, "e": 27230, "s": 27201, "text": "#GFG the value of num is 75\n" }, { "code": null, "e": 27244, "s": 27230, "text": "Dart-Keywords" }, { "code": null, "e": 27249, "s": 27244, "text": "Dart" }, { "code": null, "e": 27347, "s": 27249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27379, "s": 27347, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 27418, "s": 27379, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 27444, "s": 27418, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 27477, "s": 27444, "text": "Flutter - Row and Column Widgets" }, { "code": null, "e": 27504, "s": 27477, "text": "Flutter - BoxShadow Widget" }, { "code": null, "e": 27518, "s": 27504, "text": "Dart Tutorial" }, { "code": null, "e": 27564, "s": 27518, "text": "How to Append or Concatenate Strings in Dart?" }, { "code": null, "e": 27590, "s": 27564, "text": "ListView Class in Flutter" }, { "code": null, "e": 27616, "s": 27590, "text": "Flutter - Flexible Widget" } ]
Count number of edges in an undirected graph in C++
Given the task is to count the number of edges in an undirected graph. An undirected graph is a set of vertices which are connected together to form a graph, whose all the edges are bidirectional. Undirected graphs can travel in any direction from one node to another connected node. Below is a visual representation of the undirected graph. Now, according to the problem we have to find the number of edges in the undirected graph. Edges in a graph are the lines to which two vertices are joined. Input − insert(graph_list, 0, 1); insert(graph_list, 0, 2); insert(graph_list, 1, 2); insert(graph_list, 1, 4); insert(graph_list, 2, 4); insert(graph_list, 2, 3); insert(graph_list, 3, 4); Output − count of edges are: 7 Initialise a list to store all the vertices of the graph’s list and insert the values accordingly. Initialise a list to store all the vertices of the graph’s list and insert the values accordingly. In function count_edges, declare a variable count=0 which is to return the count of the edges. In function count_edges, declare a variable count=0 which is to return the count of the edges. Traverse the list using a loop until we reach the last vertice and add the value of count with graph_list[i].size() and store it back to the count variable. Traverse the list using a loop until we reach the last vertice and add the value of count with graph_list[i].size() and store it back to the count variable. After we reach the last vertice, divide the value of count by two, and print the result. After we reach the last vertice, divide the value of count by two, and print the result. Live Demo #include<bits/stdc++.h> using namespace std; //function to insert vertices void insert(list<int> graph_list[], int u, int v){ graph_list[u].push_back(v); graph_list[v].push_back(u); } //function to count the total number of edges void count_edges(list<int> graph_list[], int v){ int count=0; //traverse the loop till the vertice is found for (int i = 0 ; i < v ; i++){ count += graph_list[i].size(); } count = count/2; cout<<"count of edges are: "<<count; } int main(int argc, char* argv[]){ //creating 5 vertices in a graph int vertices = 5; //declare list to create a graph and pass the vertices list<int> graph_list[vertices]; //call insert function passing the list variable, vertice, linked vertice insert(graph_list, 0, 1); insert(graph_list, 0, 2); insert(graph_list, 1, 2); insert(graph_list, 1, 4); insert(graph_list, 2, 4); insert(graph_list, 2, 3); insert(graph_list, 3, 4); //calling count function that will count the edges count_edges(graph_list, vertices); return 0 ; } If we run the above code we will get the following output − count of edges are: 7
[ { "code": null, "e": 1346, "s": 1062, "text": "Given the task is to count the number of edges in an undirected graph. An undirected graph is a set of vertices which are connected together to form a graph, whose all the edges are bidirectional. Undirected graphs can travel in any direction from one node to another connected node." }, { "code": null, "e": 1404, "s": 1346, "text": "Below is a visual representation of the undirected graph." }, { "code": null, "e": 1495, "s": 1404, "text": "Now, according to the problem we have to find the number of edges in the undirected graph." }, { "code": null, "e": 1560, "s": 1495, "text": "Edges in a graph are the lines to which two vertices are joined." }, { "code": null, "e": 1568, "s": 1560, "text": "Input −" }, { "code": null, "e": 1750, "s": 1568, "text": "insert(graph_list, 0, 1);\ninsert(graph_list, 0, 2);\ninsert(graph_list, 1, 2);\ninsert(graph_list, 1, 4);\ninsert(graph_list, 2, 4);\ninsert(graph_list, 2, 3);\ninsert(graph_list, 3, 4);" }, { "code": null, "e": 1759, "s": 1750, "text": "Output −" }, { "code": null, "e": 1781, "s": 1759, "text": "count of edges are: 7" }, { "code": null, "e": 1880, "s": 1781, "text": "Initialise a list to store all the vertices of the graph’s list and insert the values accordingly." }, { "code": null, "e": 1979, "s": 1880, "text": "Initialise a list to store all the vertices of the graph’s list and insert the values accordingly." }, { "code": null, "e": 2074, "s": 1979, "text": "In function count_edges, declare a variable count=0 which is to return the count of the edges." }, { "code": null, "e": 2169, "s": 2074, "text": "In function count_edges, declare a variable count=0 which is to return the count of the edges." }, { "code": null, "e": 2326, "s": 2169, "text": "Traverse the list using a loop until we reach the last vertice and add the value of count with graph_list[i].size() and store it back to the count variable." }, { "code": null, "e": 2483, "s": 2326, "text": "Traverse the list using a loop until we reach the last vertice and add the value of count with graph_list[i].size() and store it back to the count variable." }, { "code": null, "e": 2572, "s": 2483, "text": "After we reach the last vertice, divide the value of count by two, and print the result." }, { "code": null, "e": 2661, "s": 2572, "text": "After we reach the last vertice, divide the value of count by two, and print the result." }, { "code": null, "e": 2672, "s": 2661, "text": " Live Demo" }, { "code": null, "e": 3732, "s": 2672, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//function to insert vertices\nvoid insert(list<int> graph_list[], int u, int v){\n graph_list[u].push_back(v);\n graph_list[v].push_back(u);\n}\n//function to count the total number of edges\nvoid count_edges(list<int> graph_list[], int v){\n int count=0;\n //traverse the loop till the vertice is found\n for (int i = 0 ; i < v ; i++){\n count += graph_list[i].size();\n }\n count = count/2;\n cout<<\"count of edges are: \"<<count;\n}\nint main(int argc, char* argv[]){\n //creating 5 vertices in a graph\n int vertices = 5;\n //declare list to create a graph and pass the vertices\n list<int> graph_list[vertices];\n //call insert function passing the list variable, vertice, linked vertice\n insert(graph_list, 0, 1);\n insert(graph_list, 0, 2);\n insert(graph_list, 1, 2);\n insert(graph_list, 1, 4);\n insert(graph_list, 2, 4);\n insert(graph_list, 2, 3);\n insert(graph_list, 3, 4);\n //calling count function that will count the edges\n count_edges(graph_list, vertices);\n return 0 ;\n}" }, { "code": null, "e": 3792, "s": 3732, "text": "If we run the above code we will get the following output −" }, { "code": null, "e": 3814, "s": 3792, "text": "count of edges are: 7" } ]
How to Print to the Console in Android Studio? - GeeksforGeeks
23 Mar, 2021 In computer technology, the console is simply a combination of a monitor and an input device. Generally, the input device is referred to here as the pair of mouse and keyboard. In order to proceed with the topic, we have to understand the terminology of computer science, which is an important part of the process of developing software, and it’s called debugging. Debugging is the process of identifying a bug or an error and fixing it properly for the software. We have to test the software before producing it on market in multiple phases. We have to debug the errors also, then only software will be pure error-free and it will be ready for production. The most of the things which computer does with our code is invisible for us. For Debugging, we have to identify the error first then only we can solve that error. If you want to see the error, then you have to print or log it to our console directly. There are many and different methods in different programming languages for doing it. In C, We do it using printf(), in C++ we will use cout, and in Java, we generally use System.out.println. We all know, that in the android studio we have to code in a different way. Android has its own methods and components, we have to code the application using them. This is slightly different from normal programming. In today’s article we are going to learn about that how can we print to the console in Android Studio. The Logcat is a window in android studio, which displays system information when a garbage collection occurs and also the messages which you have added to your Log class. It displays the message in real-time. It also keeps the history of the messages. You can also learn more about the Logcat window from Here. The log class is a pre-defined class in android studio which allows the developer to print messages in Logcat Window, which is the console for Android Studio. Every message is written using a log, Contains a special type or format that represents for what purpose the message is being written. Java Kotlin Log.d(tag, message); Log.d(tag, message) Above is the sample of a default code for printing something to the logcat. The d is the symbol here that the message is written for debugging the code. More symbols and types are below mentioned in the Log class. The priority of verbose is the lowest and the assert has the highest priority. Below is the list of types of messages in the log class in chronological order. V (Verbose) D (Debug) I (Information) W (Warning) E (Error) A (Assert) Log class always takes two arguments, the tag, and the message. The tag is like an identifier of your message you can choose it according to preference and in place of messages, you have to type your log message. Now, we are aware that in the android studio we have to use the Log Class to print something on the Logcat window which is the console for android. So, Let’s see a real-world implementation of this method called Logcat. Step 1: Start a New Project in Android Studio or Open an existing project on which you want to work. Here is the guide to Starting a new project on Android Studio. Step 2: Go to your Java or Kotlin file for the activity, and in your onCreate method write the log messages with help of the Log class. Below is our code that we have used in the MainActivity for Random number generation and Printing log messages. Java package com.voicex.printlogmessages; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.util.Log; import java.util.Random; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final int random = new Random().nextInt(5); switch (random) { case 0: Log.i("NumberGenerated", "Function has generated zero."); break; case 1: Log.i("NumberGenerated", "Function has generated one."); break; case 2: Log.i("NumberGenerated", "Function has generated two."); break; case 3: Log.i("NumberGenerated", "Function has generated three."); break; case 4: Log.i("NumberGenerated", "Function has generated four."); break; case 5: Log.i("NumberGenerated", "Function has generated five."); break; } }} Note: Choose your desired activity, for which you want to print on console. For example, here we are working on MainActivity and generating a random number, and printing it using conditional statements. You can do this or can do something similar to it. At bottom of the page, we will also share the GitHub repository of the application which we have made in this article. You can refer to that. Step 3: Now try to build and run your android application, in the meantime also click on the Logcat button which will be on the bottom. Log messages will appear according to the condition cause here we have used the conditional statements. In the logcat window, these are the buttons for many tasks: Clear logcat: Clears the visible Logcat window Scroll to the end: Take you to the end of the logcat window, where you can see the latest messages. Up the stack trace and Down the stack trace: Navigates up and down the stack traces in the log Use soft wraps: Enables the line wrapping and prevents the horizontal scrolling Print: Print logcat messages on paper or save them as a PDF. Restart: Clears the log and restarts it. Logcat header: Open customization options for log messages Screen capture: Captures the logcat window as an image Screen record: Records the video up to 3 Minutes of logcat window. You can select regex optionally, for using a regular expression search pattern. Then type something in the search field which you want to search. The search results will be displayed. If you want to store the search string in this session then press enter after typing the search string. On the top right corner of the logcat window, you will see a filter button and will find three options: Show only selected applications: Displays the messages generated by the app code only.No Filters: Apply no filtersEdit Filter Configurations: Modify your custom filter or create new filters Show only selected applications: Displays the messages generated by the app code only. No Filters: Apply no filters Edit Filter Configurations: Modify your custom filter or create new filters GitHub link as a Resource: Click Here Android-Studio Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Android Listview in Java with Example How to Post Data to API using Retrofit in Android? Retrofit with Kotlin Coroutine in Android How to Add Image to Drawable Folder in Android Studio? How to Change the Background Color After Clicking the Button in Android? How to Retrieve Data from the Firebase Realtime Database in Android? GridView in Android with Example ImageView in Android with Example
[ { "code": null, "e": 24725, "s": 24697, "text": "\n23 Mar, 2021" }, { "code": null, "e": 25721, "s": 24725, "text": "In computer technology, the console is simply a combination of a monitor and an input device. Generally, the input device is referred to here as the pair of mouse and keyboard. In order to proceed with the topic, we have to understand the terminology of computer science, which is an important part of the process of developing software, and it’s called debugging. Debugging is the process of identifying a bug or an error and fixing it properly for the software. We have to test the software before producing it on market in multiple phases. We have to debug the errors also, then only software will be pure error-free and it will be ready for production. The most of the things which computer does with our code is invisible for us. For Debugging, we have to identify the error first then only we can solve that error. If you want to see the error, then you have to print or log it to our console directly. There are many and different methods in different programming languages for doing it. " }, { "code": null, "e": 26147, "s": 25721, "text": "In C, We do it using printf(), in C++ we will use cout, and in Java, we generally use System.out.println. We all know, that in the android studio we have to code in a different way. Android has its own methods and components, we have to code the application using them. This is slightly different from normal programming. In today’s article we are going to learn about that how can we print to the console in Android Studio. " }, { "code": null, "e": 26458, "s": 26147, "text": "The Logcat is a window in android studio, which displays system information when a garbage collection occurs and also the messages which you have added to your Log class. It displays the message in real-time. It also keeps the history of the messages. You can also learn more about the Logcat window from Here." }, { "code": null, "e": 26753, "s": 26458, "text": "The log class is a pre-defined class in android studio which allows the developer to print messages in Logcat Window, which is the console for Android Studio. Every message is written using a log, Contains a special type or format that represents for what purpose the message is being written. " }, { "code": null, "e": 26758, "s": 26753, "text": "Java" }, { "code": null, "e": 26765, "s": 26758, "text": "Kotlin" }, { "code": "Log.d(tag, message);", "e": 26786, "s": 26765, "text": null }, { "code": "Log.d(tag, message)", "e": 26806, "s": 26786, "text": null }, { "code": null, "e": 27179, "s": 26806, "text": "Above is the sample of a default code for printing something to the logcat. The d is the symbol here that the message is written for debugging the code. More symbols and types are below mentioned in the Log class. The priority of verbose is the lowest and the assert has the highest priority. Below is the list of types of messages in the log class in chronological order." }, { "code": null, "e": 27191, "s": 27179, "text": "V (Verbose)" }, { "code": null, "e": 27201, "s": 27191, "text": "D (Debug)" }, { "code": null, "e": 27217, "s": 27201, "text": "I (Information)" }, { "code": null, "e": 27229, "s": 27217, "text": "W (Warning)" }, { "code": null, "e": 27239, "s": 27229, "text": "E (Error)" }, { "code": null, "e": 27250, "s": 27239, "text": "A (Assert)" }, { "code": null, "e": 27463, "s": 27250, "text": "Log class always takes two arguments, the tag, and the message. The tag is like an identifier of your message you can choose it according to preference and in place of messages, you have to type your log message." }, { "code": null, "e": 27683, "s": 27463, "text": "Now, we are aware that in the android studio we have to use the Log Class to print something on the Logcat window which is the console for android. So, Let’s see a real-world implementation of this method called Logcat." }, { "code": null, "e": 27847, "s": 27683, "text": "Step 1: Start a New Project in Android Studio or Open an existing project on which you want to work. Here is the guide to Starting a new project on Android Studio." }, { "code": null, "e": 28096, "s": 27847, "text": "Step 2: Go to your Java or Kotlin file for the activity, and in your onCreate method write the log messages with help of the Log class. Below is our code that we have used in the MainActivity for Random number generation and Printing log messages. " }, { "code": null, "e": 28101, "s": 28096, "text": "Java" }, { "code": "package com.voicex.printlogmessages; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.util.Log; import java.util.Random; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final int random = new Random().nextInt(5); switch (random) { case 0: Log.i(\"NumberGenerated\", \"Function has generated zero.\"); break; case 1: Log.i(\"NumberGenerated\", \"Function has generated one.\"); break; case 2: Log.i(\"NumberGenerated\", \"Function has generated two.\"); break; case 3: Log.i(\"NumberGenerated\", \"Function has generated three.\"); break; case 4: Log.i(\"NumberGenerated\", \"Function has generated four.\"); break; case 5: Log.i(\"NumberGenerated\", \"Function has generated five.\"); break; } }}", "e": 29255, "s": 28101, "text": null }, { "code": null, "e": 29510, "s": 29255, "text": "Note: Choose your desired activity, for which you want to print on console. For example, here we are working on MainActivity and generating a random number, and printing it using conditional statements. You can do this or can do something similar to it. " }, { "code": null, "e": 29652, "s": 29510, "text": "At bottom of the page, we will also share the GitHub repository of the application which we have made in this article. You can refer to that." }, { "code": null, "e": 29892, "s": 29652, "text": "Step 3: Now try to build and run your android application, in the meantime also click on the Logcat button which will be on the bottom. Log messages will appear according to the condition cause here we have used the conditional statements." }, { "code": null, "e": 29952, "s": 29892, "text": "In the logcat window, these are the buttons for many tasks:" }, { "code": null, "e": 29999, "s": 29952, "text": "Clear logcat: Clears the visible Logcat window" }, { "code": null, "e": 30099, "s": 29999, "text": "Scroll to the end: Take you to the end of the logcat window, where you can see the latest messages." }, { "code": null, "e": 30194, "s": 30099, "text": "Up the stack trace and Down the stack trace: Navigates up and down the stack traces in the log" }, { "code": null, "e": 30274, "s": 30194, "text": "Use soft wraps: Enables the line wrapping and prevents the horizontal scrolling" }, { "code": null, "e": 30335, "s": 30274, "text": "Print: Print logcat messages on paper or save them as a PDF." }, { "code": null, "e": 30376, "s": 30335, "text": "Restart: Clears the log and restarts it." }, { "code": null, "e": 30435, "s": 30376, "text": "Logcat header: Open customization options for log messages" }, { "code": null, "e": 30490, "s": 30435, "text": "Screen capture: Captures the logcat window as an image" }, { "code": null, "e": 30557, "s": 30490, "text": "Screen record: Records the video up to 3 Minutes of logcat window." }, { "code": null, "e": 30845, "s": 30557, "text": "You can select regex optionally, for using a regular expression search pattern. Then type something in the search field which you want to search. The search results will be displayed. If you want to store the search string in this session then press enter after typing the search string." }, { "code": null, "e": 30949, "s": 30845, "text": "On the top right corner of the logcat window, you will see a filter button and will find three options:" }, { "code": null, "e": 31139, "s": 30949, "text": "Show only selected applications: Displays the messages generated by the app code only.No Filters: Apply no filtersEdit Filter Configurations: Modify your custom filter or create new filters" }, { "code": null, "e": 31226, "s": 31139, "text": "Show only selected applications: Displays the messages generated by the app code only." }, { "code": null, "e": 31255, "s": 31226, "text": "No Filters: Apply no filters" }, { "code": null, "e": 31331, "s": 31255, "text": "Edit Filter Configurations: Modify your custom filter or create new filters" }, { "code": null, "e": 31369, "s": 31331, "text": "GitHub link as a Resource: Click Here" }, { "code": null, "e": 31384, "s": 31369, "text": "Android-Studio" }, { "code": null, "e": 31391, "s": 31384, "text": "Picked" }, { "code": null, "e": 31399, "s": 31391, "text": "Android" }, { "code": null, "e": 31407, "s": 31399, "text": "Android" }, { "code": null, "e": 31505, "s": 31407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31514, "s": 31505, "text": "Comments" }, { "code": null, "e": 31527, "s": 31514, "text": "Old Comments" }, { "code": null, "e": 31566, "s": 31527, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31616, "s": 31566, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 31654, "s": 31616, "text": "Android Listview in Java with Example" }, { "code": null, "e": 31705, "s": 31654, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 31747, "s": 31705, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31802, "s": 31747, "text": "How to Add Image to Drawable Folder in Android Studio?" }, { "code": null, "e": 31875, "s": 31802, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 31944, "s": 31875, "text": "How to Retrieve Data from the Firebase Realtime Database in Android?" }, { "code": null, "e": 31977, "s": 31944, "text": "GridView in Android with Example" } ]
Apache Tapestry - Quick Guide
Apache Tapestry is an open source web framework written in Java. It is a component based web framework. Tapestry components are Java Classes. They are neither inherited from a framework specific base class nor implementation of an interface and they are just plain POJOs (Plain old Java Objects). The important feature of the Java used by tapestry is Annotation. Tapestry web pages are constructed by using one or more components, each having a XML based template and component class decorated with a lot of Tapestry's Annotations. Tapestry can create anything ranging from a tiny, single-page web application to a massive one consisting of hundreds of pages. Some of the benefits provided by tapestry are − Highly scalable web applications. Adaptive API. Fast and mature framework. Persistent state storage management. Build-in Inversion of Control. Tapestry has the following features − Live class reloading Clear and detailed exception reporting Static structure, dynamic behaviors. Extensive use of Plain Old Java Objects (POJOs) Code less, deliver more. Already Java has a lot of web frameworks like JSP, Struts, etc., Then, why do we need another framework? Most of the today's Java Web Frameworks are complex and have a steep learning curve. They are old fashioned and requires compile, test and deploy cycle for every update. On the other hand, Tapestry provides a modern approach to web application programming by providing live class reloading. While other frameworks are introducing lots of interfaces, abstract & base classes, Tapestry just introduces a small set of annotations and still provides the ability to write large application with rich AJAX support. Tapestry tries to use the available features of Java as much as possible. For example, all Tapestry pages are simply POJOs. It does not enforce any custom interfaces or base class to write the application. Instead, it uses Annotation (a light weight option to extend the functionality of a Java class) to provide features. It is based on battle-tested Java Servlet API and is implemented as a Servlet Filter. It provides a new dimension to the web application and the programming is quite Simple, Flexible, Understandable and Robust. Let us discuss the sequence of action taking place when a tapestry page is requested. Step 1 − The Java Servlet receives the page request. This Java Servlet is the configured in such a way that the incoming request will be forwarded to tapestry. The configuration is done in the web.xml as specified in the following program. Filter and Filter Mapping tag redirects all the request to Tapestry Filter. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>My Tapestry Application</display-name> <context-param> <param-name>tapestry.app-package</param-name> <param-value>org.example.myapp</param-value> </context-param> <filter> <filter-name>app</filter-name> <filter-class>org.apache.tapestry5.TapestryFilter</filter-class> </filter> <filter-mapping> <filter-name>app</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Step 2 − The Tapestry Filter calls the HttpServletRequestHandler Service by its Service() method. Step 3 − HttpServletRequestHandler stores the request and response in RequestGlobals. It also wraps the request and response as a Request and Response object and sends it to the RequestHandler. Step 4 − The RequestHandler is an abstraction on top of HttpServletRequest of Servlet API. Some of the salient feature of the tapestry is done in RequestHandler section. The feature of tapestry can be extended by writing a filter in RequestHandler. RequestHandler provides several build-in filters, which include − CheckForUpdates Filter − Responsible for live class reloading. This filter checks the java classes for changes and update the application as necessary. CheckForUpdates Filter − Responsible for live class reloading. This filter checks the java classes for changes and update the application as necessary. Localization Filter − Identify the location of the user and provide localization support for the application. Localization Filter − Identify the location of the user and provide localization support for the application. StaticFiles Filter − Identify the static request and aborts the process. Once the process is aborted, Java Servlet takes control and process the request. StaticFiles Filter − Identify the static request and aborts the process. Once the process is aborted, Java Servlet takes control and process the request. Error Filter − Catches the uncaught exception and presents the exception report page. Error Filter − Catches the uncaught exception and presents the exception report page. The RequestHandler also modifies and stores the request and response in the RequestQlobalsand invokes the MasterDispatcher service. Step 5 − The MasterDispatcher is responsible for rendering the page by calling several dispatchers is a specific order. The four-main dispatchers called by MasterDispatcher is as follows − RootPath Dispatcher − It recognizes the root path “/” of the request and render the same as Start page. RootPath Dispatcher − It recognizes the root path “/” of the request and render the same as Start page. Asset Dispatcher − It recognized the asset (Java assets) request by checking the url pattern /assets/ and sends the requested assets as byte streams. Asset Dispatcher − It recognized the asset (Java assets) request by checking the url pattern /assets/ and sends the requested assets as byte streams. PageRender Dispatcher − Bulk of the tapestry operations are done in PageRender Dispatcher and the next dispatcher Component Dispatcher. This dispatcher recognizes the particular page of that request and its activation context (extra information). It then renders that particular page and sends it to the client. For example, if the request url is /product/12123434, the dispatcher will check if any class with name product/12123434 is available. If found, it calls product/12123434 class, generate the response and send it to the client. If not, it checks for product class. If found, it calls product class with extra information 121234434, generates the response and sends it to the client. This extra information is called Activation Context. If no class is found, it simply forwards the request to Component Dispatcher. PageRender Dispatcher − Bulk of the tapestry operations are done in PageRender Dispatcher and the next dispatcher Component Dispatcher. This dispatcher recognizes the particular page of that request and its activation context (extra information). It then renders that particular page and sends it to the client. For example, if the request url is /product/12123434, the dispatcher will check if any class with name product/12123434 is available. If found, it calls product/12123434 class, generate the response and send it to the client. If not, it checks for product class. If found, it calls product class with extra information 121234434, generates the response and sends it to the client. This extra information is called Activation Context. If no class is found, it simply forwards the request to Component Dispatcher. Component Dispatcher − Component Dispatcher matches the URL of the page with the pattern – /<class_name>/<component_id>:<event_type>/<activation_context>. For example, /product/grid:sort/asc represents the product class, grid component, sortevent type and asc activation context. Here, event_type is optional and if none is provided, the default event type action will be triggered. Usually, the response of the component dispatcher is to send a redirect to the client. Mostly, the redirect will match PageRender Dispatcher in the next request and proper response will be send to the client. Component Dispatcher − Component Dispatcher matches the URL of the page with the pattern – /<class_name>/<component_id>:<event_type>/<activation_context>. For example, /product/grid:sort/asc represents the product class, grid component, sortevent type and asc activation context. Here, event_type is optional and if none is provided, the default event type action will be triggered. Usually, the response of the component dispatcher is to send a redirect to the client. Mostly, the redirect will match PageRender Dispatcher in the next request and proper response will be send to the client. In this chapter, we will discuss how to install Tapestry on our machine. Tapestry's only dependency is Core Java. Tapestry is developed independently without using any third party library / framework. Even the IoC library used by tapestry is developed from the scratch. Web application written in tapestry can be built and deployed from console itself. We can use Maven, Eclipse and Jetty to improve the development experience. Maven provides quick start application templates and options to host application in Jetty, Java's de-facto development server. Eclipse provides extensive project management features and integrates well with maven. An ideal tapestry application development needs the following − Java 1.6 or later Apache Maven Eclipse IDE Jetty Server Hopefully, you have installed Maven on your machine. To verify the Maven installation, type the command given below − mvn --version You could see the response as shown below − Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-1110T22:11:47+05:30) Maven home: /Users/workspace/maven/apache-maven-3.3.9 Java version: 1.8.0_92, vendor: Oracle Corporation Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home/jre Default locale: en_US, platform encoding: UTF-8 OS name: "mac os x", version: "10.11.4", arch: "x86_64", family: "mac" If Maven is not installed, then download and install the latest version of maven by visiting the Maven website. The latest version of tapestry is 5.4 and can be downloaded from the Tapestry website. It is enough to download the binary package. If we use the Maven Quick Start Template, then it is not necessary to download Tapestry separately. Maven automatically downloads the necessary Tapestry Jars and configures the application. We will discuss how to create a basic Tapestry Application using Maven in the next chapter. After Tapestry installation, let us create a new initial project using Maven as shown below − $ mvn archetype:generate -DarchetypeCatalog=http://tapestry.apache.org You could see the response as shown below − [INFO] Scanning for projects... [INFO] [INFO] --------------------------------------------------------------------------------- [INFO] Building Maven Stub Project (No POM) 1 [INFO] --------------------------------------------------------------------------------- [INFO] [INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > generatesources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) < generatesources @ standalone-pom <<< [INFO] [INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom --- [INFO] Generating project in Interactive mode [INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0) After Maven building all the operations, choose archetype to create Tapestry 5 QuickStart project as follows − Choose archetype − https://tapestry.apache.org → org.apache.tapestry:quickstart (Tapestry 5 Quickstart Project) https://tapestry.apache.org → org.apache.tapestry:quickstart (Tapestry 5 Quickstart Project) https://tapestry.apache.org → org.apache.tapestry:tapestry-archetype (Tapestry 4.1.6 Archetype) https://tapestry.apache.org → org.apache.tapestry:tapestry-archetype (Tapestry 4.1.6 Archetype) Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 1 Now you will get a response like what is shown below − Choose org.apache.tapestry:quickstart version: 1: 5.0.19 2: 5.1.0.5 3: 5.2.6 4: 5.3.7 5: 5.4.1 Extract the QuickStart version number as follows − Choose a number: 5: 5 Here, the QuickStart project takes the version for the option 5, “5.4.1”. Now, Tapestry archetype asks the following information one by one as follows − 5.1 groupId − Define value for property 'groupId': : com.example 5.1 groupId − Define value for property 'groupId': : com.example 5.2 artifactId − Define value for property 'artifactId': : Myapp 5.2 artifactId − Define value for property 'artifactId': : Myapp 5.3 version − Define value for property 'version': 1.0-SNAPSHOT: : 5.3 version − Define value for property 'version': 1.0-SNAPSHOT: : 5.4 package name − Define value for property 'package': com.example: : com.example.Myapp 5.4 package name − Define value for property 'package': com.example: : com.example.Myapp Now your screen asks confirmation from you − Confirm properties configuration − groupId − com.example groupId − com.example artifactId − Myapp artifactId − Myapp version − 1.0-SNAPSHOT version − 1.0-SNAPSHOT package − com.example.Myapp package − com.example.Myapp Verify all the properties and confirm the changes using the option shown below − Y: : Y You would see the screen like the one shown below. [INFO] --------------------------------------------------------------------------------- [INFO] Using following parameters for creating project from Archetype: quickstart:5.4.1 [INFO] --------------------------------------------------------------------------------- [INFO] Parameter: groupId, Value: com.example [INFO] Parameter: artifactId, Value: Myapp [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Parameter: package, Value: com.example.Myapp [INFO] Parameter: packageInPathFormat, Value: com/example/Myapp [INFO] Parameter: package, Value: com.example.Myapp [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] Parameter: groupId, Value: com.example [INFO] Parameter: artifactId, Value: Myapp [WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/test/java [WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/main/webapp [WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/main/resources/com/ example/Myapp [WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/test/resource [WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/test/conf [WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/site [INFO] project created from Archetype in dir: /Users/workspace/tapestry/Myapp [INFO] --------------------------------------------------------------------------------- [INFO] BUILD SUCCESS [INFO] --------------------------------------------------------------------------------- [INFO] Total time: 11:28 min [INFO] Finished at: 2016-09-14T00:47:23+05:30 [INFO] Final Memory: 14M/142M [INFO] --------------------------------------------------------------------------------- Here, you have successfully built the Tapestry Quick Start project. Move to the location of the newly created Myapp directory with the following command and start coding. cd Myapp To run the skeleton project, use the following command. mvn jetty:run -Dtapestry.execution-mode=development You get a screen like this, [INFO] Scanning for projects... [INFO] [INFO] --------------------------------------------------------------------------------- [INFO] Building Myapp Tapestry 5 Application 1.0-SNAPSHOT [INFO] --------------------------------------------------------------------------------- ........ ........ ........ Application 'app' (version 1.0-SNAPSHOT-DEV) startup time: 346 ms to build IoC Registry, 1,246 ms overall. ______ __ ____ /_ __/__ ____ ___ ___ / /_______ __ / __/ / / / _ `/ _ \/ -_|_-</ __/ __/ // / /__ \ /_/ \_,_/ .__/\__/___/\__/_/ \_, / /____/ /_/ /___/ 5.4.1 (development mode) [INFO] Started SelectChannelConnector@0.0.0.0:8080 [INFO] Started Jetty Server As of now, we have created a basic Quick Start project in Tapestry. To view the running application in the web browser, just type the following URL in the address bar and press enter − https://localhost:8080/myapp Here, myapp is the name of the application and the default port of the application in development mode is 8080. In the previous chapter, we discussed about how to create a Tapestry Quick Start application in CLI. This chapter explains about creating a skeleton application in Eclipse IDE. Let us use a Maven archetype to create skeleton application. To configure a new application, you can follow the steps given below. Open your Eclipse and choose File → New → Project... → option as shown in the following screenshot. Now, choose Maven → Maven project option. Note − If Maven is not configured then configure and create a project. After selecting the Maven project, click Next and again click the Next button. After that, you will get a screen where you should choose the configure option. Once it is configured, you will get the following screen. After the first step is done, you should click on Add Remote Catalog. Then add the following changes as shown in the following screenshot. Now, Apache Tapestry Catalog is added. Then, choose filter option org.apache.tapestry quickstart 5.4.1 as shown below. Then click Next and the following screen will appear. Add the following changes to the Tapestry Catalog configuration. Then click Finish button, now we have created the first skeleton application. The first time you use Maven, project creation may take a while as Maven downloads many JAR dependencies for Maven, Jetty and Tapestry. After Maven finishes, you'll see a new directory, MyFirstApplication in your Package Explorer view. You can use Maven to run Jetty directly. Right-click on the MyFirstApplication project in your Package Explorer view and select Run As → Maven Build... you will the screen shown below. In the configuration dialog box, enter goals option as “jetty:run” then click Run button. Once Jetty is initialized, you'll see the following screen in your console. Type the following URL to run the application in a web browser – https://loclhost:8080/MyFirstApplication To stop the Jetty server, click the red square icon in your console as shown below. Here is the layout of the source code created by Maven Quickstart CLI. Also, this is the suggested layout of a standard Tapestry Application. ├── build.gradle ├── gradle │ └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── pom.xml ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ └── MyFirstApplication │ │ │ ├── components │ │ │ ├── data │ │ │ ├── entities │ │ │ ├── pages │ │ │ └── services │ │ ├── resources │ │ │ ├── com │ │ │ │ └── example │ │ │ │ └── MyFirstApplication │ │ │ │ ├── components │ │ │ │ ├── logback.xml │ │ │ │ └── pages │ │ │ │ └── Index.properties │ │ │ ├── hibernate.cfg.xml │ │ │ └── log4j.properties │ │ └── webapp │ │ ├── favicon.ico │ │ ├── images │ │ │ └── tapestry.png │ │ ├── mybootstrap │ │ │ ├── css │ │ │ │ ├── bootstrap.css │ │ │ │ └── bootstrap-theme.css │ │ │ ├── fonts │ ├── glyphicons-halflings-regular.eot │ │ │ │ ├── glyphicons-halflings-regular.svg │ │ │ │ ├── glyphicons-halflings-regular.ttf │ │ │ │ ├── glyphicons-halflings-regular.woff │ │ │ │ └── glyphicons-halflings-regular.woff2 │ │ │ └── js │ │ └── WEB-INF │ │ ├── app.properties │ │ └── web.xml │ ├── site │ │ ├── apt │ │ │ └── index.apt │ │ └── site.xml │ └── test │ ├── conf │ │ ├── testng.xml │ │ └── webdefault.xml │ ├── java │ │ └── PLACEHOLDER │ └── resources │ └── PLACEHOLDER └── target ├── classes │ ├── com │ │ └── example │ │ └── MyFirstApplication │ │ ├── components │ │ ├── data │ │ ├── entities │ │ ├── logback.xml │ │ ├── pages │ │ │ └── Index.properties │ │ └── services │ ├── hibernate.cfg.xml │ └── log4j.properties ├── m2e-wtp │ └── web-resources │ └── META-INF │ ├── MANIFEST.MF │ └── maven │ └── com.example │ └──MyFirstApplication │ ├── pom.properties │ └── pom.xml ├── test-classes │ └── PLACEHOLDER └── work ├── jsp ├── sampleapp.properties └── sampleapp.script The default layout is arranged like the WAR Internal File Format. Using WAR format helps to run the application without packaging and deploying. This layout is just a suggestion, but the application can be arranged in any format, if it is packaged into a proper WAR format while deploying. The source code can be divided into the following four main sections. Java Code − All java source codes are placed under /src/main/java folder. Tapestry page classes are placed under the “Pages” folder and Tapestry component classes are placed under components folder. Tapestry service classes are placed under services folder. Java Code − All java source codes are placed under /src/main/java folder. Tapestry page classes are placed under the “Pages” folder and Tapestry component classes are placed under components folder. Tapestry service classes are placed under services folder. ClassPath Resources − In Tapestry, most of the classes have associated resources (XML Template, JavaScript files, etc.). These resources are placed under the /src/main/resources folder. Tapestry Page Classes have its associated resources under the “Pages” folder and Tapestry components classes have its associated resources under the Components folder. These resources are packaged into the WEB-INF/classes folder of the WAR. ClassPath Resources − In Tapestry, most of the classes have associated resources (XML Template, JavaScript files, etc.). These resources are placed under the /src/main/resources folder. Tapestry Page Classes have its associated resources under the “Pages” folder and Tapestry components classes have its associated resources under the Components folder. These resources are packaged into the WEB-INF/classes folder of the WAR. Context Resources − They are static resources of a web application like Images, Style Sheet and JavaScript Library / Modules. They are usually placed under the /src/main/webapp folder and they are called Context Resources. Also, the web application description file (of Java Servlet), web.xml is placed under the WEB-INF folder of context resources. Context Resources − They are static resources of a web application like Images, Style Sheet and JavaScript Library / Modules. They are usually placed under the /src/main/webapp folder and they are called Context Resources. Also, the web application description file (of Java Servlet), web.xml is placed under the WEB-INF folder of context resources. Testing Code − These are optional files used to test the application and placed under the src/test/java and src/test/Resources Folders. They are not packaged into WAR. Testing Code − These are optional files used to test the application and placed under the src/test/java and src/test/Resources Folders. They are not packaged into WAR. Apache Tapestry follows Convention over Configuration in every aspect of programming. Every feature of the framework does have a sensible default convention. For example, as we learned in the Project Layout chapter, all pages need to be placed in the /src/main/java/«package_path»/pages/ folder to be considered as Tapestry Pages. In another sense, there is no need configure a particular Java Class as Tapestry Pages. It is enough to place the class in a pre-defined location. In some cases, it is odd to follow the default convention of Tapestry. For example, Tapestry component can have a method setupRender which will be fired at the start the rendering phase. A developer may want to use their own opiniated name, say initializeValue. In this situation, Tapestry provides Annotation to override the conventions as shown in the following code block. void setupRender() { // initialize component } @SetupRender void initializeValue() { // initialize component } Both ways of programming are valid in Tapestry. In short, Tapestry's default configuration is quite minimal. Only the Apache Tapestry Filter (Java Servlet Filter) needs to be configured in the “Web.xml” for the proper working of the application. Tapestry provides one another way to configure application and it is called as the AppModule.java. Annotation is a very important feature exploited by Tapestry to simplify the Web Application Development. Tapestry provides a lot of custom Annotations. It has Annotation for Classes, Methods and Member Fields. As discussed in the previous section, Annotation may also be used to override default convention of a feature. Tapestry annotations are grouped into four main categories and they are as follows. Used in Pages, Components and Mixins Classes. Some of the useful annotations are − @Property − It is applicable to fields. Used to convert a field into a Tapestry Property. @Property − It is applicable to fields. Used to convert a field into a Tapestry Property. @Parameter − It is applicable to fields. Used to specify a field as parameter of a component. @Parameter − It is applicable to fields. Used to specify a field as parameter of a component. @Environmental − It is applicable to fields. Used to share a private field between different components. @Environmental − It is applicable to fields. Used to share a private field between different components. @import − It is applicable to classes and fields. Used to include Assets, CSS and JavaScript. @import − It is applicable to classes and fields. Used to include Assets, CSS and JavaScript. @Path − Used in conjunction with the @Inject annotation to inject an Asset based on a path. @Path − Used in conjunction with the @Inject annotation to inject an Asset based on a path. @Log − It is applicable to classes and fields. Used for debugging purposes. Can be used emit component's event information like start of the event, end of the event, etc. @Log − It is applicable to classes and fields. Used for debugging purposes. Can be used emit component's event information like start of the event, end of the event, etc. Used to inject objects into IoC Container. Some of the useful annotations are − @Inject − It is applicable to fields. Used to mark parameters that should be injected into the IoC container. It marks fields that should be injected into components. @Inject − It is applicable to fields. Used to mark parameters that should be injected into the IoC container. It marks fields that should be injected into components. @Value − It is applicable to fields. Used along with @inject annotation to inject a literal value instead of a service (which is default behavior of @Inject annotation). @Value − It is applicable to fields. Used along with @inject annotation to inject a literal value instead of a service (which is default behavior of @Inject annotation). It is used to specify component specific information in a class (usually models or data holding classes) for high level components such as Grid (used to create advanced tabular data such as report, gallery, etc.,) Grid (used to create advanced tabular data such as report, gallery, etc.,) BeanEditForm (Used to create advanced forms) BeanEditForm (Used to create advanced forms) Hibernate (Used in advanced database access), etc. Hibernate (Used in advanced database access), etc. These Annotations are aggregated and packaged into a separate jar without any tapestry dependency. Some of the annotations are − @DataType − It is used to specify the data type of the field. Tapestry component may use this information to create design or markup in the presentation layer. @DataType − It is used to specify the data type of the field. Tapestry component may use this information to create design or markup in the presentation layer. @Validate − It is used to specify the validation rule for a field. @Validate − It is used to specify the validation rule for a field. These separations enable the Tapestry Application to use a Multi-Tier Design. Tapestry Application is simply a collection of Tapestry Pages. They work together to form a well-defined Web Application. Each Page will have a corresponding XML Template and Zero, one or more Components. The Page and Component are same except that the Page is a root component and usually created by an application developer. Components are children of the root Pagecomponent. Tapestry have lots of built-in components and has the option to create a custom component. As discussed earlier, Pages are building blocks of a Tapestry Application. Pages are plain POJOs, placed under – /src/main/java/«package_path»/pages/ folder. Every Page will have a corresponding XML Template and its default location is – /src/main/resources/«package_name»/pages/. You can see here that the path structure is similar for Page and Template except that the template is in the Resource Folder. For example, a user registration page in a Tapestry application with package name – com.example.MyFirstApplication will have the following Page and Template files − Java Class − /src/main/java/com/example/MyFirstApplication/pages/index.java Java Class − /src/main/java/com/example/MyFirstApplication/pages/index.java XML Template − /src/main/resources/com/example/MyFirstApplication/pages/index.tml XML Template − /src/main/resources/com/example/MyFirstApplication/pages/index.tml Let us create a simple Hello World page. First, we need to create a Java Class at – /src/main/java/com/example/MyFirstApplication/pages/HelloWorld.java”. package com.example.MyFirstApplication.pages; public class HelloWorld { } Then, create an XML Template at – “/src/main/resources/com/example/MyFirstApplication/pages/helloworld.html”. <html xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <head> <title>Hello World Page</title> </head> <body> <h1>Hello World</h1> </body> </html> Now, this page can be accessed at https://localhost:8080/myapp/helloworld. This is a simple tapestry page. Tapestry offers lot more features to develop dynamic web pages, which we will discuss in the following chapters. Let us consider the Tapestry XML Template in this section. XML Template is a well-formed XML document. The presentation (User Interface) layer of a Page is XML Template. An XML Template have normal HTML markup in addition to the items given below − Tapestry Namespace Expansions Elements Components Let us now discuss them in detail. Tapestry Namespaces are nothing but XML Namespaces. Namespaces should be defined in the root element of the template. It is used to include Tapestry Components and component related information in the Template. The most commonly used namespaces are as follows − xmlns:t = “https://tapestry.apache.org/schema/tapestry_5_4.xsd” — It is used to identify Tapestry's Elements, Components and Attributes. xmlns:t = “https://tapestry.apache.org/schema/tapestry_5_4.xsd” — It is used to identify Tapestry's Elements, Components and Attributes. xmlns:p = “tapestry:parameter” — It is used to pass arbitrary chunks of code to components. xmlns:p = “tapestry:parameter” — It is used to pass arbitrary chunks of code to components. An example of Tapestry Namespace is as follows − <html xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_3.xsd" xmlns:p = "tapestry:parameter"> <head> <title>Hello World Page</title> </head> <body> <h1>Hello World</h1> <t:eventlink page = "Index">refresh page</t:eventlink> </body> </html> Expansion is simple and efficient method to dynamically change the XML Template during rendering phase of the Page. Expansion uses ${<name>} syntax. There are many options to express the expansion in the XML Template. Let us see some of the most commonly used options − It maps the property defined in the corresponding Page class. It follows the Java Bean Specification for property definition in a Java class. It goes one step further by ignoring the cases for property name. Let us change the “Hello World” example using property expansion. The following code block is the modified Page class. package com.example.MyFirstApplication.pages; public class HelloWorld { // Java Bean Property public String getName { return "World!"; } } Then, change the corresponding XML Template as shown below. <html xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <head> <title>Hello World Page</title> </head> <body> <!-- expansion --> <h1>Hello ${name}</h1> </body> </html> Here, we have defined name as Java Bean Property in the Page class and dynamically processed it in XML Template using expansion ${name}. Each Page class may or may not have an associated Property file – «page_name».properties in the resources folder. The property files are plain text files having a single key / value pair (message) per line. Let us create a property file for HelloWorld Page at – “/src/main/resources/com/example/MyFirstApplication/pages/helloworld.properties” and add a “Greeting” message. Greeting = Hello The Greeting message can be used in the XML Template as ${message:greeting} <html xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <head> <title>Hello World Page</title> </head> <body> <!-- expansion --> <h1>${message:greeting} ${name}</h1> </body> </html> Tapestry has a small set of elements to be used in XML Templates. Elements are predefined tags defined under the Tapestry namespace − https://tapestry.apache.org/schema/tapestry_5_4.xsd Each element is created for a specific purpose. The available tapestry elements are as follows − When two components are nested, the parent component's template may have to wrap the child component's template. The <t:body> element is useful in this situation. One of the uses of <t:body> is in the Template Layout. In general, the User Interface of a web application will have a Common Header, Footer, Menu, etc. These common items are defined in an XML Template and it is called Template Layout or Layout Component. In Tapestry, it needs to be created by an application developer. A Layout Component is just another component and is placed under the components folder, which has the following path – src/main/«java|resources»/«package_name»/components. Let us create a simple layout component called MyCustomLayout. The code for MyCustomLayout is as follows − <!DOCTYPE html> <html xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <head> <meta charset = "UTF-8" /> <title>${title}</title> </head> <body> <div>Sample Web Application</div> <h1>${title}</h1> <t:body/> <div>(C) 2016 TutorialsPoint.</div> </body> </html> package com.example.MyFirstApplication.components; import org.apache.tapestry5.*; import org.apache.tapestry5.annotations.*; import org.apache.tapestry5.BindingConstants; public class MyCustomLayout { @Property @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL) private String title; } In the MyCustomLayout component class, we declared a title field and by using annotation, we have made it mandatory. Now, change HelloWorld.html template to use our custom layout as shown in the code block below. <html> t:type = "mycustomlayout" title = "Hello World Test page" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <h1>${message:greeting} ${name}</h1> </html> We can see here that the XML Template does not have head and body tags. Tapestry will collect these details from the layout component and the <t:body> of the layout component will be replaced by the HelloWorld Template. Once everything is done, Tapestry will emit similar markup as specified below − <!DOCTYPE html> <html> <head> <meta charset = "UTF-8" /> <title>Hello World Test Page</title> </head> <body> <div>Sample Web Application</div> <h1>Hello World Test Page</h1> <h1>Hello World!</h1> <div>(C) 2016 TutorialsPoint.</div> </body> </html> Layouts can be nested. For example, we may extend our custom layout by including administration functionality and use it for admin section as specified below. <html t:type = "MyCommonLayout" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <div><!-- Admin related items --><div> <t:body/> </html> The <t:container> is a top-level element and includes a tapestry namespace. This is used to specify the dynamic section of a component. For example, a grid component may need a template to identify how to render its rows - tr (and column td) within a HTML table. <t:container xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <td>${name}</td> <td>${age}</td> </t:container> The <t:block> is a placeholder for a dynamic section in the template. Generally, block element does not render. Only, components defined in the template uses block element. Components will inject data dynamically into the block element and render it. One of the popular use case is AJAX. The block element provides the exact position and markup for the dynamic data to be rendered. Every block element should have a corresponding Java Property. Only then it can be dynamically rendered. The id of the block element should follow Java variable identifier rules. The partial sample is provided below. @Inject private Block block; <html t:type = "mycustomlayout" title = "block example" xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h1>${title}</h1> <!-- ... ... --> <t:block t:id = "block"> <h2>Highly dynamic section</h2> I'v been updated through AJAX call The current time is: <strong>${currentTime}</strong> </t:block> <!-- ... ... --> </html> The <t:content> element is used to specify the actual content of the template. In general, all the markup is considered part of the template. If <t:content> is specified, only the markup inside it will be considered. This feature is used by designers to design a page without a layout component. The <t:remove> is just the opposite of content element. The markup inside the remove element is not considered part of the template. It can be used for server only comments and for designing purposes. Assets are static resource files such as style sheets, images and JavaScript files. Generally, assets are placed in the web application root directory /src/main/webapp. <head> <link href = "/css/site.css" rel = "stylesheet" type = "text/css"/> Tapestry also treats files stored in the Java Classpath as Assets. Tapestry provides advanced options to include Assets into the template through expansion option. Context − Option to get assets available in web context. Context − Option to get assets available in web context. <img src = "${context:image/tapestry_banner.gif}" alt = "Banner"/> asset − Components usually store its own assets inside the jar file along with Java classes. Starting from Tapestry 5.4, the standard path to store assets in classpath is META-INF/assets. For libraries, the standard path to store assets is META-INF/assets/«library_name»/. asset: can also call context: expansion to get assets from the web context. <img src = "${asset:context:image/tapestry_banner.gif}" alt = "Banner"/> Assets can be injected into the Tapestry Page or Component using Inject and Path annotation. The parameter for the Path annotation is relative path of the assets. @Inject @Path("images/edit.png") private Asset icon; The Path parameter can also contain Tapestry symbols defined in the AppModule.java section. For example, we can define a symbol, skin.root with value context:skins/basic and use it as shown below − @Inject @Path("${skin.root}/style.css") private Asset style; Including resources through tapestry provides extra functionality. One such functionality is “Localization”. Tapestry will check the current locale and include the proper resources. For example, if the current locale is set as de, then edit_de.png will be included instead of edit.png. Tapestry has built-in style sheet support. Tapestry will inject tapestry.css as a part of the core Javascript stack. From Tapestry 5.4, tapestry includes bootstrap css framework as well. We can include our own style sheet using normal link tag. In this case, the style sheets should be in the web root directory – /src/main/webapp/. <head> <link href = "/css/site.css" rel = "stylesheet" type = "text/css"/> Tapestry provides advanced options to include style sheets into the template through expansion option as discussed earlier. <head> <link href = "${context:css/site.css}" rel = "stylesheet" type = "text/css"/> Tapestry also provides Import annotation to include style sheet directly into the Java classes. @Import(stylesheet="context:css/site.css") public class MyCommonLayout { } Tapestry provides a lot of options to manage style sheet through AppModule.java. Some of the important options are − The tapestry default style sheet may be removed. The tapestry default style sheet may be removed. @Contribute(MarkupRenderer.class) public static void deactiveDefaultCSS(OrderedConfiguration<MarkupRendererFilter> configuration) { configuration.override("InjectDefaultStyleheet", null); } Bootstrap can also be disabled by overriding its path. Bootstrap can also be disabled by overriding its path. configuration.add(SymbolConstants.BOOTSTRAP_ROOT, "classpath:/METAINF/assets"); Enable dynamic minimizing of the assets (CSS and JavaScript). We need to include tapestry-webresources dependency (in pom.xml) as well. Enable dynamic minimizing of the assets (CSS and JavaScript). We need to include tapestry-webresources dependency (in pom.xml) as well. @Contribute(SymbolProvider.class) @ApplicationDefaults public static void contributeApplicationDefaults( MappedConfiguration<String, String> configuration) { configuration.add(SymbolConstants.MINIFICATION_ENABLED, "true"); } <dependency> <groupId>org.apache.tapestry</groupId> <artifactId>tapestry-webresources</artifactId> <version>5.4</version> </dependency> The current generation of web application heavily depends on JavaScript to provide rich client side experience. Tapestry acknowledges it and provide first class support for JavaScript. JavaScript support is deeply ingrained into the tapestry and available at every phase of the programming. Earlier, Tapestry used to support only Prototype and Scriptaculous. But, from version 5.4, tapestry completely rewritten the JavaScript layer to make it as generic as possible and provide first class support for JQuery, the de-facto library for JavaScript. Also, tapestry encourages Modules based JavaScript programming and supports RequireJS, a popular client side implementation of AMD (Asynchronous Module Definition - JavaScript specification to support modules and its dependency in an asynchronous manner). JavaScript files are assets of the Tapestry Application. In accordance with asset rules, JavaScript files are placed either under web context, /sr/main/webapp/ or placed inside the jar under META-INF/assets/ location. The simplest way to link JavaScript files in the XML Template is by directly using the script tag, which is − <script language = "javascript" src = "relative/path/to/js"></script>. But, tapestry does not recommend these approaches. Tapestry provides several options to link JavaScript files right in the Page / Component itself. Some of these are given below. @import annotation − @import annotation provides option to link multiple JavaScript library using context expression. It can be applied to both Page class and its method. If applied to a Page class, it applies to all its methods. If applied to a Page's Method, it only applies to that method and then Tapestry links the JavaScript library only when the method is invoked. @import annotation − @import annotation provides option to link multiple JavaScript library using context expression. It can be applied to both Page class and its method. If applied to a Page class, it applies to all its methods. If applied to a Page's Method, it only applies to that method and then Tapestry links the JavaScript library only when the method is invoked. @Import(library = {"context:js/jquery.js","context:js/myeffects.js"}) public class MyComponent { // ... } JavaScriptSupport interface − The JavaScriptSupport is an interface defined by tapestry and it has a method, importJavaScriptLibrary to import JavaScript files. JavScriptSupport object can be easily created by simply declaring and annotating with @Environmental annotation. JavaScriptSupport interface − The JavaScriptSupport is an interface defined by tapestry and it has a method, importJavaScriptLibrary to import JavaScript files. JavScriptSupport object can be easily created by simply declaring and annotating with @Environmental annotation. @Inject @Path("context:/js/myeffects.js") private Asset myEffects; @Environmental private JavaScriptSupport javaScriptSupport; void setupRender() { javaScriptSupport.importJavaScriptLibrary(myEffects); } JavaScripSupport can only be injected into a component using the @Environmental annotation. For services, we need to use an @Inject annotation or add it as an argument in the service constructor method. JavaScripSupport can only be injected into a component using the @Environmental annotation. For services, we need to use an @Inject annotation or add it as an argument in the service constructor method. @Inject private JavaScriptSupport javaScriptSupport; public MyServiceImpl(JavaScriptSupport support) { // ... } addScript method − This is similar to the JavaScriptSupport interface except that it uses the addScript method and the code is directly added to the output at the bottom of the page. addScript method − This is similar to the JavaScriptSupport interface except that it uses the addScript method and the code is directly added to the output at the bottom of the page. void afterRender() { javaScriptSupport.addScript( "$('%s').observe('click', hideMe());", container.getClientId()); } Tapestry allows a group of JavaScript files and related style sheets to be combined and used as one single entity. Currently, Tapestry includes Prototype based and JQuery based stacks. A developer can develop their own stacks by implementing the JavaScriptStack interface and register it in the AppModule.java. Once registered, the stack can be imported using the @import annotation. @Contribute(JavaScriptStackSource.class) public static void addMyStack( MappedConfiguration<String, JavaScriptStack> configuration) { configuration.addInstance("MyStack", myStack.class); } @Import(stack = "MyStack") public class myPage { } As discussed earlier, Components and Pages are the same except that the Page is the root component and includes one or more child components. Components always resides inside a page and do almost all the dynamic functionality of the page. Tapestry components renders a simple HTML links to complex grid functionality with interactive AJAX. A Component can include another component as well. Tapestry components consists of following items − Component Class − The main Java class of the component. Component Class − The main Java class of the component. XML Template − XML template is similar to the Page template. The component class renders the template as the final output. Some components may not have templates. In this case, the output will be generated by the component class itself using the MarkupWriter class. XML Template − XML template is similar to the Page template. The component class renders the template as the final output. Some components may not have templates. In this case, the output will be generated by the component class itself using the MarkupWriter class. Body − The component specified inside the page template may have custom markup and it is called “Component body”. If the component template has <body /> element, then the <body /> element will be replaced by the body of the component. This is similar to the layout discussed earlier in the XML template section. Body − The component specified inside the page template may have custom markup and it is called “Component body”. If the component template has <body /> element, then the <body /> element will be replaced by the body of the component. This is similar to the layout discussed earlier in the XML template section. Rendering − Rendering is a process which transforms XML template and body of the component into actual output of the component. Rendering − Rendering is a process which transforms XML template and body of the component into actual output of the component. Parameters − Used to create communication between component & pages and thereby passing data between them. Parameters − Used to create communication between component & pages and thereby passing data between them. Events − Delegates functionality from components to its container / parent (pages or another component). It is extensively used in page navigation purpose. Events − Delegates functionality from components to its container / parent (pages or another component). It is extensively used in page navigation purpose. The rendering of a component is done in a series of pre-defined phases. Each phase in the component system should have a corresponding method defined by convention or annotation in the component class. // Using annotaion @SetupRender void initializeValues() { // initialize values } // using convention boolean afterRender() { // do logic return true; } The phases, its method name and its annotations are listed below. Each phase has a specific purpose and they are as follows − SetupRender kick-starts the rendering process. It usually sets up the parameters of the component. BeginRender starts rendering the component. It usually renders the begin / start tag of the component. BeforeRenderTemplate is used to decorate the XML template, adding special markup around the template. It also provides an option to skip the template rendering. BeforeRenderTemplate provides an option to skip the rendering of the component's body element. AfterRenderBody will be called after the component's body is rendered. AfterRenderTemplate will be called after the component's template is rendered. AfterRender is the counterpart of the BeginRender and usually renders the close tag. CleanupRender is the counterpart of the SetupRender. It releases / disposes all the objects created during rendering process. The flow of the rendering phases is not forward only. It goes to and fro between phases depending on the return value of a phase. For example, if the SetupRender method returns false, then rendering jumps to the CleanupRender phase and vice versa. To find a clear understanding of the flow between different phases, check the flow in the diagram given below. Let us create a simple component, Hello which will have the output message as “Hello, Tapestry”. Following is the code of the Hello component and its template. package com.example.MyFirstApplication.components; public class Hello { } <html xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <div> <p>Hello, Tapestry (from component).</p> </div> </html> The Hello component can be called in a page template as − <html title = "Hello component test page" xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <t:hello /> </html> Similarly, the component may render the same output using MarkupWriter instead of the template as shown below. package com.example.MyFirstApplication.components; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.annotations.BeginRender; public class Hello { @BeginRender void renderMessage(MarkupWriter writer) { writer.write("<p>Hello, Tapestry (from component)</p>"); } } Let us change the component template and include the <body /> element as shown in the code block below. <html> xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <div> <t:body /> </div> </html> Now, the page template may include body in the component markup as shown below. <html title = "Hello component test page" xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <t:hello> <p>Hello, Tapestry (from page).</p> </t:hello> </html> The output will be as follows − <html> <div> <p>Hello, Tapestry (from page).</p> </div> </html> The primary purpose of these parameters is to create a connection between a field of the component and a property / resource of the page. Using parameters, component and its corresponding page communicate and transfer data between each other. This is called Two Way Data Binding. For example, a textbox component used to represent the age in a user management page gets its initial value (available in the database) through the parameter. Again, after the user's age is updated and submitted back, the component will send back the updated age through the same parameter. To create a new parameter in the component class, declare a field and specify a @Parameter annotation. This @Parameter has two optional arguments, which are − required − makes the parameter as mandatory. Tapestry raises exception if it is not provided. required − makes the parameter as mandatory. Tapestry raises exception if it is not provided. value − specifies the default value of the parameter. value − specifies the default value of the parameter. The parameter should be specified in the page template as attributes of the component tag. The value of the attributes should be specified using Binding Expression / Expansion, which we discussed in the earlier chapters. Some of the expansion which we learned earlier are − Property expansion (prop:«val») − Get the data from property of the page class. Property expansion (prop:«val») − Get the data from property of the page class. Message expansion (message:«val») − Get the data from key defined in index.properties file. Message expansion (message:«val») − Get the data from key defined in index.properties file. Context expansion (context:«val») − Get the data from web context folder /src/main/webapp. Context expansion (context:«val») − Get the data from web context folder /src/main/webapp. Asset expansion (asset:«val») − Get the data from resources embedded in jar file, /META-INF/assets. Asset expansion (asset:«val») − Get the data from resources embedded in jar file, /META-INF/assets. Symbol expansion (symbol:«val») − Get the data from symbols defined in AppModule.javafile. Symbol expansion (symbol:«val») − Get the data from symbols defined in AppModule.javafile. Tapestry has many more useful expansions, some of which are given below − Literal expansion (literal:«val») − A literal string. Literal expansion (literal:«val») − A literal string. Var expansion (var:«val») − Allow a render variable of the component to be read or updated. Var expansion (var:«val») − Allow a render variable of the component to be read or updated. Validate expansion (validate:«val») − A specialized string used to specify the validation rule of an object. For Example, validate:required, minLength = 5. Validate expansion (validate:«val») − A specialized string used to specify the validation rule of an object. For Example, validate:required, minLength = 5. Translate (translate:«val») − Used to specify the Translator class (converting client-side to server-side representation) in input validation. Translate (translate:«val») − Used to specify the Translator class (converting client-side to server-side representation) in input validation. Block (block:«val») − The id of the block element within the template. Block (block:«val») − The id of the block element within the template. Component (component:«val») − The id of the another component within the template. Component (component:«val») − The id of the another component within the template. All the above expansions are read-only except Property expansion and Var expansion. They are used by the component to exchange data with page. When using expansion as attribute values, ${...} should not be used. Instead just use the expansion without dollar and braces symbols. Let us create a new component, HelloWithParameter by modifying the Hello component to dynamically render the message by adding a name parameter in the component class and changing the component template and page template accordingly. Create a new component class HelloWithParameter.java. Create a new component class HelloWithParameter.java. Add a private field and name it with the @Parameter annotation. Use the required argument to make it mandatory. Add a private field and name it with the @Parameter annotation. Use the required argument to make it mandatory. @Parameter(required = true) private String name; Add a private field, result with @Propery annotation. The result property will be used in the component template. Component template does not have access to fields annotated with @Parameter and only able to access the fields annotated with @Property. The variable available in component templates are called Render Variables. Add a private field, result with @Propery annotation. The result property will be used in the component template. Component template does not have access to fields annotated with @Parameter and only able to access the fields annotated with @Property. The variable available in component templates are called Render Variables. @Property private String result; Add a RenderBody method and copy the value from the name parameter to result property. Add a RenderBody method and copy the value from the name parameter to result property. @BeginRender void initializeValues() { result = name; } Add a new component template HelloWithParamter.tml and use the result property to render the message. Add a new component template HelloWithParamter.tml and use the result property to render the message. <div> Hello, ${result} </div> Add a new property, Username in the test page (testhello.java). Add a new property, Username in the test page (testhello.java). public String getUsername() { return "User1"; } Use the newly created component in the page template and set the Username property in name parameter of HelloWithParameter component. Use the newly created component in the page template and set the Username property in name parameter of HelloWithParameter component. <t:helloWithParameter name = "username" /> The complete listing is as follows − package com.example.MyFirstApplication.components; import org.apache.tapestry5.annotations.*; public class HelloWithParameter { @Parameter(required = true) private String name; @Property private String result; @BeginRender void initializeValues() { result = name; } } <html xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <div> Hello, ${result} </div> </html> package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.*; public class TestHello { public String getUsername() { return "User1"; } } <html title = "Hello component test page" xmlns:t = "https://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <t:helloWithParameter name = "username" /> </html> The result will be as follows − <div> Hello, User1 </div> In the previous chapters, we analyzed how to create and use a simple parameter in a custom component. An advanced parameter may contain complete markup as well. In this case, the markup should be specified inside the component tag such as the sub-section in the page template. The built-in if component have markup for both success and failure condition. The markup for success is specified as the body of the component tag and the markup of failure is specified using an elseparameter. Let us see how to use the if component. The if component has two parameters − test − Simple property based parameter. test − Simple property based parameter. Else − Advanced parameter used to specify alternative markup, if the condition fails Else − Advanced parameter used to specify alternative markup, if the condition fails Tapestry will check the value of the test property using the following logic and return true or false. This is called Type Coercion, a way to convert an object of one type to another type with the same content. If the data type is String, “True” if non-blank and not the literal string “False” (case insensitive). If the data type is String, “True” if non-blank and not the literal string “False” (case insensitive). If the data type is Number, True if non-zero. If the data type is Number, True if non-zero. If the data type is Collection, True if non-empty. If the data type is Collection, True if non-empty. If the data type is Object, True (as long as it’s not null). If the data type is Object, True (as long as it’s not null). If the condition passes, the component renders its body; otherwise, it renders the body of the else parameter. The complete listing is as follows − package com.example.MyFirstApplication.pages; public class TestIf { public String getUser() { return "User1"; } } <html title = "If Test Page" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <body> <h1>Welcome!</h1> <t:if test = "user"> Welcome back, ${user} <p:else> Please <t:pagelink page = "login">Login</t:pagelink> </p:else> </t:if> </body> </html> Tapestry application is a collection of Pages interacting with each other. Till now, we have learned how to create individual pages without any communication between them. A Component event's primary purpose is to provide interaction between pages (within pages as well) using server-side events. Most of the component events originate from client-side events. For example, when a user clicks a link in a page, Tapestry will call the same page itself with target information instead of calling the target page and raises a server side event. Tapestry page will capture the event, process the target information and do a server side redirection to the target page. Tapestry follows a Post/Redirect/Get (RPG) design pattern for page navigation. In RPG, when a user does a post request by submitting a form, the server will process the posted data, but does not return the response directly. Instead, it will do a client-side redirection to another page, which will output the result. An RPG pattern is used to prevent duplicate form submissions through browser back button, browser refresh button, etc., Tapestry provides an RPG pattern by providing the following two types of request. Component Event Request − This type of request targets a particular component in a page and raises events within the component. This request only does a redirection and does not output the response. Component Event Request − This type of request targets a particular component in a page and raises events within the component. This request only does a redirection and does not output the response. Render Request − These types of requests target a page and stream the response back to the client. Render Request − These types of requests target a page and stream the response back to the client. To understand the component events and page navigation, we need to know the URL pattern of the tapestry request. The URL pattern for both types of request is as follows − Component Event Requests − Component Event Requests − /<<page_name_with_path>>.<<component_id|event_id>>/<<context_information>> Render Request − Render Request − /<<page_name_with_path>>/<<context_information>> Some of the examples of the URL patterns are − Index page can be requested by https://«domain»/«app»/index. Index page can be requested by https://«domain»/«app»/index. If the Index page is available under a sub-folder admin, then it can be requested by https://«domain»/«app»/admin/index. If the Index page is available under a sub-folder admin, then it can be requested by https://«domain»/«app»/admin/index. If the user clicks on the ActionLink component with id test in the index page, then the URL will be https://«domain»/«app»/index.test. If the user clicks on the ActionLink component with id test in the index page, then the URL will be https://«domain»/«app»/index.test. By default, Tapestry raises OnPassivate and OnActivate events for all requests. For Component event request type, tapestry raises additional one or more events depending on the component. The ActionLink component raises an Action event, while a Form component raises multiple events such as Validate, Success, etc., The events can be handled in the page class using the corresponding method handler. The method handler is created either through a method naming convention or through the @OnEvent annotation. The format of the method naming convention is On«EventName»From«ComponentId». An action event of the ActionLink component with id test can be handled by either one of the following methods − void OnActionFromTest() { } @OnEvent(component = "test", name = "action") void CustomFunctionName() { } If the method name does not have any particular component, then the method will be called for all component with matching events. void OnAction() { } OnPassivate is used to provide context information for an OnActivate event handler. In general, Tapestry provides the context information and it can be used as an argument in the OnActivateevent handler. For example, if the context information is 3 of type int, then the OnActivate event can be called as − void OnActivate(int id) { } In some scenario, the context information may not be available. In this situation, we can provide the context information to OnActivate event handler through OnPassivate event handler. The return type of the OnPassivate event handler should be used as argument of OnActivate event handler. int OnPassivate() { int id = 3; return id; } void OnActivate(int id) { } Tapestry issues page redirection based on the return values of the event handler. Event handler should return any one of the following values. Null Response − Returns null value. Tapestry will construct the current page URL and send to the client as redirect. Null Response − Returns null value. Tapestry will construct the current page URL and send to the client as redirect. public Object onAction() { return null; } String Response − Returns the string value. Tapestry will construct the URL of the page matching the value and send to the client as redirect. String Response − Returns the string value. Tapestry will construct the URL of the page matching the value and send to the client as redirect. public String onAction() { return "Index"; } Class Response − Returns a page class. Tapestry will construct the URL of the returned page class and send to the client as redirect. Class Response − Returns a page class. Tapestry will construct the URL of the returned page class and send to the client as redirect. public Object onAction() { return Index.class } Page Response − Returns a field annotated with @InjectPage. Tapestry will construct the URL of the injected page and send to the client as redirect. Page Response − Returns a field annotated with @InjectPage. Tapestry will construct the URL of the injected page and send to the client as redirect. @InjectPage private Index index; public Object onAction(){ return index; } HttpError − Returns the HTTPError object. Tapestry will issue a client side HTTP error. HttpError − Returns the HTTPError object. Tapestry will issue a client side HTTP error. public Object onAction(){ return new HttpError(302, "The Error message); } Link Response − Returns a link instance directly. Tapestry will construct the URL from Link object and send to the client as redirect. Link Response − Returns a link instance directly. Tapestry will construct the URL from Link object and send to the client as redirect. Stream Response − Returns the StreamResponse object. Tapestry will send the stream as response directly to the client browser. It is used to generate reports and images directly and send it to the client. Stream Response − Returns the StreamResponse object. Tapestry will send the stream as response directly to the client browser. It is used to generate reports and images directly and send it to the client. Url Response − Returns the java.net.URL object. Tapestry will get the corresponding URL from the object and send to the client as redirect. Url Response − Returns the java.net.URL object. Tapestry will get the corresponding URL from the object and send to the client as redirect. Object Response − Returns any values other than above specified values. Tapestry will raise an error. Object Response − Returns any values other than above specified values. Tapestry will raise an error. In general, event handler can get the context information using arguments. For example, if the context information is 3 of type int, then the event handler will be − Object onActionFromTest(int id) { } Tapestry properly handles the context information and provides it to methods through arguments. Sometimes, Tapestry may not be able to properly handle it due to complexity of the programming. At that time, we may get the complete context information and process ourselves. Object onActionFromEdit(EventContext context) { if (context.getCount() > 0) { this.selectedId = context.get(0); } else { alertManager.warn("Please select a document."); return null; } } This chapter explains about the built-in components that Tapestry has with suitable examples. Tapestry supports more than 65 built-in components. You can also create custom components. Let us cover some of the notable components in detail. The if component is used to render a block conditionally. The condition is checked by a test parameter. Create a page IfSample.java as shown below − package com.example.MyFirstApplication.pages; public class Ifsample { public String getUser() { return "user1"; } } Now, create a corresponding template file as follows − <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h3>If-else component example </h3> <t:if test = "user"> Hello ${user} <p:else> <h4> You are not a Tapestry user </h4> </p:else> </t:if> </html> Requesting the page will render the result as shown below. Result − http://localhost:8080/MyFirstApplication/ifsample The unless component is just the opposite of the if component that was discussed above. While, the delegate component does not do any rendering on its own. Instead, it normally delegates the markup to block element. Unless and if components can use delegate and block to conditionally swap the dynamic content. Create a page Unless.java as follows. package com.example.MyFirstApplication.pages; import org.apache.tapestry5.Block; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.PersistenceConstants; import org.apache.tapestry5.annotations.Persist; public class Unless { @Property @Persist(PersistenceConstants.FLASH) private String value; @Property private Boolean bool; @Inject Block t, f, n; public Block getCase() { if (bool == Boolean.TRUE ) { return t; } else { return f; } } } Now, create a corresponding template file as follows − <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h4> Delegate component </h4> <div class = "div1"> <t:delegate to = "case"/> </div> <h4> If-Unless component </h4> <div class = "div1"> <t:if test = "bool"> <t:delegate to = "block:t"/> </t:if> <t:unless test = "bool"> <t:delegate to = "block:notT"/> </t:unless> </div> <t:block id = "t"> bool == Boolean.TRUE. </t:block> <t:block id = "notT"> bool = Boolean.FALSE. </t:block> <t:block id = "f"> bool == Boolean.FALSE. </t:block> </html> Requesting the page will render the result as shown below. Result − http://localhost:8080/MyFirstApplication/unless The loop component is the basic component to loop over a collection items and render the body for every value / iteration. Create a Loop page as shown below − package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; public class Loop { @Property private int i; } Then, create the corresponding template Loop.tml <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <p>This is sample parameter rendering example...</p> <ol> <li t:type = "loop" source = "1..5" value = "var:i">${var:i}</li> </ol> </html> Loop component has the following two parameters − source − Collection source. 1...5 is a property expansion used to create an array with a specified range. source − Collection source. 1...5 is a property expansion used to create an array with a specified range. var − Render variable. Used to render the current value in the body of the template. var − Render variable. Used to render the current value in the body of the template. Requesting the page will render the result as shown below − A PageLink component is used to link a page from one page to another page. Create a PageLink test page as below − PageLink.java. package com.example.MyFirstApplication.pages; public class PageLink { } Then, create a corresponding template file as shown below − <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <body> <h3><u>Page Link</u> </h3> <div class = "page"> <t:pagelink page = "Index">Click here to navigate Index page</t:pagelink> <br/> </div> </body> </html> The PageLink component has a page parameter which should refer the target tapestry page. Result − http://localhost:8080/myFirstApplication/pagelink The EventLink component sends the event name and the corresponding parameter through the URL. Create an EventsLink page class as shown below. package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; public class EventsLink { @Property private int x; void onActivate(int count) { this.x = x; } int onPassivate() { return x; } void onAdd(int value) { x += value; } } Then, create a corresponding “EventsLink” template file as follows − <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h3> Event link example </h3> AddedCount = ${x}. <br/> <t:eventlink t:event = "add" t:context = "literal:1"> Click here to add count </t:eventlink><br/> </html> EventLink has the following two parameters − Event − The name of the event to be triggered in the EventLink component. By default, it points to the id of the component. Event − The name of the event to be triggered in the EventLink component. By default, it points to the id of the component. Context − It is an optional parameter. It defines the context for the link. Context − It is an optional parameter. It defines the context for the link. Result − http://localhost:8080/myFirstApplication/EventsLink After clicking the count value, the page will display the event name in the URL as shown in the following output screenshot. The ActionLink component is similar to the EventLink component, but it only sends the target component id. The default event name is action. Create a page “ActivationLinks.java” as shown below, package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; public class ActivationLinks { @Property private int x; void onActivate(int count) { this.x = x; } int onPassivate() { return x; } void onActionFromsub(int value) { x -= value; } } Now, create a corresponding template file as shown below − <html t:type = "Newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <div class = "div1"> Count = ${count}. <br/> <t:actionlink t:id = "sub" t:context = "literal:1"> Decrement </t:actionlink><br/> </div> </html> Here, the OnActionFromSub method will be called when clicking the ActionLink component. Result − http://localhost:8080/myFirstApplication/ActivationsLink An alert dialog box is mostly used to give a warning message to the users. For example, if the input field requires some mandatory text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message. Create a page “Alerts” as shown in the following program. package com.example.MyFirstApplication.pages; public class Alerts { public String getUser() { return "user1"; } } Then, create a corresponding template file as follows − <html t:type = "Newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h3>Alerts</h3> <div class = "alert alert-info"> <h5> Welcome ${user} </h5> </div> </html> An Alert has three severity levels, which are − Info Warn Error The above template is created using an info alert. It is defined as alert-info. You can create other severities depending on the need. Requesting the page will produce the following result − http://localhost:8080/myFirstApplication/Alerts The Form Component is used to create a form in the tapestry page for user input. A form can contain text fields, date fields, checkbox fields, select options, submit button and more. This chapter explains about some of the notable form components in detail. A Checkbox Component is used to take a choice between two mutually exclusive options. Create a page using the Checkbox as shown below − package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; public class Checkbox { @Property private boolean check1; @Property private boolean check2; } Now, create a corresponding template Checkbox.tml as shown below − <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h3> checkbox component</h3> <t:form> <t:checkbox t:id = "check1"/> I have a bike <br/> <t:checkbox t:id = "check2"/> I have a car </t:form> </html> Here, the checkbox parameter id matches to the corresponding Boolean value. Result − After requesting the page,http://localhost:8080/myFirstApplication/checkbox it produces the following result. The TextField component allows the user to edit a single line of text. Create a page Text as shown below. package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.corelib.components.TextField;public class Text { @Property private String fname; @Property private String lname; } Then, create a corresponding template as shown below – Text.tml <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <p> Form application </p> <body> <h3> Text field created from Tapestry component </h3> <t:form> <table> <tr> <td> Firstname: </td> <td><t:textfield t:id = "fname" /> </td> <td>Lastname: </td> <td> <t:textfield t:id = "lname" /> </td> </tr> </table> </t:form> </body> </html> Here, the Text page includes a property named fname and lname. The component id's are accessed by the properties. Requesting the page will produce the following result − http://localhost:8080/myFirstApplication/Text The PasswordField is a specialized text field entry for password. Create a page Password as shown below − package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.corelib.components.PasswordField; public class Password { @Property private String pwd; } Now, create a corresponding template file is as shown below − <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <p> Form application </p> <h3> Password field created from Tapestry component </h3> <t:form> <table> <tr> <td> Password: </td> <td><t:passwordfield t:id = "pwd"/> </td> </tr> </table> </t:form> </html> Here, the PasswordField component has the parameter id, which points to the property pwd. Requesting the page will produce the following result − http://localhost:8080/myFirstApplication/Password The TextArea component is a multi-line input text control. Create a page TxtArea as shown below. package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.corelib.components.TextArea; public class TxtArea { @Property private String str; } Then, create a corresponding template file is as shown below. <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h3>TextArea component </h3> <t:form> <table> <tr> <td><t:textarea t:id = "str"/> </td> </tr> </table> </t:form> </html> Here, the TextArea component parameter id points to the property “str”. Requesting the page will produce the following result − http://localhost:8080/myFirstApplication/TxtArea** The Select component contains a drop-down list of choices. Create a page SelectOption as shown below. package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.corelib.components.Select; public class SelectOption { @Property private String color0; @Property private Color1 color1; public enum Color1 { YELLOW, RED, GREEN, BLUE, ORANGE } } Then, create a corresponding template is as follows − <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <p> Form application </p> <h3> select component </h3> <t:form> <table> <tr> <td> Select your color here: </td> <td> <select t:type = "select" t:id = "color1"></select></td> </tr> </table> </t:form> </html> Here, the Select component has two parameters − Type − Type of the property is an enum. Type − Type of the property is an enum. Id − Id points to the Tapestry property “color1”. Id − Id points to the Tapestry property “color1”. Requesting the page will produce the following result − http://localhost:8080/myFirstApplication/SelectOption The RadioGroup component provides a container group for Radio components. The Radio and RadioGroup components work together to update a property of an object. This component should wrap around other Radio components. Create a new page “Radiobutton.java” as shown below − package com.example.MyFirstApplication.pages; import org.apache.tapestry5.PersistenceConstants; import org.apache.tapestry5.annotations.Persist; import org.apache.tapestry5.annotations.Property; public class Radiobutton { @Property @Persist(PersistenceConstants.FLASH) private String value; } Then, create a corresponding template file is as shown below − <html t:type = "Newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h3>RadioGroup component </h3> <t:form> <t:radiogroup t:id = "value"> <t:radio t:id = "radioT" value = "literal:T" label = "Male" /> <t:label for = "radioT"/> <t:radio t:id = "radioF" value = "literal:F" label = "Female"/> <t:label for = "radioF"/> </t:radiogroup> </t:form> </html> Here, the RadioGroup component id is binding with property “value”. Requesting the page will produce the following result. http://localhost:8080/myFirstApplication/Radiobutton When a user clicks a submit button, the form is sent to the address specified in the action setting of the tag. Create a page SubmitComponent as shown below. package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.InjectPage; public class SubmitComponent { @InjectPage private Index page1; Object onSuccess() { return page1; } } Now, create a corresponding template file as shown below. <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <h3>Tapestry Submit component </h3> <body> <t:form> <t:submit t:id = "submit1" value = "Click to go Index"/> </t:form> </body> </html> Here, the Submit component submits the value to the Index page. Requesting the page will produce the following result − http://localhost:8080/myFirstApplication/SubmitComponent Form validation normally occurs at the server after the client has entered all the necessary data and then submitted the form. If the data entered by a client was incorrect or simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. Let us consider the following simple example to understand the process of validation. Create a page Validate as shown below. package com.example.MyFirstApplication.pages; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.PersistenceConstants; import org.apache.tapestry5.annotations.Persist; public class Validate { @Property @Persist(PersistenceConstants.FLASH) private String firstName; @Property @Persist(PersistenceConstants.FLASH) private String lastName; } Now, create a corresponding template file as shown below. <html t:type = "newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <t:form> <table> <tr> <td><t:label for = "firstName"/>:</td> <td><input t:type = "TextField" t:id = "firstName" t:validate = "required, maxlength = 7" size = "10"/></td> </tr> <tr> <td><t:label for = "lastName"/>:</td> <td><input t:type = "TextField" t:id = "lastName" t:validate = "required, maxLength = 5" size = "10"/></td> </tr> </table> <t:submit t:id = "sub" value =" Form validation"/> </t:form> </html> Form Validation has the following significant parameters − Max − defines the maximum value, for e.g. = «maximum value, 20». Max − defines the maximum value, for e.g. = «maximum value, 20». MaxDate − defines the maxDate, for e.g. = «maximum date, 06/09/2013». Similarly, you can assign MinDate as well. MaxDate − defines the maxDate, for e.g. = «maximum date, 06/09/2013». Similarly, you can assign MinDate as well. MaxLength − maxLength for e.g. = «maximum length, 80». MaxLength − maxLength for e.g. = «maximum length, 80». Min − minimum. Min − minimum. MinLength − minimum Length for e.g. = «minmum length, 2». MinLength − minimum Length for e.g. = «minmum length, 2». Email − Email validation which uses either standard email regexp ^\w[._\w]*\w@\w[-._\w]*\w\.\w2,6$ or none. Email − Email validation which uses either standard email regexp ^\w[._\w]*\w@\w[-._\w]*\w\.\w2,6$ or none. Requesting the page will produce the following result − http://localhost:8080/myFirstApplication/Validate AJAX stands for Asynchronous JavaScript and XML. It is a technique for creating better, faster and more interactive web applications with the help of XML, JSON, HTML, CSS, and JavaScript. AJAX allows you to send and receive data asynchronously without reloading the web page, so it is fast. A Zone Component is used to provide the content (markup) as well as the position of the content itself. The body of the Zone Component is used internally by Tapestry to generate the content. Once the dynamic content is generated, Tapestry will send it to the client, rerender the data in the correct place, trigger and animate the HTML to draw the attention of the user. This Zone component is used along with an EventLink component. An EventLink has option to tie it to a particular zone using the t:zone attributes. Once the zone is configured in EventLink, clicking the EventLink will trigger the zone update. In addition, the EventLink events (refreshZone) can be used to control the generation of dynamic data. A simple example of AJAX is as follows − <html t:type = "Newlayout" title = "About MyFirstApplication" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd" xmlns:p = "tapestry:parameter"> <body> <h1>Ajax time zone example</h1> <div class = "div1"> <a t:type = "eventlink" t:event = "refreshZone" href = "#" t:zone = "timeZone">Ajax Link </a><br/><br/> <t:zone t:id = "timeZone" id = "timeZone">Time zone: ${serverTime}</t:zone> </div> </body> </html> package com.example.MyFirstApplication.pages; import java.util.Date; import org.apache.tapestry5.annotations.InjectComponent; import org.apache.tapestry5.corelib.components.Zone; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.Request; public class AjaxZone { @Inject private Request request; @InjectComponent private Zone timeZone; void onRefreshPage() { } Object onRefreshZone() { return request.isXHR() ? timeZone.getBody() : null; } public Date getServerTime() { return new Date(); } } The result will show at: http://localhost:8080/MyFirstApplication/AjaxZone In this chapter, we will discuss about the integration of BeanEditForm and Grid component with Hibernate. Hibernate is integrated into the tapestry through the hibernate module. To enable hibernate module, add tapestry-hibernate dependency and optionally hsqldb in the pom.xml file. Now, configure hibernate through the hibernate.cfg.xml file placed at the root of the resource folder. <dependency> <groupId>org.apache.tapestry</groupId> <artifactId>tapestry-hibernate</artifactId> <version>${tapestry-release-version}</version> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.3.2</version> </dependency> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name = "hibernate.connection.driver_class"> org.hsqldb.jdbcDriver </property> <property name = "hibernate.connection.url"> jdbc:hsqldb:./target/work/sampleapp;shutdown = true </property> <property name = "hibernate.dialect"> org.hibernate.dialect.HSQLDialect </property> <property name = "hibernate.connection.username">sa</property> <property name = "hibernate.connection.password"></property> <property name = "hbm2ddl.auto">update</property> <property name = "hibernate.show_sql">true</property> <property name = "hibernate.format_sql">true</property> </session-factory> </hibernate-configuration> Let us see how to create the employee add page using the BeanEditForm component and the employee list page using the Grid component. The persistence layer is handled by Hibernate module. Create an employee class and decorate it with @Entity annotation. Then, add validation annotation for relevant fields and hibernate related annotation @Id and @GeneratedValue for id field. Also, create gender as enum type. package com.example.MyFirstApplication.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.apache.tapestry5.beaneditor.NonVisual; import org.apache.tapestry5.beaneditor.Validate; @Entity public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @NonVisual public Long id; @Validate("required") public String firstName; @Validate("required") public String lastName; @Validate("required") public String userName; @Validate("required") public String password; @Validate("required") public String email; public String phone; @Validate("required") public String Street; @Validate("required") public String city; @Validate("required") public String state; @Validate("required,regexp=^\\d{5}(-\\d{4})?$") public String zip; } Gender.java (enum) package com.example.MyFirstApplication.data; public enum Gender { Male, Female } Create the employee list page, ListEmployee.java in the new folder employee under pages and corresponding template file ListEmployee.tml at /src/main/resources/pages/employee folder. Tapestry provides a short URL for sub folders by removing repeated data. For example, the ListEmployee page can be accessed by a normal URL – (/employee/listemployee) and by the short URL – (/employee/list). Inject the Hibernate session into the list page using @Inject annotation. Define a property getEmployees in the list page and populate it with employees using injected session object. Complete the code for employee class as shown below. package com.example.MyFirstApplication.pages.employee; import java.util.List; import org.apache.tapestry5.annotations.Import; import org.apache.tapestry5.ioc.annotations.Inject; import org.hibernate.Session; import com.example.MyFirstApplication.entities.Employee; import org.apache.tapestry5.annotations.Import; @Import(stylesheet="context:mybootstrap/css/bootstrap.css") public class ListEmployee { @Inject private Session session; public List<Employee> getEmployees() { return session.createCriteria(Employee.class).list(); } } Create the template file for ListEmployee class. The template will have two main components, which are − PageLink − Create employee link page. PageLink − Create employee link page. Grid − Used to render the employee details. The grid component has sources attributes to inject employee list and include attributes to include the fields to be rendered. Grid − Used to render the employee details. The grid component has sources attributes to inject employee list and include attributes to include the fields to be rendered. ListEmployee.tml (list all employees) <html t:type = "simplelayout" title = "List Employee" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <h1>Employees</h1> <ul> <li><t:pagelink page = "employee/create">Create new employee</t:pagelink></li> </ul> <t:grid source = "employees" include = "userName,firstName,lastName,gender,dateOfBirth,phone,city,state"/> </html> Create employee creation template file and include BeanEditForm component. The component has the following attributes − object − Includes source. object − Includes source. reorder − Defines the order of the fields to be rendered. reorder − Defines the order of the fields to be rendered. submitlabel − The message of the form submission button submitlabel − The message of the form submission button The complete coding is as follows − <html t:type = "simplelayout" title = "Create New Address" xmlns:t = "http://tapestry.apache.org/schema/tapestry_5_4.xsd"> <t:beaneditform object = "employee" submitlabel = "message:submit-label" reorder = "userName,password,firstName,lastName, dateOfBirth,gender,email,phone,s treet,city,state,zip" /> </html> Create employee creation class and include session, employee property, list page (navigation link) and define the OnSuccess event (place to update the data) of the component. The session data is persisted into the database using the hibernate session. The complete coding is as follows − package com.example.MyFirstApplication.pages.employee; import com.example.MyFirstApplication.entities.Employee; import com.example.MyFirstApplication.pages.employee.ListEmployee; import org.apache.tapestry5.annotations.InjectPage; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.hibernate.annotations.CommitAfter; import org.apache.tapestry5.ioc.annotations.Inject; import org.hibernate.Session; public class CreateEmployee { @Property private Employee employee; @Inject private Session session; @InjectPage private ListEmployee listPage; @CommitAfter Object onSuccess() { session.persist(employee); return listPage; } } Add the CreateEmployee.properties file and include the message to be used in form validations. The complete code is as follows − zip-regexp=^\\d{5}(-\\d{4})?$ zip-regexp-message = Zip Codes are five or nine digits. Example: 02134 or 901251655. submit-label = Create Employee The screenshot of the employee creation page and listing page are shown below − Every web application should have some way to store certain user data like user object, user preferences, etc. For example, in a shopping cart application, the user's selected items / products should be saved in a temporary bucket (cart) until the user prefers to buy the products. We can save the items in a database, but it will be too expensive since all users are not going to buy the selected items. So, we need a temporary arrangement to store / persist the items. Apache Tapestry Provides two ways to persist the data and they are − Persistence page data Session Storage Both has its own advantages and limitations. We will check it in the following sections. The Persistence Page Data is a simple concept to persist data in a single page between requests and it is also called as Page Level Persistence. It can be done using the @Persist annotation. @Persist public int age; Once a field is annotated with @Persist, the field's value will be persisted across request and if the value is changed during request, it will be reflected when it is accessed next time. Apache Tapestry provides five types of strategy to implement the @Persist concept. They are as follows − Session Strategy − The data is persisted using the Session and it is a default strategy. Session Strategy − The data is persisted using the Session and it is a default strategy. Flash Strategy − The data is persisted using Session as well, but it is a very short lived one. The data will be available in only one subsequent request. Flash Strategy − The data is persisted using Session as well, but it is a very short lived one. The data will be available in only one subsequent request. @Persist(PersistenceConstants.FLASH) private int age; Client Strategy − The data is persisted in the client side such as URL query string, hidden field in the form, etc. Client Strategy − The data is persisted in the client side such as URL query string, hidden field in the form, etc. @Persist(PersistenceConstants.FLASH) private int age; Hibernate Entity Strategy − The data is persisted using the Hibernate module as Entity. The entity will be stored in Hibernate and its reference (Java class name and its primary key) will be saved as token in HttpSession. The entity will be restored by using the token available in HttpSession. Hibernate Entity Strategy − The data is persisted using the Hibernate module as Entity. The entity will be stored in Hibernate and its reference (Java class name and its primary key) will be saved as token in HttpSession. The entity will be restored by using the token available in HttpSession. @Persist(HibernatePersistenceConstants.ENTITY) private Category category; JPA Entity Strategy − The data is persisted using a JPA module. It will only able to store Entity. JPA Entity Strategy − The data is persisted using a JPA module. It will only able to store Entity. @Persist(JpaPersistenceConstants.ENTITY) private User user; Session storage is an advanced concept used to store data which needs to be available across pages like data in multiple page wizard, logged in user details, etc. The Session Storage provides two options, one to store complex object and another to store simple values Session Store Object − Used to store complex object. Session Store Object − Used to store complex object. Session Attributes − Used to store simple values. Session Attributes − Used to store simple values. An SSO can be created using @SessionStore annotation. The SSO will store the object using type of the object. For example, the Cart Object will be stored using a Cart class name as token. So, any complex object can be stored once in an application (one per user). public class MySSOPage { @SessionState private ShoppingCart cart; } An SSO is a specialized store and should be used to store only complex / special object. Simple data types can also be stored using an SSO, but storing simple data types like String makes it only store one “String” value in the application. Using a single “String” value in the application is simply not possible. You can use simple data types as Apache Tapestry provides Session Attributes. Session Attributes enable the data to be stored by name instead of its type. public class MyPage { @SessionAttribute private String loggedInUsername; } By default, Session Attributes uses the field name to refer the data in session. We can change the reference name by annotation parameter as shown below − public class MyPage { @SessionAttribute("loggedInUserName") private String userName; } One of the main issues in using name as session reference is that we may accidentally use the same name in more than one class / page. In this case, the data stored maybe changed unexpectedly. To fix this issue, it will be better to use the name along with class / page name and package name like com.myapp.pages.register.email, where com.myapp.pages is the package name, register is the page / class name and finally email is variable (to be stored) name. In this chapter, we will discuss a few advanced features of Apache Tapestry in detail. Tapestry provides built-in Inversion of Control library. Tapestry is deeply integrated into IoC and uses IoC for all its features. Tapestry IoC configuration is based on Java itself instead of XML like many other IoC containers. Tapestry IoC based modules are packaged into JAR file and just dropped into the classpath with zero configuration. Tapestry IoC usage is based on lightness, which means − Small interfaces of two or three methods. Small interfaces of two or three methods. Small methods with two or three parameters. Small methods with two or three parameters. Anonymous communication via events, rather than explicit method invocations. Anonymous communication via events, rather than explicit method invocations. Module is a way to extend the functionality of the Tapestry application. Tapestry has both built-in modules and large number of third-party modules. Hibernate is one of the hot and very useful module provided by Tapestry. It also has modules integrating JMX, JPA, Spring Framework, JSR 303 Bean Validation, JSON, etc. Some of the notable third-party modules are − Tapestry-Cayenne Tapestry5-googleanalytics Gang of tapestry 5 - Tapestry5-HighCharts Gang of tapestry 5 - Tapestry5-jqPlot Gang of tapestry 5 - Tapestry5-Jquery Gang of tapestry 5 - Tapestry5-Jquery-mobile Gang of tapestry 5 - Tapestry5-Portlet One of the best feature of the tapestry is Detailed Error Reporting. Tapestry helps a developer by providing the state of art exception reporting. Tapestry exception report is simple HTML with detailed information. Anyone can easily understand the report. Tapestry shows the error in HTML as well as save the exception in a plain text with date and time of the exception occurred. This will help developer to check the exception in production environment as well. The developer can remain confident of fixing any issues like broken templates, unexpected null values, unmatched request, etc., Tapestry will reload the templates and classes automatically when modified. This feature enables the immediate reflection of application changes without going through build and test cycle. Also, this feature greatly improves the productivity of the application development. Consider the root package of the application is org.example.myfirstapp. Then, the classes in the following paths are scanned for reloading. org.example.myfirstapp.pages org.example.myfirstapp.components org.example.myfirstapp.mixins org.example.myfirstapp.base org.example.myfirstapp.services The live class reloading can be disabled by setting the production mode to true in AppModule.java. configuration.add(SymbolicConstants.PRODUCTION_MODE,”false”); Unit testing is a technique by which individual pages and components are tested. Tapestry provides easy options to unit test pages and components. Unit testing a page: Tapestry provide a class PageTester to test the application. This acts as both the browser and servlet container. It renders the page without the browser in the server-side itself and the resulting document can be checked for correct rendering. Consider a simple page Hello, which renders hello and the hello text is enclosed inside a html element with id hello_id. To test this feature, we can use PageTester as shown below − public class PageTest extends Assert { @Test public void test1() { Sring appPackage = "org.example.myfirstapp"; // package name String appName = "App1"; // app name PageTester tester = new PageTester(appPackage, appName, "src/main/webapp"); Document doc = tester.renderPage("Hello"); assertEquals(doc.getElementById("hello_id").getChildText(), "hello"); } } The PageTester also provides option to include context information, form submission, link navigation etc., in addition to rendering the page. Integrated testing helps to test the application as a module instead of checking the individual pages as in unit testing. In Integrated testing, multiple modules can be tested together as a unit. Tapestry provides a small library called Tapestry Test Utilities to do integrated testing. This library integrates with Selenium testing tool to perform the testing. The library provides a base class SeleniumTestCase, which starts and manages the Selenium server, Selenium client and Jetty Instance. One of the example of integrated testing is as follows − import org.apache.tapestry5.test.SeleniumTestCase; import org.testng.annotations.Test; public class IntegrationTest extends SeleniumTestCase { @Test public void persist_entities() { open("/persistitem"); assertEquals(getText("//span[@id='name']").length(), 0); clickAndWait("link = create item"); assertText("//span[@id = 'name']", "name"); } } The Development dashboard is the default page which is used to identify / resolve the problems in your application. The Dashboard is accessed by the URL http://localhost:8080/myfirstapp/core/t5dashboard. The dashboard shows all the pages, services and component libraries available in the application. Tapestry automatically compress the response using GZIP compression and stream it to the client. This feature will reduce the network traffic and aids faster delivery of the page. The compression can be configured using the symbol tapestry.min-gzip-size in AppModule.java. The default value is 100 bytes. Tapestry will compress the response once the size of the response crosses 100 bytes. Tapestry provides many options to secure the application against known security vulnerabilities in web application. Some of these options are listed below − HTTPS − Tapestry pages can be annotated with @Secure to make it a secure page and accessible by the https protocol only. HTTPS − Tapestry pages can be annotated with @Secure to make it a secure page and accessible by the https protocol only. Page access control − Controlling the page to be accessed by a certain user only. Page access control − Controlling the page to be accessed by a certain user only. White-Listed Page − Tapestry pages can be annotated with a @WhitelistAccessOnly to make it accessible only through the localhost. White-Listed Page − Tapestry pages can be annotated with a @WhitelistAccessOnly to make it accessible only through the localhost. Asset Security − Under tapestry, only certain types of files are accessible. Others can be accessed only when the MD5 hash of the file is provided. Asset Security − Under tapestry, only certain types of files are accessible. Others can be accessed only when the MD5 hash of the file is provided. Serialized Object Date − Tapestry integrates a HMAC into serialized Java object data and sends it to the client to avoid message tampering. Serialized Object Date − Tapestry integrates a HMAC into serialized Java object data and sends it to the client to avoid message tampering. Cross Site Request Forgery − Tapestry provides a 3rd party module called tapestry-csrf-protection to prevent any CSRF attacks. Cross Site Request Forgery − Tapestry provides a 3rd party module called tapestry-csrf-protection to prevent any CSRF attacks. Security Framework integration − Tapestry does not lock into a single authentication / authorization implementation. Tapestry can be integrated with any popular authentication framework. Security Framework integration − Tapestry does not lock into a single authentication / authorization implementation. Tapestry can be integrated with any popular authentication framework. Tapestry provides extensive support for logging, the automatic recording of the progress of the application as it runs. Tapestry uses the de-facto Java logging library, SLF4J. The annotation @Log can be in any component method to emit the entry and exit of the method and the possible exception as well. Also, the Tapestry provided logger object can be injected into any component using the @Inject annotation as shown below − public class MyPage { @Inject private Logger logger; // . . . void onSuccessFromForm() { logger.info("Changes saved successfully"); } @Log void onValidateFromForm() { // logic } } Finally, we can now say that Apache Tapestry brings best ways to build concise, scalable, maintainable, robust and Ajax-enabled applications. Tapestry can be integrated with any third-party Java application. It can also help in creating a large web application as it is quite easy and fast. 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": 2371, "s": 2074, "text": "Apache Tapestry is an open source web framework written in Java. It is a component based web framework. Tapestry components are Java Classes. They are neither inherited from a framework specific base class nor implementation of an interface and they are just plain POJOs (Plain old Java Objects)." }, { "code": null, "e": 2734, "s": 2371, "text": "The important feature of the Java used by tapestry is Annotation. Tapestry web pages are constructed by using one or more components, each having a XML based template and component class decorated with a lot of Tapestry's Annotations. Tapestry can create anything ranging from a tiny, single-page web application to a massive one consisting of hundreds of pages." }, { "code": null, "e": 2782, "s": 2734, "text": "Some of the benefits provided by tapestry are −" }, { "code": null, "e": 2816, "s": 2782, "text": "Highly scalable web applications." }, { "code": null, "e": 2830, "s": 2816, "text": "Adaptive API." }, { "code": null, "e": 2857, "s": 2830, "text": "Fast and mature framework." }, { "code": null, "e": 2894, "s": 2857, "text": "Persistent state storage management." }, { "code": null, "e": 2925, "s": 2894, "text": "Build-in Inversion of Control." }, { "code": null, "e": 2963, "s": 2925, "text": "Tapestry has the following features −" }, { "code": null, "e": 2984, "s": 2963, "text": "Live class reloading" }, { "code": null, "e": 3023, "s": 2984, "text": "Clear and detailed exception reporting" }, { "code": null, "e": 3060, "s": 3023, "text": "Static structure, dynamic behaviors." }, { "code": null, "e": 3108, "s": 3060, "text": "Extensive use of Plain Old Java Objects (POJOs)" }, { "code": null, "e": 3133, "s": 3108, "text": "Code less, deliver more." }, { "code": null, "e": 3408, "s": 3133, "text": "Already Java has a lot of web frameworks like JSP, Struts, etc., Then, why do we need another framework? Most of the today's Java Web Frameworks are complex and have a steep learning curve. They are old fashioned and requires compile, test and deploy cycle for every update." }, { "code": null, "e": 3747, "s": 3408, "text": "On the other hand, Tapestry provides a modern approach to web application programming by providing live class reloading. While other frameworks are introducing lots of interfaces, abstract & base classes, Tapestry just introduces a small set of annotations and still provides the ability to write large application with rich AJAX support." }, { "code": null, "e": 4281, "s": 3747, "text": "Tapestry tries to use the available features of Java as much as possible. For example, all Tapestry pages are simply POJOs. It does not enforce any custom interfaces or base class to write the application. Instead, it uses Annotation (a light weight option to extend the functionality of a Java class) to provide features. It is based on battle-tested Java Servlet API and is implemented as a Servlet Filter. It provides a new dimension to the web application and the programming is quite Simple, Flexible, Understandable and Robust." }, { "code": null, "e": 4367, "s": 4281, "text": "Let us discuss the sequence of action taking place when a tapestry page is requested." }, { "code": null, "e": 4683, "s": 4367, "text": "Step 1 − The Java Servlet receives the page request. This Java Servlet is the configured in such a way that the incoming request will be forwarded to tapestry. The configuration is done in the web.xml as specified in the following program. Filter and Filter Mapping tag redirects all the request to Tapestry Filter." }, { "code": null, "e": 5294, "s": 4683, "text": "<!DOCTYPE web-app PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\" \n \"http://java.sun.com/dtd/web-app_2_3.dtd\"> \n<web-app> \n <display-name>My Tapestry Application</display-name> \n <context-param> \n <param-name>tapestry.app-package</param-name> \n <param-value>org.example.myapp</param-value> \n </context-param> \n <filter> \n <filter-name>app</filter-name> \n <filter-class>org.apache.tapestry5.TapestryFilter</filter-class> \n </filter> \n <filter-mapping> \n <filter-name>app</filter-name> \n <url-pattern>/*</url-pattern> \n </filter-mapping> \n</web-app> " }, { "code": null, "e": 5392, "s": 5294, "text": "Step 2 − The Tapestry Filter calls the HttpServletRequestHandler Service by its Service() method." }, { "code": null, "e": 5586, "s": 5392, "text": "Step 3 − HttpServletRequestHandler stores the request and response in RequestGlobals. It also wraps the request and response as a Request and Response object and sends it to the RequestHandler." }, { "code": null, "e": 5901, "s": 5586, "text": "Step 4 − The RequestHandler is an abstraction on top of HttpServletRequest of Servlet API. Some of the salient feature of the tapestry is done in RequestHandler section. The feature of tapestry can be extended by writing a filter in RequestHandler. RequestHandler provides several build-in filters, which include −" }, { "code": null, "e": 6053, "s": 5901, "text": "CheckForUpdates Filter − Responsible for live class reloading. This filter checks the java classes for changes and update the application as necessary." }, { "code": null, "e": 6205, "s": 6053, "text": "CheckForUpdates Filter − Responsible for live class reloading. This filter checks the java classes for changes and update the application as necessary." }, { "code": null, "e": 6315, "s": 6205, "text": "Localization Filter − Identify the location of the user and provide localization support for the application." }, { "code": null, "e": 6425, "s": 6315, "text": "Localization Filter − Identify the location of the user and provide localization support for the application." }, { "code": null, "e": 6579, "s": 6425, "text": "StaticFiles Filter − Identify the static request and aborts the process. Once the process is aborted, Java Servlet takes control and process the request." }, { "code": null, "e": 6733, "s": 6579, "text": "StaticFiles Filter − Identify the static request and aborts the process. Once the process is aborted, Java Servlet takes control and process the request." }, { "code": null, "e": 6819, "s": 6733, "text": "Error Filter − Catches the uncaught exception and presents the exception report page." }, { "code": null, "e": 6905, "s": 6819, "text": "Error Filter − Catches the uncaught exception and presents the exception report page." }, { "code": null, "e": 7037, "s": 6905, "text": "The RequestHandler also modifies and stores the request and response in the RequestQlobalsand invokes the MasterDispatcher service." }, { "code": null, "e": 7226, "s": 7037, "text": "Step 5 − The MasterDispatcher is responsible for rendering the page by calling several dispatchers is a specific order. The four-main dispatchers called by MasterDispatcher is as follows −" }, { "code": null, "e": 7330, "s": 7226, "text": "RootPath Dispatcher − It recognizes the root path “/” of the request and render the same as Start page." }, { "code": null, "e": 7434, "s": 7330, "text": "RootPath Dispatcher − It recognizes the root path “/” of the request and render the same as Start page." }, { "code": null, "e": 7584, "s": 7434, "text": "Asset Dispatcher − It recognized the asset (Java assets) request by checking the url pattern /assets/ and sends the requested assets as byte streams." }, { "code": null, "e": 7734, "s": 7584, "text": "Asset Dispatcher − It recognized the asset (Java assets) request by checking the url pattern /assets/ and sends the requested assets as byte streams." }, { "code": null, "e": 8558, "s": 7734, "text": "PageRender Dispatcher − Bulk of the tapestry operations are done in PageRender Dispatcher and the next dispatcher Component Dispatcher. This dispatcher recognizes the particular page of that request and its activation context (extra information). It then renders that particular page and sends it to the client. For example, if the request url is /product/12123434, the dispatcher will check if any class with name product/12123434 is available. If found, it calls product/12123434 class, generate the response and send it to the client. If not, it checks for product class. If found, it calls product class with extra information 121234434, generates the response and sends it to the client. This extra information is called Activation Context. If no class is found, it simply forwards the request to Component Dispatcher." }, { "code": null, "e": 9382, "s": 8558, "text": "PageRender Dispatcher − Bulk of the tapestry operations are done in PageRender Dispatcher and the next dispatcher Component Dispatcher. This dispatcher recognizes the particular page of that request and its activation context (extra information). It then renders that particular page and sends it to the client. For example, if the request url is /product/12123434, the dispatcher will check if any class with name product/12123434 is available. If found, it calls product/12123434 class, generate the response and send it to the client. If not, it checks for product class. If found, it calls product class with extra information 121234434, generates the response and sends it to the client. This extra information is called Activation Context. If no class is found, it simply forwards the request to Component Dispatcher." }, { "code": null, "e": 9975, "s": 9382, "text": "Component Dispatcher − Component Dispatcher matches the URL of the page with the pattern – /<class_name>/<component_id>:<event_type>/<activation_context>. For example, /product/grid:sort/asc represents the product class, grid component, sortevent type and asc activation context. Here, event_type is optional and if none is provided, the default event type action will be triggered. Usually, the response of the component dispatcher is to send a redirect to the client. Mostly, the redirect will match PageRender Dispatcher in the next request and proper response will be send to the client." }, { "code": null, "e": 10568, "s": 9975, "text": "Component Dispatcher − Component Dispatcher matches the URL of the page with the pattern – /<class_name>/<component_id>:<event_type>/<activation_context>. For example, /product/grid:sort/asc represents the product class, grid component, sortevent type and asc activation context. Here, event_type is optional and if none is provided, the default event type action will be triggered. Usually, the response of the component dispatcher is to send a redirect to the client. Mostly, the redirect will match PageRender Dispatcher in the next request and proper response will be send to the client." }, { "code": null, "e": 10641, "s": 10568, "text": "In this chapter, we will discuss how to install Tapestry on our machine." }, { "code": null, "e": 10921, "s": 10641, "text": "Tapestry's only dependency is Core Java. Tapestry is developed independently without using any third party library / framework. Even the IoC library used by tapestry is developed from the scratch. Web application written in tapestry can be built and deployed from console itself." }, { "code": null, "e": 11210, "s": 10921, "text": "We can use Maven, Eclipse and Jetty to improve the development experience. Maven provides quick start application templates and options to host application in Jetty, Java's de-facto development server. Eclipse provides extensive project management features and integrates well with maven." }, { "code": null, "e": 11274, "s": 11210, "text": "An ideal tapestry application development needs the following −" }, { "code": null, "e": 11292, "s": 11274, "text": "Java 1.6 or later" }, { "code": null, "e": 11305, "s": 11292, "text": "Apache Maven" }, { "code": null, "e": 11317, "s": 11305, "text": "Eclipse IDE" }, { "code": null, "e": 11330, "s": 11317, "text": "Jetty Server" }, { "code": null, "e": 11448, "s": 11330, "text": "Hopefully, you have installed Maven on your machine. To verify the Maven installation, type the command given below −" }, { "code": null, "e": 11463, "s": 11448, "text": "mvn --version\n" }, { "code": null, "e": 11507, "s": 11463, "text": "You could see the response as shown below −" }, { "code": null, "e": 11904, "s": 11507, "text": "Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-1110T22:11:47+05:30) \nMaven home: /Users/workspace/maven/apache-maven-3.3.9 \nJava version: 1.8.0_92, vendor: Oracle Corporation \nJava home: /Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home/jre \nDefault locale: en_US, platform encoding: UTF-8 \nOS name: \"mac os x\", version: \"10.11.4\", arch: \"x86_64\", family: \"mac\"\n" }, { "code": null, "e": 12016, "s": 11904, "text": "If Maven is not installed, then download and install the latest version of maven by visiting the Maven website." }, { "code": null, "e": 12430, "s": 12016, "text": "The latest version of tapestry is 5.4 and can be downloaded from the Tapestry website. It is enough to download the binary package. If we use the Maven Quick Start Template, then it is not necessary to download Tapestry separately. Maven automatically downloads the necessary Tapestry Jars and configures the application. We will discuss how to create a basic Tapestry Application using Maven in the next chapter." }, { "code": null, "e": 12524, "s": 12430, "text": "After Tapestry installation, let us create a new initial project using Maven as shown below −" }, { "code": null, "e": 12596, "s": 12524, "text": "$ mvn archetype:generate -DarchetypeCatalog=http://tapestry.apache.org\n" }, { "code": null, "e": 12640, "s": 12596, "text": "You could see the response as shown below −" }, { "code": null, "e": 13391, "s": 12640, "text": "[INFO] Scanning for projects... \n[INFO] \n[INFO] --------------------------------------------------------------------------------- \n[INFO] Building Maven Stub Project (No POM) 1 \n[INFO] ---------------------------------------------------------------------------------\n[INFO] \n[INFO] >>> maven-archetype-plugin:2.4:generate (default-cli) > \ngeneratesources @ standalone-pom >>> \n[INFO] \n[INFO] <<< maven-archetype-plugin:2.4:generate (default-cli) \n< generatesources @ standalone-pom <<< \n[INFO] \n[INFO] --- maven-archetype-plugin:2.4:generate (default-cli) @ standalone-pom --- \n[INFO] Generating project in Interactive mode \n[INFO] No archetype defined. Using maven-archetype-quickstart \n(org.apache.maven.archetypes:maven-archetype-quickstart:1.0)\n" }, { "code": null, "e": 13502, "s": 13391, "text": "After Maven building all the operations, choose archetype to create Tapestry 5 QuickStart project as follows −" }, { "code": null, "e": 13521, "s": 13502, "text": "Choose archetype −" }, { "code": null, "e": 13615, "s": 13521, "text": "https://tapestry.apache.org → org.apache.tapestry:quickstart (Tapestry 5 Quickstart Project)" }, { "code": null, "e": 13709, "s": 13615, "text": "https://tapestry.apache.org → org.apache.tapestry:quickstart (Tapestry 5 Quickstart Project)" }, { "code": null, "e": 13805, "s": 13709, "text": "https://tapestry.apache.org → org.apache.tapestry:tapestry-archetype (Tapestry 4.1.6 Archetype)" }, { "code": null, "e": 13901, "s": 13805, "text": "https://tapestry.apache.org → org.apache.tapestry:tapestry-archetype (Tapestry 4.1.6 Archetype)" }, { "code": null, "e": 13994, "s": 13901, "text": "Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 1" }, { "code": null, "e": 14049, "s": 13994, "text": "Now you will get a response like what is shown below −" }, { "code": null, "e": 14150, "s": 14049, "text": "Choose org.apache.tapestry:quickstart version: \n1: 5.0.19\n2: 5.1.0.5 \n3: 5.2.6 \n4: 5.3.7 \n5: 5.4.1 \n" }, { "code": null, "e": 14201, "s": 14150, "text": "Extract the QuickStart version number as follows −" }, { "code": null, "e": 14224, "s": 14201, "text": "Choose a number: 5: 5\n" }, { "code": null, "e": 14377, "s": 14224, "text": "Here, the QuickStart project takes the version for the option 5, “5.4.1”. Now, Tapestry archetype asks the following information one by one as follows −" }, { "code": null, "e": 14442, "s": 14377, "text": "5.1 groupId − Define value for property 'groupId': : com.example" }, { "code": null, "e": 14507, "s": 14442, "text": "5.1 groupId − Define value for property 'groupId': : com.example" }, { "code": null, "e": 14572, "s": 14507, "text": "5.2 artifactId − Define value for property 'artifactId': : Myapp" }, { "code": null, "e": 14637, "s": 14572, "text": "5.2 artifactId − Define value for property 'artifactId': : Myapp" }, { "code": null, "e": 14705, "s": 14637, "text": "5.3 version − Define value for property 'version': 1.0-SNAPSHOT: :" }, { "code": null, "e": 14773, "s": 14705, "text": "5.3 version − Define value for property 'version': 1.0-SNAPSHOT: :" }, { "code": null, "e": 14863, "s": 14773, "text": "5.4 package name − Define value for property 'package': com.example: : com.example.Myapp" }, { "code": null, "e": 14953, "s": 14863, "text": "5.4 package name − Define value for property 'package': com.example: : com.example.Myapp" }, { "code": null, "e": 14998, "s": 14953, "text": "Now your screen asks confirmation from you −" }, { "code": null, "e": 15033, "s": 14998, "text": "Confirm properties configuration −" }, { "code": null, "e": 15055, "s": 15033, "text": "groupId − com.example" }, { "code": null, "e": 15077, "s": 15055, "text": "groupId − com.example" }, { "code": null, "e": 15096, "s": 15077, "text": "artifactId − Myapp" }, { "code": null, "e": 15115, "s": 15096, "text": "artifactId − Myapp" }, { "code": null, "e": 15138, "s": 15115, "text": "version − 1.0-SNAPSHOT" }, { "code": null, "e": 15161, "s": 15138, "text": "version − 1.0-SNAPSHOT" }, { "code": null, "e": 15189, "s": 15161, "text": "package − com.example.Myapp" }, { "code": null, "e": 15217, "s": 15189, "text": "package − com.example.Myapp" }, { "code": null, "e": 15298, "s": 15217, "text": "Verify all the properties and confirm the changes using the option shown below −" }, { "code": null, "e": 15308, "s": 15298, "text": " Y: : Y \n" }, { "code": null, "e": 15359, "s": 15308, "text": "You would see the screen like the one shown below." }, { "code": null, "e": 17041, "s": 15359, "text": "[INFO] ---------------------------------------------------------------------------------\n[INFO] Using following parameters for creating project from Archetype: quickstart:5.4.1 \n[INFO] ---------------------------------------------------------------------------------\n[INFO] Parameter: groupId, Value: com.example \n[INFO] Parameter: artifactId, Value: Myapp \n[INFO] Parameter: version, Value: 1.0-SNAPSHOT \n[INFO] Parameter: package, Value: com.example.Myapp \n[INFO] Parameter: packageInPathFormat, Value: com/example/Myapp \n[INFO] Parameter: package, Value: com.example.Myapp \n[INFO] Parameter: version, Value: 1.0-SNAPSHOT \n[INFO] Parameter: groupId, Value: com.example \n[INFO] Parameter: artifactId, Value: Myapp \n[WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/test/java \n[WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/main/webapp \n[WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/main/resources/com/\nexample/Myapp \n[WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/test/resource \n[WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/test/conf \n[WARNING] Don't override file /Users/workspace/tapestry/Myapp/src/site \n[INFO] project created from Archetype in dir: /Users/workspace/tapestry/Myapp \n[INFO] --------------------------------------------------------------------------------- \n[INFO] BUILD SUCCESS \n[INFO] --------------------------------------------------------------------------------- \n[INFO] Total time: 11:28 min \n[INFO] Finished at: 2016-09-14T00:47:23+05:30 \n[INFO] Final Memory: 14M/142M \n[INFO] ---------------------------------------------------------------------------------\n" }, { "code": null, "e": 17212, "s": 17041, "text": "Here, you have successfully built the Tapestry Quick Start project. Move to the location of the newly created Myapp directory with the following command and start coding." }, { "code": null, "e": 17223, "s": 17212, "text": "cd Myapp \n" }, { "code": null, "e": 17279, "s": 17223, "text": "To run the skeleton project, use the following command." }, { "code": null, "e": 17332, "s": 17279, "text": "mvn jetty:run -Dtapestry.execution-mode=development\n" }, { "code": null, "e": 17360, "s": 17332, "text": "You get a screen like this," }, { "code": null, "e": 18107, "s": 17360, "text": "[INFO] Scanning for projects... \n[INFO] \n[INFO] ---------------------------------------------------------------------------------\n[INFO] Building Myapp Tapestry 5 Application 1.0-SNAPSHOT \n[INFO] ---------------------------------------------------------------------------------\n........ \n........ \n........ \nApplication 'app' (version 1.0-SNAPSHOT-DEV) startup time: 346 ms to build IoC \nRegistry, 1,246 ms overall. \n ______ __ ____ \n/_ __/__ ____ ___ ___ / /_______ __ / __/ \n / / / _ `/ _ \\/ -_|_-</ __/ __/ // / /__ \\ \n/_/ \\_,_/ .__/\\__/___/\\__/_/ \\_, / /____/ \n /_/ /___/ 5.4.1 (development mode) \n[INFO] Started SelectChannelConnector@0.0.0.0:8080 \n[INFO] Started Jetty Server\n" }, { "code": null, "e": 18292, "s": 18107, "text": "As of now, we have created a basic Quick Start project in Tapestry. To view the running application in the web browser, just type the following URL in the address bar and press enter −" }, { "code": null, "e": 18321, "s": 18292, "text": "https://localhost:8080/myapp" }, { "code": null, "e": 18433, "s": 18321, "text": "Here, myapp is the name of the application and the default port of the application in development mode is 8080." }, { "code": null, "e": 18610, "s": 18433, "text": "In the previous chapter, we discussed about how to create a Tapestry Quick Start application in CLI. This chapter explains about creating a skeleton application in Eclipse IDE." }, { "code": null, "e": 18741, "s": 18610, "text": "Let us use a Maven archetype to create skeleton application. To configure a new application, you can follow the steps given below." }, { "code": null, "e": 18841, "s": 18741, "text": "Open your Eclipse and choose File → New → Project... → option as shown in the following screenshot." }, { "code": null, "e": 18883, "s": 18841, "text": "Now, choose Maven → Maven project option." }, { "code": null, "e": 18954, "s": 18883, "text": "Note − If Maven is not configured then configure and create a project." }, { "code": null, "e": 19033, "s": 18954, "text": "After selecting the Maven project, click Next and again click the Next button." }, { "code": null, "e": 19171, "s": 19033, "text": "After that, you will get a screen where you should choose the configure option. Once it is configured, you will get the following screen." }, { "code": null, "e": 19310, "s": 19171, "text": "After the first step is done, you should click on Add Remote Catalog. Then add the following changes as shown in the following screenshot." }, { "code": null, "e": 19429, "s": 19310, "text": "Now, Apache Tapestry Catalog is added. Then, choose filter option org.apache.tapestry quickstart 5.4.1 as shown below." }, { "code": null, "e": 19483, "s": 19429, "text": "Then click Next and the following screen will appear." }, { "code": null, "e": 19548, "s": 19483, "text": "Add the following changes to the Tapestry Catalog configuration." }, { "code": null, "e": 19862, "s": 19548, "text": "Then click Finish button, now we have created the first skeleton application. The first time you use Maven, project creation may take a while as Maven downloads many JAR dependencies for Maven, Jetty and Tapestry. After Maven finishes, you'll see a new directory, MyFirstApplication in your Package Explorer view." }, { "code": null, "e": 20047, "s": 19862, "text": "You can use Maven to run Jetty directly. Right-click on the MyFirstApplication project in your Package Explorer view and select Run As → Maven Build... you will the screen shown below." }, { "code": null, "e": 20137, "s": 20047, "text": "In the configuration dialog box, enter goals option as “jetty:run” then click Run button." }, { "code": null, "e": 20213, "s": 20137, "text": "Once Jetty is initialized, you'll see the following screen in your console." }, { "code": null, "e": 20278, "s": 20213, "text": "Type the following URL to run the application in a web browser –" }, { "code": null, "e": 20319, "s": 20278, "text": "https://loclhost:8080/MyFirstApplication" }, { "code": null, "e": 20403, "s": 20319, "text": "To stop the Jetty server, click the red square icon in your console as shown below." }, { "code": null, "e": 20545, "s": 20403, "text": "Here is the layout of the source code created by Maven Quickstart CLI. Also, this is the suggested layout of a standard Tapestry Application." }, { "code": null, "e": 23224, "s": 20545, "text": "├── build.gradle \n├── gradle \n│ └── wrapper \n│ ├── gradle-wrapper.jar \n│ └── gradle-wrapper.properties \n├── gradlew \n├── gradlew.bat \n├── pom.xml \n├── src \n│ ├── main \n│ │ ├── java \n│ │ │ └── com \n│ │ │ └── example \n│ │ │ └── MyFirstApplication \n│ │ │ ├── components \n│ │ │ ├── data \n│ │ │ ├── entities \n│ │ │ ├── pages \n│ │ │ └── services \n│ │ ├── resources \n│ │ │ ├── com \n│ │ │ │ └── example \n│ │ │ │ └── MyFirstApplication \n│ │ │ │ ├── components \n│ │ │ │ ├── logback.xml \n│ │ │ │ └── pages \n│ │ │ │ └── Index.properties \n│ │ │ ├── hibernate.cfg.xml \n│ │ │ └── log4j.properties\n│ │ └── webapp \n│ │ ├── favicon.ico \n│ │ ├── images \n│ │ │ └── tapestry.png \n│ │ ├── mybootstrap \n│ │ │ ├── css \n│ │ │ │ ├── bootstrap.css \n│ │ │ │ └── bootstrap-theme.css \n│ │ │ ├── fonts \n│ ├── glyphicons-halflings-regular.eot \n│ │ │ │ ├── glyphicons-halflings-regular.svg \n│ │ │ │ ├── glyphicons-halflings-regular.ttf \n│ │ │ │ ├── glyphicons-halflings-regular.woff \n│ │ │ │ └── glyphicons-halflings-regular.woff2 \n│ │ │ └── js \n│ │ └── WEB-INF \n│ │ ├── app.properties \n│ │ └── web.xml \n│ ├── site \n│ │ ├── apt \n│ │ │ └── index.apt \n│ │ └── site.xml \n│ └── test \n│ ├── conf \n│ │ ├── testng.xml \n│ │ └── webdefault.xml \n│ ├── java \n│ │ └── PLACEHOLDER \n│ └── resources \n│ └── PLACEHOLDER \n└── target \n ├── classes \n │ ├── com \n │ │ └── example\n │ │ └── MyFirstApplication \n │ │ ├── components \n │ │ ├── data \n │ │ ├── entities \n │ │ ├── logback.xml \n │ │ ├── pages \n │ │ │ └── Index.properties \n │ │ └── services \n │ ├── hibernate.cfg.xml \n │ └── log4j.properties \n ├── m2e-wtp \n │ └── web-resources \n │ └── META-INF \n │ ├── MANIFEST.MF \n │ └── maven \n │ └── com.example \n │ └──MyFirstApplication \n │ ├── pom.properties \n │ └── pom.xml \n ├── test-classes \n │ └── PLACEHOLDER \n └── work \n ├── jsp \n ├── sampleapp.properties \n └── sampleapp.script\n" }, { "code": null, "e": 23514, "s": 23224, "text": "The default layout is arranged like the WAR Internal File Format. Using WAR format helps to run the application without packaging and deploying. This layout is just a suggestion, but the application can be arranged in any format, if it is packaged into a proper WAR format while deploying." }, { "code": null, "e": 23584, "s": 23514, "text": "The source code can be divided into the following four main sections." }, { "code": null, "e": 23842, "s": 23584, "text": "Java Code − All java source codes are placed under /src/main/java folder. Tapestry page classes are placed under the “Pages” folder and Tapestry component classes are placed under components folder. Tapestry service classes are placed under services folder." }, { "code": null, "e": 24100, "s": 23842, "text": "Java Code − All java source codes are placed under /src/main/java folder. Tapestry page classes are placed under the “Pages” folder and Tapestry component classes are placed under components folder. Tapestry service classes are placed under services folder." }, { "code": null, "e": 24527, "s": 24100, "text": "ClassPath Resources − In Tapestry, most of the classes have associated resources (XML Template, JavaScript files, etc.). These resources are placed under the /src/main/resources folder. Tapestry Page Classes have its associated resources under the “Pages” folder and Tapestry components classes have its associated resources under the Components folder. These resources are packaged into the WEB-INF/classes folder of the WAR." }, { "code": null, "e": 24954, "s": 24527, "text": "ClassPath Resources − In Tapestry, most of the classes have associated resources (XML Template, JavaScript files, etc.). These resources are placed under the /src/main/resources folder. Tapestry Page Classes have its associated resources under the “Pages” folder and Tapestry components classes have its associated resources under the Components folder. These resources are packaged into the WEB-INF/classes folder of the WAR." }, { "code": null, "e": 25304, "s": 24954, "text": "Context Resources − They are static resources of a web application like Images, Style Sheet and JavaScript Library / Modules. They are usually placed under the /src/main/webapp folder and they are called Context Resources. Also, the web application description file (of Java Servlet), web.xml is placed under the WEB-INF folder of context resources." }, { "code": null, "e": 25654, "s": 25304, "text": "Context Resources − They are static resources of a web application like Images, Style Sheet and JavaScript Library / Modules. They are usually placed under the /src/main/webapp folder and they are called Context Resources. Also, the web application description file (of Java Servlet), web.xml is placed under the WEB-INF folder of context resources." }, { "code": null, "e": 25822, "s": 25654, "text": "Testing Code − These are optional files used to test the application and placed under the src/test/java and src/test/Resources Folders. They are not packaged into WAR." }, { "code": null, "e": 25990, "s": 25822, "text": "Testing Code − These are optional files used to test the application and placed under the src/test/java and src/test/Resources Folders. They are not packaged into WAR." }, { "code": null, "e": 26148, "s": 25990, "text": "Apache Tapestry follows Convention over Configuration in every aspect of programming. Every feature of the framework does have a sensible default convention." }, { "code": null, "e": 26321, "s": 26148, "text": "For example, as we learned in the Project Layout chapter, all pages need to be placed in the /src/main/java/«package_path»/pages/ folder to be considered as Tapestry Pages." }, { "code": null, "e": 26539, "s": 26321, "text": "In another sense, there is no need configure a particular Java Class as Tapestry Pages. It is enough to place the class in a pre-defined location. In some cases, it is odd to follow the default convention of Tapestry." }, { "code": null, "e": 26844, "s": 26539, "text": "For example, Tapestry component can have a method setupRender which will be fired at the start the rendering phase. A developer may want to use their own opiniated name, say initializeValue. In this situation, Tapestry provides Annotation to override the conventions as shown in the following code block." }, { "code": null, "e": 26968, "s": 26844, "text": "void setupRender() { \n // initialize component \n} \n@SetupRender \nvoid initializeValue() { \n // initialize component \n}" }, { "code": null, "e": 27214, "s": 26968, "text": "Both ways of programming are valid in Tapestry. In short, Tapestry's default configuration is quite minimal. Only the Apache Tapestry Filter (Java Servlet Filter) needs to be configured in the “Web.xml” for the proper working of the application." }, { "code": null, "e": 27313, "s": 27214, "text": "Tapestry provides one another way to configure application and it is called as the AppModule.java." }, { "code": null, "e": 27719, "s": 27313, "text": "Annotation is a very important feature exploited by Tapestry to simplify the Web Application Development. Tapestry provides a lot of custom Annotations. It has Annotation for Classes, Methods and Member Fields. As discussed in the previous section, Annotation may also be used to override default convention of a feature. Tapestry annotations are grouped into four main categories and they are as follows." }, { "code": null, "e": 27802, "s": 27719, "text": "Used in Pages, Components and Mixins Classes. Some of the useful annotations are −" }, { "code": null, "e": 27892, "s": 27802, "text": "@Property − It is applicable to fields. Used to convert a field into a Tapestry Property." }, { "code": null, "e": 27982, "s": 27892, "text": "@Property − It is applicable to fields. Used to convert a field into a Tapestry Property." }, { "code": null, "e": 28076, "s": 27982, "text": "@Parameter − It is applicable to fields. Used to specify a field as parameter of a component." }, { "code": null, "e": 28170, "s": 28076, "text": "@Parameter − It is applicable to fields. Used to specify a field as parameter of a component." }, { "code": null, "e": 28275, "s": 28170, "text": "@Environmental − It is applicable to fields. Used to share a private field between different components." }, { "code": null, "e": 28380, "s": 28275, "text": "@Environmental − It is applicable to fields. Used to share a private field between different components." }, { "code": null, "e": 28474, "s": 28380, "text": "@import − It is applicable to classes and fields. Used to include Assets, CSS and JavaScript." }, { "code": null, "e": 28568, "s": 28474, "text": "@import − It is applicable to classes and fields. Used to include Assets, CSS and JavaScript." }, { "code": null, "e": 28660, "s": 28568, "text": "@Path − Used in conjunction with the @Inject annotation to inject an Asset based on a path." }, { "code": null, "e": 28752, "s": 28660, "text": "@Path − Used in conjunction with the @Inject annotation to inject an Asset based on a path." }, { "code": null, "e": 28923, "s": 28752, "text": "@Log − It is applicable to classes and fields. Used for debugging purposes. Can be used emit component's event information like start of the event, end of the event, etc." }, { "code": null, "e": 29094, "s": 28923, "text": "@Log − It is applicable to classes and fields. Used for debugging purposes. Can be used emit component's event information like start of the event, end of the event, etc." }, { "code": null, "e": 29174, "s": 29094, "text": "Used to inject objects into IoC Container. Some of the useful annotations are −" }, { "code": null, "e": 29341, "s": 29174, "text": "@Inject − It is applicable to fields. Used to mark parameters that should be injected into the IoC container. It marks fields that should be injected into components." }, { "code": null, "e": 29508, "s": 29341, "text": "@Inject − It is applicable to fields. Used to mark parameters that should be injected into the IoC container. It marks fields that should be injected into components." }, { "code": null, "e": 29678, "s": 29508, "text": "@Value − It is applicable to fields. Used along with @inject annotation to inject a literal value instead of a service (which is default behavior of @Inject annotation)." }, { "code": null, "e": 29848, "s": 29678, "text": "@Value − It is applicable to fields. Used along with @inject annotation to inject a literal value instead of a service (which is default behavior of @Inject annotation)." }, { "code": null, "e": 29987, "s": 29848, "text": "It is used to specify component specific information in a class (usually models or data holding classes) for high level components such as" }, { "code": null, "e": 30062, "s": 29987, "text": "Grid (used to create advanced tabular data such as report, gallery, etc.,)" }, { "code": null, "e": 30137, "s": 30062, "text": "Grid (used to create advanced tabular data such as report, gallery, etc.,)" }, { "code": null, "e": 30182, "s": 30137, "text": "BeanEditForm (Used to create advanced forms)" }, { "code": null, "e": 30227, "s": 30182, "text": "BeanEditForm (Used to create advanced forms)" }, { "code": null, "e": 30278, "s": 30227, "text": "Hibernate (Used in advanced database access), etc." }, { "code": null, "e": 30329, "s": 30278, "text": "Hibernate (Used in advanced database access), etc." }, { "code": null, "e": 30458, "s": 30329, "text": "These Annotations are aggregated and packaged into a separate jar without any tapestry dependency. Some of the annotations are −" }, { "code": null, "e": 30618, "s": 30458, "text": "@DataType − It is used to specify the data type of the field. Tapestry component may use this information to create design or markup in the presentation layer." }, { "code": null, "e": 30778, "s": 30618, "text": "@DataType − It is used to specify the data type of the field. Tapestry component may use this information to create design or markup in the presentation layer." }, { "code": null, "e": 30845, "s": 30778, "text": "@Validate − It is used to specify the validation rule for a field." }, { "code": null, "e": 30912, "s": 30845, "text": "@Validate − It is used to specify the validation rule for a field." }, { "code": null, "e": 30990, "s": 30912, "text": "These separations enable the Tapestry Application to use a Multi-Tier Design." }, { "code": null, "e": 31317, "s": 30990, "text": "Tapestry Application is simply a collection of Tapestry Pages. They work together to form a well-defined Web Application. Each Page will have a corresponding XML Template and Zero, one or more Components. The Page and Component are same except that the Page is a root component and usually created by an application developer." }, { "code": null, "e": 31459, "s": 31317, "text": "Components are children of the root Pagecomponent. Tapestry have lots of built-in components and has the option to create a custom component." }, { "code": null, "e": 31740, "s": 31459, "text": "As discussed earlier, Pages are building blocks of a Tapestry Application. Pages are plain POJOs, placed under – /src/main/java/«package_path»/pages/ folder. Every Page will have a corresponding XML Template and its default location is – /src/main/resources/«package_name»/pages/." }, { "code": null, "e": 31866, "s": 31740, "text": "You can see here that the path structure is similar for Page and Template except that the template is in the Resource Folder." }, { "code": null, "e": 32031, "s": 31866, "text": "For example, a user registration page in a Tapestry application with package name – com.example.MyFirstApplication will have the following Page and Template files −" }, { "code": null, "e": 32107, "s": 32031, "text": "Java Class −\n/src/main/java/com/example/MyFirstApplication/pages/index.java" }, { "code": null, "e": 32120, "s": 32107, "text": "Java Class −" }, { "code": null, "e": 32183, "s": 32120, "text": "/src/main/java/com/example/MyFirstApplication/pages/index.java" }, { "code": null, "e": 32266, "s": 32183, "text": "XML Template − \n/src/main/resources/com/example/MyFirstApplication/pages/index.tml" }, { "code": null, "e": 32282, "s": 32266, "text": "XML Template − " }, { "code": null, "e": 32349, "s": 32282, "text": "/src/main/resources/com/example/MyFirstApplication/pages/index.tml" }, { "code": null, "e": 32503, "s": 32349, "text": "Let us create a simple Hello World page. First, we need to create a Java Class at – /src/main/java/com/example/MyFirstApplication/pages/HelloWorld.java”." }, { "code": null, "e": 32579, "s": 32503, "text": "package com.example.MyFirstApplication.pages; \npublic class HelloWorld { \n}" }, { "code": null, "e": 32613, "s": 32579, "text": "Then, create an XML Template at –" }, { "code": null, "e": 32689, "s": 32613, "text": "“/src/main/resources/com/example/MyFirstApplication/pages/helloworld.html”." }, { "code": null, "e": 32881, "s": 32689, "text": "<html xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <head> \n <title>Hello World Page</title> \n </head> \n <body> \n <h1>Hello World</h1> \n </body> \n</html>" }, { "code": null, "e": 33101, "s": 32881, "text": "Now, this page can be accessed at https://localhost:8080/myapp/helloworld. This is a simple tapestry page. Tapestry offers lot more features to develop dynamic web pages, which we will discuss in the following chapters." }, { "code": null, "e": 33350, "s": 33101, "text": "Let us consider the Tapestry XML Template in this section. XML Template is a well-formed XML document. The presentation (User Interface) layer of a Page is XML Template. An XML Template have normal HTML markup in addition to the items given below −" }, { "code": null, "e": 33369, "s": 33350, "text": "Tapestry Namespace" }, { "code": null, "e": 33380, "s": 33369, "text": "Expansions" }, { "code": null, "e": 33389, "s": 33380, "text": "Elements" }, { "code": null, "e": 33400, "s": 33389, "text": "Components" }, { "code": null, "e": 33435, "s": 33400, "text": "Let us now discuss them in detail." }, { "code": null, "e": 33697, "s": 33435, "text": "Tapestry Namespaces are nothing but XML Namespaces. Namespaces should be defined in the root element of the template. It is used to include Tapestry Components and component related information in the Template. The most commonly used namespaces are as follows −" }, { "code": null, "e": 33834, "s": 33697, "text": "xmlns:t = “https://tapestry.apache.org/schema/tapestry_5_4.xsd” — It is used to identify Tapestry's Elements, Components and Attributes." }, { "code": null, "e": 33971, "s": 33834, "text": "xmlns:t = “https://tapestry.apache.org/schema/tapestry_5_4.xsd” — It is used to identify Tapestry's Elements, Components and Attributes." }, { "code": null, "e": 34063, "s": 33971, "text": "xmlns:p = “tapestry:parameter” — It is used to pass arbitrary chunks of code to components." }, { "code": null, "e": 34155, "s": 34063, "text": "xmlns:p = “tapestry:parameter” — It is used to pass arbitrary chunks of code to components." }, { "code": null, "e": 34204, "s": 34155, "text": "An example of Tapestry Namespace is as follows −" }, { "code": null, "e": 34499, "s": 34204, "text": "<html xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_3.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <head> \n <title>Hello World Page</title> \n </head> \n <body> \n <h1>Hello World</h1> \n <t:eventlink page = \"Index\">refresh page</t:eventlink> \n </body> \n</html>" }, { "code": null, "e": 34769, "s": 34499, "text": "Expansion is simple and efficient method to dynamically change the XML Template during rendering phase of the Page. Expansion uses ${<name>} syntax. There are many options to express the expansion in the XML Template. Let us see some of the most commonly used options −" }, { "code": null, "e": 35096, "s": 34769, "text": "It maps the property defined in the corresponding Page class. It follows the Java Bean Specification for property definition in a Java class. It goes one step further by ignoring the cases for property name. Let us change the “Hello World” example using property expansion. The following code block is the modified Page class." }, { "code": null, "e": 35258, "s": 35096, "text": "package com.example.MyFirstApplication.pages; \npublic class HelloWorld { \n // Java Bean Property \n public String getName { \n return \"World!\"; \n } \n}" }, { "code": null, "e": 35318, "s": 35258, "text": "Then, change the corresponding XML Template as shown below." }, { "code": null, "e": 35538, "s": 35318, "text": "<html xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <head> \n <title>Hello World Page</title> \n </head> \n <body> \n <!-- expansion --> \n <h1>Hello ${name}</h1> \n </body> \n</html>" }, { "code": null, "e": 35675, "s": 35538, "text": "Here, we have defined name as Java Bean Property in the Page class and dynamically processed it in XML Template using expansion ${name}." }, { "code": null, "e": 35937, "s": 35675, "text": "Each Page class may or may not have an associated Property file – «page_name».properties in the resources folder. The property files are plain text files having a single key / value pair (message) per line. Let us create a property file for HelloWorld Page at –" }, { "code": null, "e": 36048, "s": 35937, "text": "“/src/main/resources/com/example/MyFirstApplication/pages/helloworld.properties” and add a “Greeting” message." }, { "code": null, "e": 36066, "s": 36048, "text": "Greeting = Hello\n" }, { "code": null, "e": 36142, "s": 36066, "text": "The Greeting message can be used in the XML Template as ${message:greeting}" }, { "code": null, "e": 36376, "s": 36142, "text": "<html xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <head> \n <title>Hello World Page</title> \n </head> \n <body> \n <!-- expansion --> \n <h1>${message:greeting} ${name}</h1> \n </body> \n</html>" }, { "code": null, "e": 36511, "s": 36376, "text": "Tapestry has a small set of elements to be used in XML Templates. Elements are predefined tags defined under the Tapestry namespace −" }, { "code": null, "e": 36563, "s": 36511, "text": "https://tapestry.apache.org/schema/tapestry_5_4.xsd" }, { "code": null, "e": 36660, "s": 36563, "text": "Each element is created for a specific purpose. The available tapestry elements are as follows −" }, { "code": null, "e": 36878, "s": 36660, "text": "When two components are nested, the parent component's template may have to wrap the child component's template. The <t:body> element is useful in this situation. One of the uses of <t:body> is in the Template Layout." }, { "code": null, "e": 37317, "s": 36878, "text": "In general, the User Interface of a web application will have a Common Header, Footer, Menu, etc. These common items are defined in an XML Template and it is called Template Layout or Layout Component. In Tapestry, it needs to be created by an application developer. A Layout Component is just another component and is placed under the components folder, which has the following path – src/main/«java|resources»/«package_name»/components." }, { "code": null, "e": 37424, "s": 37317, "text": "Let us create a simple layout component called MyCustomLayout. The code for MyCustomLayout is as follows −" }, { "code": null, "e": 37765, "s": 37424, "text": "<!DOCTYPE html> \n<html xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <head> \n <meta charset = \"UTF-8\" />\n <title>${title}</title> \n </head> \n <body> \n <div>Sample Web Application</div> \n <h1>${title}</h1> \n <t:body/> \n \n <div>(C) 2016 TutorialsPoint.</div> \n </body> \n</html> " }, { "code": null, "e": 38094, "s": 37765, "text": "package com.example.MyFirstApplication.components; \n\nimport org.apache.tapestry5.*; \nimport org.apache.tapestry5.annotations.*; \nimport org.apache.tapestry5.BindingConstants; \n\npublic class MyCustomLayout { \n @Property \n @Parameter(required = true, defaultPrefix = BindingConstants.LITERAL) \n private String title; \n}" }, { "code": null, "e": 38307, "s": 38094, "text": "In the MyCustomLayout component class, we declared a title field and by using annotation, we have made it mandatory. Now, change HelloWorld.html template to use our custom layout as shown in the code block below." }, { "code": null, "e": 38495, "s": 38307, "text": "<html>\n t:type = \"mycustomlayout\" title = \"Hello World Test page\"\n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <h1>${message:greeting} ${name}</h1> \n</html>" }, { "code": null, "e": 38795, "s": 38495, "text": "We can see here that the XML Template does not have head and body tags. Tapestry will collect these details from the layout component and the <t:body> of the layout component will be replaced by the HelloWorld Template. Once everything is done, Tapestry will emit similar markup as specified below −" }, { "code": null, "e": 39103, "s": 38795, "text": "<!DOCTYPE html> \n<html> \n <head> \n <meta charset = \"UTF-8\" /> \n <title>Hello World Test Page</title> \n </head> \n <body> \n <div>Sample Web Application</div> \n <h1>Hello World Test Page</h1> \n <h1>Hello World!</h1> \n <div>(C) 2016 TutorialsPoint.</div> \n </body> \n</html>" }, { "code": null, "e": 39262, "s": 39103, "text": "Layouts can be nested. For example, we may extend our custom layout by including administration functionality and use it for admin section as specified below." }, { "code": null, "e": 39435, "s": 39262, "text": "<html t:type = \"MyCommonLayout\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n \n <div><!-- Admin related items --><div> \n <t:body/> \n \n</html>" }, { "code": null, "e": 39571, "s": 39435, "text": "The <t:container> is a top-level element and includes a tapestry namespace. This is used to specify the dynamic section of a component." }, { "code": null, "e": 39698, "s": 39571, "text": "For example, a grid component may need a template to identify how to render its rows - tr (and column td) within a HTML table." }, { "code": null, "e": 39832, "s": 39698, "text": "<t:container xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <td>${name}</td> \n <td>${age}</td> \n</t:container>" }, { "code": null, "e": 40120, "s": 39832, "text": "The <t:block> is a placeholder for a dynamic section in the template. Generally, block element does not render. Only, components defined in the template uses block element. Components will inject data dynamically into the block element and render it. One of the popular use case is AJAX." }, { "code": null, "e": 40431, "s": 40120, "text": "The block element provides the exact position and markup for the dynamic data to be rendered. Every block element should have a corresponding Java Property. Only then it can be dynamically rendered. The id of the block element should follow Java variable identifier rules. The partial sample is provided below." }, { "code": null, "e": 40882, "s": 40431, "text": "@Inject \nprivate Block block; \n<html t:type = \"mycustomlayout\" title = \"block example\" \n xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n<h1>${title}</h1> \n<!-- \n ... \n ... \n--> \n<t:block t:id = \"block\"> \n <h2>Highly dynamic section</h2> \n I'v been updated through AJAX call \n The current time is: <strong>${currentTime}</strong>\n</t:block> \n<!-- \n ... \n ... \n--> \n</html>" }, { "code": null, "e": 41178, "s": 40882, "text": "The <t:content> element is used to specify the actual content of the template. In general, all the markup is considered part of the template. If <t:content> is specified, only the markup inside it will be considered. This feature is used by designers to design a page without a layout component." }, { "code": null, "e": 41379, "s": 41178, "text": "The <t:remove> is just the opposite of content element. The markup inside the remove element is not considered part of the template. It can be used for server only comments and for designing purposes." }, { "code": null, "e": 41548, "s": 41379, "text": "Assets are static resource files such as style sheets, images and JavaScript files. Generally, assets are placed in the web application root directory /src/main/webapp." }, { "code": null, "e": 41628, "s": 41548, "text": "<head> \n <link href = \"/css/site.css\" rel = \"stylesheet\" type = \"text/css\"/>\n" }, { "code": null, "e": 41792, "s": 41628, "text": "Tapestry also treats files stored in the Java Classpath as Assets. Tapestry provides advanced options to include Assets into the template through expansion option." }, { "code": null, "e": 41849, "s": 41792, "text": "Context − Option to get assets available in web context." }, { "code": null, "e": 41906, "s": 41849, "text": "Context − Option to get assets available in web context." }, { "code": null, "e": 41974, "s": 41906, "text": "<img src = \"${context:image/tapestry_banner.gif}\" alt = \"Banner\"/>\n" }, { "code": null, "e": 42323, "s": 41974, "text": "asset − Components usually store its own assets inside the jar file along with Java classes. Starting from Tapestry 5.4, the standard path to store assets in classpath is META-INF/assets. For libraries, the standard path to store assets is META-INF/assets/«library_name»/. asset: can also call context: expansion to get assets from the web context." }, { "code": null, "e": 42397, "s": 42323, "text": "<img src = \"${asset:context:image/tapestry_banner.gif}\" alt = \"Banner\"/>\n" }, { "code": null, "e": 42560, "s": 42397, "text": "Assets can be injected into the Tapestry Page or Component using Inject and Path annotation. The parameter for the Path annotation is relative path of the assets." }, { "code": null, "e": 42616, "s": 42560, "text": "@Inject \n@Path(\"images/edit.png\") \nprivate Asset icon;\n" }, { "code": null, "e": 42708, "s": 42616, "text": "The Path parameter can also contain Tapestry symbols defined in the AppModule.java section." }, { "code": null, "e": 42814, "s": 42708, "text": "For example, we can define a symbol, skin.root with value context:skins/basic and use it as shown below −" }, { "code": null, "e": 42878, "s": 42814, "text": "@Inject \n@Path(\"${skin.root}/style.css\") \nprivate Asset style;\n" }, { "code": null, "e": 43060, "s": 42878, "text": "Including resources through tapestry provides extra functionality. One such functionality is “Localization”. Tapestry will check the current locale and include the proper resources." }, { "code": null, "e": 43164, "s": 43060, "text": "For example, if the current locale is set as de, then edit_de.png will be included instead of edit.png." }, { "code": null, "e": 43497, "s": 43164, "text": "Tapestry has built-in style sheet support. Tapestry will inject tapestry.css as a part of the core Javascript stack. From Tapestry 5.4, tapestry includes bootstrap css framework as well. We can include our own style sheet using normal link tag. In this case, the style sheets should be in the web root directory – /src/main/webapp/." }, { "code": null, "e": 43577, "s": 43497, "text": "<head> \n <link href = \"/css/site.css\" rel = \"stylesheet\" type = \"text/css\"/>\n" }, { "code": null, "e": 43701, "s": 43577, "text": "Tapestry provides advanced options to include style sheets into the template through expansion option as discussed earlier." }, { "code": null, "e": 43792, "s": 43701, "text": "<head> \n <link href = \"${context:css/site.css}\" rel = \"stylesheet\" type = \"text/css\"/> \n" }, { "code": null, "e": 43888, "s": 43792, "text": "Tapestry also provides Import annotation to include style sheet directly into the Java classes." }, { "code": null, "e": 43966, "s": 43888, "text": "@Import(stylesheet=\"context:css/site.css\") \npublic class MyCommonLayout { \n} " }, { "code": null, "e": 44083, "s": 43966, "text": "Tapestry provides a lot of options to manage style sheet through AppModule.java. Some of the important options are −" }, { "code": null, "e": 44132, "s": 44083, "text": "The tapestry default style sheet may be removed." }, { "code": null, "e": 44181, "s": 44132, "text": "The tapestry default style sheet may be removed." }, { "code": null, "e": 44380, "s": 44181, "text": "@Contribute(MarkupRenderer.class) \n\npublic static void \ndeactiveDefaultCSS(OrderedConfiguration<MarkupRendererFilter> configuration) { \n configuration.override(\"InjectDefaultStyleheet\", null); \n} " }, { "code": null, "e": 44435, "s": 44380, "text": "Bootstrap can also be disabled by overriding its path." }, { "code": null, "e": 44490, "s": 44435, "text": "Bootstrap can also be disabled by overriding its path." }, { "code": null, "e": 44571, "s": 44490, "text": "configuration.add(SymbolConstants.BOOTSTRAP_ROOT, \"classpath:/METAINF/assets\");\n" }, { "code": null, "e": 44707, "s": 44571, "text": "Enable dynamic minimizing of the assets (CSS and JavaScript). We need to include tapestry-webresources dependency (in pom.xml) as well." }, { "code": null, "e": 44843, "s": 44707, "text": "Enable dynamic minimizing of the assets (CSS and JavaScript). We need to include tapestry-webresources dependency (in pom.xml) as well." }, { "code": null, "e": 45236, "s": 44843, "text": "@Contribute(SymbolProvider.class) \n@ApplicationDefaults \n\npublic static void contributeApplicationDefaults( \n MappedConfiguration<String, String> configuration) { \n \n configuration.add(SymbolConstants.MINIFICATION_ENABLED, \"true\"); \n} \n\n<dependency> \n <groupId>org.apache.tapestry</groupId> \n <artifactId>tapestry-webresources</artifactId> \n <version>5.4</version> \n</dependency> " }, { "code": null, "e": 45527, "s": 45236, "text": "The current generation of web application heavily depends on JavaScript to provide rich client side experience. Tapestry acknowledges it and provide first class support for JavaScript. JavaScript support is deeply ingrained into the tapestry and available at every phase of the programming." }, { "code": null, "e": 46040, "s": 45527, "text": "Earlier, Tapestry used to support only Prototype and Scriptaculous. But, from version 5.4, tapestry completely rewritten the JavaScript layer to make it as generic as possible and provide first class support for JQuery, the de-facto library for JavaScript. Also, tapestry encourages Modules based JavaScript programming and supports RequireJS, a popular client side implementation of AMD (Asynchronous Module Definition - JavaScript specification to support modules and its dependency in an asynchronous manner)." }, { "code": null, "e": 46258, "s": 46040, "text": "JavaScript files are assets of the Tapestry Application. In accordance with asset rules, JavaScript files are placed either under web context, /sr/main/webapp/ or placed inside the jar under META-INF/assets/ location." }, { "code": null, "e": 46618, "s": 46258, "text": "The simplest way to link JavaScript files in the XML Template is by directly using the script tag, which is − <script language = \"javascript\" src = \"relative/path/to/js\"></script>. But, tapestry does not recommend these approaches. Tapestry provides several options to link JavaScript files right in the Page / Component itself. Some of these are given below." }, { "code": null, "e": 46990, "s": 46618, "text": "@import annotation − @import annotation provides option to link multiple JavaScript library using context expression. It can be applied to both Page class and its method. If applied to a Page class, it applies to all its methods. If applied to a Page's Method, it only applies to that method and then Tapestry links the JavaScript library only when the method is invoked." }, { "code": null, "e": 47362, "s": 46990, "text": "@import annotation − @import annotation provides option to link multiple JavaScript library using context expression. It can be applied to both Page class and its method. If applied to a Page class, it applies to all its methods. If applied to a Page's Method, it only applies to that method and then Tapestry links the JavaScript library only when the method is invoked." }, { "code": null, "e": 47475, "s": 47362, "text": "@Import(library = {\"context:js/jquery.js\",\"context:js/myeffects.js\"}) \n\npublic class MyComponent { \n // ... \n}" }, { "code": null, "e": 47749, "s": 47475, "text": "JavaScriptSupport interface − The JavaScriptSupport is an interface defined by tapestry and it has a method, importJavaScriptLibrary to import JavaScript files. JavScriptSupport object can be easily created by simply declaring and annotating with @Environmental annotation." }, { "code": null, "e": 48023, "s": 47749, "text": "JavaScriptSupport interface − The JavaScriptSupport is an interface defined by tapestry and it has a method, importJavaScriptLibrary to import JavaScript files. JavScriptSupport object can be easily created by simply declaring and annotating with @Environmental annotation." }, { "code": null, "e": 48239, "s": 48023, "text": "@Inject @Path(\"context:/js/myeffects.js\") \nprivate Asset myEffects; \n\n@Environmental \nprivate JavaScriptSupport javaScriptSupport; \nvoid setupRender() { \n javaScriptSupport.importJavaScriptLibrary(myEffects); \n}" }, { "code": null, "e": 48442, "s": 48239, "text": "JavaScripSupport can only be injected into a component using the @Environmental annotation. For services, we need to use an @Inject annotation or add it as an argument in the service constructor method." }, { "code": null, "e": 48645, "s": 48442, "text": "JavaScripSupport can only be injected into a component using the @Environmental annotation. For services, we need to use an @Inject annotation or add it as an argument in the service constructor method." }, { "code": null, "e": 48764, "s": 48645, "text": "@Inject \nprivate JavaScriptSupport javaScriptSupport; \npublic MyServiceImpl(JavaScriptSupport support) { \n // ... \n}" }, { "code": null, "e": 48947, "s": 48764, "text": "addScript method − This is similar to the JavaScriptSupport interface except that it uses the addScript method and the code is directly added to the output at the bottom of the page." }, { "code": null, "e": 49130, "s": 48947, "text": "addScript method − This is similar to the JavaScriptSupport interface except that it uses the addScript method and the code is directly added to the output at the bottom of the page." }, { "code": null, "e": 49258, "s": 49130, "text": "void afterRender() { \n javaScriptSupport.addScript(\n \"$('%s').observe('click', hideMe());\", container.getClientId()); \n}" }, { "code": null, "e": 49443, "s": 49258, "text": "Tapestry allows a group of JavaScript files and related style sheets to be combined and used as one single entity. Currently, Tapestry includes Prototype based and JQuery based stacks." }, { "code": null, "e": 49642, "s": 49443, "text": "A developer can develop their own stacks by implementing the JavaScriptStack interface and register it in the AppModule.java. Once registered, the stack can be imported using the @import annotation." }, { "code": null, "e": 49900, "s": 49642, "text": "@Contribute(JavaScriptStackSource.class) \npublic static void addMyStack(\n MappedConfiguration<String, JavaScriptStack> configuration) { \n \n configuration.addInstance(\"MyStack\", myStack.class); \n} \n\n@Import(stack = \"MyStack\") \npublic class myPage { \n}" }, { "code": null, "e": 50139, "s": 49900, "text": "As discussed earlier, Components and Pages are the same except that the Page is the root component and includes one or more child components. Components always resides inside a page and do almost all the dynamic functionality of the page." }, { "code": null, "e": 50341, "s": 50139, "text": "Tapestry components renders a simple HTML links to complex grid functionality with interactive AJAX. A Component can include another component as well. Tapestry components consists of following items −" }, { "code": null, "e": 50397, "s": 50341, "text": "Component Class − The main Java class of the component." }, { "code": null, "e": 50453, "s": 50397, "text": "Component Class − The main Java class of the component." }, { "code": null, "e": 50719, "s": 50453, "text": "XML Template − XML template is similar to the Page template. The component class renders the template as the final output. Some components may not have templates. In this case, the output will be generated by the component class itself using the MarkupWriter class." }, { "code": null, "e": 50985, "s": 50719, "text": "XML Template − XML template is similar to the Page template. The component class renders the template as the final output. Some components may not have templates. In this case, the output will be generated by the component class itself using the MarkupWriter class." }, { "code": null, "e": 51297, "s": 50985, "text": "Body − The component specified inside the page template may have custom markup and it is called “Component body”. If the component template has <body /> element, then the <body /> element will be replaced by the body of the component. This is similar to the layout discussed earlier in the XML template section." }, { "code": null, "e": 51609, "s": 51297, "text": "Body − The component specified inside the page template may have custom markup and it is called “Component body”. If the component template has <body /> element, then the <body /> element will be replaced by the body of the component. This is similar to the layout discussed earlier in the XML template section." }, { "code": null, "e": 51737, "s": 51609, "text": "Rendering − Rendering is a process which transforms XML template and body of the component into actual output of the component." }, { "code": null, "e": 51865, "s": 51737, "text": "Rendering − Rendering is a process which transforms XML template and body of the component into actual output of the component." }, { "code": null, "e": 51972, "s": 51865, "text": "Parameters − Used to create communication between component & pages and thereby passing data between them." }, { "code": null, "e": 52079, "s": 51972, "text": "Parameters − Used to create communication between component & pages and thereby passing data between them." }, { "code": null, "e": 52235, "s": 52079, "text": "Events − Delegates functionality from components to its container / parent (pages or another component). It is extensively used in page navigation purpose." }, { "code": null, "e": 52391, "s": 52235, "text": "Events − Delegates functionality from components to its container / parent (pages or another component). It is extensively used in page navigation purpose." }, { "code": null, "e": 52593, "s": 52391, "text": "The rendering of a component is done in a series of pre-defined phases. Each phase in the component system should have a corresponding method defined by convention or annotation in the component class." }, { "code": null, "e": 52763, "s": 52593, "text": "// Using annotaion \n@SetupRender \nvoid initializeValues() { \n // initialize values \n}\n\n// using convention \nboolean afterRender() { \n // do logic \n return true; \n}" }, { "code": null, "e": 52829, "s": 52763, "text": "The phases, its method name and its annotations are listed below." }, { "code": null, "e": 52889, "s": 52829, "text": "Each phase has a specific purpose and they are as follows −" }, { "code": null, "e": 52988, "s": 52889, "text": "SetupRender kick-starts the rendering process. It usually sets up the parameters of the component." }, { "code": null, "e": 53091, "s": 52988, "text": "BeginRender starts rendering the component. It usually renders the begin / start tag of the component." }, { "code": null, "e": 53252, "s": 53091, "text": "BeforeRenderTemplate is used to decorate the XML template, adding special markup around the template. It also provides an option to skip the template rendering." }, { "code": null, "e": 53347, "s": 53252, "text": "BeforeRenderTemplate provides an option to skip the rendering of the component's body element." }, { "code": null, "e": 53418, "s": 53347, "text": "AfterRenderBody will be called after the component's body is rendered." }, { "code": null, "e": 53497, "s": 53418, "text": "AfterRenderTemplate will be called after the component's template is rendered." }, { "code": null, "e": 53582, "s": 53497, "text": "AfterRender is the counterpart of the BeginRender and usually renders the close tag." }, { "code": null, "e": 53708, "s": 53582, "text": "CleanupRender is the counterpart of the SetupRender. It releases / disposes all the objects created during rendering process." }, { "code": null, "e": 53838, "s": 53708, "text": "The flow of the rendering phases is not forward only. It goes to and fro between phases depending on the return value of a phase." }, { "code": null, "e": 54067, "s": 53838, "text": "For example, if the SetupRender method returns false, then rendering jumps to the CleanupRender phase and vice versa. To find a clear understanding of the flow between different phases, check the flow in the diagram given below." }, { "code": null, "e": 54227, "s": 54067, "text": "Let us create a simple component, Hello which will have the output message as “Hello, Tapestry”. Following is the code of the Hello component and its template." }, { "code": null, "e": 54305, "s": 54227, "text": "package com.example.MyFirstApplication.components; \npublic class Hello { \n}" }, { "code": null, "e": 54500, "s": 54305, "text": "<html \n xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <div> \n <p>Hello, Tapestry (from component).</p> \n </div> \n \n</html>" }, { "code": null, "e": 54558, "s": 54500, "text": "The Hello component can be called in a page template as −" }, { "code": null, "e": 54727, "s": 54558, "text": "<html title = \"Hello component test page\" \n xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n<t:hello /> \n</html>" }, { "code": null, "e": 54838, "s": 54727, "text": "Similarly, the component may render the same output using MarkupWriter instead of the template as shown below." }, { "code": null, "e": 55150, "s": 54838, "text": "package com.example.MyFirstApplication.components; \n \nimport org.apache.tapestry5.MarkupWriter; \nimport org.apache.tapestry5.annotations.BeginRender; \n\npublic class Hello { \n @BeginRender \n void renderMessage(MarkupWriter writer) { \n writer.write(\"<p>Hello, Tapestry (from component)</p>\"); \n } \n}" }, { "code": null, "e": 55254, "s": 55150, "text": "Let us change the component template and include the <body /> element as shown in the code block below." }, { "code": null, "e": 55418, "s": 55254, "text": "<html> \n xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <div> \n <t:body /> \n </div> \n</html>" }, { "code": null, "e": 55498, "s": 55418, "text": "Now, the page template may include body in the component markup as shown below." }, { "code": null, "e": 55729, "s": 55498, "text": "<html title = \"Hello component test page\" \n xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <t:hello> \n <p>Hello, Tapestry (from page).</p> \n </t:hello> \n</html>" }, { "code": null, "e": 55761, "s": 55729, "text": "The output will be as follows −" }, { "code": null, "e": 55841, "s": 55761, "text": "<html> \n <div> \n <p>Hello, Tapestry (from page).</p> \n </div> \n</html>" }, { "code": null, "e": 56121, "s": 55841, "text": "The primary purpose of these parameters is to create a connection between a field of the component and a property / resource of the page. Using parameters, component and its corresponding page communicate and transfer data between each other. This is called Two Way Data Binding." }, { "code": null, "e": 56412, "s": 56121, "text": "For example, a textbox component used to represent the age in a user management page gets its initial value (available in the database) through the parameter. Again, after the user's age is updated and submitted back, the component will send back the updated age through the same parameter." }, { "code": null, "e": 56571, "s": 56412, "text": "To create a new parameter in the component class, declare a field and specify a @Parameter annotation. This @Parameter has two optional arguments, which are −" }, { "code": null, "e": 56665, "s": 56571, "text": "required − makes the parameter as mandatory. Tapestry raises exception if it is not provided." }, { "code": null, "e": 56759, "s": 56665, "text": "required − makes the parameter as mandatory. Tapestry raises exception if it is not provided." }, { "code": null, "e": 56813, "s": 56759, "text": "value − specifies the default value of the parameter." }, { "code": null, "e": 56867, "s": 56813, "text": "value − specifies the default value of the parameter." }, { "code": null, "e": 57141, "s": 56867, "text": "The parameter should be specified in the page template as attributes of the component tag. The value of the attributes should be specified using Binding Expression / Expansion, which we discussed in the earlier chapters. Some of the expansion which we learned earlier are −" }, { "code": null, "e": 57221, "s": 57141, "text": "Property expansion (prop:«val») − Get the data from property of the page class." }, { "code": null, "e": 57301, "s": 57221, "text": "Property expansion (prop:«val») − Get the data from property of the page class." }, { "code": null, "e": 57393, "s": 57301, "text": "Message expansion (message:«val») − Get the data from key defined in index.properties file." }, { "code": null, "e": 57485, "s": 57393, "text": "Message expansion (message:«val») − Get the data from key defined in index.properties file." }, { "code": null, "e": 57576, "s": 57485, "text": "Context expansion (context:«val») − Get the data from web context folder /src/main/webapp." }, { "code": null, "e": 57667, "s": 57576, "text": "Context expansion (context:«val») − Get the data from web context folder /src/main/webapp." }, { "code": null, "e": 57767, "s": 57667, "text": "Asset expansion (asset:«val») − Get the data from resources embedded in jar file, /META-INF/assets." }, { "code": null, "e": 57867, "s": 57767, "text": "Asset expansion (asset:«val») − Get the data from resources embedded in jar file, /META-INF/assets." }, { "code": null, "e": 57958, "s": 57867, "text": "Symbol expansion (symbol:«val») − Get the data from symbols defined in AppModule.javafile." }, { "code": null, "e": 58049, "s": 57958, "text": "Symbol expansion (symbol:«val») − Get the data from symbols defined in AppModule.javafile." }, { "code": null, "e": 58123, "s": 58049, "text": "Tapestry has many more useful expansions, some of which are given below −" }, { "code": null, "e": 58177, "s": 58123, "text": "Literal expansion (literal:«val») − A literal string." }, { "code": null, "e": 58231, "s": 58177, "text": "Literal expansion (literal:«val») − A literal string." }, { "code": null, "e": 58323, "s": 58231, "text": "Var expansion (var:«val») − Allow a render variable of the component to be read or updated." }, { "code": null, "e": 58415, "s": 58323, "text": "Var expansion (var:«val») − Allow a render variable of the component to be read or updated." }, { "code": null, "e": 58571, "s": 58415, "text": "Validate expansion (validate:«val») − A specialized string used to specify the validation rule of an object. For Example, validate:required, minLength = 5." }, { "code": null, "e": 58727, "s": 58571, "text": "Validate expansion (validate:«val») − A specialized string used to specify the validation rule of an object. For Example, validate:required, minLength = 5." }, { "code": null, "e": 58870, "s": 58727, "text": "Translate (translate:«val») − Used to specify the Translator class (converting client-side to server-side representation) in input validation." }, { "code": null, "e": 59013, "s": 58870, "text": "Translate (translate:«val») − Used to specify the Translator class (converting client-side to server-side representation) in input validation." }, { "code": null, "e": 59084, "s": 59013, "text": "Block (block:«val») − The id of the block element within the template." }, { "code": null, "e": 59155, "s": 59084, "text": "Block (block:«val») − The id of the block element within the template." }, { "code": null, "e": 59238, "s": 59155, "text": "Component (component:«val») − The id of the another component within the template." }, { "code": null, "e": 59321, "s": 59238, "text": "Component (component:«val») − The id of the another component within the template." }, { "code": null, "e": 59599, "s": 59321, "text": "All the above expansions are read-only except Property expansion and Var expansion. They are used by the component to exchange data with page. When using expansion as attribute values, ${...} should not be used. Instead just use the expansion without dollar and braces symbols." }, { "code": null, "e": 59833, "s": 59599, "text": "Let us create a new component, HelloWithParameter by modifying the Hello component to dynamically render the message by adding a name parameter in the component class and changing the component template and page template accordingly." }, { "code": null, "e": 59887, "s": 59833, "text": "Create a new component class HelloWithParameter.java." }, { "code": null, "e": 59941, "s": 59887, "text": "Create a new component class HelloWithParameter.java." }, { "code": null, "e": 60053, "s": 59941, "text": "Add a private field and name it with the @Parameter annotation. Use the required argument to make it mandatory." }, { "code": null, "e": 60165, "s": 60053, "text": "Add a private field and name it with the @Parameter annotation. Use the required argument to make it mandatory." }, { "code": null, "e": 60216, "s": 60165, "text": "@Parameter(required = true) \nprivate String name;\n" }, { "code": null, "e": 60542, "s": 60216, "text": "Add a private field, result with @Propery annotation. The result property will be used in the component template. Component template does not have access to fields annotated with @Parameter and only able to access the fields annotated with @Property. The variable available in component templates are called Render Variables." }, { "code": null, "e": 60868, "s": 60542, "text": "Add a private field, result with @Propery annotation. The result property will be used in the component template. Component template does not have access to fields annotated with @Parameter and only able to access the fields annotated with @Property. The variable available in component templates are called Render Variables." }, { "code": null, "e": 60904, "s": 60868, "text": "@Property \n private String result;\n" }, { "code": null, "e": 60991, "s": 60904, "text": "Add a RenderBody method and copy the value from the name parameter to result property." }, { "code": null, "e": 61078, "s": 60991, "text": "Add a RenderBody method and copy the value from the name parameter to result property." }, { "code": null, "e": 61140, "s": 61078, "text": "@BeginRender \nvoid initializeValues() { \n result = name; \n}" }, { "code": null, "e": 61242, "s": 61140, "text": "Add a new component template HelloWithParamter.tml and use the result property to render the message." }, { "code": null, "e": 61344, "s": 61242, "text": "Add a new component template HelloWithParamter.tml and use the result property to render the message." }, { "code": null, "e": 61375, "s": 61344, "text": "<div> Hello, ${result} </div>\n" }, { "code": null, "e": 61439, "s": 61375, "text": "Add a new property, Username in the test page (testhello.java)." }, { "code": null, "e": 61503, "s": 61439, "text": "Add a new property, Username in the test page (testhello.java)." }, { "code": null, "e": 61556, "s": 61503, "text": "public String getUsername() { \n return \"User1\"; \n}" }, { "code": null, "e": 61690, "s": 61556, "text": "Use the newly created component in the page template and set the Username property in name parameter of HelloWithParameter component." }, { "code": null, "e": 61824, "s": 61690, "text": "Use the newly created component in the page template and set the Username property in name parameter of HelloWithParameter component." }, { "code": null, "e": 61869, "s": 61824, "text": "<t:helloWithParameter name = \"username\" /> \n" }, { "code": null, "e": 61906, "s": 61869, "text": "The complete listing is as follows −" }, { "code": null, "e": 62225, "s": 61906, "text": "package com.example.MyFirstApplication.components; \n\nimport org.apache.tapestry5.annotations.*; \npublic class HelloWithParameter { \n @Parameter(required = true) \n private String name; \n \n @Property \n private String result; \n \n @BeginRender \n void initializeValues() { \n result = name; \n } \n}" }, { "code": null, "e": 62386, "s": 62225, "text": "<html \n xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <div> Hello, ${result} </div> \n \n</html>" }, { "code": null, "e": 62571, "s": 62386, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.*; \npublic class TestHello { \n public String getUsername() { \n return \"User1\"; \n } \n}" }, { "code": null, "e": 62777, "s": 62571, "text": "<html title = \"Hello component test page\" \n xmlns:t = \"https://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n <t:helloWithParameter name = \"username\" />\n \n</html> " }, { "code": null, "e": 62809, "s": 62777, "text": "The result will be as follows −" }, { "code": null, "e": 62836, "s": 62809, "text": "<div> Hello, User1 </div>\n" }, { "code": null, "e": 63323, "s": 62836, "text": "In the previous chapters, we analyzed how to create and use a simple parameter in a custom component. An advanced parameter may contain complete markup as well. In this case, the markup should be specified inside the component tag such as the sub-section in the page template. The built-in if component have markup for both success and failure condition. The markup for success is specified as the body of the component tag and the markup of failure is specified using an elseparameter." }, { "code": null, "e": 63401, "s": 63323, "text": "Let us see how to use the if component. The if component has two parameters −" }, { "code": null, "e": 63441, "s": 63401, "text": "test − Simple property based parameter." }, { "code": null, "e": 63481, "s": 63441, "text": "test − Simple property based parameter." }, { "code": null, "e": 63566, "s": 63481, "text": "Else − Advanced parameter used to specify alternative markup, if the condition fails" }, { "code": null, "e": 63651, "s": 63566, "text": "Else − Advanced parameter used to specify alternative markup, if the condition fails" }, { "code": null, "e": 63862, "s": 63651, "text": "Tapestry will check the value of the test property using the following logic and return true or false. This is called Type Coercion, a way to convert an object of one type to another type with the same content." }, { "code": null, "e": 63965, "s": 63862, "text": "If the data type is String, “True” if non-blank and not the literal string “False” (case insensitive)." }, { "code": null, "e": 64068, "s": 63965, "text": "If the data type is String, “True” if non-blank and not the literal string “False” (case insensitive)." }, { "code": null, "e": 64114, "s": 64068, "text": "If the data type is Number, True if non-zero." }, { "code": null, "e": 64160, "s": 64114, "text": "If the data type is Number, True if non-zero." }, { "code": null, "e": 64211, "s": 64160, "text": "If the data type is Collection, True if non-empty." }, { "code": null, "e": 64262, "s": 64211, "text": "If the data type is Collection, True if non-empty." }, { "code": null, "e": 64323, "s": 64262, "text": "If the data type is Object, True (as long as it’s not null)." }, { "code": null, "e": 64384, "s": 64323, "text": "If the data type is Object, True (as long as it’s not null)." }, { "code": null, "e": 64495, "s": 64384, "text": "If the condition passes, the component renders its body; otherwise, it renders the body of the else parameter." }, { "code": null, "e": 64532, "s": 64495, "text": "The complete listing is as follows −" }, { "code": null, "e": 64663, "s": 64532, "text": "package com.example.MyFirstApplication.pages; \npublic class TestIf { \n public String getUser() { \n return \"User1\"; \n } \n}" }, { "code": null, "e": 65040, "s": 64663, "text": "<html title = \"If Test Page\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <body> \n <h1>Welcome!</h1> \n <t:if test = \"user\"> \n Welcome back, ${user} \n <p:else>\n Please <t:pagelink page = \"login\">Login</t:pagelink> \n </p:else> \n </t:if>\n </body>\n \n</html>" }, { "code": null, "e": 65401, "s": 65040, "text": "Tapestry application is a collection of Pages interacting with each other. Till now, we have learned how to create individual pages without any communication between them. A Component event's primary purpose is to provide interaction between pages (within pages as well) using server-side events. Most of the component events originate from client-side events." }, { "code": null, "e": 65704, "s": 65401, "text": "For example, when a user clicks a link in a page, Tapestry will call the same page itself with target information instead of calling the target page and raises a server side event. Tapestry page will capture the event, process the target information and do a server side redirection to the target page." }, { "code": null, "e": 66224, "s": 65704, "text": "Tapestry follows a Post/Redirect/Get (RPG) design pattern for page navigation. In RPG, when a user does a post request by submitting a form, the server will process the posted data, but does not return the response directly. Instead, it will do a client-side redirection to another page, which will output the result. An RPG pattern is used to prevent duplicate form submissions through browser back button, browser refresh button, etc., Tapestry provides an RPG pattern by providing the following two types of request." }, { "code": null, "e": 66423, "s": 66224, "text": "Component Event Request − This type of request targets a particular component in a page and raises events within the component. This request only does a redirection and does not output the response." }, { "code": null, "e": 66622, "s": 66423, "text": "Component Event Request − This type of request targets a particular component in a page and raises events within the component. This request only does a redirection and does not output the response." }, { "code": null, "e": 66721, "s": 66622, "text": "Render Request − These types of requests target a page and stream the response back to the client." }, { "code": null, "e": 66820, "s": 66721, "text": "Render Request − These types of requests target a page and stream the response back to the client." }, { "code": null, "e": 66991, "s": 66820, "text": "To understand the component events and page navigation, we need to know the URL pattern of the tapestry request. The URL pattern for both types of request is as follows −" }, { "code": null, "e": 67018, "s": 66991, "text": "Component Event Requests −" }, { "code": null, "e": 67045, "s": 67018, "text": "Component Event Requests −" }, { "code": null, "e": 67121, "s": 67045, "text": "/<<page_name_with_path>>.<<component_id|event_id>>/<<context_information>>\n" }, { "code": null, "e": 67138, "s": 67121, "text": "Render Request −" }, { "code": null, "e": 67155, "s": 67138, "text": "Render Request −" }, { "code": null, "e": 67205, "s": 67155, "text": "/<<page_name_with_path>>/<<context_information>>\n" }, { "code": null, "e": 67252, "s": 67205, "text": "Some of the examples of the URL patterns are −" }, { "code": null, "e": 67313, "s": 67252, "text": "Index page can be requested by https://«domain»/«app»/index." }, { "code": null, "e": 67374, "s": 67313, "text": "Index page can be requested by https://«domain»/«app»/index." }, { "code": null, "e": 67495, "s": 67374, "text": "If the Index page is available under a sub-folder admin, then it can be requested by https://«domain»/«app»/admin/index." }, { "code": null, "e": 67616, "s": 67495, "text": "If the Index page is available under a sub-folder admin, then it can be requested by https://«domain»/«app»/admin/index." }, { "code": null, "e": 67751, "s": 67616, "text": "If the user clicks on the ActionLink component with id test in the index page, then the URL will be https://«domain»/«app»/index.test." }, { "code": null, "e": 67886, "s": 67751, "text": "If the user clicks on the ActionLink component with id test in the index page, then the URL will be https://«domain»/«app»/index.test." }, { "code": null, "e": 68202, "s": 67886, "text": "By default, Tapestry raises OnPassivate and OnActivate events for all requests. For Component event request type, tapestry raises additional one or more events depending on the component. The ActionLink component raises an Action event, while a Form component raises multiple events such as Validate, Success, etc.," }, { "code": null, "e": 68472, "s": 68202, "text": "The events can be handled in the page class using the corresponding method handler. The method handler is created either through a method naming convention or through the @OnEvent annotation. The format of the method naming convention is On«EventName»From«ComponentId»." }, { "code": null, "e": 68585, "s": 68472, "text": "An action event of the ActionLink component with id test can be handled by either one of the following methods −" }, { "code": null, "e": 68695, "s": 68585, "text": "void OnActionFromTest() { \n} \n@OnEvent(component = \"test\", name = \"action\") \nvoid CustomFunctionName() { \n} " }, { "code": null, "e": 68825, "s": 68695, "text": "If the method name does not have any particular component, then the method will be called for all component with matching events." }, { "code": null, "e": 68847, "s": 68825, "text": "void OnAction() { \n} " }, { "code": null, "e": 69051, "s": 68847, "text": "OnPassivate is used to provide context information for an OnActivate event handler. In general, Tapestry provides the context information and it can be used as an argument in the OnActivateevent handler." }, { "code": null, "e": 69154, "s": 69051, "text": "For example, if the context information is 3 of type int, then the OnActivate event can be called as −" }, { "code": null, "e": 69184, "s": 69154, "text": "void OnActivate(int id) { \n} " }, { "code": null, "e": 69474, "s": 69184, "text": "In some scenario, the context information may not be available. In this situation, we can provide the context information to OnActivate event handler through OnPassivate event handler. The return type of the OnPassivate event handler should be used as argument of OnActivate event handler." }, { "code": null, "e": 69559, "s": 69474, "text": "int OnPassivate() { \n int id = 3; \n return id; \n} \nvoid OnActivate(int id) { \n} " }, { "code": null, "e": 69702, "s": 69559, "text": "Tapestry issues page redirection based on the return values of the event handler. Event handler should return any one of the following values." }, { "code": null, "e": 69819, "s": 69702, "text": "Null Response − Returns null value. Tapestry will construct the current page URL and send to the client as redirect." }, { "code": null, "e": 69936, "s": 69819, "text": "Null Response − Returns null value. Tapestry will construct the current page URL and send to the client as redirect." }, { "code": null, "e": 69983, "s": 69936, "text": "public Object onAction() { \n return null; \n}" }, { "code": null, "e": 70126, "s": 69983, "text": "String Response − Returns the string value. Tapestry will construct the URL of the page matching the value and send to the client as redirect." }, { "code": null, "e": 70269, "s": 70126, "text": "String Response − Returns the string value. Tapestry will construct the URL of the page matching the value and send to the client as redirect." }, { "code": null, "e": 70319, "s": 70269, "text": "public String onAction() { \n return \"Index\"; \n}" }, { "code": null, "e": 70453, "s": 70319, "text": "Class Response − Returns a page class. Tapestry will construct the URL of the returned page class and send to the client as redirect." }, { "code": null, "e": 70587, "s": 70453, "text": "Class Response − Returns a page class. Tapestry will construct the URL of the returned page class and send to the client as redirect." }, { "code": null, "e": 70640, "s": 70587, "text": "public Object onAction() { \n return Index.class \n}" }, { "code": null, "e": 70789, "s": 70640, "text": "Page Response − Returns a field annotated with @InjectPage. Tapestry will construct the URL of the injected page and send to the client as redirect." }, { "code": null, "e": 70938, "s": 70789, "text": "Page Response − Returns a field annotated with @InjectPage. Tapestry will construct the URL of the injected page and send to the client as redirect." }, { "code": null, "e": 71022, "s": 70938, "text": "@InjectPage \nprivate Index index; \n\npublic Object onAction(){ \n return index; \n}" }, { "code": null, "e": 71110, "s": 71022, "text": "HttpError − Returns the HTTPError object. Tapestry will issue a client side HTTP error." }, { "code": null, "e": 71198, "s": 71110, "text": "HttpError − Returns the HTTPError object. Tapestry will issue a client side HTTP error." }, { "code": null, "e": 71278, "s": 71198, "text": "public Object onAction(){ \n return new HttpError(302, \"The Error message); \n}" }, { "code": null, "e": 71413, "s": 71278, "text": "Link Response − Returns a link instance directly. Tapestry will construct the URL from Link object and send to the client as redirect." }, { "code": null, "e": 71548, "s": 71413, "text": "Link Response − Returns a link instance directly. Tapestry will construct the URL from Link object and send to the client as redirect." }, { "code": null, "e": 71753, "s": 71548, "text": "Stream Response − Returns the StreamResponse object. Tapestry will send the stream as response directly to the client browser. It is used to generate reports and images directly and send it to the client." }, { "code": null, "e": 71958, "s": 71753, "text": "Stream Response − Returns the StreamResponse object. Tapestry will send the stream as response directly to the client browser. It is used to generate reports and images directly and send it to the client." }, { "code": null, "e": 72098, "s": 71958, "text": "Url Response − Returns the java.net.URL object. Tapestry will get the corresponding URL from the object and send to the client as redirect." }, { "code": null, "e": 72238, "s": 72098, "text": "Url Response − Returns the java.net.URL object. Tapestry will get the corresponding URL from the object and send to the client as redirect." }, { "code": null, "e": 72340, "s": 72238, "text": "Object Response − Returns any values other than above specified values. Tapestry will raise an error." }, { "code": null, "e": 72442, "s": 72340, "text": "Object Response − Returns any values other than above specified values. Tapestry will raise an error." }, { "code": null, "e": 72608, "s": 72442, "text": "In general, event handler can get the context information using arguments. For example, if the context information is 3 of type int, then the event handler will be −" }, { "code": null, "e": 72648, "s": 72608, "text": "Object onActionFromTest(int id) { \n} \n" }, { "code": null, "e": 72921, "s": 72648, "text": "Tapestry properly handles the context information and provides it to methods through arguments. Sometimes, Tapestry may not be able to properly handle it due to complexity of the programming. At that time, we may get the complete context information and process ourselves." }, { "code": null, "e": 73141, "s": 72921, "text": "Object onActionFromEdit(EventContext context) { \n if (context.getCount() > 0) { \n this.selectedId = context.get(0); \n } else { \n alertManager.warn(\"Please select a document.\"); \n return null; \n } \n}" }, { "code": null, "e": 73381, "s": 73141, "text": "This chapter explains about the built-in components that Tapestry has with suitable examples. Tapestry supports more than 65 built-in components. You can also create custom components. Let us cover some of the notable components in detail." }, { "code": null, "e": 73485, "s": 73381, "text": "The if component is used to render a block conditionally. The condition is checked by a test parameter." }, { "code": null, "e": 73530, "s": 73485, "text": "Create a page IfSample.java as shown below −" }, { "code": null, "e": 73665, "s": 73530, "text": "package com.example.MyFirstApplication.pages; \n\npublic class Ifsample {\n public String getUser() { \n return \"user1\"; \n } \n} " }, { "code": null, "e": 73720, "s": 73665, "text": "Now, create a corresponding template file as follows −" }, { "code": null, "e": 74079, "s": 73720, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <h3>If-else component example </h3> \n <t:if test = \"user\"> \n Hello ${user} \n <p:else>\n <h4> You are not a Tapestry user </h4> \n </p:else> \n </t:if> \n</html>" }, { "code": null, "e": 74138, "s": 74079, "text": "Requesting the page will render the result as shown below." }, { "code": null, "e": 74197, "s": 74138, "text": "Result − http://localhost:8080/MyFirstApplication/ifsample" }, { "code": null, "e": 74508, "s": 74197, "text": "The unless component is just the opposite of the if component that was discussed above. While, the delegate component does not do any rendering on its own. Instead, it normally delegates the markup to block element. Unless and if components can use delegate and block to conditionally swap the dynamic content." }, { "code": null, "e": 74546, "s": 74508, "text": "Create a page Unless.java as follows." }, { "code": null, "e": 75160, "s": 74546, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.Block; \nimport org.apache.tapestry5.annotations.Property; \nimport org.apache.tapestry5.ioc.annotations.Inject; \nimport org.apache.tapestry5.PersistenceConstants; \nimport org.apache.tapestry5.annotations.Persist; \n\npublic class Unless { \n @Property \n @Persist(PersistenceConstants.FLASH) \n private String value; \n @Property \n private Boolean bool; \n @Inject \n Block t, f, n; \n \n public Block getCase() { \n if (bool == Boolean.TRUE ) { \n return t; \n } else { \n return f; \n } \n } \n} " }, { "code": null, "e": 75215, "s": 75160, "text": "Now, create a corresponding template file as follows −" }, { "code": null, "e": 75964, "s": 75215, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <h4> Delegate component </h4> \n <div class = \"div1\"> \n <t:delegate to = \"case\"/> \n </div> \n <h4> If-Unless component </h4> \n \n <div class = \"div1\"> \n <t:if test = \"bool\"> \n <t:delegate to = \"block:t\"/> \n </t:if> \n <t:unless test = \"bool\"> \n <t:delegate to = \"block:notT\"/> \n </t:unless> \n </div> \n \n <t:block id = \"t\"> \n bool == Boolean.TRUE. \n </t:block> \n \n <t:block id = \"notT\"> \n bool = Boolean.FALSE. \n </t:block> \n \n <t:block id = \"f\"> \n bool == Boolean.FALSE. \n </t:block> \n</html>" }, { "code": null, "e": 76023, "s": 75964, "text": "Requesting the page will render the result as shown below." }, { "code": null, "e": 76080, "s": 76023, "text": "Result − http://localhost:8080/MyFirstApplication/unless" }, { "code": null, "e": 76203, "s": 76080, "text": "The loop component is the basic component to loop over a collection items and render the body for every value / iteration." }, { "code": null, "e": 76239, "s": 76203, "text": "Create a Loop page as shown below −" }, { "code": null, "e": 76396, "s": 76239, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \npublic class Loop { \n @Property \n private int i; \n}" }, { "code": null, "e": 76445, "s": 76396, "text": "Then, create the corresponding template Loop.tml" }, { "code": null, "e": 76772, "s": 76445, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <p>This is sample parameter rendering example...</p> \n <ol>\n <li t:type = \"loop\" source = \"1..5\" value = \"var:i\">${var:i}</li> \n </ol> \n</html>" }, { "code": null, "e": 76822, "s": 76772, "text": "Loop component has the following two parameters −" }, { "code": null, "e": 76928, "s": 76822, "text": "source − Collection source. 1...5 is a property expansion used to create an array with a specified range." }, { "code": null, "e": 77034, "s": 76928, "text": "source − Collection source. 1...5 is a property expansion used to create an array with a specified range." }, { "code": null, "e": 77119, "s": 77034, "text": "var − Render variable. Used to render the current value in the body of the template." }, { "code": null, "e": 77204, "s": 77119, "text": "var − Render variable. Used to render the current value in the body of the template." }, { "code": null, "e": 77264, "s": 77204, "text": "Requesting the page will render the result as shown below −" }, { "code": null, "e": 77393, "s": 77264, "text": "A PageLink component is used to link a page from one page to another page. Create a PageLink test page as below − PageLink.java." }, { "code": null, "e": 77471, "s": 77393, "text": "package com.example.MyFirstApplication.pages; \n public class PageLink { \n}" }, { "code": null, "e": 77531, "s": 77471, "text": "Then, create a corresponding template file as shown below −" }, { "code": null, "e": 77912, "s": 77531, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <body> \n <h3><u>Page Link</u> </h3> \n <div class = \"page\"> \n <t:pagelink page = \"Index\">Click here to navigate Index page</t:pagelink>\n <br/> \n </div> \n </body> \n \n</html>" }, { "code": null, "e": 78001, "s": 77912, "text": "The PageLink component has a page parameter which should refer the target tapestry page." }, { "code": null, "e": 78060, "s": 78001, "text": "Result − http://localhost:8080/myFirstApplication/pagelink" }, { "code": null, "e": 78202, "s": 78060, "text": "The EventLink component sends the event name and the corresponding parameter through the URL. Create an EventsLink page class as shown below." }, { "code": null, "e": 78525, "s": 78202, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \npublic class EventsLink { \n @Property \n private int x; \n void onActivate(int count) { \n this.x = x; \n } \n int onPassivate() { \n return x; \n } \n void onAdd(int value) { \n x += value; \n } \n}" }, { "code": null, "e": 78594, "s": 78525, "text": "Then, create a corresponding “EventsLink” template file as follows −" }, { "code": null, "e": 78947, "s": 78594, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <h3> Event link example </h3> \n AddedCount = ${x}. <br/> \n <t:eventlink t:event = \"add\" t:context = \"literal:1\">\n Click here to add count\n </t:eventlink><br/> \n</html>" }, { "code": null, "e": 78992, "s": 78947, "text": "EventLink has the following two parameters −" }, { "code": null, "e": 79116, "s": 78992, "text": "Event − The name of the event to be triggered in the EventLink component. By default, it points to the id of the component." }, { "code": null, "e": 79240, "s": 79116, "text": "Event − The name of the event to be triggered in the EventLink component. By default, it points to the id of the component." }, { "code": null, "e": 79316, "s": 79240, "text": "Context − It is an optional parameter. It defines the context for the link." }, { "code": null, "e": 79392, "s": 79316, "text": "Context − It is an optional parameter. It defines the context for the link." }, { "code": null, "e": 79453, "s": 79392, "text": "Result − http://localhost:8080/myFirstApplication/EventsLink" }, { "code": null, "e": 79578, "s": 79453, "text": "After clicking the count value, the page will display the event name in the URL as shown in the following output screenshot." }, { "code": null, "e": 79719, "s": 79578, "text": "The ActionLink component is similar to the EventLink component, but it only sends the target component id. The default event name is action." }, { "code": null, "e": 79772, "s": 79719, "text": "Create a page “ActivationLinks.java” as shown below," }, { "code": null, "e": 80112, "s": 79772, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \npublic class ActivationLinks { \n @Property \n private int x; \n void onActivate(int count) { \n this.x = x; \n } \n int onPassivate() { \n return x; \n } \n void onActionFromsub(int value) { \n x -= value; \n } \n} " }, { "code": null, "e": 80171, "s": 80112, "text": "Now, create a corresponding template file as shown below −" }, { "code": null, "e": 80527, "s": 80171, "text": "<html t:type = \"Newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <div class = \"div1\"> \n Count = ${count}. <br/> \n <t:actionlink t:id = \"sub\" t:context = \"literal:1\">\n Decrement\n </t:actionlink><br/> \n </div> \n \n</html> " }, { "code": null, "e": 80615, "s": 80527, "text": "Here, the OnActionFromSub method will be called when clicking the ActionLink component." }, { "code": null, "e": 80681, "s": 80615, "text": "Result − http://localhost:8080/myFirstApplication/ActivationsLink" }, { "code": null, "e": 80940, "s": 80681, "text": "An alert dialog box is mostly used to give a warning message to the users. For example, if the input field requires some mandatory text but the user does not provide any input, then as a part of validation, you can use an alert box to give a warning message." }, { "code": null, "e": 80998, "s": 80940, "text": "Create a page “Alerts” as shown in the following program." }, { "code": null, "e": 81131, "s": 80998, "text": "package com.example.MyFirstApplication.pages; \n\npublic class Alerts { \n public String getUser() { \n return \"user1\"; \n } \n}" }, { "code": null, "e": 81187, "s": 81131, "text": "Then, create a corresponding template file as follows −" }, { "code": null, "e": 81472, "s": 81187, "text": "<html t:type = \"Newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <h3>Alerts</h3> \n <div class = \"alert alert-info\"> \n <h5> Welcome ${user} </h5> \n </div>\n \n</html>" }, { "code": null, "e": 81520, "s": 81472, "text": "An Alert has three severity levels, which are −" }, { "code": null, "e": 81525, "s": 81520, "text": "Info" }, { "code": null, "e": 81530, "s": 81525, "text": "Warn" }, { "code": null, "e": 81536, "s": 81530, "text": "Error" }, { "code": null, "e": 81671, "s": 81536, "text": "The above template is created using an info alert. It is defined as alert-info. You can create other severities depending on the need." }, { "code": null, "e": 81727, "s": 81671, "text": "Requesting the page will produce the following result −" }, { "code": null, "e": 81775, "s": 81727, "text": "http://localhost:8080/myFirstApplication/Alerts" }, { "code": null, "e": 81958, "s": 81775, "text": "The Form Component is used to create a form in the tapestry page for user input. A form can contain text fields, date fields, checkbox fields, select options, submit button and more." }, { "code": null, "e": 82033, "s": 81958, "text": "This chapter explains about some of the notable form components in detail." }, { "code": null, "e": 82169, "s": 82033, "text": "A Checkbox Component is used to take a choice between two mutually exclusive options. Create a page using the Checkbox as shown below −" }, { "code": null, "e": 82386, "s": 82169, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \n\npublic class Checkbox { \n @Property \n private boolean check1; \n \n @Property \n private boolean check2; \n}" }, { "code": null, "e": 82453, "s": 82386, "text": "Now, create a corresponding template Checkbox.tml as shown below −" }, { "code": null, "e": 82805, "s": 82453, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <h3> checkbox component</h3> \n <t:form> \n <t:checkbox t:id = \"check1\"/> I have a bike <br/> \n <t:checkbox t:id = \"check2\"/> I have a car \n </t:form> \n \n</html> " }, { "code": null, "e": 82881, "s": 82805, "text": "Here, the checkbox parameter id matches to the corresponding Boolean value." }, { "code": null, "e": 83000, "s": 82881, "text": "Result − After requesting the page,http://localhost:8080/myFirstApplication/checkbox it produces the following result." }, { "code": null, "e": 83106, "s": 83000, "text": "The TextField component allows the user to edit a single line of text. Create a page Text as shown below." }, { "code": null, "e": 83368, "s": 83106, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \nimport org.apache.tapestry5.corelib.components.TextField;public class Text { \n @Property \n private String fname; \n @Property \n private String lname; \n}" }, { "code": null, "e": 83432, "s": 83368, "text": "Then, create a corresponding template as shown below – Text.tml" }, { "code": null, "e": 84031, "s": 83432, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n <p> Form application </p>\n \n <body> \n <h3> Text field created from Tapestry component </h3> \n <t:form> \n <table> \n <tr> \n <td> \n Firstname: </td> <td><t:textfield t:id = \"fname\" /> \n </td> \n <td>Lastname: </td> <td> <t:textfield t:id = \"lname\" /> </td> \n </tr> \n </table> \n </t:form> \n </body> \n \n</html>" }, { "code": null, "e": 84145, "s": 84031, "text": "Here, the Text page includes a property named fname and lname. The component id's are accessed by the properties." }, { "code": null, "e": 84201, "s": 84145, "text": "Requesting the page will produce the following result −" }, { "code": null, "e": 84247, "s": 84201, "text": "http://localhost:8080/myFirstApplication/Text" }, { "code": null, "e": 84353, "s": 84247, "text": "The PasswordField is a specialized text field entry for password. Create a page Password as shown below −" }, { "code": null, "e": 84584, "s": 84353, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \nimport org.apache.tapestry5.corelib.components.PasswordField; \n\npublic class Password { \n @Property \n private String pwd; \n}" }, { "code": null, "e": 84646, "s": 84584, "text": "Now, create a corresponding template file is as shown below −" }, { "code": null, "e": 85100, "s": 84646, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n <p> Form application </p> \n <h3> Password field created from Tapestry component </h3> \n \n <t:form> \n <table> \n <tr> \n <td> Password: </td> \n <td><t:passwordfield t:id = \"pwd\"/> </td> \n </tr> \n </table> \n </t:form>\n \n</html> " }, { "code": null, "e": 85246, "s": 85100, "text": "Here, the PasswordField component has the parameter id, which points to the property pwd. Requesting the page will produce the following result −" }, { "code": null, "e": 85297, "s": 85246, "text": "http://localhost:8080/myFirstApplication/Password " }, { "code": null, "e": 85394, "s": 85297, "text": "The TextArea component is a multi-line input text control. Create a page TxtArea as shown below." }, { "code": null, "e": 85620, "s": 85394, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \nimport org.apache.tapestry5.corelib.components.TextArea; \n\npublic class TxtArea { \n @Property \n private String str; \n}" }, { "code": null, "e": 85682, "s": 85620, "text": "Then, create a corresponding template file is as shown below." }, { "code": null, "e": 86041, "s": 85682, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n <h3>TextArea component </h3>\n \n <t:form>\n <table>\n <tr> \n <td><t:textarea t:id = \"str\"/>\n </td>\n </tr>\n </table>\n </t:form>\n \n</html>" }, { "code": null, "e": 86169, "s": 86041, "text": "Here, the TextArea component parameter id points to the property “str”. Requesting the page will produce the following result −" }, { "code": null, "e": 86220, "s": 86169, "text": "http://localhost:8080/myFirstApplication/TxtArea**" }, { "code": null, "e": 86322, "s": 86220, "text": "The Select component contains a drop-down list of choices. Create a page SelectOption as shown below." }, { "code": null, "e": 86672, "s": 86322, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \nimport org.apache.tapestry5.corelib.components.Select; \n\npublic class SelectOption { \n @Property \n private String color0; \n \n @Property \n \n private Color1 color1; \n public enum Color1 { \n YELLOW, RED, GREEN, BLUE, ORANGE \n } \n}" }, { "code": null, "e": 86726, "s": 86672, "text": "Then, create a corresponding template is as follows −" }, { "code": null, "e": 87181, "s": 86726, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n <p> Form application </p>\n <h3> select component </h3> \n \n <t:form> \n <table> \n <tr> \n <td> Select your color here: </td> \n <td> <select t:type = \"select\" t:id = \"color1\"></select></td> \n </tr> \n </table> \n </t:form>\n \n</html>" }, { "code": null, "e": 87229, "s": 87181, "text": "Here, the Select component has two parameters −" }, { "code": null, "e": 87269, "s": 87229, "text": "Type − Type of the property is an enum." }, { "code": null, "e": 87309, "s": 87269, "text": "Type − Type of the property is an enum." }, { "code": null, "e": 87359, "s": 87309, "text": "Id − Id points to the Tapestry property “color1”." }, { "code": null, "e": 87409, "s": 87359, "text": "Id − Id points to the Tapestry property “color1”." }, { "code": null, "e": 87465, "s": 87409, "text": "Requesting the page will produce the following result −" }, { "code": null, "e": 87520, "s": 87465, "text": "http://localhost:8080/myFirstApplication/SelectOption " }, { "code": null, "e": 87791, "s": 87520, "text": "The RadioGroup component provides a container group for Radio components. The Radio and RadioGroup components work together to update a property of an object. This component should wrap around other Radio components. Create a new page “Radiobutton.java” as shown below −" }, { "code": null, "e": 88107, "s": 87791, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.PersistenceConstants; \nimport org.apache.tapestry5.annotations.Persist; \nimport org.apache.tapestry5.annotations.Property; \n\npublic class Radiobutton { \n @Property \n @Persist(PersistenceConstants.FLASH) \n private String value; \n}" }, { "code": null, "e": 88170, "s": 88107, "text": "Then, create a corresponding template file is as shown below −" }, { "code": null, "e": 88695, "s": 88170, "text": "<html t:type = \"Newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n <h3>RadioGroup component </h3> \n \n <t:form>\n <t:radiogroup t:id = \"value\">\n <t:radio t:id = \"radioT\" value = \"literal:T\" label = \"Male\" /> \n <t:label for = \"radioT\"/> \n <t:radio t:id = \"radioF\" value = \"literal:F\" label = \"Female\"/> \n <t:label for = \"radioF\"/> \n </t:radiogroup>\n </t:form>\n \n</html>" }, { "code": null, "e": 88818, "s": 88695, "text": "Here, the RadioGroup component id is binding with property “value”. Requesting the page will produce the following result." }, { "code": null, "e": 88871, "s": 88818, "text": "http://localhost:8080/myFirstApplication/Radiobutton" }, { "code": null, "e": 89029, "s": 88871, "text": "When a user clicks a submit button, the form is sent to the address specified in the action setting of the tag. Create a page SubmitComponent as shown below." }, { "code": null, "e": 89263, "s": 89029, "text": "package com.example.MyFirstApplication.pages; \nimport org.apache.tapestry5.annotations.InjectPage; \n\npublic class SubmitComponent { \n @InjectPage \n private Index page1; \n Object onSuccess() { \n return page1; \n } \n}" }, { "code": null, "e": 89321, "s": 89263, "text": "Now, create a corresponding template file as shown below." }, { "code": null, "e": 89665, "s": 89321, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n <h3>Tapestry Submit component </h3> \n \n <body> \n <t:form> \n <t:submit t:id = \"submit1\" value = \"Click to go Index\"/> \n </t:form> \n </body>\n \n</html>" }, { "code": null, "e": 89785, "s": 89665, "text": "Here, the Submit component submits the value to the Index page. Requesting the page will produce the following result −" }, { "code": null, "e": 89842, "s": 89785, "text": "http://localhost:8080/myFirstApplication/SubmitComponent" }, { "code": null, "e": 90163, "s": 89842, "text": "Form validation normally occurs at the server after the client has entered all the necessary data and then submitted the form. If the data entered by a client was incorrect or simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information." }, { "code": null, "e": 90249, "s": 90163, "text": "Let us consider the following simple example to understand the process of validation." }, { "code": null, "e": 90288, "s": 90249, "text": "Create a page Validate as shown below." }, { "code": null, "e": 90692, "s": 90288, "text": "package com.example.MyFirstApplication.pages; \n\nimport org.apache.tapestry5.annotations.Property; \nimport org.apache.tapestry5.PersistenceConstants; \nimport org.apache.tapestry5.annotations.Persist; \n\npublic class Validate { \n @Property \n @Persist(PersistenceConstants.FLASH) \n private String firstName; \n \n @Property \n @Persist(PersistenceConstants.FLASH) \n private String lastName; \n}" }, { "code": null, "e": 90750, "s": 90692, "text": "Now, create a corresponding template file as shown below." }, { "code": null, "e": 91486, "s": 90750, "text": "<html t:type = \"newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <t:form> \n <table> \n <tr> \n <td><t:label for = \"firstName\"/>:</td> \n <td><input t:type = \"TextField\" t:id = \"firstName\" \n t:validate = \"required, maxlength = 7\" size = \"10\"/></td> \n </tr> \n <tr> \n <td><t:label for = \"lastName\"/>:</td> \n <td><input t:type = \"TextField\" t:id = \"lastName\" \n t:validate = \"required, maxLength = 5\" size = \"10\"/></td> \n </tr> \n </table> \n <t:submit t:id = \"sub\" value =\" Form validation\"/> \n </t:form>\n \n</html>" }, { "code": null, "e": 91545, "s": 91486, "text": "Form Validation has the following significant parameters −" }, { "code": null, "e": 91610, "s": 91545, "text": "Max − defines the maximum value, for e.g. = «maximum value, 20»." }, { "code": null, "e": 91675, "s": 91610, "text": "Max − defines the maximum value, for e.g. = «maximum value, 20»." }, { "code": null, "e": 91788, "s": 91675, "text": "MaxDate − defines the maxDate, for e.g. = «maximum date, 06/09/2013». Similarly, you can assign MinDate as well." }, { "code": null, "e": 91901, "s": 91788, "text": "MaxDate − defines the maxDate, for e.g. = «maximum date, 06/09/2013». Similarly, you can assign MinDate as well." }, { "code": null, "e": 91956, "s": 91901, "text": "MaxLength − maxLength for e.g. = «maximum length, 80»." }, { "code": null, "e": 92011, "s": 91956, "text": "MaxLength − maxLength for e.g. = «maximum length, 80»." }, { "code": null, "e": 92026, "s": 92011, "text": "Min − minimum." }, { "code": null, "e": 92041, "s": 92026, "text": "Min − minimum." }, { "code": null, "e": 92099, "s": 92041, "text": "MinLength − minimum Length for e.g. = «minmum length, 2»." }, { "code": null, "e": 92157, "s": 92099, "text": "MinLength − minimum Length for e.g. = «minmum length, 2»." }, { "code": null, "e": 92265, "s": 92157, "text": "Email − Email validation which uses either standard email regexp ^\\w[._\\w]*\\w@\\w[-._\\w]*\\w\\.\\w2,6$ or none." }, { "code": null, "e": 92373, "s": 92265, "text": "Email − Email validation which uses either standard email regexp ^\\w[._\\w]*\\w@\\w[-._\\w]*\\w\\.\\w2,6$ or none." }, { "code": null, "e": 92429, "s": 92373, "text": "Requesting the page will produce the following result −" }, { "code": null, "e": 92479, "s": 92429, "text": "http://localhost:8080/myFirstApplication/Validate" }, { "code": null, "e": 92770, "s": 92479, "text": "AJAX stands for Asynchronous JavaScript and XML. It is a technique for creating better, faster and more interactive web applications with the help of XML, JSON, HTML, CSS, and JavaScript. AJAX allows you to send and receive data asynchronously without reloading the web page, so it is fast." }, { "code": null, "e": 93141, "s": 92770, "text": "A Zone Component is used to provide the content (markup) as well as the position of the content itself. The body of the Zone Component is used internally by Tapestry to generate the content. Once the dynamic content is generated, Tapestry will send it to the client, rerender the data in the correct place, trigger and animate the HTML to draw the attention of the user." }, { "code": null, "e": 93486, "s": 93141, "text": "This Zone component is used along with an EventLink component. An EventLink has option to tie it to a particular zone using the t:zone attributes. Once the zone is configured in EventLink, clicking the EventLink will trigger the zone update. In addition, the EventLink events (refreshZone) can be used to control the generation of dynamic data." }, { "code": null, "e": 93527, "s": 93486, "text": "A simple example of AJAX is as follows −" }, { "code": null, "e": 94030, "s": 93527, "text": "<html t:type = \"Newlayout\" title = \"About MyFirstApplication\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\" \n xmlns:p = \"tapestry:parameter\"> \n \n <body> \n <h1>Ajax time zone example</h1> \n <div class = \"div1\"> \n <a t:type = \"eventlink\" t:event = \"refreshZone\" href = \"#\" \n t:zone = \"timeZone\">Ajax Link </a><br/><br/> \n <t:zone t:id = \"timeZone\" id = \"timeZone\">Time zone: ${serverTime}</t:zone> \n </div> \n </body>\n \n</html> " }, { "code": null, "e": 94643, "s": 94030, "text": "package com.example.MyFirstApplication.pages; \n\nimport java.util.Date; \nimport org.apache.tapestry5.annotations.InjectComponent; \nimport org.apache.tapestry5.corelib.components.Zone; \nimport org.apache.tapestry5.ioc.annotations.Inject; \nimport org.apache.tapestry5.services.Request; \n\npublic class AjaxZone { \n @Inject \n private Request request; \n \n @InjectComponent \n private Zone timeZone; \n \n void onRefreshPage() { \n } \n \n Object onRefreshZone() { \n return request.isXHR() ? timeZone.getBody() : null; \n } \n \n public Date getServerTime() { \n return new Date(); \n } \n} " }, { "code": null, "e": 94718, "s": 94643, "text": "The result will show at: http://localhost:8080/MyFirstApplication/AjaxZone" }, { "code": null, "e": 95104, "s": 94718, "text": "In this chapter, we will discuss about the integration of BeanEditForm and Grid component with Hibernate. Hibernate is integrated into the tapestry through the hibernate module. To enable hibernate module, add tapestry-hibernate dependency and optionally hsqldb in the pom.xml file. Now, configure hibernate through the hibernate.cfg.xml file placed at the root of the resource folder." }, { "code": null, "e": 95404, "s": 95104, "text": "<dependency> \n <groupId>org.apache.tapestry</groupId> \n <artifactId>tapestry-hibernate</artifactId> \n <version>${tapestry-release-version}</version> \n</dependency> \n\n<dependency> \n <groupId>org.hsqldb</groupId> \n <artifactId>hsqldb</artifactId> \n <version>2.3.2</version> \n</dependency>" }, { "code": null, "e": 96346, "s": 95404, "text": "<!DOCTYPE hibernate-configuration PUBLIC \n \"-//Hibernate/Hibernate Configuration DTD 3.0//EN\" \n \"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd\"> \n\n<hibernate-configuration> \n <session-factory> \n <property name = \"hibernate.connection.driver_class\">\n org.hsqldb.jdbcDriver\n </property> \n <property name = \"hibernate.connection.url\">\n jdbc:hsqldb:./target/work/sampleapp;shutdown = true\n </property> \n <property name = \"hibernate.dialect\">\n org.hibernate.dialect.HSQLDialect\n </property> \n \n <property name = \"hibernate.connection.username\">sa</property> \n <property name = \"hibernate.connection.password\"></property> \n <property name = \"hbm2ddl.auto\">update</property>\n <property name = \"hibernate.show_sql\">true</property> \n <property name = \"hibernate.format_sql\">true</property> \n </session-factory> \n</hibernate-configuration> " }, { "code": null, "e": 96533, "s": 96346, "text": "Let us see how to create the employee add page using the BeanEditForm component and the employee list page using the Grid component. The persistence layer is handled by Hibernate module." }, { "code": null, "e": 96756, "s": 96533, "text": "Create an employee class and decorate it with @Entity annotation. Then, add validation annotation for relevant fields and hibernate related annotation @Id and @GeneratedValue for id field. Also, create gender as enum type." }, { "code": null, "e": 97847, "s": 96756, "text": "package com.example.MyFirstApplication.entities; \n\nimport javax.persistence.Entity; \nimport javax.persistence.GeneratedValue; \nimport javax.persistence.GenerationType; \nimport javax.persistence.Id; \nimport org.apache.tapestry5.beaneditor.NonVisual; \nimport org.apache.tapestry5.beaneditor.Validate; \n\n@Entity \npublic class Employee { \n @Id \n @GeneratedValue(strategy = GenerationType.IDENTITY) \n @NonVisual \n public Long id; \n\n @Validate(\"required\") \n public String firstName; \n \n @Validate(\"required\") \n public String lastName; \n\n @Validate(\"required\") \n public String userName; \n\n @Validate(\"required\") \n public String password; \n\n @Validate(\"required\") \n public String email; \n public String phone; \n\n @Validate(\"required\") \n public String Street; \n\n @Validate(\"required\") \n public String city; \n\n @Validate(\"required\") \n public String state; \n\n @Validate(\"required,regexp=^\\\\d{5}(-\\\\d{4})?$\") \n public String zip; \n} \nGender.java (enum) \npackage com.example.MyFirstApplication.data; \n\npublic enum Gender { \n Male, Female \n}" }, { "code": null, "e": 98103, "s": 97847, "text": "Create the employee list page, ListEmployee.java in the new folder employee under pages and corresponding template file ListEmployee.tml at /src/main/resources/pages/employee folder. Tapestry provides a short URL for sub folders by removing repeated data." }, { "code": null, "e": 98238, "s": 98103, "text": "For example, the ListEmployee page can be accessed by a normal URL – (/employee/listemployee) and by the short URL – (/employee/list)." }, { "code": null, "e": 98475, "s": 98238, "text": "Inject the Hibernate session into the list page using @Inject annotation. Define a property getEmployees in the list page and populate it with employees using injected session object. Complete the code for employee class as shown below." }, { "code": null, "e": 99049, "s": 98475, "text": "package com.example.MyFirstApplication.pages.employee; \n\nimport java.util.List; \nimport org.apache.tapestry5.annotations.Import; \nimport org.apache.tapestry5.ioc.annotations.Inject; \nimport org.hibernate.Session; \nimport com.example.MyFirstApplication.entities.Employee; \nimport org.apache.tapestry5.annotations.Import; \n@Import(stylesheet=\"context:mybootstrap/css/bootstrap.css\") \n\npublic class ListEmployee { \n @Inject \n private Session session; \n \n public List<Employee> getEmployees() { \n return session.createCriteria(Employee.class).list(); \n } \n} " }, { "code": null, "e": 99154, "s": 99049, "text": "Create the template file for ListEmployee class. The template will have two main components, which are −" }, { "code": null, "e": 99192, "s": 99154, "text": "PageLink − Create employee link page." }, { "code": null, "e": 99230, "s": 99192, "text": "PageLink − Create employee link page." }, { "code": null, "e": 99401, "s": 99230, "text": "Grid − Used to render the employee details. The grid component has sources attributes to inject employee list and include attributes to include the fields to be rendered." }, { "code": null, "e": 99572, "s": 99401, "text": "Grid − Used to render the employee details. The grid component has sources attributes to inject employee list and include attributes to include the fields to be rendered." }, { "code": null, "e": 99610, "s": 99572, "text": "ListEmployee.tml (list all employees)" }, { "code": null, "e": 99993, "s": 99610, "text": "<html t:type = \"simplelayout\" title = \"List Employee\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <h1>Employees</h1> \n \n <ul> \n <li><t:pagelink page = \"employee/create\">Create new employee</t:pagelink></li> \n </ul> \n <t:grid source = \"employees\" \n include = \"userName,firstName,lastName,gender,dateOfBirth,phone,city,state\"/> \n</html>" }, { "code": null, "e": 100113, "s": 99993, "text": "Create employee creation template file and include BeanEditForm component. The component has the following attributes −" }, { "code": null, "e": 100139, "s": 100113, "text": "object − Includes source." }, { "code": null, "e": 100165, "s": 100139, "text": "object − Includes source." }, { "code": null, "e": 100223, "s": 100165, "text": "reorder − Defines the order of the fields to be rendered." }, { "code": null, "e": 100281, "s": 100223, "text": "reorder − Defines the order of the fields to be rendered." }, { "code": null, "e": 100337, "s": 100281, "text": "submitlabel − The message of the form submission button" }, { "code": null, "e": 100393, "s": 100337, "text": "submitlabel − The message of the form submission button" }, { "code": null, "e": 100429, "s": 100393, "text": "The complete coding is as follows −" }, { "code": null, "e": 100781, "s": 100429, "text": "<html t:type = \"simplelayout\" title = \"Create New Address\" \n xmlns:t = \"http://tapestry.apache.org/schema/tapestry_5_4.xsd\"> \n <t:beaneditform \n object = \"employee\" \n submitlabel = \"message:submit-label\" \n reorder = \"userName,password,firstName,lastName,\n dateOfBirth,gender,email,phone,s treet,city,state,zip\" /> \n</html> " }, { "code": null, "e": 101033, "s": 100781, "text": "Create employee creation class and include session, employee property, list page (navigation link) and define the OnSuccess event (place to update the data) of the component. The session data is persisted into the database using the hibernate session." }, { "code": null, "e": 101069, "s": 101033, "text": "The complete coding is as follows −" }, { "code": null, "e": 101788, "s": 101069, "text": "package com.example.MyFirstApplication.pages.employee; \n\nimport com.example.MyFirstApplication.entities.Employee; \nimport com.example.MyFirstApplication.pages.employee.ListEmployee; \nimport org.apache.tapestry5.annotations.InjectPage; \nimport org.apache.tapestry5.annotations.Property; \nimport org.apache.tapestry5.hibernate.annotations.CommitAfter; \nimport org.apache.tapestry5.ioc.annotations.Inject; \nimport org.hibernate.Session; \n\npublic class CreateEmployee { \n @Property \n private Employee employee; \n @Inject \n private Session session; \n @InjectPage \n private ListEmployee listPage; \n @CommitAfter \n Object onSuccess() { \n session.persist(employee); \n return listPage; \n } \n}" }, { "code": null, "e": 101917, "s": 101788, "text": "Add the CreateEmployee.properties file and include the message to be used in form validations. The complete code is as follows −" }, { "code": null, "e": 102067, "s": 101917, "text": "zip-regexp=^\\\\d{5}(-\\\\d{4})?$ \nzip-regexp-message = Zip Codes are five or nine digits. Example: 02134 or 901251655. \nsubmit-label = Create Employee \n" }, { "code": null, "e": 102147, "s": 102067, "text": "The screenshot of the employee creation page and listing page are shown below −" }, { "code": null, "e": 102687, "s": 102147, "text": "Every web application should have some way to store certain user data like user object, user preferences, etc. For example, in a shopping cart application, the user's selected items / products should be saved in a temporary bucket (cart) until the user prefers to buy the products. We can save the items in a database, but it will be too expensive since all users are not going to buy the selected items. So, we need a temporary arrangement to store / persist the items. Apache Tapestry Provides two ways to persist the data and they are −" }, { "code": null, "e": 102709, "s": 102687, "text": "Persistence page data" }, { "code": null, "e": 102725, "s": 102709, "text": "Session Storage" }, { "code": null, "e": 102814, "s": 102725, "text": "Both has its own advantages and limitations. We will check it in the following sections." }, { "code": null, "e": 103005, "s": 102814, "text": "The Persistence Page Data is a simple concept to persist data in a single page between requests and it is also called as Page Level Persistence. It can be done using the @Persist annotation." }, { "code": null, "e": 103033, "s": 103005, "text": "@Persist \npublic int age; \n" }, { "code": null, "e": 103326, "s": 103033, "text": "Once a field is annotated with @Persist, the field's value will be persisted across request and if the value is changed during request, it will be reflected when it is accessed next time. Apache Tapestry provides five types of strategy to implement the @Persist concept. They are as follows −" }, { "code": null, "e": 103415, "s": 103326, "text": "Session Strategy − The data is persisted using the Session and it is a default strategy." }, { "code": null, "e": 103504, "s": 103415, "text": "Session Strategy − The data is persisted using the Session and it is a default strategy." }, { "code": null, "e": 103659, "s": 103504, "text": "Flash Strategy − The data is persisted using Session as well, but it is a very short lived one. The data will be available in only one subsequent request." }, { "code": null, "e": 103814, "s": 103659, "text": "Flash Strategy − The data is persisted using Session as well, but it is a very short lived one. The data will be available in only one subsequent request." }, { "code": null, "e": 103870, "s": 103814, "text": "@Persist(PersistenceConstants.FLASH) \nprivate int age;\n" }, { "code": null, "e": 103986, "s": 103870, "text": "Client Strategy − The data is persisted in the client side such as URL query string, hidden field in the form, etc." }, { "code": null, "e": 104102, "s": 103986, "text": "Client Strategy − The data is persisted in the client side such as URL query string, hidden field in the form, etc." }, { "code": null, "e": 104159, "s": 104102, "text": "@Persist(PersistenceConstants.FLASH) \nprivate int age; \n" }, { "code": null, "e": 104454, "s": 104159, "text": "Hibernate Entity Strategy − The data is persisted using the Hibernate module as Entity. The entity will be stored in Hibernate and its reference (Java class name and its primary key) will be saved as token in HttpSession. The entity will be restored by using the token available in HttpSession." }, { "code": null, "e": 104749, "s": 104454, "text": "Hibernate Entity Strategy − The data is persisted using the Hibernate module as Entity. The entity will be stored in Hibernate and its reference (Java class name and its primary key) will be saved as token in HttpSession. The entity will be restored by using the token available in HttpSession." }, { "code": null, "e": 104825, "s": 104749, "text": "@Persist(HibernatePersistenceConstants.ENTITY) \nprivate Category category;\n" }, { "code": null, "e": 104924, "s": 104825, "text": "JPA Entity Strategy − The data is persisted using a JPA module. It will only able to store Entity." }, { "code": null, "e": 105023, "s": 104924, "text": "JPA Entity Strategy − The data is persisted using a JPA module. It will only able to store Entity." }, { "code": null, "e": 105086, "s": 105023, "text": "@Persist(JpaPersistenceConstants.ENTITY) \nprivate User user; \n" }, { "code": null, "e": 105354, "s": 105086, "text": "Session storage is an advanced concept used to store data which needs to be available across pages like data in multiple page wizard, logged in user details, etc. The Session Storage provides two options, one to store complex object and another to store simple values" }, { "code": null, "e": 105407, "s": 105354, "text": "Session Store Object − Used to store complex object." }, { "code": null, "e": 105460, "s": 105407, "text": "Session Store Object − Used to store complex object." }, { "code": null, "e": 105510, "s": 105460, "text": "Session Attributes − Used to store simple values." }, { "code": null, "e": 105560, "s": 105510, "text": "Session Attributes − Used to store simple values." }, { "code": null, "e": 105824, "s": 105560, "text": "An SSO can be created using @SessionStore annotation. The SSO will store the object using type of the object. For example, the Cart Object will be stored using a Cart class name as token. So, any complex object can be stored once in an application (one per user)." }, { "code": null, "e": 105901, "s": 105824, "text": "public class MySSOPage { \n @SessionState \n private ShoppingCart cart; \n}" }, { "code": null, "e": 106293, "s": 105901, "text": "An SSO is a specialized store and should be used to store only complex / special object. Simple data types can also be stored using an SSO, but storing simple data types like String makes it only store one “String” value in the application. Using a single “String” value in the application is simply not possible. You can use simple data types as Apache Tapestry provides Session Attributes." }, { "code": null, "e": 106370, "s": 106293, "text": "Session Attributes enable the data to be stored by name instead of its type." }, { "code": null, "e": 106455, "s": 106370, "text": "public class MyPage { \n @SessionAttribute \n private String loggedInUsername; \n}" }, { "code": null, "e": 106610, "s": 106455, "text": "By default, Session Attributes uses the field name to refer the data in session. We can change the reference name by annotation parameter as shown below −" }, { "code": null, "e": 106706, "s": 106610, "text": "public class MyPage { \n @SessionAttribute(\"loggedInUserName\") \n private String userName; \n}" }, { "code": null, "e": 107163, "s": 106706, "text": "One of the main issues in using name as session reference is that we may accidentally use the same name in more than one class / page. In this case, the data stored maybe changed unexpectedly. To fix this issue, it will be better to use the name along with class / page name and package name like com.myapp.pages.register.email, where com.myapp.pages is the package name, register is the page / class name and finally email is variable (to be stored) name." }, { "code": null, "e": 107250, "s": 107163, "text": "In this chapter, we will discuss a few advanced features of Apache Tapestry in detail." }, { "code": null, "e": 107650, "s": 107250, "text": "Tapestry provides built-in Inversion of Control library. Tapestry is deeply integrated into IoC and uses IoC for all its features. Tapestry IoC configuration is based on Java itself instead of XML like many other IoC containers. Tapestry IoC based modules are packaged into JAR file and just dropped into the classpath with zero configuration. Tapestry IoC usage is based on lightness, which means −" }, { "code": null, "e": 107692, "s": 107650, "text": "Small interfaces of two or three methods." }, { "code": null, "e": 107734, "s": 107692, "text": "Small interfaces of two or three methods." }, { "code": null, "e": 107778, "s": 107734, "text": "Small methods with two or three parameters." }, { "code": null, "e": 107822, "s": 107778, "text": "Small methods with two or three parameters." }, { "code": null, "e": 107899, "s": 107822, "text": "Anonymous communication via events, rather than explicit method invocations." }, { "code": null, "e": 107976, "s": 107899, "text": "Anonymous communication via events, rather than explicit method invocations." }, { "code": null, "e": 108340, "s": 107976, "text": "Module is a way to extend the functionality of the Tapestry application. Tapestry has both built-in modules and large number of third-party modules. Hibernate is one of the hot and very useful module provided by Tapestry. It also has modules integrating JMX, JPA, Spring Framework, JSR 303 Bean Validation, JSON, etc. Some of the notable third-party modules are −" }, { "code": null, "e": 108357, "s": 108340, "text": "Tapestry-Cayenne" }, { "code": null, "e": 108383, "s": 108357, "text": "Tapestry5-googleanalytics" }, { "code": null, "e": 108425, "s": 108383, "text": "Gang of tapestry 5 - Tapestry5-HighCharts" }, { "code": null, "e": 108463, "s": 108425, "text": "Gang of tapestry 5 - Tapestry5-jqPlot" }, { "code": null, "e": 108501, "s": 108463, "text": "Gang of tapestry 5 - Tapestry5-Jquery" }, { "code": null, "e": 108546, "s": 108501, "text": "Gang of tapestry 5 - Tapestry5-Jquery-mobile" }, { "code": null, "e": 108585, "s": 108546, "text": "Gang of tapestry 5 - Tapestry5-Portlet" }, { "code": null, "e": 109177, "s": 108585, "text": "One of the best feature of the tapestry is Detailed Error Reporting. Tapestry helps a developer by providing the state of art exception reporting. Tapestry exception report is simple HTML with detailed information. Anyone can easily understand the report. Tapestry shows the error in HTML as well as save the exception in a plain text with date and time of the exception occurred. This will help developer to check the exception in production environment as well. The developer can remain confident of fixing any issues like broken templates, unexpected null values, unmatched request, etc.," }, { "code": null, "e": 109451, "s": 109177, "text": "Tapestry will reload the templates and classes automatically when modified. This feature enables the immediate reflection of application changes without going through build and test cycle. Also, this feature greatly improves the productivity of the application development." }, { "code": null, "e": 109591, "s": 109451, "text": "Consider the root package of the application is org.example.myfirstapp. Then, the classes in the following paths are scanned for reloading." }, { "code": null, "e": 109620, "s": 109591, "text": "org.example.myfirstapp.pages" }, { "code": null, "e": 109654, "s": 109620, "text": "org.example.myfirstapp.components" }, { "code": null, "e": 109684, "s": 109654, "text": "org.example.myfirstapp.mixins" }, { "code": null, "e": 109712, "s": 109684, "text": "org.example.myfirstapp.base" }, { "code": null, "e": 109744, "s": 109712, "text": "org.example.myfirstapp.services" }, { "code": null, "e": 109843, "s": 109744, "text": "The live class reloading can be disabled by setting the production mode to true in AppModule.java." }, { "code": null, "e": 109906, "s": 109843, "text": "configuration.add(SymbolicConstants.PRODUCTION_MODE,”false”);\n" }, { "code": null, "e": 110053, "s": 109906, "text": "Unit testing is a technique by which individual pages and components are tested. Tapestry provides easy options to unit test pages and components." }, { "code": null, "e": 110501, "s": 110053, "text": "Unit testing a page: Tapestry provide a class PageTester to test the application. This acts as both the browser and servlet container. It renders the page without the browser in the server-side itself and the resulting document can be checked for correct rendering. Consider a simple page Hello, which renders hello and the hello text is enclosed inside a html element with id hello_id. To test this feature, we can use PageTester as shown below −" }, { "code": null, "e": 110907, "s": 110501, "text": "public class PageTest extends Assert { \n @Test \n public void test1() { \n Sring appPackage = \"org.example.myfirstapp\"; // package name \n String appName = \"App1\"; // app name \n PageTester tester = new PageTester(appPackage, appName, \"src/main/webapp\"); \n Document doc = tester.renderPage(\"Hello\"); \n assertEquals(doc.getElementById(\"hello_id\").getChildText(), \"hello\"); \n } \n}" }, { "code": null, "e": 111049, "s": 110907, "text": "The PageTester also provides option to include context information, form submission, link navigation etc., in addition to rendering the page." }, { "code": null, "e": 111545, "s": 111049, "text": "Integrated testing helps to test the application as a module instead of checking the individual pages as in unit testing. In Integrated testing, multiple modules can be tested together as a unit. Tapestry provides a small library called Tapestry Test Utilities to do integrated testing. This library integrates with Selenium testing tool to perform the testing. The library provides a base class SeleniumTestCase, which starts and manages the Selenium server, Selenium client and Jetty Instance." }, { "code": null, "e": 111602, "s": 111545, "text": "One of the example of integrated testing is as follows −" }, { "code": null, "e": 111993, "s": 111602, "text": "import org.apache.tapestry5.test.SeleniumTestCase; \nimport org.testng.annotations.Test; \n\npublic class IntegrationTest extends SeleniumTestCase { \n @Test \n public void persist_entities() { \n open(\"/persistitem\"); \n assertEquals(getText(\"//span[@id='name']\").length(), 0); \n clickAndWait(\"link = create item\"); \n assertText(\"//span[@id = 'name']\", \"name\"); \n } \n}" }, { "code": null, "e": 112295, "s": 111993, "text": "The Development dashboard is the default page which is used to identify / resolve the problems in your application. The Dashboard is accessed by the URL http://localhost:8080/myfirstapp/core/t5dashboard. The dashboard shows all the pages, services and component libraries available in the application." }, { "code": null, "e": 112685, "s": 112295, "text": "Tapestry automatically compress the response using GZIP compression and stream it to the client. This feature will reduce the network traffic and aids faster delivery of the page. The compression can be configured using the symbol tapestry.min-gzip-size in AppModule.java. The default value is 100 bytes. Tapestry will compress the response once the size of the response crosses 100 bytes." }, { "code": null, "e": 112842, "s": 112685, "text": "Tapestry provides many options to secure the application against known security vulnerabilities in web application. Some of these options are listed below −" }, { "code": null, "e": 112963, "s": 112842, "text": "HTTPS − Tapestry pages can be annotated with @Secure to make it a secure page and accessible by the https protocol only." }, { "code": null, "e": 113084, "s": 112963, "text": "HTTPS − Tapestry pages can be annotated with @Secure to make it a secure page and accessible by the https protocol only." }, { "code": null, "e": 113166, "s": 113084, "text": "Page access control − Controlling the page to be accessed by a certain user only." }, { "code": null, "e": 113248, "s": 113166, "text": "Page access control − Controlling the page to be accessed by a certain user only." }, { "code": null, "e": 113378, "s": 113248, "text": "White-Listed Page − Tapestry pages can be annotated with a @WhitelistAccessOnly to make it accessible only through the localhost." }, { "code": null, "e": 113508, "s": 113378, "text": "White-Listed Page − Tapestry pages can be annotated with a @WhitelistAccessOnly to make it accessible only through the localhost." }, { "code": null, "e": 113656, "s": 113508, "text": "Asset Security − Under tapestry, only certain types of files are accessible. Others can be accessed only when the MD5 hash of the file is provided." }, { "code": null, "e": 113804, "s": 113656, "text": "Asset Security − Under tapestry, only certain types of files are accessible. Others can be accessed only when the MD5 hash of the file is provided." }, { "code": null, "e": 113944, "s": 113804, "text": "Serialized Object Date − Tapestry integrates a HMAC into serialized Java object data and sends it to the client to avoid message tampering." }, { "code": null, "e": 114084, "s": 113944, "text": "Serialized Object Date − Tapestry integrates a HMAC into serialized Java object data and sends it to the client to avoid message tampering." }, { "code": null, "e": 114211, "s": 114084, "text": "Cross Site Request Forgery − Tapestry provides a 3rd party module called tapestry-csrf-protection to prevent any CSRF attacks." }, { "code": null, "e": 114338, "s": 114211, "text": "Cross Site Request Forgery − Tapestry provides a 3rd party module called tapestry-csrf-protection to prevent any CSRF attacks." }, { "code": null, "e": 114525, "s": 114338, "text": "Security Framework integration − Tapestry does not lock into a single authentication / authorization implementation. Tapestry can be integrated with any popular authentication framework." }, { "code": null, "e": 114712, "s": 114525, "text": "Security Framework integration − Tapestry does not lock into a single authentication / authorization implementation. Tapestry can be integrated with any popular authentication framework." }, { "code": null, "e": 115139, "s": 114712, "text": "Tapestry provides extensive support for logging, the automatic recording of the progress of the application as it runs. Tapestry uses the de-facto Java logging library, SLF4J. The annotation @Log can be in any component method to emit the entry and exit of the method and the possible exception as well. Also, the Tapestry provided logger object can be injected into any component using the @Inject annotation as shown below −" }, { "code": null, "e": 115381, "s": 115139, "text": "public class MyPage { \n @Inject \n private Logger logger; \n \n // . . . \n \n void onSuccessFromForm() { \n logger.info(\"Changes saved successfully\"); \n } \n \n @Log \n void onValidateFromForm() { \n // logic \n } \n}" }, { "code": null, "e": 115672, "s": 115381, "text": "Finally, we can now say that Apache Tapestry brings best ways to build concise, scalable, maintainable, robust and Ajax-enabled applications. Tapestry can be integrated with any third-party Java application. It can also help in creating a large web application as it is quite easy and fast." }, { "code": null, "e": 115707, "s": 115672, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 115726, "s": 115707, "text": " Arnab Chakraborty" }, { "code": null, "e": 115761, "s": 115726, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 115782, "s": 115761, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 115815, "s": 115782, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 115828, "s": 115815, "text": " Nilay Mehta" }, { "code": null, "e": 115863, "s": 115828, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 115881, "s": 115863, "text": " Bigdata Engineer" }, { "code": null, "e": 115914, "s": 115881, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 115932, "s": 115914, "text": " Bigdata Engineer" }, { "code": null, "e": 115965, "s": 115932, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 115983, "s": 115965, "text": " Bigdata Engineer" }, { "code": null, "e": 115990, "s": 115983, "text": " Print" }, { "code": null, "e": 116001, "s": 115990, "text": " Add Notes" } ]
Bit Manipulation technique to replace boolean arrays of fixed size less than 64 - GeeksforGeeks
28 Jan, 2022 Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been used as a container to solve different problems. This article focuses on discussing the alternatives to boolean arrays. Integer Variable as a container In general, the Integer variable has 4 bytes (C++ taken into consideration) resulting in having 32 boolean bits to represent a number. For example, to represent 10, the boolean bits can be written as: int a = 10 In Memory-00000000000000000000000000001010 (Binary of 10 in 32-bit integer) This means one can use these bits as a boolean value inside a boolean array of size 32. A 64-bit integer can be used to increase the size if needed. How to use Integer variable as a container? Let’s discuss in detail how to use the Integer variable as a container. The first step is to initialize the integer variable as 0, to get the boolean container of size 32 with all bits initially false. Set a bit to true:Set any bit to true for any desired location by using bitwise operators such as AND, NOT, OR, and SHIFT operators. For, example, to set a bit to true at position 7- Use shift and bitwise OR operator to make the ith bit to 1 (true)int a = 0;a |= (1 << 7);Here a will become : 00000000000000000000000010000000 ↑ 0th bit Step 1: First move 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).Step 2: Next, do bitwise or with the number. Step 3: As 1 OR 0 = 1 and 1 OR 1 = 1, this will set the 7th bit to one without affecting other bits. Set a bit to false: For example, to reset a bit to false at position 7 Use shift and bitwise NOT and AND operator to make the ith bit to 0(false).int a = 0;a |= (1 << 7); // To set 7th bita &= ~(1 << 7); // To reset 7th bit Step 1: First move our 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).Step 2: Invert the bits to look like (...1101111111).Step 3: Perform AND operation with the number.Step 4: As 1 AND 0 = 0, 0 AND 0 = 0, 1 AND 1 = 1, this will set the 7th bit to one without affecting other bits. Get the value of ith bit: For example, to get the value of the 7th bit- Use AND operator to print.int a = 0;a |= (1<<7); // To set 7th bitPrint((a>>7)&1); // this will print 1(True)a &= ~(1<<7); // To reset 7th bitPrint((a>>7)&1); // this will print 0(false) Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program to implement// the above approach#include<iostream>using namespace std; // Driver codeint main(){ // This is an integer variable // used as a container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit cout << "Setting " << workingBit << "th bit to 1\n"; myBoolContainer |= (1 << workingBit); // Printing the ith bit cout << "Value at " << workingBit << "th bit = " << ((myBoolContainer >> workingBit) & 1) << "\n\n"; // Resetting the ith bit cout << "Resetting " << workingBit << "th bit to 0\n"; myBoolContainer &= ~(1 << 7); // Printing the ith bit cout << "Value at " << workingBit << "th bit = " << ((myBoolContainer >> workingBit) & 1);} // Java program to implement// the above approachimport java.io.*; // Driver codeclass GFG{ public static void main (String[] args) { // This will be the integer variable // used as boolean container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit System.out.println( "Setting " + workingBit + "th bit to 1"); myBoolContainer |= (1 << workingBit); // Printing the ith bit System.out.println( "Value at " + workingBit+"th bit = " + ((myBoolContainer >> workingBit) & 1) + "\n"); // Resetting the ith bit System.out.println( "Resetting " + workingBit + "th bit to 0"); myBoolContainer &= ~(1 << 7); // Printing the ith bit System.out.println( "Value at " + workingBit + "th bit = " + ((myBoolContainer >>workingBit) & 1)); }} # Python program to implement# the above approach# This will be the integer variable# used as boolean containermyBoolContainer = 0; # 7th bit will be used as exampleworkingBit = 7; # Setting ith bitprint("Setting " + str(workingBit) + "th bit to 1");myBoolContainer |= (1 << workingBit); # Printing the ith bitprint("Value at " + str(workingBit) + "th bit = " + str((myBoolContainer >> workingBit) & 1) + "\n"); # Resetting the ith bitprint("Resetting " + str(workingBit) + "th bit to 0");myBoolContainer &= ~(1 << 7); # Printing the ith bitprint("Value at " + str(workingBit) + "th bit = " + str((myBoolContainer >> workingBit) & 1)) //C# code for the above approachusing System;public class GFG { static public void Main() { // This will be the integer variable // used as boolean container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit Console.WriteLine("Setting " + workingBit + "th bit to 1"); myBoolContainer |= (1 << workingBit); // Printing the ith bit Console.WriteLine( "Value at " + workingBit + "th bit = " + ((myBoolContainer >> workingBit) & 1) + "\n"); // Resetting the ith bit Console.WriteLine("Resetting " + workingBit + "th bit to 0"); myBoolContainer &= ~(1 << 7); // Printing the ith bit Console.WriteLine( "Value at " + workingBit + "th bit = " + ((myBoolContainer >> workingBit) & 1)); }} // This code is contributed by Potta Lokesh // Javascript program to implement// the above approach// This is an integer variable// used as a containervar myBoolContainer = 0; // 7th bit will be used samplevar workingBit = 7; // Setting ith bitconsole.log("Setting " + workingBit + "th bit to 1\n");myBoolContainer |= (1 << workingBit); //Printing the ith bitconsole.log("Value at " + workingBit + "th bit = "+ ((myBoolContainer >> workingBit) & 1) + "\n\n"); // Resetting the ith bitconsole.log("Resetting " + workingBit + "th bit to 0\n");myBoolContainer &= ~(1 << 7); // Printing the ith bitconsole.log("Value at " + workingBit + "th bit = " + ((myBoolContainer >> workingBit) & 1)); Setting 7th bit to 1 Value at 7th bit = 1 Resetting 7th bit to 0 Value at 7th bit = 0 Solve Pangram Strings: Let’s solve the problem of pangram strings using the above approach. Approach: It is known that English alphabets of lower case range from (a-z) are having a count of no more than 26. So, in this approach, a bool array of constant size can be used. This will optimize the space complexity of the code. Below is the implementation of the pangram strings using a boolean array: C++ Java Python C# Javascript // C++ program to implement// the above approach#include <iostream>using namespace std; bool checkIsPanagram(string sentence){ // Initializing the container int n = 0; for(char &x:sentence) { // Checking that the char // is Alphabetic if(isalpha(x)) // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (tolower(x) - 'a')); } // decimal number for all ones in last // 26 bits in binary is 67108863 return n == 67108863;} // Driver codeint main(){ string s = "Pack mY box witH fIve dozen liquor jugs"; cout << checkIsPanagram(s);} // Java program to implement// the above approachimport java.io.*;class Panagram{ public boolean checkIsPanagram( String sentence) { // Initializing the container int n = 0; int size = sentence.length(); for(int i = 0; i < size; i++) { // Storing current character // in temp variable char x = sentence.charAt(i); // checking that the char is Alphabetic if(Character.isAlphabetic(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (Character.toLowerCase(x) - 'a')); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); }}; // Driver codeclass GFG{ public static void main (String[] args) { String s = "Pack mY box witH fIve dozen liquor jugs"; Panagram panagram = new Panagram(); System.out.println( panagram.checkIsPanagram(s)); }} # Python program to implement# the above approachdef isPanagram(sentence): # Initializing the container n = 0 for char in sentence: # Checking that the char # is Alphabetic if char.isalpha(): # setting ith bit to 1 # if char is a then this will # set 0th bit to 1 and so on n |= (1 << (ord(char.lower()) - ord('a'))) # Decimal number for all ones in # last 26 bits in binary is 67108863 return n == 67108863 sentence ="Pack mY box witH fIve dozen liquor jugs"print(isPanagram(sentence)) // C# program to implement// the above approachusing System; class Panagram{ public bool checkIsPanagram( String sentence) { // Initializing the container int n = 0; int size = sentence.Length; for(int i = 0; i < size; i++) { // Storing current character // in temp variable char x = sentence[i]; // checking that the char is Alphabetic if(char.IsLetter(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (char.ToLower(x) - 'a')); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); }}; // Driver codepublic class GFG{ public static void Main(String[] args) { String s = "Pack mY box witH fIve dozen liquor jugs"; Panagram panagram = new Panagram(); Console.WriteLine( panagram.checkIsPanagram(s)); }} // This code is contributed by 29AjayKumar <script>// javascript program to implement// the above approachfunction checkIsPanagram(sentence) { // Initializing the container var n = 0; var size = sentence.length; for(var i = 0; i < size; i++) { // Storing current character // in temp variable var x = sentence[i]; // checking that the char is Alphabetic if(isAlphabetic(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n = n | (1 << (x.charCodeAt(0)- 'a'.charCodeAt(0))); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); }function isAlphabetic(str){ return /^[a-zA-Z()]+$/.test(str);} // Driver codevar s ="Pack mY box witH fIve dozen liquor jugs";document.write(checkIsPanagram(s)); // This code is contributed by 29AjayKumar</script> 1 lokeshpotta20 29AjayKumar Algo-Geek 2021 Algo Geek Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find sum of factorials till N factorial (1! + 2! + 3! + ... + N!) Create a balanced BST using vector in C++ STL Generate string after adding spaces at specific positions in a given String Count of operation required to water all the plants Maximize groups to be formed such that product of size of group with its minimum element is at least K Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Cyclic Redundancy Check and Modulo-2 Division How to swap two numbers without using a temporary variable? Little and Big Endian Mystery
[ { "code": null, "e": 25290, "s": 25262, "text": "\n28 Jan, 2022" }, { "code": null, "e": 25761, "s": 25290, "text": "Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been used as a container to solve different problems. This article focuses on discussing the alternatives to boolean arrays." }, { "code": null, "e": 25793, "s": 25761, "text": "Integer Variable as a container" }, { "code": null, "e": 25994, "s": 25793, "text": "In general, the Integer variable has 4 bytes (C++ taken into consideration) resulting in having 32 boolean bits to represent a number. For example, to represent 10, the boolean bits can be written as:" }, { "code": null, "e": 26005, "s": 25994, "text": "int a = 10" }, { "code": null, "e": 26081, "s": 26005, "text": "In Memory-00000000000000000000000000001010 (Binary of 10 in 32-bit integer)" }, { "code": null, "e": 26230, "s": 26081, "text": "This means one can use these bits as a boolean value inside a boolean array of size 32. A 64-bit integer can be used to increase the size if needed." }, { "code": null, "e": 26274, "s": 26230, "text": "How to use Integer variable as a container?" }, { "code": null, "e": 26346, "s": 26274, "text": "Let’s discuss in detail how to use the Integer variable as a container." }, { "code": null, "e": 26476, "s": 26346, "text": "The first step is to initialize the integer variable as 0, to get the boolean container of size 32 with all bits initially false." }, { "code": null, "e": 26659, "s": 26476, "text": "Set a bit to true:Set any bit to true for any desired location by using bitwise operators such as AND, NOT, OR, and SHIFT operators. For, example, to set a bit to true at position 7-" }, { "code": null, "e": 26998, "s": 26659, "text": "Use shift and bitwise OR operator to make the ith bit to 1 (true)int a = 0;a |= (1 << 7);Here a will become : 00000000000000000000000010000000 ↑ 0th bit" }, { "code": null, "e": 27236, "s": 26998, "text": "Step 1: First move 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).Step 2: Next, do bitwise or with the number. Step 3: As 1 OR 0 = 1 and 1 OR 1 = 1, this will set the 7th bit to one without affecting other bits." }, { "code": null, "e": 27256, "s": 27236, "text": "Set a bit to false:" }, { "code": null, "e": 27307, "s": 27256, "text": "For example, to reset a bit to false at position 7" }, { "code": null, "e": 27460, "s": 27307, "text": "Use shift and bitwise NOT and AND operator to make the ith bit to 0(false).int a = 0;a |= (1 << 7); // To set 7th bita &= ~(1 << 7); // To reset 7th bit" }, { "code": null, "e": 27768, "s": 27460, "text": "Step 1: First move our 1 which is (..0001) in binary to 7 steps left to make it as (..10000000).Step 2: Invert the bits to look like (...1101111111).Step 3: Perform AND operation with the number.Step 4: As 1 AND 0 = 0, 0 AND 0 = 0, 1 AND 1 = 1, this will set the 7th bit to one without affecting other bits." }, { "code": null, "e": 27794, "s": 27768, "text": "Get the value of ith bit:" }, { "code": null, "e": 27840, "s": 27794, "text": "For example, to get the value of the 7th bit-" }, { "code": null, "e": 28028, "s": 27840, "text": "Use AND operator to print.int a = 0;a |= (1<<7); // To set 7th bitPrint((a>>7)&1); // this will print 1(True)a &= ~(1<<7); // To reset 7th bitPrint((a>>7)&1); // this will print 0(false)" }, { "code": null, "e": 28079, "s": 28028, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28083, "s": 28079, "text": "C++" }, { "code": null, "e": 28088, "s": 28083, "text": "Java" }, { "code": null, "e": 28095, "s": 28088, "text": "Python" }, { "code": null, "e": 28098, "s": 28095, "text": "C#" }, { "code": null, "e": 28109, "s": 28098, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include<iostream>using namespace std; // Driver codeint main(){ // This is an integer variable // used as a container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit cout << \"Setting \" << workingBit << \"th bit to 1\\n\"; myBoolContainer |= (1 << workingBit); // Printing the ith bit cout << \"Value at \" << workingBit << \"th bit = \" << ((myBoolContainer >> workingBit) & 1) << \"\\n\\n\"; // Resetting the ith bit cout << \"Resetting \" << workingBit << \"th bit to 0\\n\"; myBoolContainer &= ~(1 << 7); // Printing the ith bit cout << \"Value at \" << workingBit << \"th bit = \" << ((myBoolContainer >> workingBit) & 1);}", "e": 28915, "s": 28109, "text": null }, { "code": "// Java program to implement// the above approachimport java.io.*; // Driver codeclass GFG{ public static void main (String[] args) { // This will be the integer variable // used as boolean container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit System.out.println( \"Setting \" + workingBit + \"th bit to 1\"); myBoolContainer |= (1 << workingBit); // Printing the ith bit System.out.println( \"Value at \" + workingBit+\"th bit = \" + ((myBoolContainer >> workingBit) & 1) + \"\\n\"); // Resetting the ith bit System.out.println( \"Resetting \" + workingBit + \"th bit to 0\"); myBoolContainer &= ~(1 << 7); // Printing the ith bit System.out.println( \"Value at \" + workingBit + \"th bit = \" + ((myBoolContainer >>workingBit) & 1)); }}", "e": 29900, "s": 28915, "text": null }, { "code": "# Python program to implement# the above approach# This will be the integer variable# used as boolean containermyBoolContainer = 0; # 7th bit will be used as exampleworkingBit = 7; # Setting ith bitprint(\"Setting \" + str(workingBit) + \"th bit to 1\");myBoolContainer |= (1 << workingBit); # Printing the ith bitprint(\"Value at \" + str(workingBit) + \"th bit = \" + str((myBoolContainer >> workingBit) & 1) + \"\\n\"); # Resetting the ith bitprint(\"Resetting \" + str(workingBit) + \"th bit to 0\");myBoolContainer &= ~(1 << 7); # Printing the ith bitprint(\"Value at \" + str(workingBit) + \"th bit = \" + str((myBoolContainer >> workingBit) & 1))", "e": 30606, "s": 29900, "text": null }, { "code": "//C# code for the above approachusing System;public class GFG { static public void Main() { // This will be the integer variable // used as boolean container int myBoolContainer = 0; // 7th bit will be used for sample int workingBit = 7; // Setting ith bit Console.WriteLine(\"Setting \" + workingBit + \"th bit to 1\"); myBoolContainer |= (1 << workingBit); // Printing the ith bit Console.WriteLine( \"Value at \" + workingBit + \"th bit = \" + ((myBoolContainer >> workingBit) & 1) + \"\\n\"); // Resetting the ith bit Console.WriteLine(\"Resetting \" + workingBit + \"th bit to 0\"); myBoolContainer &= ~(1 << 7); // Printing the ith bit Console.WriteLine( \"Value at \" + workingBit + \"th bit = \" + ((myBoolContainer >> workingBit) & 1)); }} // This code is contributed by Potta Lokesh", "e": 31597, "s": 30606, "text": null }, { "code": "// Javascript program to implement// the above approach// This is an integer variable// used as a containervar myBoolContainer = 0; // 7th bit will be used samplevar workingBit = 7; // Setting ith bitconsole.log(\"Setting \" + workingBit + \"th bit to 1\\n\");myBoolContainer |= (1 << workingBit); //Printing the ith bitconsole.log(\"Value at \" + workingBit + \"th bit = \"+ ((myBoolContainer >> workingBit) & 1) + \"\\n\\n\"); // Resetting the ith bitconsole.log(\"Resetting \" + workingBit + \"th bit to 0\\n\");myBoolContainer &= ~(1 << 7); // Printing the ith bitconsole.log(\"Value at \" + workingBit + \"th bit = \" + ((myBoolContainer >> workingBit) & 1));", "e": 32345, "s": 31597, "text": null }, { "code": null, "e": 32432, "s": 32345, "text": "Setting 7th bit to 1\nValue at 7th bit = 1\n\nResetting 7th bit to 0\nValue at 7th bit = 0" }, { "code": null, "e": 32455, "s": 32432, "text": "Solve Pangram Strings:" }, { "code": null, "e": 32524, "s": 32455, "text": "Let’s solve the problem of pangram strings using the above approach." }, { "code": null, "e": 32534, "s": 32524, "text": "Approach:" }, { "code": null, "e": 32757, "s": 32534, "text": "It is known that English alphabets of lower case range from (a-z) are having a count of no more than 26. So, in this approach, a bool array of constant size can be used. This will optimize the space complexity of the code." }, { "code": null, "e": 32831, "s": 32757, "text": "Below is the implementation of the pangram strings using a boolean array:" }, { "code": null, "e": 32835, "s": 32831, "text": "C++" }, { "code": null, "e": 32840, "s": 32835, "text": "Java" }, { "code": null, "e": 32847, "s": 32840, "text": "Python" }, { "code": null, "e": 32850, "s": 32847, "text": "C#" }, { "code": null, "e": 32861, "s": 32850, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <iostream>using namespace std; bool checkIsPanagram(string sentence){ // Initializing the container int n = 0; for(char &x:sentence) { // Checking that the char // is Alphabetic if(isalpha(x)) // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (tolower(x) - 'a')); } // decimal number for all ones in last // 26 bits in binary is 67108863 return n == 67108863;} // Driver codeint main(){ string s = \"Pack mY box witH fIve dozen liquor jugs\"; cout << checkIsPanagram(s);}", "e": 33557, "s": 32861, "text": null }, { "code": "// Java program to implement// the above approachimport java.io.*;class Panagram{ public boolean checkIsPanagram( String sentence) { // Initializing the container int n = 0; int size = sentence.length(); for(int i = 0; i < size; i++) { // Storing current character // in temp variable char x = sentence.charAt(i); // checking that the char is Alphabetic if(Character.isAlphabetic(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (Character.toLowerCase(x) - 'a')); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); }}; // Driver codeclass GFG{ public static void main (String[] args) { String s = \"Pack mY box witH fIve dozen liquor jugs\"; Panagram panagram = new Panagram(); System.out.println( panagram.checkIsPanagram(s)); }}", "e": 34671, "s": 33557, "text": null }, { "code": "# Python program to implement# the above approachdef isPanagram(sentence): # Initializing the container n = 0 for char in sentence: # Checking that the char # is Alphabetic if char.isalpha(): # setting ith bit to 1 # if char is a then this will # set 0th bit to 1 and so on n |= (1 << (ord(char.lower()) - ord('a'))) # Decimal number for all ones in # last 26 bits in binary is 67108863 return n == 67108863 sentence =\"Pack mY box witH fIve dozen liquor jugs\"print(isPanagram(sentence))", "e": 35312, "s": 34671, "text": null }, { "code": "// C# program to implement// the above approachusing System; class Panagram{ public bool checkIsPanagram( String sentence) { // Initializing the container int n = 0; int size = sentence.Length; for(int i = 0; i < size; i++) { // Storing current character // in temp variable char x = sentence[i]; // checking that the char is Alphabetic if(char.IsLetter(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n |= (1 << (char.ToLower(x) - 'a')); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); }}; // Driver codepublic class GFG{ public static void Main(String[] args) { String s = \"Pack mY box witH fIve dozen liquor jugs\"; Panagram panagram = new Panagram(); Console.WriteLine( panagram.checkIsPanagram(s)); }} // This code is contributed by 29AjayKumar", "e": 36470, "s": 35312, "text": null }, { "code": "<script>// javascript program to implement// the above approachfunction checkIsPanagram(sentence) { // Initializing the container var n = 0; var size = sentence.length; for(var i = 0; i < size; i++) { // Storing current character // in temp variable var x = sentence[i]; // checking that the char is Alphabetic if(isAlphabetic(x)) { // setting ith bit to 1 // if char is 'a' then this will // set 0th bit to 1 and so on n = n | (1 << (x.charCodeAt(0)- 'a'.charCodeAt(0))); } } // Decimal number for all ones in last // 26 bits in binary is 67108863 return (n == 67108863); }function isAlphabetic(str){ return /^[a-zA-Z()]+$/.test(str);} // Driver codevar s =\"Pack mY box witH fIve dozen liquor jugs\";document.write(checkIsPanagram(s)); // This code is contributed by 29AjayKumar</script>", "e": 37487, "s": 36470, "text": null }, { "code": null, "e": 37492, "s": 37490, "text": "1" }, { "code": null, "e": 37508, "s": 37494, "text": "lokeshpotta20" }, { "code": null, "e": 37520, "s": 37508, "text": "29AjayKumar" }, { "code": null, "e": 37535, "s": 37520, "text": "Algo-Geek 2021" }, { "code": null, "e": 37545, "s": 37535, "text": "Algo Geek" }, { "code": null, "e": 37555, "s": 37545, "text": "Bit Magic" }, { "code": null, "e": 37565, "s": 37555, "text": "Bit Magic" }, { "code": null, "e": 37663, "s": 37565, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37729, "s": 37663, "text": "Find sum of factorials till N factorial (1! + 2! + 3! + ... + N!)" }, { "code": null, "e": 37775, "s": 37729, "text": "Create a balanced BST using vector in C++ STL" }, { "code": null, "e": 37851, "s": 37775, "text": "Generate string after adding spaces at specific positions in a given String" }, { "code": null, "e": 37903, "s": 37851, "text": "Count of operation required to water all the plants" }, { "code": null, "e": 38006, "s": 37903, "text": "Maximize groups to be formed such that product of size of group with its minimum element is at least K" }, { "code": null, "e": 38052, "s": 38006, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 38120, "s": 38052, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 38166, "s": 38120, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 38226, "s": 38166, "text": "How to swap two numbers without using a temporary variable?" } ]
How to select part of a Timestamp in a MySQL Query?
To select part of a timestamp in a query, you need to use YEAR() function. The syntax is as follows in MySQL. select YEAR(yourTimestampColumnName) as anyAliasName from yourTableName; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table SelectPartOfTimestampDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ShippingTime TIMESTAMP -> ); Query OK, 0 rows affected (1.11 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(now()); Query OK, 1 row affected (0.20 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval -2 year)); Query OK, 1 row affected (0.17 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval -3 year)); Query OK, 1 row affected (0.18 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval -1 year)); Query OK, 1 row affected (0.18 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval 1 year)); Query OK, 1 row affected (0.16 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval 2 year)); Query OK, 1 row affected (0.48 sec) mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(date_add(now(),interval 3 year)); Query OK, 1 row affected (0.10 sec) Display all records from the table using a select statement. The query is as follows − mysql> select *from SelectPartOfTimestampDemo; The following is the output − +----+---------------------+ | Id | ShippingTime | +----+---------------------+ | 1 | 2019-02-08 15:03:27 | | 2 | 2017-02-08 15:03:50 | | 3 | 2016-02-08 15:04:03 | | 4 | 2018-02-08 15:04:06 | | 5 | 2020-02-08 15:04:10 | | 6 | 2021-02-08 15:04:24 | | 7 | 2022-02-08 15:04:30 | +----+---------------------+ 7 rows in set (0.00 sec) Here is the query to select part of a timestamp using YEAR() function − mysql> select YEAR(ShippingTime) as PartOfTimeStamp from SelectPartOfTimestampDemo; The following is the output − +-----------------+ | PartOfTimeStamp | +-----------------+ | 2019 | | 2017 | | 2016 | | 2018 | | 2020 | | 2021 | | 2022 | +-----------------+ 7 rows in set (0.00 sec)
[ { "code": null, "e": 1172, "s": 1062, "text": "To select part of a timestamp in a query, you need to use YEAR() function. The syntax is as follows in MySQL." }, { "code": null, "e": 1245, "s": 1172, "text": "select YEAR(yourTimestampColumnName) as anyAliasName from yourTableName;" }, { "code": null, "e": 1344, "s": 1245, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1523, "s": 1344, "text": "mysql> create table SelectPartOfTimestampDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> ShippingTime TIMESTAMP\n -> );\nQuery OK, 0 rows affected (1.11 sec)" }, { "code": null, "e": 1616, "s": 1523, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2545, "s": 1616, "text": "mysql> insert into SelectPartOfTimestampDemo(ShippingTime) values(now());\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into SelectPartOfTimestampDemo(ShippingTime)\nvalues(date_add(now(),interval -2 year));\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into SelectPartOfTimestampDemo(ShippingTime)\nvalues(date_add(now(),interval -3 year));\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into SelectPartOfTimestampDemo(ShippingTime)\nvalues(date_add(now(),interval -1 year));\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into SelectPartOfTimestampDemo(ShippingTime)\nvalues(date_add(now(),interval 1 year));\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into SelectPartOfTimestampDemo(ShippingTime)\nvalues(date_add(now(),interval 2 year));\nQuery OK, 1 row affected (0.48 sec)\nmysql> insert into SelectPartOfTimestampDemo(ShippingTime)\nvalues(date_add(now(),interval 3 year));\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 2632, "s": 2545, "text": "Display all records from the table using a select statement. The query is as follows −" }, { "code": null, "e": 2679, "s": 2632, "text": "mysql> select *from SelectPartOfTimestampDemo;" }, { "code": null, "e": 2709, "s": 2679, "text": "The following is the output −" }, { "code": null, "e": 3053, "s": 2709, "text": "+----+---------------------+\n| Id | ShippingTime |\n+----+---------------------+\n| 1 | 2019-02-08 15:03:27 |\n| 2 | 2017-02-08 15:03:50 |\n| 3 | 2016-02-08 15:04:03 |\n| 4 | 2018-02-08 15:04:06 |\n| 5 | 2020-02-08 15:04:10 |\n| 6 | 2021-02-08 15:04:24 |\n| 7 | 2022-02-08 15:04:30 |\n+----+---------------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3125, "s": 3053, "text": "Here is the query to select part of a timestamp using YEAR() function −" }, { "code": null, "e": 3209, "s": 3125, "text": "mysql> select YEAR(ShippingTime) as PartOfTimeStamp from SelectPartOfTimestampDemo;" }, { "code": null, "e": 3239, "s": 3209, "text": "The following is the output −" }, { "code": null, "e": 3484, "s": 3239, "text": "+-----------------+\n| PartOfTimeStamp |\n+-----------------+\n| 2019 |\n| 2017 |\n| 2016 |\n| 2018 |\n| 2020 |\n| 2021 |\n| 2022 |\n+-----------------+\n7 rows in set (0.00 sec)" } ]
Python - Text Processing Environment
To successfully create and run the example code in this tutorial we will need an environment set up which will have both general-purpose python as well as the special packages required for Data science. We will first look as installing the general-purpose python which can be python 2 or python 3. But we will prefer python 2 for this tutorial mainly because of its maturity and wider support of external packages. The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/ You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats. Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Python on various platforms − Here are the simple steps to install Python on Unix/Linux machine. Open a Web browser and go to https://www.python.org/downloads/. Open a Web browser and go to https://www.python.org/downloads/. Follow the link to download zipped source code available for Unix/Linux. Follow the link to download zipped source code available for Unix/Linux. Download and extract files. Download and extract files. Editing the Modules/Setup file if you want to customize some options. Editing the Modules/Setup file if you want to customize some options. run ./configure script run ./configure script make make make install make install This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python. Here are the steps to install Python on Windows machine. Open a Web browser and go to https://www.python.org/downloads/. Open a Web browser and go to https://www.python.org/downloads/. Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done. Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available. Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation. Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables. The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs. The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not). In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path. To add the Python directory to the path for a particular session in Unix − In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter. In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter. In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter. In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter. In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter. In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter. Note − /usr/local/bin/python is the path of the Python directory Note − /usr/local/bin/python is the path of the Python directory To add the Python directory to the path for a particular session in Windows − At the command prompt − type path %path%;C:\Python and press Enter. Note − C:\Python is the path of the Python directory Here are important environment variables, which can be recognized by Python − PYTHONPATH It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer. PYTHONSTARTUP It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH. PYTHONCASEOK It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it. PYTHONHOME It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy. There are three different ways to start Python − You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. Enter python the command line. Start coding right away in the interactive interpreter. $python # Unix/Linux or python% # Unix/Linux or C:> python # Windows/DOS Here is the list of all the available command line options − -d It provides debug output. -O It generates optimized bytecode (resulting in .pyo files). -S Do not run import site to look for Python paths on startup. -v verbose output (detailed trace on import statements). -X disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6. -c cmd run Python script sent in as cmd string file run Python script from given file A Python script can be executed at command line by invoking the interpreter on your application, as in the following − $python script.py # Unix/Linux or python% script.py # Unix/Linux or C: >python script.py # Windows/DOS Note − Be sure the file permission mode allows execution. You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python. Unix − IDLE is the very first Unix IDE for Python. Unix − IDLE is the very first Unix IDE for Python. Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI. Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI. Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. NLTK is very straight forward to integrate into the python environment. Use the below command to add NLTK to the environment. sudo pip install -U nltk The addition of other libraries will be discussed in each chapter as and when we need for their use in the python program. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3002, "s": 2587, "text": "To successfully create and run the example code in this tutorial we will need an environment set up which will have both general-purpose python as well as the special packages required for Data science. We will first look as installing the general-purpose python which can be python 2 or python 3. But we will prefer python 2 for this tutorial mainly because of its maturity and wider support of external packages." }, { "code": null, "e": 3155, "s": 3002, "text": "The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python https://www.python.org/" }, { "code": null, "e": 3296, "s": 3155, "text": "You can download Python documentation from https://www.python.org/doc/. The documentation is available in HTML, PDF, and PostScript formats." }, { "code": null, "e": 3453, "s": 3296, "text": "Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python." }, { "code": null, "e": 3687, "s": 3453, "text": "If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation." }, { "code": null, "e": 3756, "s": 3687, "text": "Here is a quick overview of installing Python on various platforms −" }, { "code": null, "e": 3823, "s": 3756, "text": "Here are the simple steps to install Python on Unix/Linux machine." }, { "code": null, "e": 3887, "s": 3823, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 3951, "s": 3887, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 4024, "s": 3951, "text": "Follow the link to download zipped source code available for Unix/Linux." }, { "code": null, "e": 4097, "s": 4024, "text": "Follow the link to download zipped source code available for Unix/Linux." }, { "code": null, "e": 4125, "s": 4097, "text": "Download and extract files." }, { "code": null, "e": 4153, "s": 4125, "text": "Download and extract files." }, { "code": null, "e": 4223, "s": 4153, "text": "Editing the Modules/Setup file if you want to customize some options." }, { "code": null, "e": 4293, "s": 4223, "text": "Editing the Modules/Setup file if you want to customize some options." }, { "code": null, "e": 4316, "s": 4293, "text": "run ./configure script" }, { "code": null, "e": 4339, "s": 4316, "text": "run ./configure script" }, { "code": null, "e": 4344, "s": 4339, "text": "make" }, { "code": null, "e": 4349, "s": 4344, "text": "make" }, { "code": null, "e": 4362, "s": 4349, "text": "make install" }, { "code": null, "e": 4375, "s": 4362, "text": "make install" }, { "code": null, "e": 4512, "s": 4375, "text": "This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python." }, { "code": null, "e": 4569, "s": 4512, "text": "Here are the steps to install Python on Windows machine." }, { "code": null, "e": 4633, "s": 4569, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 4697, "s": 4633, "text": "Open a Web browser and go to https://www.python.org/downloads/." }, { "code": null, "e": 4805, "s": 4697, "text": "Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install." }, { "code": null, "e": 4913, "s": 4805, "text": "Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install." }, { "code": null, "e": 5112, "s": 4913, "text": "To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI." }, { "code": null, "e": 5311, "s": 5112, "text": "To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI." }, { "code": null, "e": 5495, "s": 5311, "text": "Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done." }, { "code": null, "e": 5679, "s": 5495, "text": "Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done." }, { "code": null, "e": 5990, "s": 5679, "text": "Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is available." }, { "code": null, "e": 6197, "s": 5990, "text": "Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation." }, { "code": null, "e": 6369, "s": 6197, "text": "Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables." }, { "code": null, "e": 6562, "s": 6369, "text": "The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs." }, { "code": null, "e": 6666, "s": 6562, "text": "The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not)." }, { "code": null, "e": 6829, "s": 6666, "text": "In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path." }, { "code": null, "e": 6904, "s": 6829, "text": "To add the Python directory to the path for a particular session in Unix −" }, { "code": null, "e": 6987, "s": 6904, "text": "In the csh shell − type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7070, "s": 6987, "text": "In the csh shell − type setenv PATH \"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7161, "s": 7070, "text": "In the bash shell (Linux) − type export ATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7252, "s": 7161, "text": "In the bash shell (Linux) − type export ATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7334, "s": 7252, "text": "In the sh or ksh shell − type PATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7416, "s": 7334, "text": "In the sh or ksh shell − type PATH=\"$PATH:/usr/local/bin/python\" and press Enter." }, { "code": null, "e": 7481, "s": 7416, "text": "Note − /usr/local/bin/python is the path of the Python directory" }, { "code": null, "e": 7546, "s": 7481, "text": "Note − /usr/local/bin/python is the path of the Python directory" }, { "code": null, "e": 7624, "s": 7546, "text": "To add the Python directory to the path for a particular session in Windows −" }, { "code": null, "e": 7692, "s": 7624, "text": "At the command prompt − type path %path%;C:\\Python and press Enter." }, { "code": null, "e": 7746, "s": 7692, "text": "Note − C:\\Python is the path of the Python directory" }, { "code": null, "e": 7824, "s": 7746, "text": "Here are important environment variables, which can be recognized by Python −" }, { "code": null, "e": 7835, "s": 7824, "text": "PYTHONPATH" }, { "code": null, "e": 8128, "s": 7835, "text": "It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer." }, { "code": null, "e": 8142, "s": 8128, "text": "PYTHONSTARTUP" }, { "code": null, "e": 8376, "s": 8142, "text": "It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it\ncontains commands that load utilities or modify PYTHONPATH." }, { "code": null, "e": 8389, "s": 8376, "text": "PYTHONCASEOK" }, { "code": null, "e": 8542, "s": 8389, "text": "It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it." }, { "code": null, "e": 8553, "s": 8542, "text": "PYTHONHOME" }, { "code": null, "e": 8705, "s": 8553, "text": "It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy." }, { "code": null, "e": 8754, "s": 8705, "text": "There are three different ways to start Python −" }, { "code": null, "e": 8873, "s": 8754, "text": "You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window." }, { "code": null, "e": 8904, "s": 8873, "text": "Enter python the command line." }, { "code": null, "e": 8960, "s": 8904, "text": "Start coding right away in the interactive interpreter." }, { "code": null, "e": 9034, "s": 8960, "text": "$python # Unix/Linux\nor\npython% # Unix/Linux\nor\nC:> python # Windows/DOS\n" }, { "code": null, "e": 9095, "s": 9034, "text": "Here is the list of all the available command line options −" }, { "code": null, "e": 9098, "s": 9095, "text": "-d" }, { "code": null, "e": 9124, "s": 9098, "text": "It provides debug output." }, { "code": null, "e": 9127, "s": 9124, "text": "-O" }, { "code": null, "e": 9186, "s": 9127, "text": "It generates optimized bytecode (resulting in .pyo files)." }, { "code": null, "e": 9189, "s": 9186, "text": "-S" }, { "code": null, "e": 9249, "s": 9189, "text": "Do not run import site to look for Python paths on startup." }, { "code": null, "e": 9252, "s": 9249, "text": "-v" }, { "code": null, "e": 9306, "s": 9252, "text": "verbose output (detailed trace on import statements)." }, { "code": null, "e": 9309, "s": 9306, "text": "-X" }, { "code": null, "e": 9405, "s": 9309, "text": "disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6." }, { "code": null, "e": 9412, "s": 9405, "text": "-c cmd" }, { "code": null, "e": 9452, "s": 9412, "text": "run Python script sent in as cmd string" }, { "code": null, "e": 9457, "s": 9452, "text": "file" }, { "code": null, "e": 9491, "s": 9457, "text": "run Python script from given file" }, { "code": null, "e": 9610, "s": 9491, "text": "A Python script can be executed at command line by invoking the interpreter on your application, as in the following −" }, { "code": null, "e": 9719, "s": 9610, "text": "$python script.py # Unix/Linux\n\nor\n\npython% script.py # Unix/Linux\n\nor \n\nC: >python script.py # Windows/DOS\n" }, { "code": null, "e": 9777, "s": 9719, "text": "Note − Be sure the file permission mode allows execution." }, { "code": null, "e": 9922, "s": 9777, "text": "You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python." }, { "code": null, "e": 9973, "s": 9922, "text": "Unix − IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 10024, "s": 9973, "text": "Unix − IDLE is the very first Unix IDE for Python." }, { "code": null, "e": 10112, "s": 10024, "text": "Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 10200, "s": 10112, "text": "Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI." }, { "code": null, "e": 10357, "s": 10200, "text": "Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 10514, "s": 10357, "text": "Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files." }, { "code": null, "e": 10640, "s": 10514, "text": "NLTK is very straight forward to integrate into the python environment. Use the below command to add NLTK to the environment." }, { "code": null, "e": 10666, "s": 10640, "text": "sudo pip install -U nltk\n" }, { "code": null, "e": 10789, "s": 10666, "text": "The addition of other libraries will be discussed in each chapter as and when we need for their use in the python program." }, { "code": null, "e": 10826, "s": 10789, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 10842, "s": 10826, "text": " Malhar Lathkar" }, { "code": null, "e": 10875, "s": 10842, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 10894, "s": 10875, "text": " Arnab Chakraborty" }, { "code": null, "e": 10929, "s": 10894, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 10951, "s": 10929, "text": " In28Minutes Official" }, { "code": null, "e": 10985, "s": 10951, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 11013, "s": 10985, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 11048, "s": 11013, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 11062, "s": 11048, "text": " Lets Kode It" }, { "code": null, "e": 11095, "s": 11062, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 11112, "s": 11095, "text": " Abhilash Nelson" }, { "code": null, "e": 11119, "s": 11112, "text": " Print" }, { "code": null, "e": 11130, "s": 11119, "text": " Add Notes" } ]
List FindLastIndex() Method in C# | Set -1 - GeeksforGeeks
25 Jan, 2019 This method is used to search for an element which matches the conditions defined by a specified predicate and returns the zero-based index of the last occurrence within the List<T> or a portion of it. There are 3 methods in the overload list of this method: FindLastIndex(Predicate<T>) Method FindLastIndex(Int32, Predicate<T>) Method FindLastIndex(Int32, Int32, Predicate<T>) Method Here, we will discuss only the first method i.e. FindLastIndex(Predicate<T>) List<T>.FindLastIndex(Predicate<T>) Method searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the last occurrence within the entire List<T>. Syntax: public int FindLastIndex (Predicate <T> match); Here, the match is the Predicate <T> delegate that defines the conditions of the element to search for. Return Value: If the element is found then it returns the zero-based index of type int or Int32 of the last element that matches a specified condition by the parameter “match”. And if not found then it returns “-1”. Exception: This method will throw ArgumentNullException if the match is null. Example 1: In this example, creating a List named “PC” that contains some element. Our task is to find an element named “Computer” and prints its index. // C# Program to illustrate the // FindLastIndex(Predicate<T>)// Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation // List name is "PC" List<string> PC = new List<string>(); // elements in the List PC.Add("mouse"); PC.Add("keyboard"); PC.Add("laptop"); PC.Add("Computer"); // using the method int indx = PC.FindLastIndex(predi); Console.WriteLine(indx); } // Conditional method private static bool predi(string g) { if (g == "Computer") { return true; } else { return false; } }} 3 Example 2: This example is the extended form of the previous example. In this example, we use an XML file and search an item and prints the index of that item. If the item is not found then prints “-1” and if found then prints the index. The item is\ “GeeksForGeeks”. // C# Program to illustrate the // FindLastIndex(Predicate<T>)// Methodusing System;using System.Collections.Generic;using System.Linq; class GFG { // here List<T> contains the // object "gfg" using // data from a sample XML file // "geeks" is the List name private static List<gfg> geeks = new List<gfg>(); // Main Method public static void Main() { // if the item is found // then it prints the index // if not found prints "-1" int x = geeks.FindLastIndex(FindGFG); Console.WriteLine(x); } // conditional method private static bool FindGFG(gfg g) { if (g.G == "GeeksForGeeks") { return true; } else { return false; } }} public class gfg { public string G { get; set; }} -1 Note: The List<T> is searched backward starting at the last element and ending at the first element. The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List<T> are individually passed to the Predicate<T> delegate. This method performs a linear search; therefore, this method is an O(n) operation, where n is Count. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findlastindex?view=netframework-4.7.2#System_Collections_Generic_List_1_FindLastIndex_System_Predicate__0__ CSharp-Generic-List CSharp-Generic-Namespace CSharp-method Picked Technical Scripter 2018 C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Introduction to .NET Framework Extension Method in C# C# | Class and Object C# | Abstract Classes Common Language Runtime (CLR) in C# C# | Encapsulation
[ { "code": null, "e": 24117, "s": 24089, "text": "\n25 Jan, 2019" }, { "code": null, "e": 24376, "s": 24117, "text": "This method is used to search for an element which matches the conditions defined by a specified predicate and returns the zero-based index of the last occurrence within the List<T> or a portion of it. There are 3 methods in the overload list of this method:" }, { "code": null, "e": 24411, "s": 24376, "text": "FindLastIndex(Predicate<T>) Method" }, { "code": null, "e": 24453, "s": 24411, "text": "FindLastIndex(Int32, Predicate<T>) Method" }, { "code": null, "e": 24502, "s": 24453, "text": "FindLastIndex(Int32, Int32, Predicate<T>) Method" }, { "code": null, "e": 24579, "s": 24502, "text": "Here, we will discuss only the first method i.e. FindLastIndex(Predicate<T>)" }, { "code": null, "e": 24792, "s": 24579, "text": "List<T>.FindLastIndex(Predicate<T>) Method searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the last occurrence within the entire List<T>." }, { "code": null, "e": 24800, "s": 24792, "text": "Syntax:" }, { "code": null, "e": 24848, "s": 24800, "text": "public int FindLastIndex (Predicate <T> match);" }, { "code": null, "e": 24952, "s": 24848, "text": "Here, the match is the Predicate <T> delegate that defines the conditions of the element to search for." }, { "code": null, "e": 25168, "s": 24952, "text": "Return Value: If the element is found then it returns the zero-based index of type int or Int32 of the last element that matches a specified condition by the parameter “match”. And if not found then it returns “-1”." }, { "code": null, "e": 25246, "s": 25168, "text": "Exception: This method will throw ArgumentNullException if the match is null." }, { "code": null, "e": 25399, "s": 25246, "text": "Example 1: In this example, creating a List named “PC” that contains some element. Our task is to find an element named “Computer” and prints its index." }, { "code": "// C# Program to illustrate the // FindLastIndex(Predicate<T>)// Methodusing System;using System.Collections.Generic; class GFG { // Main Method public static void Main() { // List creation // List name is \"PC\" List<string> PC = new List<string>(); // elements in the List PC.Add(\"mouse\"); PC.Add(\"keyboard\"); PC.Add(\"laptop\"); PC.Add(\"Computer\"); // using the method int indx = PC.FindLastIndex(predi); Console.WriteLine(indx); } // Conditional method private static bool predi(string g) { if (g == \"Computer\") { return true; } else { return false; } }}", "e": 26120, "s": 25399, "text": null }, { "code": null, "e": 26123, "s": 26120, "text": "3\n" }, { "code": null, "e": 26391, "s": 26123, "text": "Example 2: This example is the extended form of the previous example. In this example, we use an XML file and search an item and prints the index of that item. If the item is not found then prints “-1” and if found then prints the index. The item is\\ “GeeksForGeeks”." }, { "code": "// C# Program to illustrate the // FindLastIndex(Predicate<T>)// Methodusing System;using System.Collections.Generic;using System.Linq; class GFG { // here List<T> contains the // object \"gfg\" using // data from a sample XML file // \"geeks\" is the List name private static List<gfg> geeks = new List<gfg>(); // Main Method public static void Main() { // if the item is found // then it prints the index // if not found prints \"-1\" int x = geeks.FindLastIndex(FindGFG); Console.WriteLine(x); } // conditional method private static bool FindGFG(gfg g) { if (g.G == \"GeeksForGeeks\") { return true; } else { return false; } }} public class gfg { public string G { get; set; }}", "e": 27234, "s": 26391, "text": null }, { "code": null, "e": 27238, "s": 27234, "text": "-1\n" }, { "code": null, "e": 27244, "s": 27238, "text": "Note:" }, { "code": null, "e": 27339, "s": 27244, "text": "The List<T> is searched backward starting at the last element and ending at the first element." }, { "code": null, "e": 27565, "s": 27339, "text": "The Predicate<T> is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List<T> are individually passed to the Predicate<T> delegate." }, { "code": null, "e": 27666, "s": 27565, "text": "This method performs a linear search; therefore, this method is an O(n) operation, where n is Count." }, { "code": null, "e": 27677, "s": 27666, "text": "Reference:" }, { "code": null, "e": 27863, "s": 27677, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findlastindex?view=netframework-4.7.2#System_Collections_Generic_List_1_FindLastIndex_System_Predicate__0__" }, { "code": null, "e": 27883, "s": 27863, "text": "CSharp-Generic-List" }, { "code": null, "e": 27908, "s": 27883, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 27922, "s": 27908, "text": "CSharp-method" }, { "code": null, "e": 27929, "s": 27922, "text": "Picked" }, { "code": null, "e": 27953, "s": 27929, "text": "Technical Scripter 2018" }, { "code": null, "e": 27956, "s": 27953, "text": "C#" }, { "code": null, "e": 27975, "s": 27956, "text": "Technical Scripter" }, { "code": null, "e": 28073, "s": 27975, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28082, "s": 28073, "text": "Comments" }, { "code": null, "e": 28095, "s": 28082, "text": "Old Comments" }, { "code": null, "e": 28141, "s": 28095, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28156, "s": 28141, "text": "C# | Delegates" }, { "code": null, "e": 28196, "s": 28156, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28214, "s": 28196, "text": "C# | Constructors" }, { "code": null, "e": 28245, "s": 28214, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28268, "s": 28245, "text": "Extension Method in C#" }, { "code": null, "e": 28290, "s": 28268, "text": "C# | Class and Object" }, { "code": null, "e": 28312, "s": 28290, "text": "C# | Abstract Classes" }, { "code": null, "e": 28348, "s": 28312, "text": "Common Language Runtime (CLR) in C#" } ]
How to select first and last row record using LIMIT in MySQL?
Let us first create a table. The query to create a table is as follows mysql> create table FirstAndLastDataDemo -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20), -> EmployeeAge int -> ); Query OK, 0 rows affected (0.59 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23); Query OK, 1 row affected (0.15 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13); Query OK, 1 row affected (0.11 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24); Query OK, 1 row affected (0.14 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14); Query OK, 1 row affected (0.18 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31); Query OK, 1 row affected (0.10 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('James',18); Query OK, 1 row affected (0.16 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Maxwell',28); Query OK, 1 row affected (0.17 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27); Query OK, 1 row affected (0.12 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22); Query OK, 1 row affected (0.19 sec) Display all records from the table using a select statement. mysql> select *from FirstAndLastDataDemo; The following is the output +------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | John | 23 | | 2 | Bob | 13 | | 3 | Larry | 24 | | 4 | Sam | 14 | | 5 | Mike | 31 | | 6 | James | 18 | | 7 | Maxwell | 28 | | 8 | David | 27 | | 9 | Chris | 22 | +------------+--------------+-------------+ 9 rows in set (0.00 sec) To get first row and last row record using LIMIT, the following is the query mysql> (SELECT *from FirstAndLastDataDemo LIMIT 1) -> UNION -> (SELECT *from FirstAndLastDataDemo LIMIT 8,1); The following is the output displaying the first and last row record +------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | John | 23 | | 9 | Chris | 22 | +------------+--------------+-------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1133, "s": 1062, "text": "Let us first create a table. The query to create a table is as follows" }, { "code": null, "e": 1340, "s": 1133, "text": "mysql> create table FirstAndLastDataDemo\n -> (\n -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> EmployeeName varchar(20),\n -> EmployeeAge int\n -> );\nQuery OK, 0 rows affected (0.59 sec)" }, { "code": null, "e": 1419, "s": 1340, "text": "Insert some records in the table using insert command. The query is as follows" }, { "code": null, "e": 2513, "s": 1419, "text": "mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13);\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31);\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge)\nvalues('James',18);\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge)\nvalues('Maxwell',28);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27);\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22);\nQuery OK, 1 row affected (0.19 sec)" }, { "code": null, "e": 2574, "s": 2513, "text": "Display all records from the table using a select statement." }, { "code": null, "e": 2616, "s": 2574, "text": "mysql> select *from FirstAndLastDataDemo;" }, { "code": null, "e": 2644, "s": 2616, "text": "The following is the output" }, { "code": null, "e": 3241, "s": 2644, "text": "+------------+--------------+-------------+\n| EmployeeId | EmployeeName | EmployeeAge |\n+------------+--------------+-------------+\n| 1 | John | 23 |\n| 2 | Bob | 13 |\n| 3 | Larry | 24 |\n| 4 | Sam | 14 |\n| 5 | Mike | 31 |\n| 6 | James | 18 |\n| 7 | Maxwell | 28 |\n| 8 | David | 27 |\n| 9 | Chris | 22 |\n+------------+--------------+-------------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 3318, "s": 3241, "text": "To get first row and last row record using LIMIT, the following is the query" }, { "code": null, "e": 3434, "s": 3318, "text": "mysql> (SELECT *from FirstAndLastDataDemo LIMIT 1)\n -> UNION\n -> (SELECT *from FirstAndLastDataDemo LIMIT 8,1);" }, { "code": null, "e": 3503, "s": 3434, "text": "The following is the output displaying the first and last row record" }, { "code": null, "e": 3792, "s": 3503, "text": "+------------+--------------+-------------+\n| EmployeeId | EmployeeName | EmployeeAge |\n+------------+--------------+-------------+\n| 1 | John | 23 |\n| 9 | Chris | 22 |\n+------------+--------------+-------------+\n2 rows in set (0.00 sec)" } ]
Implementing Web Scraping in Python with BeautifulSoup?
BeautifulSoup is a class in the bs4 module of python. Basic purpose of building beautifulsoup is to parse HTML or XML documents. It is easy to install beautifulsoup on using pip module. Just run the below command on your command shell. pip install bs4 Running above command on your terminal, will see your screen something like - C:\Users\rajesh>pip install bs4 Collecting bs4 Downloading https://files.pythonhosted.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz Requirement already satisfied: beautifulsoup4 in c:\python\python361\lib\site-packages (from bs4) (4.6.0) Building wheels for collected packages: bs4 Building wheel for bs4 (setup.py) ... done Stored in directory: C:\Users\rajesh\AppData\Local\pip\Cache\wheels\a0\b0\b2\4f80b9456b87abedbc0bf2d52235414c3467d8889be38dd472 Successfully built bs4 Installing collected packages: bs4 Successfully installed bs4-0.0.1 To verify, if BeautifulSoup is successfully installed in your machine or not, just run below command in the same terminal− C:\Users\rajesh>python Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from bs4 import BeautifulSoup >>> Successful, great!. Find all the links from an html document Now, assume we have a HTML document and we want to collect all the reference links in the document. So first we will store the document as a string like below − html_doc='''<a href='wwww.Tutorialspoint.com.com'/a> <a href='wwww.nseindia.com.com'/a> <a href='wwww.codesdope.com'/a> <a href='wwww.google.com'/a> <a href='wwww.facebook.com'/a> <a href='wwww.wikipedia.org'/a> <a href='wwww.twitter.com'/a> <a href='wwww.microsoft.com'/a> <a href='wwww.github.com'/a> <a href='wwww.nytimes.com'/a> <a href='wwww.youtube.com'/a> <a href='wwww.reddit.com'/a> <a href='wwww.python.org'/a> <a href='wwww.stackoverflow.com'/a> <a href='wwww.amazon.com'/a> <a href=‘wwww.linkedin.com'/a> <a href='wwww.finace.google.com'/a>''' Now we will create a soup object by passing the above variable html_doc in the initializer function of beautifulSoup. from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc, 'html.parser') Now we have the soup object, we can apply methods of the BeautifulSoup class on it. Now we can find all the attributes of a tag and values in the attributes given in the html_doc. for tag in soup.find_all('a'): print(tag.get('href')) From above code we are trying to get all the links in the html_doc string through a loop to get every <a> in the document and get the href attribute. Below is our complete code to get all the links from the html_doc string. from bs4 import BeautifulSoup html_doc='''<a href='www.Tutorialspoint.com'/a> <a href='www.nseindia.com.com'/a> <a href='www.codesdope.com'/a> <a href='www.google.com'/a> <a href='www.facebook.com'/a> <a href='www.wikipedia.org'/a> <a href='www.twitter.com'/a> <a href='www.microsoft.com'/a> <a href='www.github.com'/a> <a href='www.nytimes.com'/a> <a href='www.youtube.com'/a> <a href='www.reddit.com'/a> <a href='www.python.org'/a> <a href='www.stackoverflow.com'/a> <a href='www.amazon.com'/a> <a href='www.rediff.com'/a>''' soup = BeautifulSoup(html_doc, 'html.parser') for tag in soup.find_all('a'): print(tag.get('href')) www.Tutorialspoint.com www.nseindia.com.com www.codesdope.com www.google.com www.facebook.com www.wikipedia.org www.twitter.com www.microsoft.com www.github.com www.nytimes.com www.youtube.com www.reddit.com www.python.org www.stackoverflow.com www.amazon.com www.rediff.com Prints all the links from a website with specific element (for example: python) mentioned in the link. Below program will print all the URLs from a specific website which contains “python” in there link. from bs4 import BeautifulSoup from urllib.request import urlopen import re html = urlopen("http://www.python.org") content = html.read() soup = BeautifulSoup(content) for a in soup.findAll('a',href=True): if re.findall('python', a['href']): print("Python URL:", a['href']) Python URL: https://docs.python.org Python URL: https://pypi.python.org/ Python URL: https://www.facebook.com/pythonlang?fref=ts Python URL: http://brochure.getpython.info/ Python URL: https://docs.python.org/3/license.html Python URL: https://wiki.python.org/moin/BeginnersGuide Python URL: https://devguide.python.org/ Python URL: https://docs.python.org/faq/ Python URL: http://wiki.python.org/moin/Languages Python URL: http://python.org/dev/peps/ Python URL: https://wiki.python.org/moin/PythonBooks Python URL: https://wiki.python.org/moin/ Python URL: https://www.python.org/psf/codeofconduct/ Python URL: http://planetpython.org/ Python URL: /events/python-events Python URL: /events/python-user-group/ Python URL: /events/python-events/past/ Python URL: /events/python-user-group/past/ Python URL: https://wiki.python.org/moin/PythonEventsCalendar#Submitting_an_Event Python URL: //docs.python.org/3/tutorial/controlflow.html#defining-functions Python URL: //docs.python.org/3/tutorial/introduction.html#lists Python URL: http://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator Python URL: //docs.python.org/3/tutorial/ Python URL: //docs.python.org/3/tutorial/controlflow.html Python URL: /downloads/release/python-373/ Python URL: https://docs.python.org Python URL: //jobs.python.org Python URL: http://blog.python.org Python URL: http://feedproxy.google.com/~r/PythonInsider/~3/Joo0vg55HKo/python-373-is-now-available.html Python URL: http://feedproxy.google.com/~r/PythonInsider/~3/N5tvkDIQ47g/python-3410-is-now-available.html Python URL: http://feedproxy.google.com/~r/PythonInsider/~3/n0mOibtx6_A/python-3.html Python URL: /events/python-events/805/ Python URL: /events/python-events/817/ Python URL: /events/python-user-group/814/ Python URL: /events/python-events/789/ Python URL: /events/python-events/831/ Python URL: /success-stories/building-an-open-source-and-cross-platform-azure-cli-with-python/ Python URL: /success-stories/building-an-open-source-and-cross-platform-azure-cli-with-python/ Python URL: http://wiki.python.org/moin/TkInter Python URL: http://www.wxpython.org/ Python URL: http://ipython.org Python URL: #python-network Python URL: http://brochure.getpython.info/ Python URL: https://docs.python.org/3/license.html Python URL: https://wiki.python.org/moin/BeginnersGuide Python URL: https://devguide.python.org/ Python URL: https://docs.python.org/faq/ Python URL: http://wiki.python.org/moin/Languages Python URL: http://python.org/dev/peps/ Python URL: https://wiki.python.org/moin/PythonBooks Python URL: https://wiki.python.org/moin/ Python URL: https://www.python.org/psf/codeofconduct/ Python URL: http://planetpython.org/ Python URL: /events/python-events Python URL: /events/python-user-group/ Python URL: /events/python-events/past/ Python URL: /events/python-user-group/past/ Python URL: https://wiki.python.org/moin/PythonEventsCalendar#Submitting_an_Event Python URL: https://devguide.python.org/ Python URL: https://bugs.python.org/ Python URL: https://mail.python.org/mailman/listinfo/python-dev Python URL: #python-network Python URL: https://github.com/python/pythondotorg/issues Python URL: https://status.python.org/
[ { "code": null, "e": 1191, "s": 1062, "text": "BeautifulSoup is a class in the bs4 module of python. Basic purpose of building beautifulsoup is to parse HTML or XML documents." }, { "code": null, "e": 1298, "s": 1191, "text": "It is easy to install beautifulsoup on using pip module. Just run the below command on your command shell." }, { "code": null, "e": 1314, "s": 1298, "text": "pip install bs4" }, { "code": null, "e": 1392, "s": 1314, "text": "Running above command on your terminal, will see your screen something like -" }, { "code": null, "e": 1987, "s": 1392, "text": "C:\\Users\\rajesh>pip install bs4\nCollecting bs4\nDownloading https://files.pythonhosted.org/packages/10/ed/7e8b97591f6f456174139ec089c769f89a94a1a4025fe967691de971f314/bs4-0.0.1.tar.gz\nRequirement already satisfied: beautifulsoup4 in c:\\python\\python361\\lib\\site-packages (from bs4) (4.6.0)\nBuilding wheels for collected packages: bs4\nBuilding wheel for bs4 (setup.py) ... done\nStored in directory: C:\\Users\\rajesh\\AppData\\Local\\pip\\Cache\\wheels\\a0\\b0\\b2\\4f80b9456b87abedbc0bf2d52235414c3467d8889be38dd472\nSuccessfully built bs4\nInstalling collected packages: bs4\nSuccessfully installed bs4-0.0.1" }, { "code": null, "e": 2110, "s": 1987, "text": "To verify, if BeautifulSoup is successfully installed in your machine or not, just run below command in the same terminal−" }, { "code": null, "e": 2332, "s": 2110, "text": "C:\\Users\\rajesh>python\nPython 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from bs4 import BeautifulSoup\n>>>" }, { "code": null, "e": 2352, "s": 2332, "text": "Successful, great!." }, { "code": null, "e": 2554, "s": 2352, "text": "Find all the links from an html document Now, assume we have a HTML document and we want to collect all the reference links in the document. So first we will store the document as a string like below −" }, { "code": null, "e": 3110, "s": 2554, "text": "html_doc='''<a href='wwww.Tutorialspoint.com.com'/a>\n<a href='wwww.nseindia.com.com'/a>\n<a href='wwww.codesdope.com'/a>\n<a href='wwww.google.com'/a>\n<a href='wwww.facebook.com'/a>\n<a href='wwww.wikipedia.org'/a>\n<a href='wwww.twitter.com'/a>\n<a href='wwww.microsoft.com'/a>\n<a href='wwww.github.com'/a>\n<a href='wwww.nytimes.com'/a>\n<a href='wwww.youtube.com'/a>\n<a href='wwww.reddit.com'/a>\n<a href='wwww.python.org'/a>\n<a href='wwww.stackoverflow.com'/a>\n<a href='wwww.amazon.com'/a>\n<a href=‘wwww.linkedin.com'/a>\n<a href='wwww.finace.google.com'/a>'''" }, { "code": null, "e": 3228, "s": 3110, "text": "Now we will create a soup object by passing the above variable html_doc in the initializer function of beautifulSoup." }, { "code": null, "e": 3304, "s": 3228, "text": "from bs4 import BeautifulSoup\nsoup = BeautifulSoup(html_doc, 'html.parser')" }, { "code": null, "e": 3484, "s": 3304, "text": "Now we have the soup object, we can apply methods of the BeautifulSoup class on it. Now we can find all the attributes of a tag and values in the attributes given in the html_doc." }, { "code": null, "e": 3538, "s": 3484, "text": "for tag in soup.find_all('a'):\nprint(tag.get('href'))" }, { "code": null, "e": 3688, "s": 3538, "text": "From above code we are trying to get all the links in the html_doc string through a loop to get every <a> in the document and get the href attribute." }, { "code": null, "e": 3762, "s": 3688, "text": "Below is our complete code to get all the links from the html_doc string." }, { "code": null, "e": 4393, "s": 3762, "text": "from bs4 import BeautifulSoup\n\nhtml_doc='''<a href='www.Tutorialspoint.com'/a>\n<a href='www.nseindia.com.com'/a>\n<a href='www.codesdope.com'/a>\n<a href='www.google.com'/a>\n<a href='www.facebook.com'/a>\n<a href='www.wikipedia.org'/a>\n<a href='www.twitter.com'/a>\n<a href='www.microsoft.com'/a>\n<a href='www.github.com'/a>\n<a href='www.nytimes.com'/a>\n<a href='www.youtube.com'/a>\n<a href='www.reddit.com'/a>\n<a href='www.python.org'/a>\n<a href='www.stackoverflow.com'/a>\n<a href='www.amazon.com'/a>\n<a href='www.rediff.com'/a>'''\n\nsoup = BeautifulSoup(html_doc, 'html.parser')\n\nfor tag in soup.find_all('a'):\nprint(tag.get('href'))" }, { "code": null, "e": 4668, "s": 4393, "text": "www.Tutorialspoint.com\nwww.nseindia.com.com\nwww.codesdope.com\nwww.google.com\nwww.facebook.com\nwww.wikipedia.org\nwww.twitter.com\nwww.microsoft.com\nwww.github.com\nwww.nytimes.com\nwww.youtube.com\nwww.reddit.com\nwww.python.org\nwww.stackoverflow.com\nwww.amazon.com\nwww.rediff.com" }, { "code": null, "e": 4772, "s": 4668, "text": " Prints all the links from a website with specific element (for example: python) mentioned in the link." }, { "code": null, "e": 4873, "s": 4772, "text": "Below program will print all the URLs from a specific website which contains “python” in there link." }, { "code": null, "e": 5147, "s": 4873, "text": "from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport re\n\nhtml = urlopen(\"http://www.python.org\")\ncontent = html.read()\nsoup = BeautifulSoup(content)\nfor a in soup.findAll('a',href=True):\nif re.findall('python', a['href']):\nprint(\"Python URL:\", a['href'])" }, { "code": null, "e": 8350, "s": 5147, "text": "Python URL: https://docs.python.org\nPython URL: https://pypi.python.org/\nPython URL: https://www.facebook.com/pythonlang?fref=ts\nPython URL: http://brochure.getpython.info/\nPython URL: https://docs.python.org/3/license.html\nPython URL: https://wiki.python.org/moin/BeginnersGuide\nPython URL: https://devguide.python.org/\nPython URL: https://docs.python.org/faq/\nPython URL: http://wiki.python.org/moin/Languages\nPython URL: http://python.org/dev/peps/\nPython URL: https://wiki.python.org/moin/PythonBooks\nPython URL: https://wiki.python.org/moin/\nPython URL: https://www.python.org/psf/codeofconduct/\nPython URL: http://planetpython.org/\nPython URL: /events/python-events\nPython URL: /events/python-user-group/\nPython URL: /events/python-events/past/\nPython URL: /events/python-user-group/past/\nPython URL: https://wiki.python.org/moin/PythonEventsCalendar#Submitting_an_Event\nPython URL: //docs.python.org/3/tutorial/controlflow.html#defining-functions\nPython URL: //docs.python.org/3/tutorial/introduction.html#lists\nPython URL: http://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator\nPython URL: //docs.python.org/3/tutorial/\nPython URL: //docs.python.org/3/tutorial/controlflow.html\nPython URL: /downloads/release/python-373/\nPython URL: https://docs.python.org\nPython URL: //jobs.python.org\nPython URL: http://blog.python.org\nPython URL: http://feedproxy.google.com/~r/PythonInsider/~3/Joo0vg55HKo/python-373-is-now-available.html\nPython URL: http://feedproxy.google.com/~r/PythonInsider/~3/N5tvkDIQ47g/python-3410-is-now-available.html\nPython URL: http://feedproxy.google.com/~r/PythonInsider/~3/n0mOibtx6_A/python-3.html\nPython URL: /events/python-events/805/\nPython URL: /events/python-events/817/\nPython URL: /events/python-user-group/814/\nPython URL: /events/python-events/789/\nPython URL: /events/python-events/831/\nPython URL: /success-stories/building-an-open-source-and-cross-platform-azure-cli-with-python/\nPython URL: /success-stories/building-an-open-source-and-cross-platform-azure-cli-with-python/\nPython URL: http://wiki.python.org/moin/TkInter\nPython URL: http://www.wxpython.org/\nPython URL: http://ipython.org\nPython URL: #python-network\nPython URL: http://brochure.getpython.info/\nPython URL: https://docs.python.org/3/license.html\nPython URL: https://wiki.python.org/moin/BeginnersGuide\nPython URL: https://devguide.python.org/\nPython URL: https://docs.python.org/faq/\nPython URL: http://wiki.python.org/moin/Languages\nPython URL: http://python.org/dev/peps/\nPython URL: https://wiki.python.org/moin/PythonBooks\nPython URL: https://wiki.python.org/moin/\nPython URL: https://www.python.org/psf/codeofconduct/\nPython URL: http://planetpython.org/\nPython URL: /events/python-events\nPython URL: /events/python-user-group/\nPython URL: /events/python-events/past/\nPython URL: /events/python-user-group/past/\nPython URL: https://wiki.python.org/moin/PythonEventsCalendar#Submitting_an_Event\nPython URL: https://devguide.python.org/\nPython URL: https://bugs.python.org/\nPython URL: https://mail.python.org/mailman/listinfo/python-dev\nPython URL: #python-network\nPython URL: https://github.com/python/pythondotorg/issues\nPython URL: https://status.python.org/\n\n" } ]
Delegation vs Inheritance in C#
A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime. To declare a delegate. delegate <return type> <delegate-name> <parameter list> Delegation has run-time flexibility i.e. you can easily change it at runtime. The instance you create in Delegation is of a known class. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time. When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class. This is how we create a base and derived class in Inheritance. <access-specifier> class <base_class> { ... } class <derived_class> : <base_class> { ... }
[ { "code": null, "e": 1181, "s": 1062, "text": "A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime." }, { "code": null, "e": 1204, "s": 1181, "text": "To declare a delegate." }, { "code": null, "e": 1260, "s": 1204, "text": "delegate <return type> <delegate-name> <parameter list>" }, { "code": null, "e": 1397, "s": 1260, "text": "Delegation has run-time flexibility i.e. you can easily change it at runtime. The instance you create in Delegation is of a known class." }, { "code": null, "e": 1626, "s": 1397, "text": "Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and speeds up implementation time." }, { "code": null, "e": 1916, "s": 1626, "text": "When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class." }, { "code": null, "e": 1979, "s": 1916, "text": "This is how we create a base and derived class in Inheritance." }, { "code": null, "e": 2076, "s": 1979, "text": "<access-specifier> class <base_class> {\n ...\n}\nclass <derived_class> : <base_class> {\n ...\n}" } ]
How to Compare Equality of Struct, Slice and Map in Golang? - GeeksforGeeks
17 May, 2020 In Golang, reflect.DeepEqual function is used to compare the equality of struct, slice, and map in Golang. It is used to check if two elements are “deeply equal” or not. Deep means that we are comparing the contents of the objects recursively. Two distinct types of values are never deeply equal. Two identical types are deeply equal if one of the following cases is true 1. Slice values are deeply equal when all of the following are true: They are both nil or both non-nil. Their length is same. Either they have same initial entry (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. 2. Struct values are deeply equal only if their corresponding fields (i.e. both exported and unexported) are deeply equal. 3. Map values are deeply equal when each of the following are true: They both are nil or non-nil Their length is same Their corresponding keys have deeply equal values Note: We need to import the reflect package to use DeepEqual. Syntax: func DeepEqual(x, y interface{}) bool Example: // Golang program to compare equality// of struct, slice, and mappackage main import ( "fmt" "reflect") type structeq struct { X int Y string Z []int} func main() { s1 := structeq{X: 50, Y: "GeeksforGeeks", Z: []int{1, 2, 3}, } s2 := structeq{X: 50, Y: "GeeksforGeeks", Z: []int{1, 2, 3}, } // comparing struct if reflect.DeepEqual(s1, s2) { fmt.Println("Struct is equal") } else { fmt.Println("Struct is not equal") } slice1 := []int{1, 2, 3} slice2 := []int{1, 2, 3, 4} // comparing slice if reflect.DeepEqual(slice1, slice2) { fmt.Println("Slice is equal") } else { fmt.Println("Slice is not equal") } map1 := map[string]int{ "x": 10, "y": 20, "z": 30, } map2 := map[string]int{ "x": 10, "y": 20, "z": 30, } // comparing map if reflect.DeepEqual(map1, map2) { fmt.Println("Map is equal") } else { fmt.Println("Map is not equal") }} Output: Struct is equal Slice is not equal Map is equal However, cmp.Equal is a better tool for comparing structs. To use this, we need to import the “github.com/google/go-cmp/cmp” package. Example: package main import ( "fmt" "github.com/google/go-cmp/cmp") type structeq struct { X int Y string Z []int} func main() { s1 := structeq{X: 50, Y: "GeeksforGeeks", Z: []int{1, 2, 3}, } s2 := structeq{X: 50, Y: "GeeksforGeeks", Z: []int{1, 2, 3}, } // comparing struct if cmp.Equal(s1, s2) { fmt.Println("Struct is equal") } else { fmt.Println("Struct is not equal") }} Output: Struct is equal Golang-Program Golang-Slices Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples How to Split a String in Golang? Arrays in Go Golang Maps Slices in Golang How to compare times in Golang? How to Trim a String in Golang? Inheritance in GoLang Different Ways to Find the Type of Variable in Golang How to Parse JSON in Golang?
[ { "code": null, "e": 24418, "s": 24390, "text": "\n17 May, 2020" }, { "code": null, "e": 24790, "s": 24418, "text": "In Golang, reflect.DeepEqual function is used to compare the equality of struct, slice, and map in Golang. It is used to check if two elements are “deeply equal” or not. Deep means that we are comparing the contents of the objects recursively. Two distinct types of values are never deeply equal. Two identical types are deeply equal if one of the following cases is true" }, { "code": null, "e": 24859, "s": 24790, "text": "1. Slice values are deeply equal when all of the following are true:" }, { "code": null, "e": 24894, "s": 24859, "text": "They are both nil or both non-nil." }, { "code": null, "e": 24916, "s": 24894, "text": "Their length is same." }, { "code": null, "e": 25043, "s": 24916, "text": "Either they have same initial entry (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal." }, { "code": null, "e": 25166, "s": 25043, "text": "2. Struct values are deeply equal only if their corresponding fields (i.e. both exported and unexported) are deeply equal." }, { "code": null, "e": 25234, "s": 25166, "text": "3. Map values are deeply equal when each of the following are true:" }, { "code": null, "e": 25263, "s": 25234, "text": "They both are nil or non-nil" }, { "code": null, "e": 25284, "s": 25263, "text": "Their length is same" }, { "code": null, "e": 25334, "s": 25284, "text": "Their corresponding keys have deeply equal values" }, { "code": null, "e": 25396, "s": 25334, "text": "Note: We need to import the reflect package to use DeepEqual." }, { "code": null, "e": 25404, "s": 25396, "text": "Syntax:" }, { "code": null, "e": 25442, "s": 25404, "text": "func DeepEqual(x, y interface{}) bool" }, { "code": null, "e": 25451, "s": 25442, "text": "Example:" }, { "code": "// Golang program to compare equality// of struct, slice, and mappackage main import ( \"fmt\" \"reflect\") type structeq struct { X int Y string Z []int} func main() { s1 := structeq{X: 50, Y: \"GeeksforGeeks\", Z: []int{1, 2, 3}, } s2 := structeq{X: 50, Y: \"GeeksforGeeks\", Z: []int{1, 2, 3}, } // comparing struct if reflect.DeepEqual(s1, s2) { fmt.Println(\"Struct is equal\") } else { fmt.Println(\"Struct is not equal\") } slice1 := []int{1, 2, 3} slice2 := []int{1, 2, 3, 4} // comparing slice if reflect.DeepEqual(slice1, slice2) { fmt.Println(\"Slice is equal\") } else { fmt.Println(\"Slice is not equal\") } map1 := map[string]int{ \"x\": 10, \"y\": 20, \"z\": 30, } map2 := map[string]int{ \"x\": 10, \"y\": 20, \"z\": 30, } // comparing map if reflect.DeepEqual(map1, map2) { fmt.Println(\"Map is equal\") } else { fmt.Println(\"Map is not equal\") }}", "e": 26504, "s": 25451, "text": null }, { "code": null, "e": 26512, "s": 26504, "text": "Output:" }, { "code": null, "e": 26561, "s": 26512, "text": "Struct is equal\nSlice is not equal\nMap is equal\n" }, { "code": null, "e": 26695, "s": 26561, "text": "However, cmp.Equal is a better tool for comparing structs. To use this, we need to import the “github.com/google/go-cmp/cmp” package." }, { "code": null, "e": 26704, "s": 26695, "text": "Example:" }, { "code": "package main import ( \"fmt\" \"github.com/google/go-cmp/cmp\") type structeq struct { X int Y string Z []int} func main() { s1 := structeq{X: 50, Y: \"GeeksforGeeks\", Z: []int{1, 2, 3}, } s2 := structeq{X: 50, Y: \"GeeksforGeeks\", Z: []int{1, 2, 3}, } // comparing struct if cmp.Equal(s1, s2) { fmt.Println(\"Struct is equal\") } else { fmt.Println(\"Struct is not equal\") }}", "e": 27156, "s": 26704, "text": null }, { "code": null, "e": 27164, "s": 27156, "text": "Output:" }, { "code": null, "e": 27181, "s": 27164, "text": "Struct is equal\n" }, { "code": null, "e": 27196, "s": 27181, "text": "Golang-Program" }, { "code": null, "e": 27210, "s": 27196, "text": "Golang-Slices" }, { "code": null, "e": 27217, "s": 27210, "text": "Picked" }, { "code": null, "e": 27229, "s": 27217, "text": "Go Language" }, { "code": null, "e": 27327, "s": 27229, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27378, "s": 27327, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 27411, "s": 27378, "text": "How to Split a String in Golang?" }, { "code": null, "e": 27424, "s": 27411, "text": "Arrays in Go" }, { "code": null, "e": 27436, "s": 27424, "text": "Golang Maps" }, { "code": null, "e": 27453, "s": 27436, "text": "Slices in Golang" }, { "code": null, "e": 27485, "s": 27453, "text": "How to compare times in Golang?" }, { "code": null, "e": 27517, "s": 27485, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 27539, "s": 27517, "text": "Inheritance in GoLang" }, { "code": null, "e": 27593, "s": 27539, "text": "Different Ways to Find the Type of Variable in Golang" } ]
Jackson - Environment Setup
You really do not need to set up your own environment to start learning Guava, a JAVA based library. Reason is very simple, we already have setup Java Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online. Try following example using Try it option available at the top right corner of the below sample code box: public class MyFirstJavaProgram { public static void main(String []args) { System.out.println("Hello World"); } } For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning. 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 following steps 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 installed Java on your machine, you would need to set environment variables to point to correct installation directories: Assuming 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'. Assuming 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 will need a text editor. There are even more 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:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html. Netbeans:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html. Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/. Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/. Download the latest version of Jackson jar file from Maven Repository - Jackson. In this tutorial, jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar are downloaded and copied into C:\> jackson folder. Set the jackson_HOME environment variable to point to the base directory location where Guava jar is stored on your machine. Assuming, we've extracted jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows. Set the CLASSPATH environment variable to point to the jackson jar location. Assuming, we've stored jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows. Print Add Notes Bookmark this page
[ { "code": null, "e": 2213, "s": 1753, "text": "You really do not need to set up your own environment to start learning Guava, a JAVA based library. Reason is very simple, we already have setup Java Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online." }, { "code": null, "e": 2319, "s": 2213, "text": "Try following example using Try it option available at the top right corner of the below sample code box:" }, { "code": null, "e": 2450, "s": 2319, "text": "public class MyFirstJavaProgram {\n\n public static void main(String []args) {\n System.out.println(\"Hello World\");\n }\n} " }, { "code": null, "e": 2576, "s": 2450, "text": "For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning." }, { "code": null, "e": 2801, "s": 2576, "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 following steps to set up the environment." }, { "code": null, "e": 2916, "s": 2801, "text": "Java SE is freely available from the link Download Java. So you download a version based on your operating system." }, { "code": null, "e": 3138, "s": 2916, "text": "Follow the instructions to download java and run the .exe to install Java on your machine. Once you installed Java on your machine, you would need to set environment variables to point to correct installation directories:" }, { "code": null, "e": 3211, "s": 3138, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory:" }, { "code": null, "e": 3266, "s": 3211, "text": "Right-click on 'My Computer' and select 'Properties'. " }, { "code": null, "e": 3321, "s": 3266, "text": "Right-click on 'My Computer' and select 'Properties'. " }, { "code": null, "e": 3391, "s": 3321, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 3461, "s": 3391, "text": "Click on the 'Environment variables' button under the 'Advanced' tab." }, { "code": null, "e": 3697, "s": 3461, "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": 3933, "s": 3697, "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": 4006, "s": 3933, "text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory:" }, { "code": null, "e": 4125, "s": 4006, "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": 4244, "s": 4125, "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": 4407, "s": 4244, "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": 4547, "s": 4407, "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": 4721, "s": 4547, "text": "To write your Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following:" }, { "code": null, "e": 4839, "s": 4721, "text": "Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 4957, "s": 4839, "text": "Notepad: On Windows machine you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad." }, { "code": null, "e": 5074, "s": 4957, "text": "Netbeans:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html." }, { "code": null, "e": 5191, "s": 5074, "text": "Netbeans:is a Java IDE that is open-source and free which can be downloaded from http://www.netbeans.org/index.html." }, { "code": null, "e": 5318, "s": 5191, "text": "Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/." }, { "code": null, "e": 5445, "s": 5318, "text": "Eclipse: is also a Java IDE developed by the eclipse open-source community and can be downloaded from http://www.eclipse.org/." }, { "code": null, "e": 5680, "s": 5445, "text": "Download the latest version of Jackson jar file from Maven Repository - Jackson. In this tutorial, jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar are downloaded and copied into C:\\> jackson folder." }, { "code": null, "e": 5974, "s": 5680, "text": "Set the jackson_HOME environment variable to point to the base directory location where Guava jar is stored on your machine. Assuming, we've extracted jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows." }, { "code": null, "e": 6217, "s": 5974, "text": "Set the CLASSPATH environment variable to point to the jackson jar location. Assuming, we've stored jackson-core-2.8.9.jar,jackson-annotations-2.8.9.jar and jackson-databind-2.8.9.jar in jackson folder on various Operating Systems as follows." }, { "code": null, "e": 6224, "s": 6217, "text": " Print" }, { "code": null, "e": 6235, "s": 6224, "text": " Add Notes" } ]
Adding Noise to a Numeric Vector in R Programming - jitter() Function - GeeksforGeeks
19 Jun, 2020 In R programming, jittering means adding small amount of random noise to a numeric vector object. In this article, we’ll learn to use jitter() function and create a plot to visualize them. Syntax: jitter(x, factor) Parameters:x: represents numeric vectorfactor: represents numeric value for factor specification Example 1: # Define numeric vectorsx <- round(runif(1000, 1, 10))y <- x + rnorm(1000, mean = 0, sd = 5) # output to be present as PNG file png(file="withoutJitter.png") # Plotting without jitter functionplot(x, y, xlim = c(0, 11), main = "Without Jitter Function") # saving the file dev.off() x_j <- jitter(x) # output to be present as PNG file png(file="withJitter.png") # Plotting with jitter functionplot(x_j, y, xlim = c(0, 11), main = "With Jitter Function") # saving the file dev.off() Output: Example 2: With large factor value # Define numeric vectorsx <- round(runif(1000, 1, 10))y <- x + rnorm(1000, mean = 0, sd = 5) # output to be present as PNG file png(file="withoutJitterFactor.png") # Plotting without jitter functionplot(x, y, xlim = c(0, 11), main = "Without Jitter Function") # saving the file dev.off() x_j <- jitter(x, factor = 2) # output to be present as PNG file png(file="withJitterFactor.png") # Plotting with jitter functionplot(x_j, y, xlim = c(0, 11), main = "With Jitter Function and Large Factor") # saving the file dev.off() Output: R Factor-Function R Vector-Function R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R R - if statement Time Series Analysis in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n19 Jun, 2020" }, { "code": null, "e": 25431, "s": 25242, "text": "In R programming, jittering means adding small amount of random noise to a numeric vector object. In this article, we’ll learn to use jitter() function and create a plot to visualize them." }, { "code": null, "e": 25457, "s": 25431, "text": "Syntax: jitter(x, factor)" }, { "code": null, "e": 25554, "s": 25457, "text": "Parameters:x: represents numeric vectorfactor: represents numeric value for factor specification" }, { "code": null, "e": 25565, "s": 25554, "text": "Example 1:" }, { "code": "# Define numeric vectorsx <- round(runif(1000, 1, 10))y <- x + rnorm(1000, mean = 0, sd = 5) # output to be present as PNG file png(file=\"withoutJitter.png\") # Plotting without jitter functionplot(x, y, xlim = c(0, 11), main = \"Without Jitter Function\") # saving the file dev.off() x_j <- jitter(x) # output to be present as PNG file png(file=\"withJitter.png\") # Plotting with jitter functionplot(x_j, y, xlim = c(0, 11), main = \"With Jitter Function\") # saving the file dev.off()", "e": 26061, "s": 25565, "text": null }, { "code": null, "e": 26069, "s": 26061, "text": "Output:" }, { "code": null, "e": 26104, "s": 26069, "text": "Example 2: With large factor value" }, { "code": "# Define numeric vectorsx <- round(runif(1000, 1, 10))y <- x + rnorm(1000, mean = 0, sd = 5) # output to be present as PNG file png(file=\"withoutJitterFactor.png\") # Plotting without jitter functionplot(x, y, xlim = c(0, 11), main = \"Without Jitter Function\") # saving the file dev.off() x_j <- jitter(x, factor = 2) # output to be present as PNG file png(file=\"withJitterFactor.png\") # Plotting with jitter functionplot(x_j, y, xlim = c(0, 11), main = \"With Jitter Function and Large Factor\") # saving the file dev.off()", "e": 26641, "s": 26104, "text": null }, { "code": null, "e": 26649, "s": 26641, "text": "Output:" }, { "code": null, "e": 26667, "s": 26649, "text": "R Factor-Function" }, { "code": null, "e": 26685, "s": 26667, "text": "R Vector-Function" }, { "code": null, "e": 26693, "s": 26685, "text": "R-plots" }, { "code": null, "e": 26704, "s": 26693, "text": "R Language" }, { "code": null, "e": 26802, "s": 26704, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26854, "s": 26802, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26892, "s": 26854, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26927, "s": 26892, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26985, "s": 26927, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27034, "s": 26985, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27071, "s": 27034, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 27121, "s": 27071, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27164, "s": 27121, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27181, "s": 27164, "text": "R - if statement" } ]
Program to find the highest altitude of a point in Python
Suppose there is a biker who is going on a road trip. There are n different points in his road trip at different altitudes. The biker starts his trip from point 0 with altitude 0. If we have a sequence called gain with n elements, gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). We have to find the highest altitude of a point. So, if the input is like gain = [-4,2,6,1,-6], then the output will be 5, because the altitudes are [0,-4,-2,4,5,-1], so the maximum is 5. To solve this, we will follow these steps − maximum := 0 maximum := 0 run_alt := 0 run_alt := 0 for each delta in gain, dorun_alt := run_alt + deltamaximum := max of maximum and run_alt for each delta in gain, do run_alt := run_alt + delta run_alt := run_alt + delta maximum := max of maximum and run_alt maximum := max of maximum and run_alt return maximum return maximum Let us see the following implementation to get better understanding − Live Demo def solve(gain): maximum = 0 run_alt = 0 for delta in gain: run_alt += delta maximum = max(maximum, run_alt) return maximum gain = [-4,2,6,1,-6] print(solve(gain)) [-4,2,6,1,-6] 5
[ { "code": null, "e": 1427, "s": 1062, "text": "Suppose there is a biker who is going on a road trip. There are n different points in his road trip at different altitudes. The biker starts his trip from point 0 with altitude 0. If we have a sequence called gain with n elements, gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). We have to find the highest altitude of a point." }, { "code": null, "e": 1566, "s": 1427, "text": "So, if the input is like gain = [-4,2,6,1,-6], then the output will be 5, because the altitudes are [0,-4,-2,4,5,-1], so the maximum is 5." }, { "code": null, "e": 1610, "s": 1566, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1623, "s": 1610, "text": "maximum := 0" }, { "code": null, "e": 1636, "s": 1623, "text": "maximum := 0" }, { "code": null, "e": 1649, "s": 1636, "text": "run_alt := 0" }, { "code": null, "e": 1662, "s": 1649, "text": "run_alt := 0" }, { "code": null, "e": 1752, "s": 1662, "text": "for each delta in gain, dorun_alt := run_alt + deltamaximum := max of maximum and run_alt" }, { "code": null, "e": 1779, "s": 1752, "text": "for each delta in gain, do" }, { "code": null, "e": 1806, "s": 1779, "text": "run_alt := run_alt + delta" }, { "code": null, "e": 1833, "s": 1806, "text": "run_alt := run_alt + delta" }, { "code": null, "e": 1871, "s": 1833, "text": "maximum := max of maximum and run_alt" }, { "code": null, "e": 1909, "s": 1871, "text": "maximum := max of maximum and run_alt" }, { "code": null, "e": 1924, "s": 1909, "text": "return maximum" }, { "code": null, "e": 1939, "s": 1924, "text": "return maximum" }, { "code": null, "e": 2009, "s": 1939, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2020, "s": 2009, "text": " Live Demo" }, { "code": null, "e": 2211, "s": 2020, "text": "def solve(gain):\n maximum = 0\n run_alt = 0\n\n for delta in gain:\n run_alt += delta\n maximum = max(maximum, run_alt)\n\n return maximum\n\ngain = [-4,2,6,1,-6]\nprint(solve(gain))" }, { "code": null, "e": 2225, "s": 2211, "text": "[-4,2,6,1,-6]" }, { "code": null, "e": 2227, "s": 2225, "text": "5" } ]
Polynomial Regression with Scikit learn: What You Should Know | by Angela Shi | Towards Data Science
Polynomial regression is an algorithm that is well known. It is a special case of linear regression, by the fact that we create some polynomial features before creating a linear regression. Or it can be considered as a linear regression with a feature space mapping (aka a polynomial kernel). With this kernel trick, it is, sort of, possible to create a polynomial regression with a degree that is infinite! In this article, we will deal with the classic polynomial regression. With scikit learn, it is possible to create one in a pipeline combining these two steps (Polynomialfeatures and LinearRegression). I will show the code below. And let’s see an example, with some simple toy data, of only 10 points. Let’s also consider the degree to be 9. You can see the final result below. Do you see anything wrong? Well, in theory, this is wrong! For 10 points, a 9th-degree polynomial should fit them perfectly! Or maybe, I am sure that some of you are thinking: why are you saying that this is wrong? This may be the right model. You think that the model should fit perfectly, but no, you are confused with polynomial interpolation! First, you can try it for yourself using the following code to create the model. import pandas as pdxdic={'X': {11: 300, 12: 170, 13: 288, 14: 360, 15: 319, 16: 330, 17: 520, 18: 345, 19: 399, 20: 479}}ydic={'y': {11: 305000, 12: 270000, 13: 360000, 14: 370000, 15: 379000, 16: 405000, 17: 407500, 18: 450000, 19: 450000, 20: 485000}}X=pd.DataFrame.from_dict(xdic)y=pd.DataFrame.from_dict(ydic)import numpy as npX_seq = np.linspace(X.min(),X.max(),300).reshape(-1,1) from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.pipeline import make_pipelinefrom sklearn.linear_model import LinearRegressiondegree=9polyreg=make_pipeline(PolynomialFeatures(degree),LinearRegression())polyreg.fit(X,y) import matplotlib.pyplot as pltplt.figure()plt.scatter(X,y)plt.plot(X_seq,polyreg.predict(X_seq),color="black")plt.title("Polynomial regression with degree "+str(degree))plt.show() Before talking about the difference between polynomial regression and polynomial interpolation. Let’s first talk about an answer that I got from the scikit learn team: you should not be doing this, expansion to a 9th-degree polynomial is nonsense. And scikit learn is built for practical use cases, and it works with finite-precision representations, not theoretical representations. Yes, they are totally right! Just look at the numbers, how big they become: 1e24! But if they cannot handle big numbers, shouldn’t they throw an error or a warning? Without any message, one will just consider that the model is correct, whereas, well, it is actually not. OK OK, I know, some of you are not convinced that the result is wrong, or maybe it is impossible to handle big numbers, let's see with another package, numpy! For the same example, polyfit from numpy has no problem finding the model. You can see the plot and the code below. coefs = np.polyfit(X.values.flatten(), y.values.flatten(), 9)plt.figure()plt.plot(X_seq, np.polyval(coefs, X_seq), color="black")plt.title("Polyfit degree "+str(degree))plt.scatter(X,y)plt.show() Now I know some of you are thinking: polyfit is a very different thing, it is an interpolation and not regression. Because when asking around, I got some answers like this (but they are not accurate, or wrong): polyfit is doing an altogether different thing. It is performing a univariate polynomial fit for some vector x to a vector y. Here we are performing a polynomial expansion of some feature space X in order to represent high-order interaction terms (equivalent to learning with a polynomial kernel) for a multivariate fit. OK, what is a polynomial interpolation? Well, for this kind of question, Wikipedia is a good source. In numerical analysis, polynomial interpolation is the interpolation of a given data set by the polynomial of lowest possible degree that passes through the points of the dataset. And we have this result that is proven: given n+1 distinct points x_0,x_0,... ,x_n and corresponding values y_0,y_1,... ,y_n, there exists a unique polynomial of degree at most n that interpolates the data (x_0,y_0),... ,(x_n,y_n). Going back to our example: there are 10 points, and we try to find a 9th-degree polynomial. So technically, we are doing polynomial interpolation. And polyfit found this unique polynomial! This is not the case for scikit learn’s polynomial regression pipeline! And this is precisely why some of you are thinking: polyfit is different from scikit learn’s polynomial regression pipeline! Now, wait! In polyfit, there is an argument, called degree. So you can modify the degree, let’s try with 5. Yes, with polyfit, it is possible to choose the degree of the polynomial and we are doing polynomial regression with it. And degree 9, chosen by the user, is the special case of polynomial interpolation. And it is reassuring because the linear regression tries to minimize the squared error. And we know that if there are 10 points, and we try to find a polynomial of degree 9, then the error can be 0 (can’t be lower!) because of the theorem of polynomial interpolation. For those who are still doubting, there is the official document for polyfit: Least squares polynomial fit. Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimizes the squared error in the order deg, deg-1, ... 0. OK, time to go back to our scikit learn’s polynomial regression pipeline. So now, why the difference? Are there really two different polynomial regression (or fit), using both Least Squares, but using them differently? I found this answer, but I am not getting it yet. Both models uses Least Squares, but the equation on which these Least Squares are used is completely different. polyfit applies it on the vandemonde matrix while the linear regression does not. While digging around, another important transformation of features should be mentioned: feature scaling. In several books on machine learning, when performing polynomial regressions, the features are scaled. Maybe from the beginning, some of you were saying that it should be done. And yes, scikit learn’s polynomial regression pipeline with the feature scaling, seems to be equivalent to polyfit! according to the plot (I didn’t really check, but visually they are the same). You can use the code below: from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.pipeline import make_pipelinefrom sklearn.linear_model import LinearRegressionfrom sklearn import preprocessingscaler = preprocessing.StandardScaler()degree=9polyreg_scaled=make_pipeline(PolynomialFeatures(degree),scaler,LinearRegression())polyreg_scaled.fit(X,y) Now, we didn’t answer our previous questions, and we have more questions: does feature scaling have an effect on linear regression? Well, the answer is No. To discuss this, there can be another article written and for our discussion about the effect of polynomial regression, we can just do another transformation. X=pd.DataFrame.from_dict(xdic)/1000 That’s right, you just divide the predictors by 1000. Now, you know that the effect on the linear regression model is only proportional, but in practice, the difference is huge. So that is why we can conclude that the initial numbers are too big for scikit learn. In the end, we can say that scikit learn’s polynomial regression pipeline (with or without scaling), should be equivalent to numpy’s polyfit, but the difference in terms of big number handling can create different results. And personally, I think that scikit learn should throw an error or at least a warning in this case. I really would like to know your opinions! If you like to know more about how polynomial regression is related to other supervised learning algorithms, you can read this article: towardsdatascience.com You will see that the polynomial regression is a special kind of feature space mapping.
[ { "code": null, "e": 580, "s": 172, "text": "Polynomial regression is an algorithm that is well known. It is a special case of linear regression, by the fact that we create some polynomial features before creating a linear regression. Or it can be considered as a linear regression with a feature space mapping (aka a polynomial kernel). With this kernel trick, it is, sort of, possible to create a polynomial regression with a degree that is infinite!" }, { "code": null, "e": 957, "s": 580, "text": "In this article, we will deal with the classic polynomial regression. With scikit learn, it is possible to create one in a pipeline combining these two steps (Polynomialfeatures and LinearRegression). I will show the code below. And let’s see an example, with some simple toy data, of only 10 points. Let’s also consider the degree to be 9. You can see the final result below." }, { "code": null, "e": 984, "s": 957, "text": "Do you see anything wrong?" }, { "code": null, "e": 1082, "s": 984, "text": "Well, in theory, this is wrong! For 10 points, a 9th-degree polynomial should fit them perfectly!" }, { "code": null, "e": 1304, "s": 1082, "text": "Or maybe, I am sure that some of you are thinking: why are you saying that this is wrong? This may be the right model. You think that the model should fit perfectly, but no, you are confused with polynomial interpolation!" }, { "code": null, "e": 1385, "s": 1304, "text": "First, you can try it for yourself using the following code to create the model." }, { "code": null, "e": 1771, "s": 1385, "text": "import pandas as pdxdic={'X': {11: 300, 12: 170, 13: 288, 14: 360, 15: 319, 16: 330, 17: 520, 18: 345, 19: 399, 20: 479}}ydic={'y': {11: 305000, 12: 270000, 13: 360000, 14: 370000, 15: 379000, 16: 405000, 17: 407500, 18: 450000, 19: 450000, 20: 485000}}X=pd.DataFrame.from_dict(xdic)y=pd.DataFrame.from_dict(ydic)import numpy as npX_seq = np.linspace(X.min(),X.max(),300).reshape(-1,1)" }, { "code": null, "e": 2007, "s": 1771, "text": "from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.pipeline import make_pipelinefrom sklearn.linear_model import LinearRegressiondegree=9polyreg=make_pipeline(PolynomialFeatures(degree),LinearRegression())polyreg.fit(X,y)" }, { "code": null, "e": 2188, "s": 2007, "text": "import matplotlib.pyplot as pltplt.figure()plt.scatter(X,y)plt.plot(X_seq,polyreg.predict(X_seq),color=\"black\")plt.title(\"Polynomial regression with degree \"+str(degree))plt.show()" }, { "code": null, "e": 2572, "s": 2188, "text": "Before talking about the difference between polynomial regression and polynomial interpolation. Let’s first talk about an answer that I got from the scikit learn team: you should not be doing this, expansion to a 9th-degree polynomial is nonsense. And scikit learn is built for practical use cases, and it works with finite-precision representations, not theoretical representations." }, { "code": null, "e": 2654, "s": 2572, "text": "Yes, they are totally right! Just look at the numbers, how big they become: 1e24!" }, { "code": null, "e": 2843, "s": 2654, "text": "But if they cannot handle big numbers, shouldn’t they throw an error or a warning? Without any message, one will just consider that the model is correct, whereas, well, it is actually not." }, { "code": null, "e": 3002, "s": 2843, "text": "OK OK, I know, some of you are not convinced that the result is wrong, or maybe it is impossible to handle big numbers, let's see with another package, numpy!" }, { "code": null, "e": 3118, "s": 3002, "text": "For the same example, polyfit from numpy has no problem finding the model. You can see the plot and the code below." }, { "code": null, "e": 3314, "s": 3118, "text": "coefs = np.polyfit(X.values.flatten(), y.values.flatten(), 9)plt.figure()plt.plot(X_seq, np.polyval(coefs, X_seq), color=\"black\")plt.title(\"Polyfit degree \"+str(degree))plt.scatter(X,y)plt.show()" }, { "code": null, "e": 3429, "s": 3314, "text": "Now I know some of you are thinking: polyfit is a very different thing, it is an interpolation and not regression." }, { "code": null, "e": 3525, "s": 3429, "text": "Because when asking around, I got some answers like this (but they are not accurate, or wrong):" }, { "code": null, "e": 3846, "s": 3525, "text": "polyfit is doing an altogether different thing. It is performing a univariate polynomial fit for some vector x to a vector y. Here we are performing a polynomial expansion of some feature space X in order to represent high-order interaction terms (equivalent to learning with a polynomial kernel) for a multivariate fit." }, { "code": null, "e": 3886, "s": 3846, "text": "OK, what is a polynomial interpolation?" }, { "code": null, "e": 3947, "s": 3886, "text": "Well, for this kind of question, Wikipedia is a good source." }, { "code": null, "e": 4127, "s": 3947, "text": "In numerical analysis, polynomial interpolation is the interpolation of a given data set by the polynomial of lowest possible degree that passes through the points of the dataset." }, { "code": null, "e": 4359, "s": 4127, "text": "And we have this result that is proven: given n+1 distinct points x_0,x_0,... ,x_n and corresponding values y_0,y_1,... ,y_n, there exists a unique polynomial of degree at most n that interpolates the data (x_0,y_0),... ,(x_n,y_n)." }, { "code": null, "e": 4620, "s": 4359, "text": "Going back to our example: there are 10 points, and we try to find a 9th-degree polynomial. So technically, we are doing polynomial interpolation. And polyfit found this unique polynomial! This is not the case for scikit learn’s polynomial regression pipeline!" }, { "code": null, "e": 4745, "s": 4620, "text": "And this is precisely why some of you are thinking: polyfit is different from scikit learn’s polynomial regression pipeline!" }, { "code": null, "e": 4756, "s": 4745, "text": "Now, wait!" }, { "code": null, "e": 4853, "s": 4756, "text": "In polyfit, there is an argument, called degree. So you can modify the degree, let’s try with 5." }, { "code": null, "e": 5057, "s": 4853, "text": "Yes, with polyfit, it is possible to choose the degree of the polynomial and we are doing polynomial regression with it. And degree 9, chosen by the user, is the special case of polynomial interpolation." }, { "code": null, "e": 5325, "s": 5057, "text": "And it is reassuring because the linear regression tries to minimize the squared error. And we know that if there are 10 points, and we try to find a polynomial of degree 9, then the error can be 0 (can’t be lower!) because of the theorem of polynomial interpolation." }, { "code": null, "e": 5618, "s": 5325, "text": "For those who are still doubting, there is the official document for polyfit: Least squares polynomial fit. Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimizes the squared error in the order deg, deg-1, ... 0." }, { "code": null, "e": 5837, "s": 5618, "text": "OK, time to go back to our scikit learn’s polynomial regression pipeline. So now, why the difference? Are there really two different polynomial regression (or fit), using both Least Squares, but using them differently?" }, { "code": null, "e": 5887, "s": 5837, "text": "I found this answer, but I am not getting it yet." }, { "code": null, "e": 6081, "s": 5887, "text": "Both models uses Least Squares, but the equation on which these Least Squares are used is completely different. polyfit applies it on the vandemonde matrix while the linear regression does not." }, { "code": null, "e": 6186, "s": 6081, "text": "While digging around, another important transformation of features should be mentioned: feature scaling." }, { "code": null, "e": 6363, "s": 6186, "text": "In several books on machine learning, when performing polynomial regressions, the features are scaled. Maybe from the beginning, some of you were saying that it should be done." }, { "code": null, "e": 6558, "s": 6363, "text": "And yes, scikit learn’s polynomial regression pipeline with the feature scaling, seems to be equivalent to polyfit! according to the plot (I didn’t really check, but visually they are the same)." }, { "code": null, "e": 6586, "s": 6558, "text": "You can use the code below:" }, { "code": null, "e": 6915, "s": 6586, "text": "from sklearn.preprocessing import PolynomialFeaturesfrom sklearn.pipeline import make_pipelinefrom sklearn.linear_model import LinearRegressionfrom sklearn import preprocessingscaler = preprocessing.StandardScaler()degree=9polyreg_scaled=make_pipeline(PolynomialFeatures(degree),scaler,LinearRegression())polyreg_scaled.fit(X,y)" }, { "code": null, "e": 7047, "s": 6915, "text": "Now, we didn’t answer our previous questions, and we have more questions: does feature scaling have an effect on linear regression?" }, { "code": null, "e": 7071, "s": 7047, "text": "Well, the answer is No." }, { "code": null, "e": 7230, "s": 7071, "text": "To discuss this, there can be another article written and for our discussion about the effect of polynomial regression, we can just do another transformation." }, { "code": null, "e": 7266, "s": 7230, "text": "X=pd.DataFrame.from_dict(xdic)/1000" }, { "code": null, "e": 7444, "s": 7266, "text": "That’s right, you just divide the predictors by 1000. Now, you know that the effect on the linear regression model is only proportional, but in practice, the difference is huge." }, { "code": null, "e": 7530, "s": 7444, "text": "So that is why we can conclude that the initial numbers are too big for scikit learn." }, { "code": null, "e": 7753, "s": 7530, "text": "In the end, we can say that scikit learn’s polynomial regression pipeline (with or without scaling), should be equivalent to numpy’s polyfit, but the difference in terms of big number handling can create different results." }, { "code": null, "e": 7853, "s": 7753, "text": "And personally, I think that scikit learn should throw an error or at least a warning in this case." }, { "code": null, "e": 7896, "s": 7853, "text": "I really would like to know your opinions!" }, { "code": null, "e": 8032, "s": 7896, "text": "If you like to know more about how polynomial regression is related to other supervised learning algorithms, you can read this article:" }, { "code": null, "e": 8055, "s": 8032, "text": "towardsdatascience.com" } ]
Spring - Page Redirection Example
The following example show how to write a simple web-based application which makes use of redirect to transfer a http request to another page. To start with, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Formbased Web Application using Spring Web Framework − Here is the content of WebController.java file package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebController { @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "index"; } @RequestMapping(value = "/redirect", method = RequestMethod.GET) public String redirect() { return "redirect:finalPage"; } @RequestMapping(value = "/finalPage", method = RequestMethod.GET) public String finalPage() { return "final"; } } Following is the content of Spring Web configuration file web.xml <web-app id = "WebApp_ID" version = "2.4" xmlns = "http://java.sun.com/xml/ns/j2ee" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring Page Redirection</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> Following is the content of another Spring Web configuration file HelloWeb-servlet.xml <?xml version = "1.0" encoding = "UTF-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:context = "http://www.springframework.org/schema/context" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package = "com.tutorialspoint" /> <bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name = "prefix" value = "/WEB-INF/jsp/" /> <property name = "suffix" value=".jsp" /> </bean> </beans> Following is the content of Spring view file index.jsp. This will be a landing page, this page will send a request to access redirect service method which will redirect this request to another service method and finally a final.jsp page will be displauyed. <%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%> <html> <head> <title>Spring Page Redirection</title> </head> <body> <h2>Spring Page Redirection</h2> <p>Click below button to redirect the result to new page</p> <form:form method = "GET" action = "/HelloWeb/redirect"> <table> <tr> <td> <input type = "submit" value = "Redirect Page"/> </td> </tr> </table> </form:form> </body> </html> Following is the content of Spring view file final.jsp. This is the final redirected page. <%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%> <html> <head> <title>Spring Page Redirection</title> </head> <body> <h2>Redirected Page</h2> </body> </html> Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEB-INF/lib folder. commons-logging-x.y.z.jar org.springframework.asm-x.y.z.jar org.springframework.beans-x.y.z.jar org.springframework.context-x.y.z.jar org.springframework.core-x.y.z.jar org.springframework.expression-x.y.z.jar org.springframework.web.servlet-x.y.z.jar org.springframework.web-x.y.z.jar spring-web.jar Once you are done with creating source and configuration files, export your application. Right click on your application and use Export > WAR File option and save your HelloWeb.war file in Tomcat's webapps folder. Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application. Click the "Redirect Page" button to submit the form and to get the final redirected page. You should see the following result if everything is fine with your Spring Web Application. 102 Lectures 8 hours Karthikeya T 39 Lectures 5 hours Chaand Sheikh 73 Lectures 5.5 hours Senol Atac 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac 69 Lectures 5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2598, "s": 2292, "text": "The following example show how to write a simple web-based application which makes use of redirect to transfer a http request to another page. To start with, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Formbased Web Application using Spring Web Framework −" }, { "code": null, "e": 2645, "s": 2598, "text": "Here is the content of WebController.java file" }, { "code": null, "e": 3277, "s": 2645, "text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class WebController {\n @RequestMapping(value = \"/index\", method = RequestMethod.GET)\n public String index() {\n return \"index\";\n }\n @RequestMapping(value = \"/redirect\", method = RequestMethod.GET)\n public String redirect() {\n return \"redirect:finalPage\";\n }\n @RequestMapping(value = \"/finalPage\", method = RequestMethod.GET)\n public String finalPage() {\n return \"final\";\n }\n}" }, { "code": null, "e": 3343, "s": 3277, "text": "Following is the content of Spring Web configuration file web.xml" }, { "code": null, "e": 4002, "s": 3343, "text": "<web-app id = \"WebApp_ID\" version = \"2.4\"\n xmlns = \"http://java.sun.com/xml/ns/j2ee\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/j2ee \n http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\">\n \n <display-name>Spring Page Redirection</display-name>\n \n <servlet>\n <servlet-name>HelloWeb</servlet-name>\n <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>HelloWeb</servlet-name>\n <url-pattern>/</url-pattern>\n </servlet-mapping>\n \n</web-app>" }, { "code": null, "e": 4089, "s": 4002, "text": "Following is the content of another Spring Web configuration file HelloWeb-servlet.xml" }, { "code": null, "e": 4907, "s": 4089, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:context = \"http://www.springframework.org/schema/context\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans \n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\n http://www.springframework.org/schema/context \n http://www.springframework.org/schema/context/spring-context-3.0.xsd\">\n \n <context:component-scan base-package = \"com.tutorialspoint\" />\n \n <bean id = \"viewResolver\" \n class = \"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n \n <property name = \"prefix\" value = \"/WEB-INF/jsp/\" />\n <property name = \"suffix\" value=\".jsp\" />\n </bean>\n \n</beans>" }, { "code": null, "e": 5164, "s": 4907, "text": "Following is the content of Spring view file index.jsp. This will be a landing page, this page will send a request to access redirect service method which will redirect this request to another service method and finally a final.jsp page will be displauyed." }, { "code": null, "e": 5723, "s": 5164, "text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring Page Redirection</title>\n </head>\n\n <body>\n <h2>Spring Page Redirection</h2>\n <p>Click below button to redirect the result to new page</p>\n \n <form:form method = \"GET\" action = \"/HelloWeb/redirect\">\n <table>\n <tr>\n <td>\n <input type = \"submit\" value = \"Redirect Page\"/>\n </td>\n </tr>\n </table> \n </form:form>\n </body>\n \n</html>" }, { "code": null, "e": 5814, "s": 5723, "text": "Following is the content of Spring view file final.jsp. This is the final redirected page." }, { "code": null, "e": 6025, "s": 5814, "text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring Page Redirection</title>\n </head>\n\n <body>\n <h2>Redirected Page</h2>\n </body>\n</html>" }, { "code": null, "e": 6202, "s": 6025, "text": "Finally, following is the list of Spring and other libraries to be included in your web application. You simply drag these files and drop them in WebContent/WEB-INF/lib folder." }, { "code": null, "e": 6228, "s": 6202, "text": "commons-logging-x.y.z.jar" }, { "code": null, "e": 6262, "s": 6228, "text": "org.springframework.asm-x.y.z.jar" }, { "code": null, "e": 6298, "s": 6262, "text": "org.springframework.beans-x.y.z.jar" }, { "code": null, "e": 6336, "s": 6298, "text": "org.springframework.context-x.y.z.jar" }, { "code": null, "e": 6371, "s": 6336, "text": "org.springframework.core-x.y.z.jar" }, { "code": null, "e": 6412, "s": 6371, "text": "org.springframework.expression-x.y.z.jar" }, { "code": null, "e": 6454, "s": 6412, "text": "org.springframework.web.servlet-x.y.z.jar" }, { "code": null, "e": 6488, "s": 6454, "text": "org.springframework.web-x.y.z.jar" }, { "code": null, "e": 6503, "s": 6488, "text": "spring-web.jar" }, { "code": null, "e": 6717, "s": 6503, "text": "Once you are done with creating source and configuration files, export your application. Right click on your application and use Export > WAR File option and save your HelloWeb.war file in Tomcat's webapps folder." }, { "code": null, "e": 6988, "s": 6717, "text": "Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application." }, { "code": null, "e": 7170, "s": 6988, "text": "Click the \"Redirect Page\" button to submit the form and to get the final redirected page. You should see the following result if everything is fine with your Spring Web Application." }, { "code": null, "e": 7204, "s": 7170, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 7218, "s": 7204, "text": " Karthikeya T" }, { "code": null, "e": 7251, "s": 7218, "text": "\n 39 Lectures \n 5 hours \n" }, { "code": null, "e": 7266, "s": 7251, "text": " Chaand Sheikh" }, { "code": null, "e": 7301, "s": 7266, "text": "\n 73 Lectures \n 5.5 hours \n" }, { "code": null, "e": 7313, "s": 7301, "text": " Senol Atac" }, { "code": null, "e": 7348, "s": 7313, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7360, "s": 7348, "text": " Senol Atac" }, { "code": null, "e": 7395, "s": 7360, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7407, "s": 7395, "text": " Senol Atac" }, { "code": null, "e": 7440, "s": 7407, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 7452, "s": 7440, "text": " Senol Atac" }, { "code": null, "e": 7459, "s": 7452, "text": " Print" }, { "code": null, "e": 7470, "s": 7459, "text": " Add Notes" } ]
Program to display hostname and IP address C
In this section we will see how to see the Host name and IP address of the local system in an easier way. We will write a C program to find the host name and IP. Some of the following functions are used. These functions have a different task. Let us see the functions and their tasks. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> void check_host_name(int hostname) { //This function returns host name for local computer if (hostname == -1) { perror("gethostname"); exit(1); } } void check_host_entry(struct hostent * hostentry) { //find host info from host name if (hostentry == NULL) { perror("gethostbyname"); exit(1); } } void IP_formatter(char *IPbuffer) { //convert IP string to dotted decimal format if (NULL == IPbuffer) { perror("inet_ntoa"); exit(1); } } main() { char host[256]; char *IP; struct hostent *host_entry; int hostname; hostname = gethostname(host, sizeof(host)); //find the host name check_host_name(hostname); host_entry = gethostbyname(host); //find host information check_host_entry(host_entry); IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); //Convert into IP string printf("Current Host Name: %s\n", host); printf("Host IP: %s\n", IP); } Current Host Name: soumyadeep-VirtualBox Host IP: 127.0.1.1
[ { "code": null, "e": 1224, "s": 1062, "text": "In this section we will see how to see the Host name and IP address of the local system in an easier way. We will write a C program to find the host name and IP." }, { "code": null, "e": 1347, "s": 1224, "text": "Some of the following functions are used. These functions have a different task. Let us see the functions and their tasks." }, { "code": null, "e": 2478, "s": 1347, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <errno.h>\n#include <netdb.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\nvoid check_host_name(int hostname) { //This function returns host name for local computer\n if (hostname == -1) {\n perror(\"gethostname\");\n exit(1);\n }\n}\nvoid check_host_entry(struct hostent * hostentry) { //find host info from host name\n if (hostentry == NULL) {\n perror(\"gethostbyname\");\n exit(1);\n }\n}\nvoid IP_formatter(char *IPbuffer) { //convert IP string to dotted decimal format\n if (NULL == IPbuffer) {\n perror(\"inet_ntoa\");\n exit(1);\n }\n}\nmain() {\n char host[256];\n char *IP;\n struct hostent *host_entry;\n int hostname;\n hostname = gethostname(host, sizeof(host)); //find the host name\n check_host_name(hostname);\n host_entry = gethostbyname(host); //find host information\n check_host_entry(host_entry);\n IP = inet_ntoa(*((struct in_addr*) host_entry->h_addr_list[0])); //Convert into IP string\n printf(\"Current Host Name: %s\\n\", host);\n printf(\"Host IP: %s\\n\", IP);\n}" }, { "code": null, "e": 2538, "s": 2478, "text": "Current Host Name: soumyadeep-VirtualBox\nHost IP: 127.0.1.1" } ]
Rotate Matrix in Python
Suppose we have one n x n 2D matrix. We have to rotate this matrix 90 degrees clockwise. So if the matrix is like- Then the output will be To solve this, we will follow these steps − Consider temp_mat = [], col := length of matrix – 1 for col in range 0 to length of matrixtemp := []for row in range length of matrix – 1 down to -1add matrix[row, col] in tempadd temp into temp_mat temp := [] for row in range length of matrix – 1 down to -1add matrix[row, col] in temp add matrix[row, col] in temp add temp into temp_mat for i in range 0 to length of matrixfor j in range 0 to length of matrixmatrix[i, j] := temp_mat[i, j] for j in range 0 to length of matrixmatrix[i, j] := temp_mat[i, j] matrix[i, j] := temp_mat[i, j] Let us see the following implementation to get better understanding − Live Demo class Solution(object): def rotate(self, matrix): temp_matrix = [] column = len(matrix)-1 for column in range(len(matrix)): temp = [] for row in range(len(matrix)-1,-1,-1): temp.append(matrix[row][column]) temp_matrix.append(temp) for i in range(len(matrix)): for j in range(len(matrix)): matrix[i][j] = temp_matrix[i][j] return matrix ob1 = Solution() print(ob1.rotate([[1,5,7],[9,6,3],[2,1,3]])) [[1,5,7],[9,6,3],[2,1,3]] [[2, 9, 1], [1, 6, 5], [3, 3, 7]]
[ { "code": null, "e": 1177, "s": 1062, "text": "Suppose we have one n x n 2D matrix. We have to rotate this matrix 90 degrees clockwise. So if the matrix is like-" }, { "code": null, "e": 1201, "s": 1177, "text": "Then the output will be" }, { "code": null, "e": 1245, "s": 1201, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1297, "s": 1245, "text": "Consider temp_mat = [], col := length of matrix – 1" }, { "code": null, "e": 1444, "s": 1297, "text": "for col in range 0 to length of matrixtemp := []for row in range length of matrix – 1 down to -1add matrix[row, col] in tempadd temp into temp_mat" }, { "code": null, "e": 1455, "s": 1444, "text": "temp := []" }, { "code": null, "e": 1532, "s": 1455, "text": "for row in range length of matrix – 1 down to -1add matrix[row, col] in temp" }, { "code": null, "e": 1561, "s": 1532, "text": "add matrix[row, col] in temp" }, { "code": null, "e": 1584, "s": 1561, "text": "add temp into temp_mat" }, { "code": null, "e": 1687, "s": 1584, "text": "for i in range 0 to length of matrixfor j in range 0 to length of matrixmatrix[i, j] := temp_mat[i, j]" }, { "code": null, "e": 1754, "s": 1687, "text": "for j in range 0 to length of matrixmatrix[i, j] := temp_mat[i, j]" }, { "code": null, "e": 1785, "s": 1754, "text": "matrix[i, j] := temp_mat[i, j]" }, { "code": null, "e": 1855, "s": 1785, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 1865, "s": 1855, "text": "Live Demo" }, { "code": null, "e": 2357, "s": 1865, "text": "class Solution(object):\n def rotate(self, matrix):\n temp_matrix = []\n column = len(matrix)-1\n for column in range(len(matrix)):\n temp = []\n for row in range(len(matrix)-1,-1,-1):\n temp.append(matrix[row][column])\n temp_matrix.append(temp)\n for i in range(len(matrix)):\n for j in range(len(matrix)):\n matrix[i][j] = temp_matrix[i][j]\n return matrix\n\nob1 = Solution()\nprint(ob1.rotate([[1,5,7],[9,6,3],[2,1,3]]))" }, { "code": null, "e": 2383, "s": 2357, "text": "[[1,5,7],[9,6,3],[2,1,3]]" }, { "code": null, "e": 2417, "s": 2383, "text": "[[2, 9, 1], [1, 6, 5], [3, 3, 7]]" } ]
Beginner’s guide to transfer learning on Google Colab | by Suchandra Datta | Towards Data Science
Mammoth quantities of pristine data are one of the most valuable resources in these times, which is the potential source of huge revenue thanks to advances in deep learning and associated hardware that’s needed to speed up those innumerable matrix multiplications. What if we don’t have a lot of data and procuring more isn’t feasible? Or we lack the expensive hardware that’s imperative for training very deep networks? Both can be solved by using the concept of transfer learning, which we’ll soon find out is something we are unconsciously familiar with. Transfer learning is a supervised learning method that aids construction of new models using pre-trained weights of previously constructed and fine-tuned models. Recall those situations in your life wherein you had to take a decision but lacked appropriate domain knowledge for the same. One course of action is to approach your family, professors, friends and peers; listen to their understanding of the problem, apply your own intuitions and finally arrive at an informed decision. This is exactly what happens in transfer learning too. Transfer learning can be applied in several different ways Use the pre-trained models as it is: From our analogy, this is equivalent to listening to advice from others and applying it without modifications to the problem at hand. As a feature extractor: We utilize the features the model has already learnt and expand the model further so that it can also effectively learn new features that are characteristic or peculiar to our dataset and may vary from the dataset on which the pre-trained model has been trained on. This is analogous to forming an opinion based on one’s own wisdom, coupled with advice from others. Fine-tuning the model: In this case, we train the entire model, adding some layers of our own to get maximum performance. Whereas in feature extraction, we freeze the pre-trained layers to make sure learnt features aren’t updated during backpropagation, we unfreeze all layers in this approach as we hope this way the model generalizes better for the current dataset. What do we achieve by transfer learning? It’s one of the best options to choose when we need to build high performing models with small sized datasets with lack of time, money and resources needed to get a larger, unbiased dataset. Lack of the huge amount of time needed to train very deep networks. Lack of necessary hardware In short, you don’t have to start from scratch however it’s highly recommended that you do train some feasibly small networks to understand the basics well before migrating to transfer learning. Lack of expensive GPU’s can be compensated by using platforms like Google’s Colaboratory, a Google research project that makes machine learning accessible to all irrespective of hardware requirements, sporting a Jupyter Notebook environment, GPU or TPU support and all of this brought to you via cloud. To get more info on the specs, check out their example notebook linked here https://colab.research.google.com/drive/1_x67fw9y5aBW72a8aGePFLlkPvKLpnBl We will apply this technique on a simple binary image classification problem, differentiation between cat and dog images. Our dataset is pretty simple, with total 1,000 images of dogs and cats, encoded with labels 0 and 1 respectively. For image classification, there are lots of established network architectures that we can go through to derive our model from scratch, prior to using pre-trained ones. LeNet-5 is the first one that was employed for handwritten digit classification. With the advent of ImageNet Large Scale Visual Recognition Challenge, AlexNet was born, along with others like VGG-16, VGG-19, ResNet50, Inception, Xception, MobileNet and the ultimate NASNet, which is a neural network model that figures out its own neural network architecture. A simple model based on AlexNet gets a training accuracy of 93% and testing accuracy of 83%. Theoretically, the minimum error that models for such type image classifications can make should be similar to human level error. Humans are adept at classifying dog and cat images so our model should exhibit an accuracy of 95% and more. Let’s try out transfer learning using VGG-16 from keras.applications.vgg16 import VGG16from keras.models import Modelfrom keras.layers import Densefrom keras.layers import Flattenfrom keras.layers import Dropoutimport numpy as npfrom keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras import regularizersvgg_model=VGG16(include_top=False, input_shape=(64,64,3))for layer in vgg_model.layers: layer.trainable=False Among the many pre-trained models available under keras.applications, we choose VGG-16 as it’s architecture is similar to the one we’ve already used. To use the model as a feature extractor, we set include_top=False, so we can add our custom ANN or CNN onto the existing model. Further to make sure that pre-trained weights aren’t adjusted during backpropagation, we set layer.trainable=False. Later on, however, it’s found that accuracy with this setting doesn’t rise above 78% so it will be commented out to perform fine-tuning. x = vgg_model.output#add flatten layer so we can add the fully connected layer later#This is using the Keras functional API but Sequential API works #just as wellx = Flatten()(x)x = Dense(64, activation='relu')(x)x = Dropout(0.2)(x)x = Dense(1, activation='sigmoid')(x)#create the new modelmodel = Model(input=vgg_model.input, output=x)print(model.summary()) Next, the custom model, here a simple ANN is added on. Then the final model is constructed. Image data augmentation is applied to compensate for the size of the dataset. After some hyperparameter tuning, training and testing accuracy of 98% and 91% were obtained, for only 37 epochs, whereas we needed 70 epochs to get 83% accuracy on the one made from scratch. The same approach was also applied to ResNet50 which gave 92% and 87% as train and test accuracy. None of these however are perfect, with more tuning, more accuracy will be obtained. On a closing note, some things that cropped up during transfer learning All pre-trained models expect RGB color images. All models have a minimum image size which can’t be changed arbitrarily, otherwise after a series of convolutions, the later layers will be expected to perform matrix multiplication of arrays of incompatible sizes. Small batch sizes < 128 aren’t helpful for the current problem. ResNet50, MobileNet and similar architectures have a BatchNormalization layer. During training, these layers aren’t updated, so the normalization is done with pre-computed values from the dataset on which this has been trained previously. If these values are widely different from the current dataset, low accuracy will be obtained. Unfreezing the layers yielded better results. (Frankly this is what I understood from this discussion here https://github.com/keras-team/keras/issues/9214#issuecomment-397916155 feel free to point out mistakes and add your viewpoints) Dog and cat images were correctly identified after training as expected. It also started classifying lions as cats and wolves as dogs. It classifies cartoon images of dogs and cats too. Here’s my humble attempt at demystifying some of the underlying concepts governing transfer learning and hopefully ease fellow coders’ transition into the land of deep learning. I’m pretty much a beginner myself, dabbling with these as I find it insanely interesting and cool, striving to be a self-taught data scientist. If you are in the same situation too, I hope you soon get the model accuracy that you’re struggling for right now. Thanks for reading this far, feel free to point out bugs, share your thoughts and happy learning!
[ { "code": null, "e": 730, "s": 172, "text": "Mammoth quantities of pristine data are one of the most valuable resources in these times, which is the potential source of huge revenue thanks to advances in deep learning and associated hardware that’s needed to speed up those innumerable matrix multiplications. What if we don’t have a lot of data and procuring more isn’t feasible? Or we lack the expensive hardware that’s imperative for training very deep networks? Both can be solved by using the concept of transfer learning, which we’ll soon find out is something we are unconsciously familiar with." }, { "code": null, "e": 1328, "s": 730, "text": "Transfer learning is a supervised learning method that aids construction of new models using pre-trained weights of previously constructed and fine-tuned models. Recall those situations in your life wherein you had to take a decision but lacked appropriate domain knowledge for the same. One course of action is to approach your family, professors, friends and peers; listen to their understanding of the problem, apply your own intuitions and finally arrive at an informed decision. This is exactly what happens in transfer learning too. Transfer learning can be applied in several different ways" }, { "code": null, "e": 1499, "s": 1328, "text": "Use the pre-trained models as it is: From our analogy, this is equivalent to listening to advice from others and applying it without modifications to the problem at hand." }, { "code": null, "e": 1889, "s": 1499, "text": "As a feature extractor: We utilize the features the model has already learnt and expand the model further so that it can also effectively learn new features that are characteristic or peculiar to our dataset and may vary from the dataset on which the pre-trained model has been trained on. This is analogous to forming an opinion based on one’s own wisdom, coupled with advice from others." }, { "code": null, "e": 2257, "s": 1889, "text": "Fine-tuning the model: In this case, we train the entire model, adding some layers of our own to get maximum performance. Whereas in feature extraction, we freeze the pre-trained layers to make sure learnt features aren’t updated during backpropagation, we unfreeze all layers in this approach as we hope this way the model generalizes better for the current dataset." }, { "code": null, "e": 2298, "s": 2257, "text": "What do we achieve by transfer learning?" }, { "code": null, "e": 2489, "s": 2298, "text": "It’s one of the best options to choose when we need to build high performing models with small sized datasets with lack of time, money and resources needed to get a larger, unbiased dataset." }, { "code": null, "e": 2557, "s": 2489, "text": "Lack of the huge amount of time needed to train very deep networks." }, { "code": null, "e": 2584, "s": 2557, "text": "Lack of necessary hardware" }, { "code": null, "e": 2779, "s": 2584, "text": "In short, you don’t have to start from scratch however it’s highly recommended that you do train some feasibly small networks to understand the basics well before migrating to transfer learning." }, { "code": null, "e": 3232, "s": 2779, "text": "Lack of expensive GPU’s can be compensated by using platforms like Google’s Colaboratory, a Google research project that makes machine learning accessible to all irrespective of hardware requirements, sporting a Jupyter Notebook environment, GPU or TPU support and all of this brought to you via cloud. To get more info on the specs, check out their example notebook linked here https://colab.research.google.com/drive/1_x67fw9y5aBW72a8aGePFLlkPvKLpnBl" }, { "code": null, "e": 4327, "s": 3232, "text": "We will apply this technique on a simple binary image classification problem, differentiation between cat and dog images. Our dataset is pretty simple, with total 1,000 images of dogs and cats, encoded with labels 0 and 1 respectively. For image classification, there are lots of established network architectures that we can go through to derive our model from scratch, prior to using pre-trained ones. LeNet-5 is the first one that was employed for handwritten digit classification. With the advent of ImageNet Large Scale Visual Recognition Challenge, AlexNet was born, along with others like VGG-16, VGG-19, ResNet50, Inception, Xception, MobileNet and the ultimate NASNet, which is a neural network model that figures out its own neural network architecture. A simple model based on AlexNet gets a training accuracy of 93% and testing accuracy of 83%. Theoretically, the minimum error that models for such type image classifications can make should be similar to human level error. Humans are adept at classifying dog and cat images so our model should exhibit an accuracy of 95% and more." }, { "code": null, "e": 4372, "s": 4327, "text": "Let’s try out transfer learning using VGG-16" }, { "code": null, "e": 4770, "s": 4372, "text": "from keras.applications.vgg16 import VGG16from keras.models import Modelfrom keras.layers import Densefrom keras.layers import Flattenfrom keras.layers import Dropoutimport numpy as npfrom keras.preprocessing.image import ImageDataGeneratorfrom tensorflow.keras import regularizersvgg_model=VGG16(include_top=False, input_shape=(64,64,3))for layer in vgg_model.layers: layer.trainable=False" }, { "code": null, "e": 5301, "s": 4770, "text": "Among the many pre-trained models available under keras.applications, we choose VGG-16 as it’s architecture is similar to the one we’ve already used. To use the model as a feature extractor, we set include_top=False, so we can add our custom ANN or CNN onto the existing model. Further to make sure that pre-trained weights aren’t adjusted during backpropagation, we set layer.trainable=False. Later on, however, it’s found that accuracy with this setting doesn’t rise above 78% so it will be commented out to perform fine-tuning." }, { "code": null, "e": 5660, "s": 5301, "text": "x = vgg_model.output#add flatten layer so we can add the fully connected layer later#This is using the Keras functional API but Sequential API works #just as wellx = Flatten()(x)x = Dense(64, activation='relu')(x)x = Dropout(0.2)(x)x = Dense(1, activation='sigmoid')(x)#create the new modelmodel = Model(input=vgg_model.input, output=x)print(model.summary())" }, { "code": null, "e": 6205, "s": 5660, "text": "Next, the custom model, here a simple ANN is added on. Then the final model is constructed. Image data augmentation is applied to compensate for the size of the dataset. After some hyperparameter tuning, training and testing accuracy of 98% and 91% were obtained, for only 37 epochs, whereas we needed 70 epochs to get 83% accuracy on the one made from scratch. The same approach was also applied to ResNet50 which gave 92% and 87% as train and test accuracy. None of these however are perfect, with more tuning, more accuracy will be obtained." }, { "code": null, "e": 6277, "s": 6205, "text": "On a closing note, some things that cropped up during transfer learning" }, { "code": null, "e": 6325, "s": 6277, "text": "All pre-trained models expect RGB color images." }, { "code": null, "e": 6540, "s": 6325, "text": "All models have a minimum image size which can’t be changed arbitrarily, otherwise after a series of convolutions, the later layers will be expected to perform matrix multiplication of arrays of incompatible sizes." }, { "code": null, "e": 6604, "s": 6540, "text": "Small batch sizes < 128 aren’t helpful for the current problem." }, { "code": null, "e": 7172, "s": 6604, "text": "ResNet50, MobileNet and similar architectures have a BatchNormalization layer. During training, these layers aren’t updated, so the normalization is done with pre-computed values from the dataset on which this has been trained previously. If these values are widely different from the current dataset, low accuracy will be obtained. Unfreezing the layers yielded better results. (Frankly this is what I understood from this discussion here https://github.com/keras-team/keras/issues/9214#issuecomment-397916155 feel free to point out mistakes and add your viewpoints)" }, { "code": null, "e": 7358, "s": 7172, "text": "Dog and cat images were correctly identified after training as expected. It also started classifying lions as cats and wolves as dogs. It classifies cartoon images of dogs and cats too." } ]
Set custom Auto Increment with ZEROFILL in MySQL
Let us first create a table. Here. We have set UserId column with ZEROFILL and AUTO_INCREMENT mysql> create table DemoTable1831 ( UserId int(7) zerofill auto_increment, PRIMARY KEY(UserId) ); Query OK, 0 rows affected (0.00 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1831 values(101); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1831 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1831 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1831 values(); Query OK, 1 row affected (0.00 sec) Display all records from the table using select statement − mysql> select * from DemoTable1831; This will produce the following output. All the values have zerofill for UserId field width 7 +---------+ | UserId | +---------+ | 0000101 | | 0000102 | | 0000103 | | 0000104 | +---------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1156, "s": 1062, "text": "Let us first create a table. Here. We have set UserId column with ZEROFILL and AUTO_INCREMENT" }, { "code": null, "e": 1311, "s": 1156, "text": "mysql> create table DemoTable1831\n (\n UserId int(7) zerofill auto_increment,\n PRIMARY KEY(UserId)\n );\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1367, "s": 1311, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1686, "s": 1367, "text": "mysql> insert into DemoTable1831 values(101);\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1831 values();\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1831 values();\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1831 values();\nQuery OK, 1 row affected (0.00 sec)" }, { "code": null, "e": 1746, "s": 1686, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1782, "s": 1746, "text": "mysql> select * from DemoTable1831;" }, { "code": null, "e": 1876, "s": 1782, "text": "This will produce the following output. All the values have zerofill for UserId field width 7" }, { "code": null, "e": 1997, "s": 1876, "text": "+---------+\n| UserId |\n+---------+\n| 0000101 |\n| 0000102 |\n| 0000103 |\n| 0000104 |\n+---------+\n4 rows in set (0.00 sec)" } ]
Domain constraints in DBMS - GeeksforGeeks
01 Sep, 2021 In DBMS, constraints are the set of rules that ensures that when an authorized user modifies the database they do not disturb the data consistency and the constraints are specified within the DDL commands like “alter” and “create” command. There are several types of constraints available in DBMS and they are: Domain constraints Entity Integrity constraints Referential Integrity constraints Key constraints In this article, we will only discuss domain constraints. Domain Constraints are user-defined columns that help the user to enter the value according to the data type. And if it encounters a wrong input it gives the message to the user that the column is not fulfilled properly. Or in other words, it is an attribute that specifies all the possible values that the attribute can hold like integer, character, date, time, string, etc. It defines the domain or the set of values for an attribute and ensures that the value taken by the attribute must be an atomic value(Can’t be divided) from its domain. Domain Constraint = data type(integer / character/date / time / string / etc.) + Constraints(NOT NULL / UNIQUE / PRIMARY KEY / FOREIGN KEY / CHECK / DEFAULT) Type of domain constraints: There are two types of constraints that come under domain constraint and they are: 1. Domain Constraints – Not Null: Null values are the values that are unassigned or we can also say that which are unknown or the missing attribute values and by default, a column can hold the null values. Now as we know that the Not Null constraint restricts a column to not accept the null values which means it only restricts a field to always contain a value which means you cannot insert a new record or update a record without adding a value into the field. Example: In the ’employee’ database, every employee must have a name associated with them. Create table employee (employee_id varchar(30), employee_name varchar(30) not null, salary NUMBER); 2. Domain Constraints – Check: It defines a condition that each row must satisfy which means it restricts the value of a column between ranges or we can say that it is just like a condition or filter checking before saving data into a column. It ensures that when a tuple is inserted inside the relation must satisfy the predicate given in the check clause. Example: We need to check whether the entered id number is greater than 0 or not for the employee table. Create table employee (employee_id varchar(30) not null check(employee_id > 0), employee_name varchar(30), salary NUMBER); The above example creates CHECK constraints on the employee_id column and specifies that the column employee_id must only include integers greater than 0. Note: In DBMS a table is a combination of rows and columns in which we have some unique attribute names associated with it. And basically, a domain is a unique set of values present in a table. Let’s take an example, suppose we have a table student which consists of 3 attributes as NAME, ROLL NO, and MARKS. Now ROLL NO attributes can have only numbers associated with them and they won’t contain any alphabet. So we can say that it contains the domain of integer only and it can be only a positive number greater than 0. Example 1: Creating a table “student” with the “ROLL” field having a value greater than 0. Domain: Table: The above example will only accept the roll no. which is greater than 0. Example 2: Creating a table “Employee” with the “AGE” field having a value greater than 18. Domain: Table: The above example will only accept the Employee with an age greater than 18. Picked Class 12 DBMS School Learning School Programming DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Communication - Definition, Components, Types, Channels What is an IP Address? Sorting Algorithms in Python SQL HAVING Clause with Examples Cardinality in DBMS SQL | WITH clause SQL | Join (Inner, Left, Right and Full Joins) ACID Properties in DBMS SQL query to find second highest salary? Normal Forms in DBMS
[ { "code": null, "e": 24236, "s": 24208, "text": "\n01 Sep, 2021" }, { "code": null, "e": 24547, "s": 24236, "text": "In DBMS, constraints are the set of rules that ensures that when an authorized user modifies the database they do not disturb the data consistency and the constraints are specified within the DDL commands like “alter” and “create” command. There are several types of constraints available in DBMS and they are:" }, { "code": null, "e": 24566, "s": 24547, "text": "Domain constraints" }, { "code": null, "e": 24595, "s": 24566, "text": "Entity Integrity constraints" }, { "code": null, "e": 24629, "s": 24595, "text": "Referential Integrity constraints" }, { "code": null, "e": 24645, "s": 24629, "text": "Key constraints" }, { "code": null, "e": 24703, "s": 24645, "text": "In this article, we will only discuss domain constraints." }, { "code": null, "e": 25248, "s": 24703, "text": "Domain Constraints are user-defined columns that help the user to enter the value according to the data type. And if it encounters a wrong input it gives the message to the user that the column is not fulfilled properly. Or in other words, it is an attribute that specifies all the possible values that the attribute can hold like integer, character, date, time, string, etc. It defines the domain or the set of values for an attribute and ensures that the value taken by the attribute must be an atomic value(Can’t be divided) from its domain." }, { "code": null, "e": 25460, "s": 25248, "text": "Domain Constraint = data type(integer / character/date / time / string / etc.) + \n Constraints(NOT NULL / UNIQUE / PRIMARY KEY / \n FOREIGN KEY / CHECK / DEFAULT)" }, { "code": null, "e": 25488, "s": 25460, "text": "Type of domain constraints:" }, { "code": null, "e": 25571, "s": 25488, "text": "There are two types of constraints that come under domain constraint and they are:" }, { "code": null, "e": 26035, "s": 25571, "text": "1. Domain Constraints – Not Null: Null values are the values that are unassigned or we can also say that which are unknown or the missing attribute values and by default, a column can hold the null values. Now as we know that the Not Null constraint restricts a column to not accept the null values which means it only restricts a field to always contain a value which means you cannot insert a new record or update a record without adding a value into the field." }, { "code": null, "e": 26126, "s": 26035, "text": "Example: In the ’employee’ database, every employee must have a name associated with them." }, { "code": null, "e": 26226, "s": 26126, "text": "Create table employee\n(employee_id varchar(30),\nemployee_name varchar(30) not null,\nsalary NUMBER);" }, { "code": null, "e": 26584, "s": 26226, "text": "2. Domain Constraints – Check: It defines a condition that each row must satisfy which means it restricts the value of a column between ranges or we can say that it is just like a condition or filter checking before saving data into a column. It ensures that when a tuple is inserted inside the relation must satisfy the predicate given in the check clause." }, { "code": null, "e": 26689, "s": 26584, "text": "Example: We need to check whether the entered id number is greater than 0 or not for the employee table." }, { "code": null, "e": 26812, "s": 26689, "text": "Create table employee\n(employee_id varchar(30) not null check(employee_id > 0),\nemployee_name varchar(30),\nsalary NUMBER);" }, { "code": null, "e": 26967, "s": 26812, "text": "The above example creates CHECK constraints on the employee_id column and specifies that the column employee_id must only include integers greater than 0." }, { "code": null, "e": 27490, "s": 26967, "text": "Note: In DBMS a table is a combination of rows and columns in which we have some unique attribute names associated with it. And basically, a domain is a unique set of values present in a table. Let’s take an example, suppose we have a table student which consists of 3 attributes as NAME, ROLL NO, and MARKS. Now ROLL NO attributes can have only numbers associated with them and they won’t contain any alphabet. So we can say that it contains the domain of integer only and it can be only a positive number greater than 0." }, { "code": null, "e": 27501, "s": 27490, "text": "Example 1:" }, { "code": null, "e": 27581, "s": 27501, "text": "Creating a table “student” with the “ROLL” field having a value greater than 0." }, { "code": null, "e": 27589, "s": 27581, "text": "Domain:" }, { "code": null, "e": 27596, "s": 27589, "text": "Table:" }, { "code": null, "e": 27669, "s": 27596, "text": "The above example will only accept the roll no. which is greater than 0." }, { "code": null, "e": 27680, "s": 27669, "text": "Example 2:" }, { "code": null, "e": 27761, "s": 27680, "text": "Creating a table “Employee” with the “AGE” field having a value greater than 18." }, { "code": null, "e": 27769, "s": 27761, "text": "Domain:" }, { "code": null, "e": 27776, "s": 27769, "text": "Table:" }, { "code": null, "e": 27853, "s": 27776, "text": "The above example will only accept the Employee with an age greater than 18." }, { "code": null, "e": 27860, "s": 27853, "text": "Picked" }, { "code": null, "e": 27869, "s": 27860, "text": "Class 12" }, { "code": null, "e": 27874, "s": 27869, "text": "DBMS" }, { "code": null, "e": 27890, "s": 27874, "text": "School Learning" }, { "code": null, "e": 27909, "s": 27890, "text": "School Programming" }, { "code": null, "e": 27914, "s": 27909, "text": "DBMS" }, { "code": null, "e": 28012, "s": 27914, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28073, "s": 28012, "text": "Data Communication - Definition, Components, Types, Channels" }, { "code": null, "e": 28096, "s": 28073, "text": "What is an IP Address?" }, { "code": null, "e": 28125, "s": 28096, "text": "Sorting Algorithms in Python" }, { "code": null, "e": 28157, "s": 28125, "text": "SQL HAVING Clause with Examples" }, { "code": null, "e": 28177, "s": 28157, "text": "Cardinality in DBMS" }, { "code": null, "e": 28195, "s": 28177, "text": "SQL | WITH clause" }, { "code": null, "e": 28242, "s": 28195, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 28266, "s": 28242, "text": "ACID Properties in DBMS" }, { "code": null, "e": 28307, "s": 28266, "text": "SQL query to find second highest salary?" } ]
How to Load Excel Files with Hidden Rows and Columns into Pandas | by Zeya LT | Towards Data Science
I learned something new recently — that it is possible to exclude hidden rows and/or columns when reading Excel files as Pandas DataFrames, all thanks to the openpyxl package, and I’d like to share it with you. It is not uncommon to have rows or columns of an Excel file hidden. Less-relevant columns may be hidden to keep a spreadsheet neater; or rows may be hidden to deliberately ignore duplicate data. Whatever the reasons are, it may be of value to keep them hidden when loading a file as a Pandas DataFrame, as it may affect subsequent data wrangling and exploration. Unfortunately, the traditional way of reading Excel files as Pandas DataFrames — using the pandas.read_excel() method — does not facilitate that. In this post, we will explore how we can identify hidden rows and columns of an Excel file using the openpyxl package and hence exclude them when loading it as a Pandas DataFrame. We will be using a small subset of the titanic training dataset publicly available on Kaggle. For simplicity, I have limited the number of rows of data to 20. I have also deliberately hidden Columns F (“Age”), I (“Ticket”) and K (“Cabin”), as well as Rows 6, 11, 16 and 21. Typically, we use Pandas’ read_excel() method to load a dataset in Excel as a Pandas DataFrame. Let’s see what happens when we do that for our titanic dataset containing hidden rows and columns. >>> import pandas as pd>>> df = pd.read_excel("data/titanic.xlsx")>>> df By default, the read_excel() method reads in data from all rows and columns from the specified Excel file. In other words, it does not exclude the hidden rows and columns. To load as Pandas DataFrames without hidden rows and columns, we can use the openpyxl package, a Python library to “read/write Excel 2010 xlsx/xlsm/xltx/xltm files”. Since openpyxl is not a standard Python built-in library, you will first need to install it. Open a command line window and type the following command: >>> pip install openpyxl To open an existing Excel file using the openpyxl package, we use the openpyxl.load_workbook() method, specifying the name of the path where the Excel file is stored. >>> import openpyxl# Open an Excel workbook>>> workbook = openpyxl.load_workbook("data/titanic.xlsx") This creates a Workbook object which, according to the documentation, is the “top-level container for all document information”. This object contains many attributes pertaining to the input file, including the .sheetnames attribute which returns the list of the names of all worksheets in the workbook. # Create a list of names of all worksheets in `workbook`>>> sheet_names = workbook.sheetnames# Create a `Worksheet` object >>> worksheet = workbook[sheet_names[0]] In our titanic.xlsx file, we only have one worksheet named “train”, so we get the sheet name by taking the first element of the sheet_names list. Next, we create a Worksheet object from the Workbook object. Similarly, the Worksheet object contains attributes pertaining to the specified worksheet. To find indices of all hidden rows, we make use of the .row_dimensions attribute of the Worksheet object, like this: # List of indices corresponding to all hidden rows>>> hidden_rows_idx = [ row - 2 for row, dimension in worksheet.row_dimensions.items() if dimension.hidden ]>>> print(hidden_rows_idx)[4, 9, 14, 19] Notice that we need to take row — 2 instead of just row because we want to find indices corresponding to the Pandas DataFrame, not the Excel file. To find names of all hidden columns, we first use the .column_dimension attribute of the Worksheet object: # List of indices corresponding to all hidden columns>>> hidden_cols = [ col for col, dimension in worksheet.column_dimensions.items() if dimension.hidden ]>>> print(hidden_cols)['F', 'I', 'K'] This generates a list comprising uppercase alphabets that correspond to the hidden columns of an Excel worksheet. Thus, we need to somehow convert the hidden_cols list into a list of names of the hidden columns. To do so, we use Python’s built-in library, string, and its .ascii_uppercase attribute: # List of indices corresponding to all hidden columns>>> hidden_cols_idx = [ string.ascii_uppercase.index(col_name) for col_name in hidden_cols ]# Find names of columns corresponding to hidden column indices>>> hidden_cols_name = df.columns[hidden_cols_idx].tolist()>>> print(hidden_cols_name)['Age', 'Ticket', 'Cabin'] Disclaimer: Do note that using string.ascii_uppercase assumes that there are at most 26 columns. If there are more than 26 columns, the code will need to be modified. Finally, once we have the indices for the hidden rows and names for the hidden columns, the rest is simple. To exclude those hidden rows and columns, we simply use Pandas’ .drop()method. # Drop the hidden columns>>> df.drop(hidden_cols_name, axis=1, inplace=True)# Drop the hidden rows>>> df.drop(hidden_rows_idx, axis=0, inplace=True)# Reset the index >>> df.reset_index(drop=True, inplace=True)>>> df Here’s a code snippet that puts together the above codes with some simple refactoring: So, there you have it — a Python code that allows you to read an Excel file containing hidden rows and/or columns as is, as Pandas DataFrames. This particular use-case only scratches the surface of what the openpyxl package offers. For more information about the openpyxl package, check out its documentation here. The codes shown in this post can also be found as a notebook at this GitHub repo. Hello! I’m Zeya. Thanks for reading this post. If you’ve found it useful, do let me know in the comments. I welcome discussions, questions and constructive feedback too. Feel free to follow me on Medium or reach out to me via LinkedIn or Twitter. Have a great day!
[ { "code": null, "e": 383, "s": 172, "text": "I learned something new recently — that it is possible to exclude hidden rows and/or columns when reading Excel files as Pandas DataFrames, all thanks to the openpyxl package, and I’d like to share it with you." }, { "code": null, "e": 578, "s": 383, "text": "It is not uncommon to have rows or columns of an Excel file hidden. Less-relevant columns may be hidden to keep a spreadsheet neater; or rows may be hidden to deliberately ignore duplicate data." }, { "code": null, "e": 746, "s": 578, "text": "Whatever the reasons are, it may be of value to keep them hidden when loading a file as a Pandas DataFrame, as it may affect subsequent data wrangling and exploration." }, { "code": null, "e": 892, "s": 746, "text": "Unfortunately, the traditional way of reading Excel files as Pandas DataFrames — using the pandas.read_excel() method — does not facilitate that." }, { "code": null, "e": 1072, "s": 892, "text": "In this post, we will explore how we can identify hidden rows and columns of an Excel file using the openpyxl package and hence exclude them when loading it as a Pandas DataFrame." }, { "code": null, "e": 1346, "s": 1072, "text": "We will be using a small subset of the titanic training dataset publicly available on Kaggle. For simplicity, I have limited the number of rows of data to 20. I have also deliberately hidden Columns F (“Age”), I (“Ticket”) and K (“Cabin”), as well as Rows 6, 11, 16 and 21." }, { "code": null, "e": 1541, "s": 1346, "text": "Typically, we use Pandas’ read_excel() method to load a dataset in Excel as a Pandas DataFrame. Let’s see what happens when we do that for our titanic dataset containing hidden rows and columns." }, { "code": null, "e": 1614, "s": 1541, "text": ">>> import pandas as pd>>> df = pd.read_excel(\"data/titanic.xlsx\")>>> df" }, { "code": null, "e": 1786, "s": 1614, "text": "By default, the read_excel() method reads in data from all rows and columns from the specified Excel file. In other words, it does not exclude the hidden rows and columns." }, { "code": null, "e": 1952, "s": 1786, "text": "To load as Pandas DataFrames without hidden rows and columns, we can use the openpyxl package, a Python library to “read/write Excel 2010 xlsx/xlsm/xltx/xltm files”." }, { "code": null, "e": 2104, "s": 1952, "text": "Since openpyxl is not a standard Python built-in library, you will first need to install it. Open a command line window and type the following command:" }, { "code": null, "e": 2129, "s": 2104, "text": ">>> pip install openpyxl" }, { "code": null, "e": 2296, "s": 2129, "text": "To open an existing Excel file using the openpyxl package, we use the openpyxl.load_workbook() method, specifying the name of the path where the Excel file is stored." }, { "code": null, "e": 2398, "s": 2296, "text": ">>> import openpyxl# Open an Excel workbook>>> workbook = openpyxl.load_workbook(\"data/titanic.xlsx\")" }, { "code": null, "e": 2701, "s": 2398, "text": "This creates a Workbook object which, according to the documentation, is the “top-level container for all document information”. This object contains many attributes pertaining to the input file, including the .sheetnames attribute which returns the list of the names of all worksheets in the workbook." }, { "code": null, "e": 2865, "s": 2701, "text": "# Create a list of names of all worksheets in `workbook`>>> sheet_names = workbook.sheetnames# Create a `Worksheet` object >>> worksheet = workbook[sheet_names[0]]" }, { "code": null, "e": 3072, "s": 2865, "text": "In our titanic.xlsx file, we only have one worksheet named “train”, so we get the sheet name by taking the first element of the sheet_names list. Next, we create a Worksheet object from the Workbook object." }, { "code": null, "e": 3280, "s": 3072, "text": "Similarly, the Worksheet object contains attributes pertaining to the specified worksheet. To find indices of all hidden rows, we make use of the .row_dimensions attribute of the Worksheet object, like this:" }, { "code": null, "e": 3505, "s": 3280, "text": "# List of indices corresponding to all hidden rows>>> hidden_rows_idx = [ row - 2 for row, dimension in worksheet.row_dimensions.items() if dimension.hidden ]>>> print(hidden_rows_idx)[4, 9, 14, 19]" }, { "code": null, "e": 3652, "s": 3505, "text": "Notice that we need to take row — 2 instead of just row because we want to find indices corresponding to the Pandas DataFrame, not the Excel file." }, { "code": null, "e": 3759, "s": 3652, "text": "To find names of all hidden columns, we first use the .column_dimension attribute of the Worksheet object:" }, { "code": null, "e": 3979, "s": 3759, "text": "# List of indices corresponding to all hidden columns>>> hidden_cols = [ col for col, dimension in worksheet.column_dimensions.items() if dimension.hidden ]>>> print(hidden_cols)['F', 'I', 'K']" }, { "code": null, "e": 4279, "s": 3979, "text": "This generates a list comprising uppercase alphabets that correspond to the hidden columns of an Excel worksheet. Thus, we need to somehow convert the hidden_cols list into a list of names of the hidden columns. To do so, we use Python’s built-in library, string, and its .ascii_uppercase attribute:" }, { "code": null, "e": 4617, "s": 4279, "text": "# List of indices corresponding to all hidden columns>>> hidden_cols_idx = [ string.ascii_uppercase.index(col_name) for col_name in hidden_cols ]# Find names of columns corresponding to hidden column indices>>> hidden_cols_name = df.columns[hidden_cols_idx].tolist()>>> print(hidden_cols_name)['Age', 'Ticket', 'Cabin']" }, { "code": null, "e": 4784, "s": 4617, "text": "Disclaimer: Do note that using string.ascii_uppercase assumes that there are at most 26 columns. If there are more than 26 columns, the code will need to be modified." }, { "code": null, "e": 4971, "s": 4784, "text": "Finally, once we have the indices for the hidden rows and names for the hidden columns, the rest is simple. To exclude those hidden rows and columns, we simply use Pandas’ .drop()method." }, { "code": null, "e": 5187, "s": 4971, "text": "# Drop the hidden columns>>> df.drop(hidden_cols_name, axis=1, inplace=True)# Drop the hidden rows>>> df.drop(hidden_rows_idx, axis=0, inplace=True)# Reset the index >>> df.reset_index(drop=True, inplace=True)>>> df" }, { "code": null, "e": 5274, "s": 5187, "text": "Here’s a code snippet that puts together the above codes with some simple refactoring:" }, { "code": null, "e": 5417, "s": 5274, "text": "So, there you have it — a Python code that allows you to read an Excel file containing hidden rows and/or columns as is, as Pandas DataFrames." }, { "code": null, "e": 5589, "s": 5417, "text": "This particular use-case only scratches the surface of what the openpyxl package offers. For more information about the openpyxl package, check out its documentation here." }, { "code": null, "e": 5671, "s": 5589, "text": "The codes shown in this post can also be found as a notebook at this GitHub repo." } ]
Struts 2 - Sending Email
This chapter explains how you can send an email using your Struts 2 application. For this exercise, you need to download and install the mail.jar from JavaMail API 1.4.4 and place the mail.jar file in your WEB-INF\lib folder and then proceed to follow the standard steps of creating action, view and configuration files. The next step is to create an Action method that takes care of sending the email. Let us create a new class called Emailer.java with the following contents. package com.tutorialspoint.struts2; import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.opensymphony.xwork2.ActionSupport; public class Emailer extends ActionSupport { private String from; private String password; private String to; private String subject; private String body; static Properties properties = new Properties(); static { properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", "465"); } public String execute() { String ret = SUCCESS; try { Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } } ); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); Transport.send(message); } catch(Exception e) { ret = ERROR; e.printStackTrace(); } return ret; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public static Properties getProperties() { return properties; } public static void setProperties(Properties properties) { Emailer.properties = properties; } } As seen in the source code above, the Emailer.java has properties that correspond to the form attributes in the email.jsp page given below. These attributes are − From − The email address of the sender. As we are using Google's SMTP, we need a valid gtalk id From − The email address of the sender. As we are using Google's SMTP, we need a valid gtalk id Password − The password of the above account Password − The password of the above account To − Who to send the email to? To − Who to send the email to? Subject − subject of the email Subject − subject of the email Body − The actual email message Body − The actual email message We have not considered any validations on the above fields, validations will be added in the next chapter. Let us now look at the execute() method. The execute() method uses the javax Mail library to send an email using the supplied parameters. If the mail is sent successfully, action returns SUCCESS, otherwise it returns ERROR. Let us write main page JSP file index.jsp, which will be used to collect email related information mentioned above − <%@ page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Email Form</title> </head> <body> <em>The form below uses Google's SMTP server. So you need to enter a gmail username and password </em> <form action = "emailer" method = "post"> <label for = "from">From</label><br/> <input type = "text" name = "from"/><br/> <label for = "password">Password</label><br/> <input type = "password" name = "password"/><br/> <label for = "to">To</label><br/> <input type = "text" name = "to"/><br/> <label for = "subject">Subject</label><br/> <input type = "text" name = "subject"/><br/> <label for = "body">Body</label><br/> <input type = "text" name = "body"/><br/> <input type = "submit" value = "Send Email"/> </form> </body> </html> We will use JSP file success.jsp which will be invoked in case action returns SUCCESS, but we will have another view file in case of an ERROR is returned from the action. <%@ page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Email Success</title> </head> <body> Your email to <s:property value = "to"/> was sent successfully. </body> </html> Following will be the view file error.jsp in case of an ERROR is returned from the action. <%@ page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Email Error</title> </head> <body> There is a problem sending your email to <s:property value = "to"/>. </body> </html> Now let us put everything together using the struts.xml configuration file as follows − <?xml version = "1.0" Encoding = "UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name = "struts.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <action name = "emailer" class = "com.tutorialspoint.struts2.Emailer" method = "execute"> <result name = "success">/success.jsp</result> <result name = "error">/error.jsp</result> </action> </package> </struts> Following is the content of web.xml file − <?xml version = "1.0" Encoding = "UTF-8"?> <web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "WebApp_ID" version = "3.0"> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen − Enter the required information and click Send Email button. If everything goes fine, then you should see the following page. Print Add Notes Bookmark this page
[ { "code": null, "e": 2327, "s": 2246, "text": "This chapter explains how you can send an email using your Struts 2 application." }, { "code": null, "e": 2567, "s": 2327, "text": "For this exercise, you need to download and install the mail.jar from JavaMail API 1.4.4 and place the mail.jar file in your WEB-INF\\lib folder and then proceed to follow the standard steps of creating action, view and configuration files." }, { "code": null, "e": 2724, "s": 2567, "text": "The next step is to create an Action method that takes care of sending the email. Let us create a new class called Emailer.java with the following contents." }, { "code": null, "e": 5254, "s": 2724, "text": "package com.tutorialspoint.struts2;\n\nimport java.util.Properties;\nimport javax.mail.Message;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\nimport com.opensymphony.xwork2.ActionSupport;\n\npublic class Emailer extends ActionSupport {\n\n private String from;\n private String password;\n private String to;\n private String subject;\n private String body;\n\n static Properties properties = new Properties();\n static {\n properties.put(\"mail.smtp.host\", \"smtp.gmail.com\");\n properties.put(\"mail.smtp.socketFactory.port\", \"465\");\n properties.put(\"mail.smtp.socketFactory.class\",\n \"javax.net.ssl.SSLSocketFactory\");\n properties.put(\"mail.smtp.auth\", \"true\");\n properties.put(\"mail.smtp.port\", \"465\");\n }\n\n public String execute() {\n String ret = SUCCESS;\n try {\n Session session = Session.getDefaultInstance(properties, \n new javax.mail.Authenticator() {\n protected PasswordAuthentication \n getPasswordAuthentication() {\n return new \n PasswordAuthentication(from, password);\n }\n }\n );\n\n Message message = new MimeMessage(session);\n message.setFrom(new InternetAddress(from));\n message.setRecipients(Message.RecipientType.TO, \n InternetAddress.parse(to));\n message.setSubject(subject);\n message.setText(body);\n Transport.send(message);\n } catch(Exception e) {\n ret = ERROR;\n e.printStackTrace();\n }\n return ret;\n }\n\n public String getFrom() {\n return from;\n }\n\n public void setFrom(String from) {\n this.from = from;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getTo() {\n return to;\n }\n\n public void setTo(String to) {\n this.to = to;\n }\n\n public String getSubject() {\n return subject;\n }\n\n public void setSubject(String subject) {\n this.subject = subject;\n }\n\n public String getBody() {\n return body;\n }\n\n public void setBody(String body) {\n this.body = body;\n }\n\n public static Properties getProperties() {\n return properties;\n }\n\n public static void setProperties(Properties properties) {\n Emailer.properties = properties;\n }\n}" }, { "code": null, "e": 5417, "s": 5254, "text": "As seen in the source code above, the Emailer.java has properties that correspond to the form attributes in the email.jsp page given below. These attributes are −" }, { "code": null, "e": 5513, "s": 5417, "text": "From − The email address of the sender. As we are using Google's SMTP, we need a valid gtalk id" }, { "code": null, "e": 5609, "s": 5513, "text": "From − The email address of the sender. As we are using Google's SMTP, we need a valid gtalk id" }, { "code": null, "e": 5654, "s": 5609, "text": "Password − The password of the above account" }, { "code": null, "e": 5699, "s": 5654, "text": "Password − The password of the above account" }, { "code": null, "e": 5730, "s": 5699, "text": "To − Who to send the email to?" }, { "code": null, "e": 5761, "s": 5730, "text": "To − Who to send the email to?" }, { "code": null, "e": 5792, "s": 5761, "text": "Subject − subject of the email" }, { "code": null, "e": 5823, "s": 5792, "text": "Subject − subject of the email" }, { "code": null, "e": 5855, "s": 5823, "text": "Body − The actual email message" }, { "code": null, "e": 5887, "s": 5855, "text": "Body − The actual email message" }, { "code": null, "e": 6218, "s": 5887, "text": "We have not considered any validations on the above fields, validations will be added in the next chapter. Let us now look at the execute() method. The execute() method uses the javax Mail library to send an email using the supplied parameters. If the mail is sent successfully, action returns SUCCESS, otherwise it returns ERROR." }, { "code": null, "e": 6335, "s": 6218, "text": "Let us write main page JSP file index.jsp, which will be used to collect email related information mentioned above −" }, { "code": null, "e": 7446, "s": 6335, "text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>Email Form</title>\n </head>\n \n <body>\n <em>The form below uses Google's SMTP server. \n So you need to enter a gmail username and password\n </em>\n \n <form action = \"emailer\" method = \"post\">\n <label for = \"from\">From</label><br/>\n <input type = \"text\" name = \"from\"/><br/>\n <label for = \"password\">Password</label><br/>\n <input type = \"password\" name = \"password\"/><br/>\n <label for = \"to\">To</label><br/>\n <input type = \"text\" name = \"to\"/><br/>\n <label for = \"subject\">Subject</label><br/>\n <input type = \"text\" name = \"subject\"/><br/>\n <label for = \"body\">Body</label><br/>\n <input type = \"text\" name = \"body\"/><br/>\n <input type = \"submit\" value = \"Send Email\"/>\n </form>\n </body>\n</html>" }, { "code": null, "e": 7617, "s": 7446, "text": "We will use JSP file success.jsp which will be invoked in case action returns SUCCESS, but we will have another view file in case of an ERROR is returned from the action." }, { "code": null, "e": 8046, "s": 7617, "text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>Email Success</title>\n </head>\n \n <body>\n Your email to <s:property value = \"to\"/> was sent successfully.\n </body>\n</html>" }, { "code": null, "e": 8137, "s": 8046, "text": "Following will be the view file error.jsp in case of an ERROR is returned from the action." }, { "code": null, "e": 8569, "s": 8137, "text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n pageEncoding = \"ISO-8859-1\"%>\n<%@ taglib prefix = \"s\" uri = \"/struts-tags\"%>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \n \"http://www.w3.org/TR/html4/loose.dtd\">\n\n<html>\n <head>\n <title>Email Error</title>\n </head>\n \n <body>\n There is a problem sending your email to <s:property value = \"to\"/>.\n </body>\n</html>" }, { "code": null, "e": 8657, "s": 8569, "text": "Now let us put everything together using the struts.xml configuration file as follows −" }, { "code": null, "e": 9234, "s": 8657, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<!DOCTYPE struts PUBLIC\n \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n\n<struts>\n <constant name = \"struts.devMode\" value = \"true\" />\n <package name = \"helloworld\" extends = \"struts-default\">\n\n <action name = \"emailer\" \n class = \"com.tutorialspoint.struts2.Emailer\"\n method = \"execute\">\n <result name = \"success\">/success.jsp</result>\n <result name = \"error\">/error.jsp</result>\n </action>\n\n </package>\n</struts>" }, { "code": null, "e": 9277, "s": 9234, "text": "Following is the content of web.xml file −" }, { "code": null, "e": 10088, "s": 9277, "text": "<?xml version = \"1.0\" Encoding = \"UTF-8\"?>\n<web-app xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns = \"http://java.sun.com/xml/ns/javaee\" \n xmlns:web = \"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n id = \"WebApp_ID\" version = \"3.0\">\n \n <display-name>Struts 2</display-name>\n \n <welcome-file-list>\n <welcome-file>index.jsp</welcome-file>\n </welcome-file-list>\n\n <filter>\n <filter-name>struts2</filter-name>\n <filter-class>\n org.apache.struts2.dispatcher.FilterDispatcher\n </filter-class>\n </filter>\n\n <filter-mapping>\n <filter-name>struts2</filter-name>\n <url-pattern>/*</url-pattern>\n </filter-mapping>\n</web-app>" }, { "code": null, "e": 10374, "s": 10088, "text": "Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen −" }, { "code": null, "e": 10499, "s": 10374, "text": "Enter the required information and click Send Email button. If everything goes fine, then you should see the following page." }, { "code": null, "e": 10506, "s": 10499, "text": " Print" }, { "code": null, "e": 10517, "s": 10506, "text": " Add Notes" } ]
A Dog Detector and Breed Classifier | by Henry Dashwood | Towards Data Science
In a field like physics, things keep getting harder, to the point that it’s very difficult to understand what’s going on at the cutting edge unless it’s in highly simplified terms. In computer science though, and artificial intelligence in particular, knowledge built up slowly over 70+ years by people all over the world is still very intuitive. In fact, thanks to high level programming languages, frameworks, and a community that values sharing knowledge in easily accessible formats, it’s getting easier to enter the field! In this blog post we will do something that was impossible a decade ago but which students like myself can now pull off in a few lines of Python; build a system that can identify whether a person or dog is in a photo and tell us what breed it is (or most resembles!). You can find the code at my Github. There are several ways to solve image classification problems. In this blog post we will be using convolutional neural networks for determining the dog breed. Before that though we will using the Viola-Jones haar cascade classifier method to detect if the photo contains a human face. CNNs get the most attention nowadays but you will have definitely seen the Viola-Jones method before. It’s what draws boxes around faces whenever you open your camera. A great video explainer by the University of Nottingham’s Mike Pound can be watched here. Briefly, we work out which filters are best at discriminating between faces and non faces. The best filter is applied to each region of the image. If a region passes it gets tested on the next filter. This is repeated for about 6000 other filters and if a region passes them all we conclude that it contains a face. There is lots of other stuff in the paper. For instance, the authors developed a simple yet clever way to efficiently calculate the pixel value of a region in the image. All we need to do though is download these pretrained filters from a library called OpenCV and run our photo through them. import cv2def face_detector(img_path): img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) return len(faces) > 0 And just like that it counts up how many human faces are in the image! Unfortunately, the good people at OpenCV have not built us some nice haar filters for dogs. Instead we will use ImageNet, a dataset of 14 million images labelled into 20,000 categories. It’s been one of the leading computer vision benchmarks over the last decade. We will be using a smaller version of ImageNet with 1000 categories of which categories 151–268 are dog breeds. We can use a pretrained CNN called Resnet which we will download from Keras’s website (more on Keras in a bit). from keras.applications.resnet50 import ResNet50ResNet50_model_ = ResNet50(weights='imagenet') We need to do a little bit of preprocessing so that the model can make a prediction about our images: from keras.preprocessing import image from tqdm import tqdmdef path_to_tensor(img_path): img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) return np.expand_dims(x, axis=0)def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors) And now we can see if the prediction made by the model matches one of the dog breed categories: from keras.applications.resnet50 import preprocess_input, decode_predictionsdef ResNet50_predict_labels(img_path): img = preprocess_input(path_to_tensor(img_path)) return np.argmax(ResNet50_model_.predict(img))def dog_detector(img_path): prediction = ResNet50_predict_labels(img_path) return ((prediction <= 268) & (prediction >= 151)) At the end of all that, when I tested the detectors on 100 sample images, the face and dog detectors didn’t have any false negatives. The dog detector didn’t have any false positives either! So we can say that there is some sort of dog, or person, in the picture. But I could have done that. Could I tell the difference between 117 different breeds though, probably not. Let’s see if we can tell the difference with machine learning. It’s time to crack out the Keras library. Frameworks like Tensorflow, Pytorch, Theano, or CNTK perform machine learning operations for us. Keras is a library that sits on top of some of these and so we can write our code in a more concise and readable way. Here is how we define our CNN in Keras: model = Sequential()model.add(Conv2D(32, (3, 3), input_shape = (224, 224, 3), use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(MaxPooling2D(pool_size = (2,2)))model.add(Dropout(0.2))model.add(Conv2D(64, (2,2), use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(MaxPooling2D(pool_size = (2,2)))model.add(Dropout(0.2))model.add(Conv2D(128, (2,2), use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Dropout(0.2))model.add(Flatten())model.add(Dense(512, use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.2))model.add(Dense(256, use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.2))model.add(Dense(len(dog_names), activation='softmax'))model.summary() What’s going on here? We have 3 convolutional layers followed by 3 fully connected layers. This final layer has a softmax activation function which means our output will be the a probability distribution with 1000 values, one for each possible result in the ImageNet-1000 database we are using. We will define our optimizer and loss function next. There are a lot of terms in these lines so I’ll try to unpack them. SGD or stochastic gradient descent is is best likened to rolling down a mountain. If you find a way down, keep going. If not, try a different direction. Remember in multidimensional maths land there are many more than just 3 dimensions to choose from. You’ll know when you reach a local minimum in a certain direction because the gradient of the curve you are on will get smaller. This all handled for us under the hood. lr is our learning rate. How much should we change the model given a new piece of information? Small rates mean slow training but big rates mean we might jump over the best solution to the other side of the valley. The best solution is to use... decay means we start off with a big learning rate and decrease with each epoch as we near the bottom of the mountain/valley. clipnorm is used to clip gradients so that they don’t become absurdly large or shallow which would make it hard to do gradient descent. clipnorm clips the value if this happens but also scales the gradients so we aren’t clipping some and not others nesterov momentum is when we calculate the gradient having looked ahead a step. It helps us train a bit faster. categorical_crossentropy is the loss function. It means we are judging the performance of the model, and the extent to which we need to adjust it, on how much new information we receive after we check our results. If I am sure I’ve seen a golden retriever and I’m right, not much new information has been created. If I was unsure then some has been created. And if I was sure it wasn’t a golden retriever but it was, lots of information has been created. accuracy is the metric we will monitor. It does what it says on the tin. It calculates the mean accuracy rate across all predictions for multiclass classification problems. In other words what fraction of dogs were correctly classified. sgd = SGD(lr=0.01, clipnorm=1, decay=1e-6, momentum = 0.9, nesterov=True)model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) And then we are good to train! checkpointer = ModelCheckpoint( filepath='saved_models/weights.best.from_scratch.hdf5', verbose=1, save_best_only=True)model.fit(train_tensors, train_targets, validation_data=(valid_tensors, valid_targets), epochs=5, batch_size=20, callbacks=[checkpointer], verbose=1) If we run it for 6 epochs this is what happens: The training loss improves as we train but the validation loss looks like it is about to flatten out. This means our model would start to overfit if we trained it for much longer. On the test set the model correctly predicted the breeds of 3.7% of the dogs it saw. This is about 4 times better than random guessing but leaves quite a bit of room for improvement. Enter transfer learning. We can take a pretrained model, like we did with our detector and add our own layers to the end of it to make predictions for us. The model we will use is Resnet50 and has been trained by researchers at Microsoft on bigger machines and for more time than I have access to. We can download the weights, store them locally and then unpack the features like so: bottleneck_features = np.load( 'bottleneck_features/DogResnet50Data.npz' )train_Resnet50 = bottleneck_features['train']valid_Resnet50 = bottleneck_features['valid']test_Resnet50 = bottleneck_features['test'] It’s very easy with Keras to take Resnet50 and add our own layers to the end of it. Once again, we want our output to be a distribution each breed’s probability Resnet50_model = Sequential()Resnet50_model.add( GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]) )Resnet50_model.add(Dense(133, activation='softmax')) After that it’s just the same as before Resnet50_model.compile( loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'] )checkpointer = ModelCheckpoint( filepath='saved_models/weights.best.Resnet50.hdf5', verbose=1, save_best_only=True )resnet50_hist = Resnet50_model.fit( train_Resnet50, train_targets, validation_data=(valid_Resnet50, valid_targets), epochs=20, batch_size=56, callbacks=[checkpointer], verbose=1 ) How good is this model? Well, on the test set it correctly predicts 84% of the breeds! That’s way more than even my dog mad family and I would get. Combining our human and dog detectors with the breed predictor, let’s try this out on some photos. However if we peer into the model’s predictions we can see that Dalmation came second so not too bad. bottleneck_feature = extract_Resnet50(path_to_tensor('images/pongo.png'))predicted_vector = Resnet50_model.predict(bottleneck_feature)top_predictions = np.argpartition(predicted_vector.flatten(), -4)[-4:]for i in top_predictions: print(dog_names[i]) There is lots more we could do here. The best models in the world get better test accuracies than me on versions of ImageNet with many more possible categories. We could get some of that improvement by renting multiple GPUs, acquiring more labelled images etc but that basically boils down to spending money and isn’t conceptually very interesting. One way we could improve this model would be to use data augmentation. For instance, by flipping, shifting, rotating, darkening, lightening, adding noise and many more possible operations we can artificially increase the number of images the to which the model could be exposed by several times. I experimented with data augmentation during this project with disappointing results. It is possible that with some parameter tuning and longer training I would have seen some improvement. We could alter the CNN itself. It is possible that more layers with more features, different loss functions, learning rates and all sorts of other changes would have made it perform better. A big part of deep learning is making changes to a model and only learning afterwards if it actually improved things. If I had more GPU time, I might have tried using grid search to systematically experiment with different hyperparameters overnight. In this post we have: Loaded and preprocessed images from ImageNet. Loaded up some pretrained haar cascade classifiers in order to detect human faces using the Viola Jones method. Loaded a pretrained CNN to in order to detect dogs. Wrote and trained a CNN from scratch to classify dog breeds. This was successful 3.7% of the time on the test set which sounds low but was 4 times better than chance. Used transfer learning to radically improve the performance of the CNN so that it was accurate on the test set 84% of the time. Tested the model on a few of my own photos. Discussed ways to improve the model going forward. Maybe you learnt something in this post. I learnt a lot writing it. If you spot a mistake or think something could be better worded, let me know and I’ll update it!
[ { "code": null, "e": 700, "s": 172, "text": "In a field like physics, things keep getting harder, to the point that it’s very difficult to understand what’s going on at the cutting edge unless it’s in highly simplified terms. In computer science though, and artificial intelligence in particular, knowledge built up slowly over 70+ years by people all over the world is still very intuitive. In fact, thanks to high level programming languages, frameworks, and a community that values sharing knowledge in easily accessible formats, it’s getting easier to enter the field!" }, { "code": null, "e": 968, "s": 700, "text": "In this blog post we will do something that was impossible a decade ago but which students like myself can now pull off in a few lines of Python; build a system that can identify whether a person or dog is in a photo and tell us what breed it is (or most resembles!)." }, { "code": null, "e": 1004, "s": 968, "text": "You can find the code at my Github." }, { "code": null, "e": 1289, "s": 1004, "text": "There are several ways to solve image classification problems. In this blog post we will be using convolutional neural networks for determining the dog breed. Before that though we will using the Viola-Jones haar cascade classifier method to detect if the photo contains a human face." }, { "code": null, "e": 1863, "s": 1289, "text": "CNNs get the most attention nowadays but you will have definitely seen the Viola-Jones method before. It’s what draws boxes around faces whenever you open your camera. A great video explainer by the University of Nottingham’s Mike Pound can be watched here. Briefly, we work out which filters are best at discriminating between faces and non faces. The best filter is applied to each region of the image. If a region passes it gets tested on the next filter. This is repeated for about 6000 other filters and if a region passes them all we conclude that it contains a face." }, { "code": null, "e": 2156, "s": 1863, "text": "There is lots of other stuff in the paper. For instance, the authors developed a simple yet clever way to efficiently calculate the pixel value of a region in the image. All we need to do though is download these pretrained filters from a library called OpenCV and run our photo through them." }, { "code": null, "e": 2345, "s": 2156, "text": "import cv2def face_detector(img_path): img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) return len(faces) > 0" }, { "code": null, "e": 2416, "s": 2345, "text": "And just like that it counts up how many human faces are in the image!" }, { "code": null, "e": 2792, "s": 2416, "text": "Unfortunately, the good people at OpenCV have not built us some nice haar filters for dogs. Instead we will use ImageNet, a dataset of 14 million images labelled into 20,000 categories. It’s been one of the leading computer vision benchmarks over the last decade. We will be using a smaller version of ImageNet with 1000 categories of which categories 151–268 are dog breeds." }, { "code": null, "e": 2904, "s": 2792, "text": "We can use a pretrained CNN called Resnet which we will download from Keras’s website (more on Keras in a bit)." }, { "code": null, "e": 2999, "s": 2904, "text": "from keras.applications.resnet50 import ResNet50ResNet50_model_ = ResNet50(weights='imagenet')" }, { "code": null, "e": 3101, "s": 2999, "text": "We need to do a little bit of preprocessing so that the model can make a prediction about our images:" }, { "code": null, "e": 3475, "s": 3101, "text": "from keras.preprocessing import image from tqdm import tqdmdef path_to_tensor(img_path): img = image.load_img(img_path, target_size=(224, 224)) x = image.img_to_array(img) return np.expand_dims(x, axis=0)def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors)" }, { "code": null, "e": 3571, "s": 3475, "text": "And now we can see if the prediction made by the model matches one of the dog breed categories:" }, { "code": null, "e": 3919, "s": 3571, "text": "from keras.applications.resnet50 import preprocess_input, decode_predictionsdef ResNet50_predict_labels(img_path): img = preprocess_input(path_to_tensor(img_path)) return np.argmax(ResNet50_model_.predict(img))def dog_detector(img_path): prediction = ResNet50_predict_labels(img_path) return ((prediction <= 268) & (prediction >= 151))" }, { "code": null, "e": 4110, "s": 3919, "text": "At the end of all that, when I tested the detectors on 100 sample images, the face and dog detectors didn’t have any false negatives. The dog detector didn’t have any false positives either!" }, { "code": null, "e": 4353, "s": 4110, "text": "So we can say that there is some sort of dog, or person, in the picture. But I could have done that. Could I tell the difference between 117 different breeds though, probably not. Let’s see if we can tell the difference with machine learning." }, { "code": null, "e": 4610, "s": 4353, "text": "It’s time to crack out the Keras library. Frameworks like Tensorflow, Pytorch, Theano, or CNTK perform machine learning operations for us. Keras is a library that sits on top of some of these and so we can write our code in a more concise and readable way." }, { "code": null, "e": 4650, "s": 4610, "text": "Here is how we define our CNN in Keras:" }, { "code": null, "e": 5536, "s": 4650, "text": "model = Sequential()model.add(Conv2D(32, (3, 3), input_shape = (224, 224, 3), use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(MaxPooling2D(pool_size = (2,2)))model.add(Dropout(0.2))model.add(Conv2D(64, (2,2), use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(MaxPooling2D(pool_size = (2,2)))model.add(Dropout(0.2))model.add(Conv2D(128, (2,2), use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2,2)))model.add(Dropout(0.2))model.add(Flatten())model.add(Dense(512, use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.2))model.add(Dense(256, use_bias=False))model.add(BatchNormalization())model.add(Activation('relu'))model.add(Dropout(0.2))model.add(Dense(len(dog_names), activation='softmax'))model.summary()" }, { "code": null, "e": 5831, "s": 5536, "text": "What’s going on here? We have 3 convolutional layers followed by 3 fully connected layers. This final layer has a softmax activation function which means our output will be the a probability distribution with 1000 values, one for each possible result in the ImageNet-1000 database we are using." }, { "code": null, "e": 5952, "s": 5831, "text": "We will define our optimizer and loss function next. There are a lot of terms in these lines so I’ll try to unpack them." }, { "code": null, "e": 6373, "s": 5952, "text": "SGD or stochastic gradient descent is is best likened to rolling down a mountain. If you find a way down, keep going. If not, try a different direction. Remember in multidimensional maths land there are many more than just 3 dimensions to choose from. You’ll know when you reach a local minimum in a certain direction because the gradient of the curve you are on will get smaller. This all handled for us under the hood." }, { "code": null, "e": 6619, "s": 6373, "text": "lr is our learning rate. How much should we change the model given a new piece of information? Small rates mean slow training but big rates mean we might jump over the best solution to the other side of the valley. The best solution is to use..." }, { "code": null, "e": 6744, "s": 6619, "text": "decay means we start off with a big learning rate and decrease with each epoch as we near the bottom of the mountain/valley." }, { "code": null, "e": 6993, "s": 6744, "text": "clipnorm is used to clip gradients so that they don’t become absurdly large or shallow which would make it hard to do gradient descent. clipnorm clips the value if this happens but also scales the gradients so we aren’t clipping some and not others" }, { "code": null, "e": 7105, "s": 6993, "text": "nesterov momentum is when we calculate the gradient having looked ahead a step. It helps us train a bit faster." }, { "code": null, "e": 7560, "s": 7105, "text": "categorical_crossentropy is the loss function. It means we are judging the performance of the model, and the extent to which we need to adjust it, on how much new information we receive after we check our results. If I am sure I’ve seen a golden retriever and I’m right, not much new information has been created. If I was unsure then some has been created. And if I was sure it wasn’t a golden retriever but it was, lots of information has been created." }, { "code": null, "e": 7797, "s": 7560, "text": "accuracy is the metric we will monitor. It does what it says on the tin. It calculates the mean accuracy rate across all predictions for multiclass classification problems. In other words what fraction of dogs were correctly classified." }, { "code": null, "e": 7980, "s": 7797, "text": "sgd = SGD(lr=0.01, clipnorm=1, decay=1e-6, momentum = 0.9, nesterov=True)model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])" }, { "code": null, "e": 8011, "s": 7980, "text": "And then we are good to train!" }, { "code": null, "e": 8332, "s": 8011, "text": "checkpointer = ModelCheckpoint( filepath='saved_models/weights.best.from_scratch.hdf5', verbose=1, save_best_only=True)model.fit(train_tensors, train_targets, validation_data=(valid_tensors, valid_targets), epochs=5, batch_size=20, callbacks=[checkpointer], verbose=1)" }, { "code": null, "e": 8380, "s": 8332, "text": "If we run it for 6 epochs this is what happens:" }, { "code": null, "e": 8560, "s": 8380, "text": "The training loss improves as we train but the validation loss looks like it is about to flatten out. This means our model would start to overfit if we trained it for much longer." }, { "code": null, "e": 8743, "s": 8560, "text": "On the test set the model correctly predicted the breeds of 3.7% of the dogs it saw. This is about 4 times better than random guessing but leaves quite a bit of room for improvement." }, { "code": null, "e": 9041, "s": 8743, "text": "Enter transfer learning. We can take a pretrained model, like we did with our detector and add our own layers to the end of it to make predictions for us. The model we will use is Resnet50 and has been trained by researchers at Microsoft on bigger machines and for more time than I have access to." }, { "code": null, "e": 9127, "s": 9041, "text": "We can download the weights, store them locally and then unpack the features like so:" }, { "code": null, "e": 9387, "s": 9127, "text": "bottleneck_features = np.load( 'bottleneck_features/DogResnet50Data.npz' )train_Resnet50 = bottleneck_features['train']valid_Resnet50 = bottleneck_features['valid']test_Resnet50 = bottleneck_features['test']" }, { "code": null, "e": 9548, "s": 9387, "text": "It’s very easy with Keras to take Resnet50 and add our own layers to the end of it. Once again, we want our output to be a distribution each breed’s probability" }, { "code": null, "e": 9726, "s": 9548, "text": "Resnet50_model = Sequential()Resnet50_model.add( GlobalAveragePooling2D(input_shape=train_Resnet50.shape[1:]) )Resnet50_model.add(Dense(133, activation='softmax'))" }, { "code": null, "e": 9766, "s": 9726, "text": "After that it’s just the same as before" }, { "code": null, "e": 10471, "s": 9766, "text": "Resnet50_model.compile( loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'] )checkpointer = ModelCheckpoint( filepath='saved_models/weights.best.Resnet50.hdf5', verbose=1, save_best_only=True )resnet50_hist = Resnet50_model.fit( train_Resnet50, train_targets, validation_data=(valid_Resnet50, valid_targets), epochs=20, batch_size=56, callbacks=[checkpointer], verbose=1 )" }, { "code": null, "e": 10619, "s": 10471, "text": "How good is this model? Well, on the test set it correctly predicts 84% of the breeds! That’s way more than even my dog mad family and I would get." }, { "code": null, "e": 10718, "s": 10619, "text": "Combining our human and dog detectors with the breed predictor, let’s try this out on some photos." }, { "code": null, "e": 10820, "s": 10718, "text": "However if we peer into the model’s predictions we can see that Dalmation came second so not too bad." }, { "code": null, "e": 11073, "s": 10820, "text": "bottleneck_feature = extract_Resnet50(path_to_tensor('images/pongo.png'))predicted_vector = Resnet50_model.predict(bottleneck_feature)top_predictions = np.argpartition(predicted_vector.flatten(), -4)[-4:]for i in top_predictions: print(dog_names[i])" }, { "code": null, "e": 11422, "s": 11073, "text": "There is lots more we could do here. The best models in the world get better test accuracies than me on versions of ImageNet with many more possible categories. We could get some of that improvement by renting multiple GPUs, acquiring more labelled images etc but that basically boils down to spending money and isn’t conceptually very interesting." }, { "code": null, "e": 11907, "s": 11422, "text": "One way we could improve this model would be to use data augmentation. For instance, by flipping, shifting, rotating, darkening, lightening, adding noise and many more possible operations we can artificially increase the number of images the to which the model could be exposed by several times. I experimented with data augmentation during this project with disappointing results. It is possible that with some parameter tuning and longer training I would have seen some improvement." }, { "code": null, "e": 12347, "s": 11907, "text": "We could alter the CNN itself. It is possible that more layers with more features, different loss functions, learning rates and all sorts of other changes would have made it perform better. A big part of deep learning is making changes to a model and only learning afterwards if it actually improved things. If I had more GPU time, I might have tried using grid search to systematically experiment with different hyperparameters overnight." }, { "code": null, "e": 12369, "s": 12347, "text": "In this post we have:" }, { "code": null, "e": 12415, "s": 12369, "text": "Loaded and preprocessed images from ImageNet." }, { "code": null, "e": 12527, "s": 12415, "text": "Loaded up some pretrained haar cascade classifiers in order to detect human faces using the Viola Jones method." }, { "code": null, "e": 12579, "s": 12527, "text": "Loaded a pretrained CNN to in order to detect dogs." }, { "code": null, "e": 12746, "s": 12579, "text": "Wrote and trained a CNN from scratch to classify dog breeds. This was successful 3.7% of the time on the test set which sounds low but was 4 times better than chance." }, { "code": null, "e": 12874, "s": 12746, "text": "Used transfer learning to radically improve the performance of the CNN so that it was accurate on the test set 84% of the time." }, { "code": null, "e": 12918, "s": 12874, "text": "Tested the model on a few of my own photos." }, { "code": null, "e": 12969, "s": 12918, "text": "Discussed ways to improve the model going forward." } ]
Machine Learning Basics: Support Vector Regression | by Gurucharan M K | Towards Data Science
In the previous stories, I explained the Machine Learning program for building Linear and Polynomial Regression model in Python. In this article, we will go through the program for building a Support Vector Regression model based on non-linear data. Support Vector Machine (SVM) is a very popular Machine Learning algorithm that is used in both Regression and Classification. Support Vector Regression is similar to Linear Regression in that the equation of the line is y= wx+b In SVR, this straight line is referred to as hyperplane. The data points on either side of the hyperplane that are closest to the hyperplane are called Support Vectors which is used to plot the boundary line. Unlike other Regression models that try to minimize the error between the real and predicted value, the SVR tries to fit the best line within a threshold value (Distance between hyperplane and boundary line), a. Thus, we can say that SVR model tries satisfy the condition -a < y-wx+b < a. It used the points with this boundary to predict the value. For a non-linear regression, the kernel function transforms the data to a higher dimensional and performs the linear separation. Here we will use the rbf kernel. In this example, we will go through the implementation of Support Vector Regression (SVM), in which we will predict the Marks of a student based on his or her number of hours put into study. In this data, we have one independent variable Hours of Study and one dependent variable Marks. In this problem, we have to train a SVR model with this data to understand the correlation between the Hours of Study and Marks of the student and be able to predict the student’s mark based on their number of hours dedicated to studies. In this first step, we will be importing the libraries required to build the ML model. The NumPy library and the matplotlib are imported. Additionally, we have imported the Pandas library for data analysis. import numpy as npimport matplotlib.pyplot as pltimport pandas as pd In this step, we shall use pandas to store the data obtained from my github repository and store it as a Pandas DataFrame using the function “pd.read_csv”. We go through our dataset and assign the independent variable (x) to the column “Hours of Study” and the dependent variable (y) to the last column, which is the “Marks” to be predicted. dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/SampleData.csv')X = dataset.iloc[:, 0].valuesy = dataset.iloc[:, 1].valuesy = np.array(y).reshape(-1,1)dataset.head(5)>>Hours of Study Marks32.502345 31.70700653.426804 68.77759661.530358 62.56238247.475640 71.54663259.813208 87.230925 We use the corresponding .iloc function to slice the DataFrame to assign these indexes to X and Y. In this, the Hours of Study is taken as the independent variable and is assigned to X. The dependent variable that is to be predicted is the last column which is Marks and it is assigned to y. We will reshape the variable y to a column vector using reshape(-1,1). Most of the data that are available usually are of varying ranges and magnitudes which makes building the model difficult. Thus, the range of the data needs to be normalized to a smaller range which enables the model to be more accurate when training. In this dataset, the data is normalized between to small values near zero. For example, the score of 87.23092513 is normalized to 1.00475931 and score of 53.45439421 is normalized to -1.22856288. from sklearn.preprocessing import StandardScalersc_X = StandardScaler()sc_y = StandardScaler()X = sc_X.fit_transform(X.reshape(-1,1))y = sc_y.fit_transform(y.reshape(-1,1)) Feature Scaling is mostly performed internally in most of the common Regression and Classification models. Support Vector Machine is not a commonly used class and hence the data is normalized to a limited range. In building any ML model, we always need to split the data into the training set and the test set. The SVR Model will be trained with the values of the training set and the predictions are tested on the test set. Out of 100 rows, 80 rows are used for training and the model is tested on the remaining 20 rows as given by the condition, test_size=0.2 from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2) In this, the function SVM is imported and is assigned to the variable regressor. The kernel “rbf” (Radial Basis Function) is used. RBF kernel is used to introduce a non-linearity to the SVR model. This is done because our data is non-linear. The regressor.fit is used to fit the variables X_train and y_train by reshaping the data accordingly. from sklearn.svm import SVRregressor = SVR(kernel = 'rbf')regressor.fit(X_train.reshape(-1,1), y_train.reshape(-1,1)) In this step, we are going to predict the scores of the test set using the SVR model built. Theregressor.predict function is used to predict the values for the X_test. We assign the predicted values to y_pred. We now have two data, y_test (real values) and y_pred (predicted values). y_pred = regressor.predict(X_test)y_pred = sc_y.inverse_transform(y_pred) In this step, we shall display the values of y_test as Real Values and y_pred values as Predicted Values for each X_test against each other in a Pandas DataFrame. df = pd.DataFrame({'Real Values':sc_y.inverse_transform(y_test.reshape(-1)), 'Predicted Values':y_pred})df>>Real Values Predicted Values31.707006 53.82438676.617341 61.43021065.101712 63.92184985.498068 80.77305681.536991 72.68690679.102830 60.35781095.244153 89.52315752.725494 54.61608795.455053 82.00337080.207523 81.57528779.052406 67.22512183.432071 73.54188585.668203 78.03398371.300880 76.53606152.682983 63.99328445.570589 53.91218463.358790 76.07784057.812513 62.17874882.892504 64.17200383.878565 93.823265 We can see that there is a significant deviation of the predicted values with the real values of the test set and hence we can conclude that this model is not the perfect fit for the following data. In this last step, we shall visualize the SVR model that was built using the given data and plot the values of “y” and “y_pred” on the graph to visualize the results X_grid = np.arange(min(X), max(X), 0.1)X_grid = X_grid.reshape((len(X_grid), 1))plt.scatter(sc_X.inverse_transform(X_test), sc_y.inverse_transform(y_test.reshape(-1)), color = 'red')plt.scatter(sc_X.inverse_transform(X_test), y_pred, color = 'green')plt.title('SVR Regression')plt.xlabel('Position level')plt.ylabel('Salary')plt.show() In this graph, the Real values are plotted in “Red” color and the Predicted values are plotted in “Green” color. The plot of the SVR model is also shown in “Black” color. I am attaching a link of my github repository where you can find the Google Colab notebook and the data files for your reference. github.com Hope I have been able to clearly explain the program for building a Support Vector Regression model with a non-linear dataset. You can also find the explanation of the program for other Regression models below: Simple Linear Regression Multiple Linear Regression Polynomial Regression Support Vector Regression Decision Tree Regression Random Forest Regression We will come across the more complex models of Regression, Classification and Clustering in the upcoming articles. Till then, Happy Machine Learning!
[ { "code": null, "e": 297, "s": 47, "text": "In the previous stories, I explained the Machine Learning program for building Linear and Polynomial Regression model in Python. In this article, we will go through the program for building a Support Vector Regression model based on non-linear data." }, { "code": null, "e": 734, "s": 297, "text": "Support Vector Machine (SVM) is a very popular Machine Learning algorithm that is used in both Regression and Classification. Support Vector Regression is similar to Linear Regression in that the equation of the line is y= wx+b In SVR, this straight line is referred to as hyperplane. The data points on either side of the hyperplane that are closest to the hyperplane are called Support Vectors which is used to plot the boundary line." }, { "code": null, "e": 1083, "s": 734, "text": "Unlike other Regression models that try to minimize the error between the real and predicted value, the SVR tries to fit the best line within a threshold value (Distance between hyperplane and boundary line), a. Thus, we can say that SVR model tries satisfy the condition -a < y-wx+b < a. It used the points with this boundary to predict the value." }, { "code": null, "e": 1245, "s": 1083, "text": "For a non-linear regression, the kernel function transforms the data to a higher dimensional and performs the linear separation. Here we will use the rbf kernel." }, { "code": null, "e": 1436, "s": 1245, "text": "In this example, we will go through the implementation of Support Vector Regression (SVM), in which we will predict the Marks of a student based on his or her number of hours put into study." }, { "code": null, "e": 1770, "s": 1436, "text": "In this data, we have one independent variable Hours of Study and one dependent variable Marks. In this problem, we have to train a SVR model with this data to understand the correlation between the Hours of Study and Marks of the student and be able to predict the student’s mark based on their number of hours dedicated to studies." }, { "code": null, "e": 1977, "s": 1770, "text": "In this first step, we will be importing the libraries required to build the ML model. The NumPy library and the matplotlib are imported. Additionally, we have imported the Pandas library for data analysis." }, { "code": null, "e": 2046, "s": 1977, "text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd" }, { "code": null, "e": 2202, "s": 2046, "text": "In this step, we shall use pandas to store the data obtained from my github repository and store it as a Pandas DataFrame using the function “pd.read_csv”." }, { "code": null, "e": 2388, "s": 2202, "text": "We go through our dataset and assign the independent variable (x) to the column “Hours of Study” and the dependent variable (y) to the last column, which is the “Marks” to be predicted." }, { "code": null, "e": 2750, "s": 2388, "text": "dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/SampleData.csv')X = dataset.iloc[:, 0].valuesy = dataset.iloc[:, 1].valuesy = np.array(y).reshape(-1,1)dataset.head(5)>>Hours of Study Marks32.502345 31.70700653.426804 68.77759661.530358 62.56238247.475640 71.54663259.813208 87.230925" }, { "code": null, "e": 3113, "s": 2750, "text": "We use the corresponding .iloc function to slice the DataFrame to assign these indexes to X and Y. In this, the Hours of Study is taken as the independent variable and is assigned to X. The dependent variable that is to be predicted is the last column which is Marks and it is assigned to y. We will reshape the variable y to a column vector using reshape(-1,1)." }, { "code": null, "e": 3561, "s": 3113, "text": "Most of the data that are available usually are of varying ranges and magnitudes which makes building the model difficult. Thus, the range of the data needs to be normalized to a smaller range which enables the model to be more accurate when training. In this dataset, the data is normalized between to small values near zero. For example, the score of 87.23092513 is normalized to 1.00475931 and score of 53.45439421 is normalized to -1.22856288." }, { "code": null, "e": 3734, "s": 3561, "text": "from sklearn.preprocessing import StandardScalersc_X = StandardScaler()sc_y = StandardScaler()X = sc_X.fit_transform(X.reshape(-1,1))y = sc_y.fit_transform(y.reshape(-1,1))" }, { "code": null, "e": 3946, "s": 3734, "text": "Feature Scaling is mostly performed internally in most of the common Regression and Classification models. Support Vector Machine is not a commonly used class and hence the data is normalized to a limited range." }, { "code": null, "e": 4296, "s": 3946, "text": "In building any ML model, we always need to split the data into the training set and the test set. The SVR Model will be trained with the values of the training set and the predictions are tested on the test set. Out of 100 rows, 80 rows are used for training and the model is tested on the remaining 20 rows as given by the condition, test_size=0.2" }, { "code": null, "e": 4423, "s": 4296, "text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)" }, { "code": null, "e": 4767, "s": 4423, "text": "In this, the function SVM is imported and is assigned to the variable regressor. The kernel “rbf” (Radial Basis Function) is used. RBF kernel is used to introduce a non-linearity to the SVR model. This is done because our data is non-linear. The regressor.fit is used to fit the variables X_train and y_train by reshaping the data accordingly." }, { "code": null, "e": 4885, "s": 4767, "text": "from sklearn.svm import SVRregressor = SVR(kernel = 'rbf')regressor.fit(X_train.reshape(-1,1), y_train.reshape(-1,1))" }, { "code": null, "e": 5169, "s": 4885, "text": "In this step, we are going to predict the scores of the test set using the SVR model built. Theregressor.predict function is used to predict the values for the X_test. We assign the predicted values to y_pred. We now have two data, y_test (real values) and y_pred (predicted values)." }, { "code": null, "e": 5243, "s": 5169, "text": "y_pred = regressor.predict(X_test)y_pred = sc_y.inverse_transform(y_pred)" }, { "code": null, "e": 5406, "s": 5243, "text": "In this step, we shall display the values of y_test as Real Values and y_pred values as Predicted Values for each X_test against each other in a Pandas DataFrame." }, { "code": null, "e": 6005, "s": 5406, "text": "df = pd.DataFrame({'Real Values':sc_y.inverse_transform(y_test.reshape(-1)), 'Predicted Values':y_pred})df>>Real Values Predicted Values31.707006 53.82438676.617341 61.43021065.101712 63.92184985.498068 80.77305681.536991 72.68690679.102830 60.35781095.244153 89.52315752.725494 54.61608795.455053 82.00337080.207523 81.57528779.052406 67.22512183.432071 73.54188585.668203 78.03398371.300880 76.53606152.682983 63.99328445.570589 53.91218463.358790 76.07784057.812513 62.17874882.892504 64.17200383.878565 93.823265" }, { "code": null, "e": 6204, "s": 6005, "text": "We can see that there is a significant deviation of the predicted values with the real values of the test set and hence we can conclude that this model is not the perfect fit for the following data." }, { "code": null, "e": 6370, "s": 6204, "text": "In this last step, we shall visualize the SVR model that was built using the given data and plot the values of “y” and “y_pred” on the graph to visualize the results" }, { "code": null, "e": 6706, "s": 6370, "text": "X_grid = np.arange(min(X), max(X), 0.1)X_grid = X_grid.reshape((len(X_grid), 1))plt.scatter(sc_X.inverse_transform(X_test), sc_y.inverse_transform(y_test.reshape(-1)), color = 'red')plt.scatter(sc_X.inverse_transform(X_test), y_pred, color = 'green')plt.title('SVR Regression')plt.xlabel('Position level')plt.ylabel('Salary')plt.show()" }, { "code": null, "e": 6877, "s": 6706, "text": "In this graph, the Real values are plotted in “Red” color and the Predicted values are plotted in “Green” color. The plot of the SVR model is also shown in “Black” color." }, { "code": null, "e": 7007, "s": 6877, "text": "I am attaching a link of my github repository where you can find the Google Colab notebook and the data files for your reference." }, { "code": null, "e": 7018, "s": 7007, "text": "github.com" }, { "code": null, "e": 7145, "s": 7018, "text": "Hope I have been able to clearly explain the program for building a Support Vector Regression model with a non-linear dataset." }, { "code": null, "e": 7229, "s": 7145, "text": "You can also find the explanation of the program for other Regression models below:" }, { "code": null, "e": 7254, "s": 7229, "text": "Simple Linear Regression" }, { "code": null, "e": 7281, "s": 7254, "text": "Multiple Linear Regression" }, { "code": null, "e": 7303, "s": 7281, "text": "Polynomial Regression" }, { "code": null, "e": 7329, "s": 7303, "text": "Support Vector Regression" }, { "code": null, "e": 7354, "s": 7329, "text": "Decision Tree Regression" }, { "code": null, "e": 7379, "s": 7354, "text": "Random Forest Regression" } ]
Spring Boot - Zuul Proxy Server and Routing
Zuul Server is a gateway application that handles all the requests and does the dynamic routing of microservice applications. The Zuul Server is also known as Edge Server. For Example, /api/user is mapped to the user service and /api/products is mapped to the product service and Zuul Server dynamically routes the requests to the respective backend application. In this chapter, we are going to see in detail how to create Zuul Server application in Spring Boot. The Zuul Server is bundled with Spring Cloud dependency. You can download the Spring Boot project from Spring Initializer page https://start.spring.io/ and choose the Zuul Server dependency. Add the @EnableZuulProxy annotation on your main Spring Boot application. The @EnableZuulProxy annotation is used to make your Spring Boot application act as a Zuul Proxy server. package com.tutorialspoint.zuulserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy public class ZuulserverApplication { public static void main(String[] args) { SpringApplication.run(ZuulserverApplication.class, args); } } You will have to add the Spring Cloud Starter Zuul dependency in our build configuration file. Maven users will have to add the following dependency in your pom.xml file − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> For Gradle users, add the below dependency in your build.gradle file compile('org.springframework.cloud:spring-cloud-starter-zuul') For Zuul routing, add the below properties in your application.properties file or application.yml file. spring.application.name = zuulserver zuul.routes.products.path = /api/demo/** zuul.routes.products.url = http://localhost:8080/ server.port = 8111 This means that http calls to /api/demo/ get forwarded to the products service. For example, /api/demo/products is forwarded to /products. yaml file users can use the application.yml file shown below − server: port: 8111 spring: application: name: zuulserver zuul: routes: products: path: /api/demo/** url: http://localhost:8080/ Note − The http://localhost:8080/ application should already be running before routing via Zuul Proxy. The complete build configuration file is given below. Maven users can use the pom.xml file given below − <?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>zuulserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>zuulserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle users can use the build.gradle file given below − buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = 'Edgware.RELEASE' } dependencies { compile('org.springframework.cloud:spring-cloud-starter-zuul') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command given below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command shown below − java –jar <JARFILE> You can find the application has started on the Tomcat port 8111 as shown here. Now, hit the URL http://localhost:8111/api/demo/products in your web browser and you can see the output of /products REST Endpoint as shown below −
[ { "code": null, "e": 3331, "s": 3159, "text": "Zuul Server is a gateway application that handles all the requests and does the dynamic routing of microservice applications. The Zuul Server is also known as Edge Server." }, { "code": null, "e": 3522, "s": 3331, "text": "For Example, /api/user is mapped to the user service and /api/products is mapped to the product service and Zuul Server dynamically routes the requests to the respective backend application." }, { "code": null, "e": 3623, "s": 3522, "text": "In this chapter, we are going to see in detail how to create Zuul Server application in Spring Boot." }, { "code": null, "e": 3814, "s": 3623, "text": "The Zuul Server is bundled with Spring Cloud dependency. You can download the Spring Boot project from Spring Initializer page https://start.spring.io/ and choose the Zuul Server dependency." }, { "code": null, "e": 3993, "s": 3814, "text": "Add the @EnableZuulProxy annotation on your main Spring Boot application. The @EnableZuulProxy annotation is used to make your Spring Boot application act as a Zuul Proxy server." }, { "code": null, "e": 4409, "s": 3993, "text": "package com.tutorialspoint.zuulserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.netflix.zuul.EnableZuulProxy;\n\n@SpringBootApplication\n@EnableZuulProxy\npublic class ZuulserverApplication {\n public static void main(String[] args) {\n SpringApplication.run(ZuulserverApplication.class, args);\n }\n}" }, { "code": null, "e": 4504, "s": 4409, "text": "You will have to add the Spring Cloud Starter Zuul dependency in our build configuration file." }, { "code": null, "e": 4581, "s": 4504, "text": "Maven users will have to add the following dependency in your pom.xml file −" }, { "code": null, "e": 4710, "s": 4581, "text": "<dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-zuul</artifactId>\n</dependency>" }, { "code": null, "e": 4779, "s": 4710, "text": "For Gradle users, add the below dependency in your build.gradle file" }, { "code": null, "e": 4843, "s": 4779, "text": "compile('org.springframework.cloud:spring-cloud-starter-zuul')\n" }, { "code": null, "e": 4947, "s": 4843, "text": "For Zuul routing, add the below properties in your application.properties file or application.yml file." }, { "code": null, "e": 5094, "s": 4947, "text": "spring.application.name = zuulserver\nzuul.routes.products.path = /api/demo/**\nzuul.routes.products.url = http://localhost:8080/\nserver.port = 8111" }, { "code": null, "e": 5233, "s": 5094, "text": "This means that http calls to /api/demo/ get forwarded to the products service. For example, /api/demo/products is forwarded to /products." }, { "code": null, "e": 5296, "s": 5233, "text": "yaml file users can use the application.yml file shown below −" }, { "code": null, "e": 5454, "s": 5296, "text": "server:\n port: 8111\nspring:\n application: \n name: zuulserver\nzuul:\n\nroutes:\n products:\n path: /api/demo/**\n url: http://localhost:8080/" }, { "code": null, "e": 5557, "s": 5454, "text": "Note − The http://localhost:8080/ application should already be running before routing via Zuul Proxy." }, { "code": null, "e": 5611, "s": 5557, "text": "The complete build configuration file is given below." }, { "code": null, "e": 5662, "s": 5611, "text": "Maven users can use the pom.xml file given below −" }, { "code": null, "e": 7706, "s": 5662, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>zuulserver</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>zuulserver</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.9.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n <spring-cloud.version>Edgware.RELEASE</spring-cloud.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-zuul</artifactId>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <dependencyManagement>\n <dependencies>\n <dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-dependencies</artifactId>\n <version>${spring-cloud.version}</version>\n <type>pom</type>\n <scope>import</scope>\n </dependency>\n </dependencies>\n </dependencyManagement>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>" }, { "code": null, "e": 7763, "s": 7706, "text": "Gradle users can use the build.gradle file given below −" }, { "code": null, "e": 8534, "s": 7763, "text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\n\nrepositories {\n mavenCentral()\n}\next {\n springCloudVersion = 'Edgware.RELEASE'\n}\ndependencies {\n compile('org.springframework.cloud:spring-cloud-starter-zuul')\n testCompile('org.springframework.boot:spring-boot-starter-test')\n}\ndependencyManagement {\n imports {\n mavenBom \"org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}\"\n }\n}" }, { "code": null, "e": 8661, "s": 8534, "text": "You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below −" }, { "code": null, "e": 8710, "s": 8661, "text": "For Maven, you can use the command given below −" }, { "code": null, "e": 8729, "s": 8710, "text": "mvn clean install\n" }, { "code": null, "e": 8806, "s": 8729, "text": "After “BUILD SUCCESS”, you can find the JAR file under the target directory." }, { "code": null, "e": 8856, "s": 8806, "text": "For Gradle, you can use the command given below −" }, { "code": null, "e": 8876, "s": 8856, "text": "gradle clean build\n" }, { "code": null, "e": 8960, "s": 8876, "text": "After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory." }, { "code": null, "e": 9017, "s": 8960, "text": "Now, run the JAR file by using the command shown below −" }, { "code": null, "e": 9039, "s": 9017, "text": "java –jar <JARFILE> \n" }, { "code": null, "e": 9119, "s": 9039, "text": "You can find the application has started on the Tomcat port 8111 as shown here." } ]
Differences between == and equals() method in Java
In java both == and equals() method is used to check the equality of two variables or objects. Following are the important differences between == and equals() method. public class JavaTester { public static void main(String args[]) { String s1 = new String("TUTORIALSPOINT"); String s2 = new String("TUTORIALSPOINT"); //Reference comparison System.out.println(s1 == s2); //Content comparison System.out.println(s1.equals(s2)); // integer-type System.out.println(10 == 10); // char-type System.out.println('a' == 'a'); } } false true true true
[ { "code": null, "e": 1282, "s": 1187, "text": "In java both == and equals() method is used to check the equality of two variables or objects." }, { "code": null, "e": 1354, "s": 1282, "text": "Following are the important differences between == and equals() method." }, { "code": null, "e": 1775, "s": 1354, "text": "public class JavaTester {\n public static void main(String args[]) {\n String s1 = new String(\"TUTORIALSPOINT\");\n String s2 = new String(\"TUTORIALSPOINT\");\n //Reference comparison\n System.out.println(s1 == s2);\n //Content comparison\n System.out.println(s1.equals(s2));\n // integer-type\n System.out.println(10 == 10);\n // char-type\n System.out.println('a' == 'a');\n }\n}" }, { "code": null, "e": 1796, "s": 1775, "text": "false\ntrue\ntrue\ntrue" } ]
How to apply background image with linear gradient using Tailwind CSS ?
25 May, 2021 In this article, we will see how to apply background images with a linear gradient using Tailwind CSS. Tailwind CSS is a highly customizable, utility-first CSS framework from which we can use utility classes to build any design. To apply background images with linear gradients we use the background image utility of Tailwind CSS. It is the alternative to the CSS background-image property. To work with Tailwind CSS, we have to add Tailwind CSS pre-compiled file to our project folder. Installation: Method 1: Install Tailwind via npm Step 1:npm init -y Step 2:npm install tailwindcss Step 3: Now we have to add Tailwind to our CSS by using the @tailwind directive to inject Tailwind’s base, components, and utility styles into our CSS file. @tailwind base; @tailwind components; @tailwind utilities; Step 4: npx tailwindcss init (It is an optional step that is used to create a Tailwind config file.) Step 5: npx tailwindcss build styles.css -o output.css Method 2: Using Tailwind CSS file via CDN <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"> Example: In this example, we have used the bg-gradient-to-br class to set the linear gradient to the bottom right. HTML <!DOCTYPE html><html><head> <link href= "https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"></head><body> <div class="font-bold m-3"> <h1 class="text-3xl text-green-800 my-4" > GeeksforGeeks </h1> <p class=" text-xl text-black-700 my-3"> Tailwind CSS Background Image Class </p> </div> <div class=" m-4 w-96 h-52 bg-gradient-to-br from-blue-400 via-green-500 to-red-500"> </div></body></html> Output: Example: In this example, we have used all background image classes i.e. bg-gradient-to-{direction}. HTML <!DOCTYPE html><html><head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"></head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Background Image Class</b> <div class="m-4 grid grid-cols-3 gap-2"> <div class="h-12 w-34 bg-gradient-to-r rounded-lg from-blue-400 via-green-500 to-red-500"> </div> <div class="h-12 w-34 bg-gradient-to-tr rounded-lg from-blue-400 via-green-500 to-red-500"> </div> <div class="h-12 w-34 bg-gradient-to-br rounded-lg from-blue-400 via-green-500 to-red-500"> </div> <div class="h-12 w-34 bg-gradient-to-b rounded-lg from-blue-400 via-green-500 to-red-500"> </div> <div class="h-12 w-34 bg-gradient-to-bl rounded-lg from-blue-400 via-green-500 to-red-500"> </div> <div class="h-12 w-34 bg-gradient-to-tl rounded-lg from-blue-400 via-green-500 to-red-500"> </div> <div class="h-12 w-34 bg-gradient-to-l rounded-lg from-blue-400 via-green-500 to-red-500"> </div></body></html> Output: Picked Tailwind CSS Tailwind CSS-Questions CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Form validation using jQuery How to Change the Position of Scrollbar using CSS ? Build a Survey Form using HTML and CSS Installation of Node.js on Linux How to set the default value for an HTML <select> element ? How do you run JavaScript script through the Terminal? Node.js fs.readFileSync() Method How to set space between the flexbox ?
[ { "code": null, "e": 54, "s": 26, "text": "\n25 May, 2021" }, { "code": null, "e": 158, "s": 54, "text": "In this article, we will see how to apply background images with a linear gradient using Tailwind CSS. " }, { "code": null, "e": 543, "s": 158, "text": "Tailwind CSS is a highly customizable, utility-first CSS framework from which we can use utility classes to build any design. To apply background images with linear gradients we use the background image utility of Tailwind CSS. It is the alternative to the CSS background-image property. To work with Tailwind CSS, we have to add Tailwind CSS pre-compiled file to our project folder. " }, { "code": null, "e": 557, "s": 543, "text": "Installation:" }, { "code": null, "e": 592, "s": 557, "text": "Method 1: Install Tailwind via npm" }, { "code": null, "e": 611, "s": 592, "text": "Step 1:npm init -y" }, { "code": null, "e": 642, "s": 611, "text": "Step 2:npm install tailwindcss" }, { "code": null, "e": 800, "s": 642, "text": "Step 3: Now we have to add Tailwind to our CSS by using the @tailwind directive to inject Tailwind’s base, components, and utility styles into our CSS file. " }, { "code": null, "e": 863, "s": 800, "text": "@tailwind base; \n@tailwind components; \n@tailwind utilities;" }, { "code": null, "e": 872, "s": 863, "text": "Step 4: " }, { "code": null, "e": 965, "s": 872, "text": "npx tailwindcss init\n(It is an optional step that is used to create a Tailwind config file.)" }, { "code": null, "e": 974, "s": 965, "text": "Step 5: " }, { "code": null, "e": 1023, "s": 974, "text": "npx tailwindcss build styles.css -o output.css " }, { "code": null, "e": 1065, "s": 1023, "text": "Method 2: Using Tailwind CSS file via CDN" }, { "code": null, "e": 1151, "s": 1065, "text": "<link href=\"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\">" }, { "code": null, "e": 1266, "s": 1151, "text": "Example: In this example, we have used the bg-gradient-to-br class to set the linear gradient to the bottom right." }, { "code": null, "e": 1271, "s": 1266, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href= \"https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css\" rel=\"stylesheet\"></head><body> <div class=\"font-bold m-3\"> <h1 class=\"text-3xl text-green-800 my-4\" > GeeksforGeeks </h1> <p class=\" text-xl text-black-700 my-3\"> Tailwind CSS Background Image Class </p> </div> <div class=\" m-4 w-96 h-52 bg-gradient-to-br from-blue-400 via-green-500 to-red-500\"> </div></body></html>", "e": 1790, "s": 1271, "text": null }, { "code": null, "e": 1798, "s": 1790, "text": "Output:" }, { "code": null, "e": 1899, "s": 1798, "text": "Example: In this example, we have used all background image classes i.e. bg-gradient-to-{direction}." }, { "code": null, "e": 1904, "s": 1899, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"></head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Background Image Class</b> <div class=\"m-4 grid grid-cols-3 gap-2\"> <div class=\"h-12 w-34 bg-gradient-to-r rounded-lg from-blue-400 via-green-500 to-red-500\"> </div> <div class=\"h-12 w-34 bg-gradient-to-tr rounded-lg from-blue-400 via-green-500 to-red-500\"> </div> <div class=\"h-12 w-34 bg-gradient-to-br rounded-lg from-blue-400 via-green-500 to-red-500\"> </div> <div class=\"h-12 w-34 bg-gradient-to-b rounded-lg from-blue-400 via-green-500 to-red-500\"> </div> <div class=\"h-12 w-34 bg-gradient-to-bl rounded-lg from-blue-400 via-green-500 to-red-500\"> </div> <div class=\"h-12 w-34 bg-gradient-to-tl rounded-lg from-blue-400 via-green-500 to-red-500\"> </div> <div class=\"h-12 w-34 bg-gradient-to-l rounded-lg from-blue-400 via-green-500 to-red-500\"> </div></body></html>", "e": 3087, "s": 1904, "text": null }, { "code": null, "e": 3095, "s": 3087, "text": "Output:" }, { "code": null, "e": 3102, "s": 3095, "text": "Picked" }, { "code": null, "e": 3115, "s": 3102, "text": "Tailwind CSS" }, { "code": null, "e": 3138, "s": 3115, "text": "Tailwind CSS-Questions" }, { "code": null, "e": 3142, "s": 3138, "text": "CSS" }, { "code": null, "e": 3159, "s": 3142, "text": "Web Technologies" }, { "code": null, "e": 3257, "s": 3159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3296, "s": 3257, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3335, "s": 3296, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3364, "s": 3335, "text": "Form validation using jQuery" }, { "code": null, "e": 3416, "s": 3364, "text": "How to Change the Position of Scrollbar using CSS ?" }, { "code": null, "e": 3455, "s": 3416, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 3488, "s": 3455, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3548, "s": 3488, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 3603, "s": 3548, "text": "How do you run JavaScript script through the Terminal?" }, { "code": null, "e": 3636, "s": 3603, "text": "Node.js fs.readFileSync() Method" } ]
Program for Identity Matrix
15 Jun, 2022 Introduction to Identity Matrix : The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix. In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix. Examples: Input : 2 Output : 1 0 0 1 Input : 4 Output : 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 The explanation is simple. We need to make all the elements of principal or main diagonal as 1 and everything else as 0. Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. C++ C Java Python3 C# PHP Javascript // C++ program to print Identity Matrix#include<bits/stdc++.h>using namespace std; int Identity(int num){ int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) cout << 1 << " "; else cout << 0 << " "; } cout << endl; } return 0;} // Driver Codeint main(){ int size = 5; Identity(size); return 0;} // This code is contributed by shubhamsingh10 // C program to print Identity Matrix#include<stdio.h> int Identity(int num){ int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) printf("%d ", 1); else printf("%d ", 0); } printf("\n"); } return 0;} // Driver Codeint main(){ int size = 5; identity(size); return 0;} // Java program to print Identity Matrixclass GFG { static int identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) System.out.print( 1+" "); else System.out.print( 0+" "); } System.out.println(); } return 0; } // Driver Code public static void main(String args[]) { int size = 5; identity(size); }} /*This code is contributed by Nikita tiwari.*/ # Python code to print identity matrix # Function to print identity matrixdef Identity(size): for row in range(0, size): for col in range(0, size): # Here end is used to stay in same line if (row == col): print("1 ", end=" ") else: print("0 ", end=" ") print() # Driver Code size = 5Identity(size) // C# program to print Identity Matrixusing System; class GFG { static int identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) Console.Write( 1+" "); else Console.Write( 0+" "); } Console.WriteLine(); } return 0; } // Driver Code public static void Main() { int size = 5; identity(size); }} /*This code is contributed by vt_m.*/ <?php// PHP program to print// Identity Matrix function Identity($num){ $row; $col; for ($row = 0; $row < $num; $row++) { for ($col = 0; $col < $num; $col++) { // Checking if row is // equal to column if ($row == $col) echo 1," "; else echo 0," "; } echo"\n"; } return 0;} // Driver Code $size = 5; identity($size); // This code is contributed by anuj_67.?> <script> // Program to print Identity Matrix function Identity(num){ var row; var col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) document.write( 1 + " "); else document.write( 0 + " "); } document.write(" \n" + "<br>"); } return 0;} // Driver Code size = 5; Identity(size); //This code is contributed by simranarora5sos </script> Output: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Time Complexity: O(row x col) Auxiliary Space: O(1), as no extra space is used Program to check if a given square matrix is Identity Matrix : C++ C Java Python3 C# PHP Javascript // CPP program to check if a given matrix is identity#include<iostream>using namespace std; const int MAX = 100; bool isIdentity(int mat[][MAX], int N){ for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true;} // Driver Codeint main(){ int N = 4; int mat[][MAX] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) cout << "Yes "; else cout << "No "; return 0;} // C program to check identity matrix#include <stdio.h> // Function to check identity matrixint isidentity(int a[][100], int N){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (i == j && a[i][j] != 1) return 0; else if (i != j && a[i][j] != 0) return 0; } } return 1;}int main(){ // code int N = 4; int a[][100] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; if (isidentity(a, N)) printf("Yes"); else printf("No"); return 0;} // This code is contributed by aayushi2402 // Java program to check if a given// matrix is identityclass GFG { int MAX = 100; static boolean isIdentity(int mat[][], int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true; } // Driver Code public static void main(String args[]) { int N = 4; int mat[][] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) System.out.println("Yes "); else System.out.println("No "); }} /*This code is contributed by Nikita Tiwari.*/ # Python3 program to check# if a given matrix is identityMAX = 100;def isIdentity(mat, N): for row in range(N): for col in range(N): if (row == col and mat[row][col] != 1): return False; elif (row != col and mat[row][col] != 0): return False; return True; # Driver CodeN = 4;mat = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];if (isIdentity(mat, N)): print("Yes ");else: print("No "); # This code is contributed# by mits // C# program to check if a given// matrix is identityusing System; class GFG { //int MAX = 100; static bool isIdentity(int[,] mat, int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row,col] != 1) return false; else if (row != col && mat[row,col] != 0) return false; } } return true; } // Driver Code public static void Main() { int N = 4; int [,]mat = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) Console.WriteLine("Yes "); else Console.WriteLine("No "); }} /*This code is contributed by vt_m.*/ <?php// PHP program to check if a// given matrix is identity// $MAX = 100; function isIdentity($mat, $N){ for ($row = 0; $row < $N; $row++) { for ( $col = 0; $col < $N; $col++) { if ($row == $col and $mat[$row][$col] != 1) return false; else if ($row != $col && $mat[$row][$col] != 0) return false; } } return true;} // Driver Code $N = 4; $mat = array(array(1, 0, 0, 0), array(0, 1, 0, 0), array(0, 0, 1, 0), array(0, 0, 0, 1)); if (isIdentity($mat, $N)) echo "Yes "; else echo "No "; // This code is contributed by anuj_67.?> <script> // JavaScript program to check if a given// matrix is identitylet MAX = 100; function isIdentity(mat, N){ for(let row = 0; row < N; row++) { for(let col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true;} // Driver Codelet N = 4;let mat = [ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]; if (isIdentity(mat, N)) document.write("Yes ");else document.write("No "); // This code is contributed by sanjoy_62 </script> Output: Yes Time Complexity: O(row x col) Auxiliary Space: O(1), as no extra space is used This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Mithun Kumar SHUBHAMSINGH10 simranarora5sos sanjoy_62 aayushi2402 sachinvinod1904 Mathematical Matrix School Programming Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 86, "s": 52, "text": "Introduction to Identity Matrix :" }, { "code": null, "e": 314, "s": 86, "text": " The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix. " }, { "code": null, "e": 677, "s": 314, "text": "In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix." }, { "code": null, "e": 689, "s": 677, "text": "Examples: " }, { "code": null, "e": 928, "s": 689, "text": "Input : 2\nOutput : 1 0\n 0 1\n\nInput : 4\nOutput : 1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\nThe explanation is simple. We need to make all\nthe elements of principal or main diagonal as \n1 and everything else as 0." }, { "code": null, "e": 1104, "s": 928, "text": "Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. " }, { "code": null, "e": 1108, "s": 1104, "text": "C++" }, { "code": null, "e": 1110, "s": 1108, "text": "C" }, { "code": null, "e": 1115, "s": 1110, "text": "Java" }, { "code": null, "e": 1123, "s": 1115, "text": "Python3" }, { "code": null, "e": 1126, "s": 1123, "text": "C#" }, { "code": null, "e": 1130, "s": 1126, "text": "PHP" }, { "code": null, "e": 1141, "s": 1130, "text": "Javascript" }, { "code": "// C++ program to print Identity Matrix#include<bits/stdc++.h>using namespace std; int Identity(int num){ int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) cout << 1 << \" \"; else cout << 0 << \" \"; } cout << endl; } return 0;} // Driver Codeint main(){ int size = 5; Identity(size); return 0;} // This code is contributed by shubhamsingh10", "e": 1686, "s": 1141, "text": null }, { "code": "// C program to print Identity Matrix#include<stdio.h> int Identity(int num){ int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) printf(\"%d \", 1); else printf(\"%d \", 0); } printf(\"\\n\"); } return 0;} // Driver Codeint main(){ int size = 5; identity(size); return 0;}", "e": 2157, "s": 1686, "text": null }, { "code": "// Java program to print Identity Matrixclass GFG { static int identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) System.out.print( 1+\" \"); else System.out.print( 0+\" \"); } System.out.println(); } return 0; } // Driver Code public static void main(String args[]) { int size = 5; identity(size); }} /*This code is contributed by Nikita tiwari.*/", "e": 2825, "s": 2157, "text": null }, { "code": "# Python code to print identity matrix # Function to print identity matrixdef Identity(size): for row in range(0, size): for col in range(0, size): # Here end is used to stay in same line if (row == col): print(\"1 \", end=\" \") else: print(\"0 \", end=\" \") print() # Driver Code size = 5Identity(size)", "e": 3210, "s": 2825, "text": null }, { "code": "// C# program to print Identity Matrixusing System; class GFG { static int identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) Console.Write( 1+\" \"); else Console.Write( 0+\" \"); } Console.WriteLine(); } return 0; } // Driver Code public static void Main() { int size = 5; identity(size); }} /*This code is contributed by vt_m.*/", "e": 3859, "s": 3210, "text": null }, { "code": "<?php// PHP program to print// Identity Matrix function Identity($num){ $row; $col; for ($row = 0; $row < $num; $row++) { for ($col = 0; $col < $num; $col++) { // Checking if row is // equal to column if ($row == $col) echo 1,\" \"; else echo 0,\" \"; } echo\"\\n\"; } return 0;} // Driver Code $size = 5; identity($size); // This code is contributed by anuj_67.?>", "e": 4354, "s": 3859, "text": null }, { "code": "<script> // Program to print Identity Matrix function Identity(num){ var row; var col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) document.write( 1 + \" \"); else document.write( 0 + \" \"); } document.write(\" \\n\" + \"<br>\"); } return 0;} // Driver Code size = 5; Identity(size); //This code is contributed by simranarora5sos </script>", "e": 4903, "s": 4354, "text": null }, { "code": null, "e": 4912, "s": 4903, "text": "Output: " }, { "code": null, "e": 4992, "s": 4912, "text": "1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n0 0 0 1 0 \n0 0 0 0 1 " }, { "code": null, "e": 5022, "s": 4992, "text": "Time Complexity: O(row x col)" }, { "code": null, "e": 5135, "s": 5022, "text": "Auxiliary Space: O(1), as no extra space is used Program to check if a given square matrix is Identity Matrix : " }, { "code": null, "e": 5139, "s": 5135, "text": "C++" }, { "code": null, "e": 5141, "s": 5139, "text": "C" }, { "code": null, "e": 5146, "s": 5141, "text": "Java" }, { "code": null, "e": 5154, "s": 5146, "text": "Python3" }, { "code": null, "e": 5157, "s": 5154, "text": "C#" }, { "code": null, "e": 5161, "s": 5157, "text": "PHP" }, { "code": null, "e": 5172, "s": 5161, "text": "Javascript" }, { "code": "// CPP program to check if a given matrix is identity#include<iostream>using namespace std; const int MAX = 100; bool isIdentity(int mat[][MAX], int N){ for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true;} // Driver Codeint main(){ int N = 4; int mat[][MAX] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) cout << \"Yes \"; else cout << \"No \"; return 0;}", "e": 5876, "s": 5172, "text": null }, { "code": "// C program to check identity matrix#include <stdio.h> // Function to check identity matrixint isidentity(int a[][100], int N){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if (i == j && a[i][j] != 1) return 0; else if (i != j && a[i][j] != 0) return 0; } } return 1;}int main(){ // code int N = 4; int a[][100] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; if (isidentity(a, N)) printf(\"Yes\"); else printf(\"No\"); return 0;} // This code is contributed by aayushi2402", "e": 6552, "s": 5876, "text": null }, { "code": "// Java program to check if a given// matrix is identityclass GFG { int MAX = 100; static boolean isIdentity(int mat[][], int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true; } // Driver Code public static void main(String args[]) { int N = 4; int mat[][] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) System.out.println(\"Yes \"); else System.out.println(\"No \"); }} /*This code is contributed by Nikita Tiwari.*/", "e": 7446, "s": 6552, "text": null }, { "code": "# Python3 program to check# if a given matrix is identityMAX = 100;def isIdentity(mat, N): for row in range(N): for col in range(N): if (row == col and mat[row][col] != 1): return False; elif (row != col and mat[row][col] != 0): return False; return True; # Driver CodeN = 4;mat = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];if (isIdentity(mat, N)): print(\"Yes \");else: print(\"No \"); # This code is contributed# by mits", "e": 8000, "s": 7446, "text": null }, { "code": "// C# program to check if a given// matrix is identityusing System; class GFG { //int MAX = 100; static bool isIdentity(int[,] mat, int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row,col] != 1) return false; else if (row != col && mat[row,col] != 0) return false; } } return true; } // Driver Code public static void Main() { int N = 4; int [,]mat = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) Console.WriteLine(\"Yes \"); else Console.WriteLine(\"No \"); }} /*This code is contributed by vt_m.*/", "e": 8866, "s": 8000, "text": null }, { "code": "<?php// PHP program to check if a// given matrix is identity// $MAX = 100; function isIdentity($mat, $N){ for ($row = 0; $row < $N; $row++) { for ( $col = 0; $col < $N; $col++) { if ($row == $col and $mat[$row][$col] != 1) return false; else if ($row != $col && $mat[$row][$col] != 0) return false; } } return true;} // Driver Code $N = 4; $mat = array(array(1, 0, 0, 0), array(0, 1, 0, 0), array(0, 0, 1, 0), array(0, 0, 0, 1)); if (isIdentity($mat, $N)) echo \"Yes \"; else echo \"No \"; // This code is contributed by anuj_67.?>", "e": 9584, "s": 8866, "text": null }, { "code": "<script> // JavaScript program to check if a given// matrix is identitylet MAX = 100; function isIdentity(mat, N){ for(let row = 0; row < N; row++) { for(let col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true;} // Driver Codelet N = 4;let mat = [ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]; if (isIdentity(mat, N)) document.write(\"Yes \");else document.write(\"No \"); // This code is contributed by sanjoy_62 </script>", "e": 10253, "s": 9584, "text": null }, { "code": null, "e": 10261, "s": 10253, "text": "Output:" }, { "code": null, "e": 10265, "s": 10261, "text": "Yes" }, { "code": null, "e": 10295, "s": 10265, "text": "Time Complexity: O(row x col)" }, { "code": null, "e": 10344, "s": 10295, "text": "Auxiliary Space: O(1), as no extra space is used" }, { "code": null, "e": 10514, "s": 10344, "text": "This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 10519, "s": 10514, "text": "vt_m" }, { "code": null, "e": 10532, "s": 10519, "text": "Mithun Kumar" }, { "code": null, "e": 10547, "s": 10532, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 10563, "s": 10547, "text": "simranarora5sos" }, { "code": null, "e": 10573, "s": 10563, "text": "sanjoy_62" }, { "code": null, "e": 10585, "s": 10573, "text": "aayushi2402" }, { "code": null, "e": 10601, "s": 10585, "text": "sachinvinod1904" }, { "code": null, "e": 10614, "s": 10601, "text": "Mathematical" }, { "code": null, "e": 10621, "s": 10614, "text": "Matrix" }, { "code": null, "e": 10640, "s": 10621, "text": "School Programming" }, { "code": null, "e": 10653, "s": 10640, "text": "Mathematical" }, { "code": null, "e": 10660, "s": 10653, "text": "Matrix" } ]
Python | Get Top N elements from Records
29 Oct, 2019 Sometimes, while working with data, we can have a problem in which we have records and we require to find the highest N scores from it. This kind of application is popular in web development domain. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using sorted() + lambdaThe combination of above functionality can be used to perform this particular task. In this, we just employ sorted function with reverse flag true, and print the top N elements using list slicing. # Python3 code to demonstrate working of# Get Top N elements from Records# Using sorted() + lambda # Initializing list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] # Initializing N N = 2 # printing original listprint("The original list is : " + str(test_list)) # Get Top N elements from Records# Using sorted() + lambdares = sorted(test_list, key = lambda x: x[1], reverse = True)[:N] # printing resultprint("The top N records are : " + str(res)) The original list is : [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] The top N records are : [('Manjeet', 10), ('Nikhil', 8)] Method #2 : Using sorted() + itemgetter()The combination of above functions can also be used to perform this particular task. In this, the task performed by lambda function is performed by itemgetter() is used to get the index in tuple which has to be included in calculations. # Python3 code to demonstrate working of# Get Top N elements from Records# Using sorted() + itemgetter()from operator import itemgetter # Initializing list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] # Initializing N N = 2 # printing original listprint("The original list is : " + str(test_list)) # Get Top N elements from Records# Using sorted() + itemgetter()res = sorted(test_list, key = itemgetter(1), reverse = True)[:N] # printing resultprint("The top N records are : " + str(res)) The original list is : [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] The top N records are : [('Manjeet', 10), ('Nikhil', 8)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2019" }, { "code": null, "e": 291, "s": 28, "text": "Sometimes, while working with data, we can have a problem in which we have records and we require to find the highest N scores from it. This kind of application is popular in web development domain. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 523, "s": 291, "text": "Method #1 : Using sorted() + lambdaThe combination of above functionality can be used to perform this particular task. In this, we just employ sorted function with reverse flag true, and print the top N elements using list slicing." }, { "code": "# Python3 code to demonstrate working of# Get Top N elements from Records# Using sorted() + lambda # Initializing list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] # Initializing N N = 2 # printing original listprint(\"The original list is : \" + str(test_list)) # Get Top N elements from Records# Using sorted() + lambdares = sorted(test_list, key = lambda x: x[1], reverse = True)[:N] # printing resultprint(\"The top N records are : \" + str(res))", "e": 1004, "s": 523, "text": null }, { "code": null, "e": 1147, "s": 1004, "text": "The original list is : [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)]\nThe top N records are : [('Manjeet', 10), ('Nikhil', 8)]\n" }, { "code": null, "e": 1427, "s": 1149, "text": "Method #2 : Using sorted() + itemgetter()The combination of above functions can also be used to perform this particular task. In this, the task performed by lambda function is performed by itemgetter() is used to get the index in tuple which has to be included in calculations." }, { "code": "# Python3 code to demonstrate working of# Get Top N elements from Records# Using sorted() + itemgetter()from operator import itemgetter # Initializing list test_list = [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)] # Initializing N N = 2 # printing original listprint(\"The original list is : \" + str(test_list)) # Get Top N elements from Records# Using sorted() + itemgetter()res = sorted(test_list, key = itemgetter(1), reverse = True)[:N] # printing resultprint(\"The top N records are : \" + str(res))", "e": 1950, "s": 1427, "text": null }, { "code": null, "e": 2093, "s": 1950, "text": "The original list is : [('Manjeet', 10), ('Akshat', 4), ('Akash', 2), ('Nikhil', 8)]\nThe top N records are : [('Manjeet', 10), ('Nikhil', 8)]\n" }, { "code": null, "e": 2114, "s": 2093, "text": "Python list-programs" }, { "code": null, "e": 2121, "s": 2114, "text": "Python" }, { "code": null, "e": 2137, "s": 2121, "text": "Python Programs" }, { "code": null, "e": 2235, "s": 2137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2277, "s": 2235, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2299, "s": 2277, "text": "Enumerate() in Python" }, { "code": null, "e": 2325, "s": 2299, "text": "Python String | replace()" }, { "code": null, "e": 2357, "s": 2325, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2386, "s": 2357, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2408, "s": 2386, "text": "Defaultdict in Python" }, { "code": null, "e": 2447, "s": 2408, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2485, "s": 2447, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2534, "s": 2485, "text": "Python | Convert string dictionary to dictionary" } ]
PHP in_array() Function
03 Dec, 2021 In this article, we will see how to find the value in the array using the in_array() function in PHP, & will also understand its implementation through the examples. The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise. Syntax: bool in_array( $val, $array_name, $mode ) Parameters: The in_array() function accepts 3 parameters, out of which 2 are compulsory and another 1 is optional. All three parameters are described below: $val: This is a required parameter that specifies the element or value to be searched in the given array. This parameter can be of mixed type i.e, it can be of string type or integer type, or any other type. If this parameter is of string type then the search will be performed in a case-sensitive manner. $array_name: This is a required parameter and it specifies the array in which we want to search. $mode: This is an optional parameter and is of boolean type. This parameter specifies the mode in which we want to perform the search. If it is set to TRUE, then the in_array() function searches for the value with the same type of value as specified by the $val parameter. The default value of this parameter is FALSE. Return Value: The in_array() function returns a boolean value i.e, TRUE if the value $val is found in the array otherwise it returns FALSE. Approach: In order to search an array for a specific value, we will be using the in_array() function where the parameter for the search is of string type & its value is set to true. Otherwise, this function returns a false value if the specified value is not found in an array. We will understand the concept of the in_array() function in PHP, through the example. Example 1: The below program performs the search using the in_array() function in non-strict mode ie, the last parameter $mode is set to false which is its default value. The value to be searched is of string type whereas this value in the array is of integer type still the in_array() function returns true as the search is in non-strict mode. PHP <?php $marks = array(100, 65, 70, 87); if (in_array("100", $marks)) { echo "found"; } else { echo "not found"; }?> found Example 2: The below program performs the search using the in_array() function in strict mode ie., the last parameter $mode is set to true and the function will now also check the type of values. PHP <?php $name = array("ravi", "ram", "rani", 87); if (in_array("ravi", $name, TRUE)) { echo "found \n"; } else { echo "not found \n"; } if (in_array(87, $name, TRUE)) { echo "found \n"; } else { echo "not found \n"; } if (in_array("87", $name, TRUE)) { echo "found \n"; } else { echo "not found \n"; }?> found found not found Reference: http://php.net/manual/en/function.in-array.php 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. arorakashish0911 bhaskargeeksforgeeks PHP-array PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime How to get parameters from a URL string in PHP? Download file from URL using PHP Split a comma delimited string into an array in PHP Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Dec, 2021" }, { "code": null, "e": 219, "s": 53, "text": "In this article, we will see how to find the value in the array using the in_array() function in PHP, & will also understand its implementation through the examples." }, { "code": null, "e": 430, "s": 219, "text": "The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise. " }, { "code": null, "e": 438, "s": 430, "text": "Syntax:" }, { "code": null, "e": 480, "s": 438, "text": "bool in_array( $val, $array_name, $mode )" }, { "code": null, "e": 637, "s": 480, "text": "Parameters: The in_array() function accepts 3 parameters, out of which 2 are compulsory and another 1 is optional. All three parameters are described below:" }, { "code": null, "e": 943, "s": 637, "text": "$val: This is a required parameter that specifies the element or value to be searched in the given array. This parameter can be of mixed type i.e, it can be of string type or integer type, or any other type. If this parameter is of string type then the search will be performed in a case-sensitive manner." }, { "code": null, "e": 1040, "s": 943, "text": "$array_name: This is a required parameter and it specifies the array in which we want to search." }, { "code": null, "e": 1359, "s": 1040, "text": "$mode: This is an optional parameter and is of boolean type. This parameter specifies the mode in which we want to perform the search. If it is set to TRUE, then the in_array() function searches for the value with the same type of value as specified by the $val parameter. The default value of this parameter is FALSE." }, { "code": null, "e": 1499, "s": 1359, "text": "Return Value: The in_array() function returns a boolean value i.e, TRUE if the value $val is found in the array otherwise it returns FALSE." }, { "code": null, "e": 1777, "s": 1499, "text": "Approach: In order to search an array for a specific value, we will be using the in_array() function where the parameter for the search is of string type & its value is set to true. Otherwise, this function returns a false value if the specified value is not found in an array." }, { "code": null, "e": 1864, "s": 1777, "text": "We will understand the concept of the in_array() function in PHP, through the example." }, { "code": null, "e": 2209, "s": 1864, "text": "Example 1: The below program performs the search using the in_array() function in non-strict mode ie, the last parameter $mode is set to false which is its default value. The value to be searched is of string type whereas this value in the array is of integer type still the in_array() function returns true as the search is in non-strict mode." }, { "code": null, "e": 2213, "s": 2209, "text": "PHP" }, { "code": "<?php $marks = array(100, 65, 70, 87); if (in_array(\"100\", $marks)) { echo \"found\"; } else { echo \"not found\"; }?>", "e": 2341, "s": 2213, "text": null }, { "code": null, "e": 2347, "s": 2341, "text": "found" }, { "code": null, "e": 2543, "s": 2347, "text": "Example 2: The below program performs the search using the in_array() function in strict mode ie., the last parameter $mode is set to true and the function will now also check the type of values." }, { "code": null, "e": 2547, "s": 2543, "text": "PHP" }, { "code": "<?php $name = array(\"ravi\", \"ram\", \"rani\", 87); if (in_array(\"ravi\", $name, TRUE)) { echo \"found \\n\"; } else { echo \"not found \\n\"; } if (in_array(87, $name, TRUE)) { echo \"found \\n\"; } else { echo \"not found \\n\"; } if (in_array(\"87\", $name, TRUE)) { echo \"found \\n\"; } else { echo \"not found \\n\"; }?>", "e": 2913, "s": 2547, "text": null }, { "code": null, "e": 2938, "s": 2913, "text": "found \nfound \nnot found " }, { "code": null, "e": 2996, "s": 2938, "text": "Reference: http://php.net/manual/en/function.in-array.php" }, { "code": null, "e": 3165, "s": 2996, "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": 3182, "s": 3165, "text": "arorakashish0911" }, { "code": null, "e": 3203, "s": 3182, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 3213, "s": 3203, "text": "PHP-array" }, { "code": null, "e": 3217, "s": 3213, "text": "PHP" }, { "code": null, "e": 3234, "s": 3217, "text": "Web Technologies" }, { "code": null, "e": 3238, "s": 3234, "text": "PHP" }, { "code": null, "e": 3336, "s": 3238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3376, "s": 3336, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3421, "s": 3376, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 3469, "s": 3421, "text": "How to get parameters from a URL string in PHP?" }, { "code": null, "e": 3502, "s": 3469, "text": "Download file from URL using PHP" }, { "code": null, "e": 3554, "s": 3502, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 3587, "s": 3554, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3649, "s": 3587, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3710, "s": 3649, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3760, "s": 3710, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Largest sum contiguous subarray having only non-negative elements
02 Mar, 2022 Given an integer array arr[], the task is to find the largest sum contiguous subarray of non-negative elements and return its sum. Examples: Input: arr[] = {1, 4, -3, 9, 5, -6} Output: 14 Explanation: Subarray [9, 5] is the subarray having maximum sum with all non-negative elements. Input: arr[] = {12, 0, 10, 3, 11} Output: 36 Naive Approach: The simplest approach is to generate all subarrays having only non-negative elements while traversing the subarray and calculating the sum of every valid subarray and updating the maximum sum. Time Complexity: O(N^2) Efficient Approach: To optimize the above approach, traverse the array, and for every non-negative element encountered, keep calculating the sum. For every negative element encountered, update the maximum sum after comparison with the current sum. Reset the sum to 0 and proceed to the next element. 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 return Largest Sum Contiguous// Subarray having non-negative numberint maxNonNegativeSubArray(int A[], int N){ // Length of given array int l = N; int sum = 0, i = 0; int Max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum Max = max(Max, sum); } // Reset sum sum = 0; } // Return the maximum sum return Max;} // Driver codeint main(){ int arr[] = { 1, 4, -3, 9, 5, -6 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxNonNegativeSubArray(arr, N); return 0;} // This code is contributed by divyeshrabadiya07 // Java program to implement// the above approachimport java.util.*; class GFG { // Function to return Largest Sum Contiguous // Subarray having non-negative number static int maxNonNegativeSubArray(int[] A) { // Length of given array int l = A.length; int sum = 0, i = 0; int max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum max = Math.max(max, sum); } // Reset sum sum = 0; } // Return the maximum sum return max; } // Driver Code public static void main(String[] args) { int[] arr = { 1, 4, -3, 9, 5, -6 }; System.out.println(maxNonNegativeSubArray( arr)); }} # Python3 program for the above approachimport math # Function to return Largest Sum Contiguous# Subarray having non-negative numberdef maxNonNegativeSubArray(A, N): # Length of given array l = N sum = 0 i = 0 Max = -1 # Traversing array while (i < l): # Increment i counter to avoid # negative elements while (i < l and A[i] < 0): i += 1 continue # Calculating sum of contiguous # subarray of non-negative # elements while (i < l and 0 <= A[i]): sum += A[i] i += 1 # Update the maximum sum Max = max(Max, sum) # Reset sum sum = 0; # Return the maximum sum return Max # Driver codearr = [ 1, 4, -3, 9, 5, -6 ] # Length of arrayN = len(arr) print(maxNonNegativeSubArray(arr, N)) # This code is contributed by sanjoy_62 // C# program to implement// the above approachusing System; class GFG{ // Function to return Largest Sum Contiguous// Subarray having non-negative numberstatic int maxNonNegativeSubArray(int[] A){ // Length of given array int l = A.Length; int sum = 0, i = 0; int max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum max = Math.Max(max, sum); } // Reset sum sum = 0; } // Return the maximum sum return max;} // Driver Codepublic static void Main(){ int[] arr = { 1, 4, -3, 9, 5, -6 }; Console.Write(maxNonNegativeSubArray(arr));}} // This code is contributed by chitranayal <script> // Javascript program to implement// the above approach // Function to return Largest Sum Contiguous// Subarray having non-negative numberfunction maxNonNegativeSubArray(A, N){ // Length of given array var l = N; var sum = 0, i = 0; var Max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum Max = Math.max(Max, sum); } // Reset sum sum = 0; } // Return the maximum sum return Max;} // Driver codevar arr = [1, 4, -3, 9, 5, -6];var N = arr.length;document.write( maxNonNegativeSubArray(arr, N)); // This code is contributed by famously.</script> 14 Time Complexity: O(N) Auxiliary Space: O(1) C++ Java Python3 C# Javascript #include <iostream> using namespace std; int main(){ int arr[] = { 1, 4, -3, 9, 5, -6 }; int n = sizeof(arr) / sizeof(arr[0]); int max_so_far = 0, max_right_here = 0; int start = 0, end = 0, s = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; } } cout << ("Sub Array : "); for (int i = start; i <= end; i++) { cout << arr[i] << " "; } cout << endl; cout << "Largest Sum : " << max_so_far;} // This code is contributed by SoumikMondal import java.util.*; class GFG{ public static void main(String[] args){ int arr[] = { 1, 4, -3, 9, 5, -6 }; int n = arr.length; int max_so_far = 0, max_right_here = 0; int start = 0, end = 0, s = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; } } System.out.print("Sub Array : "); for (int i = start; i <= end; i++) { System.out.print( arr[i]); System.out.print(" "); } System.out.println(); System.out.print("Largest Sum : "); System.out.print( max_so_far);} } // This code is contributed by amreshkumar3. arr = [1, 4, -3, 9, 5, -6]n = len(arr)max_so_far = 0max_right_here = 0start = 0end = 0s = 0for i in range(0, n): if arr[i] < 0: s = i + 1 max_right_here = 0 else: max_right_here += arr[i] if max_right_here > max_so_far: max_so_far = max_right_here start = s end = i print("Sub Array : ")for i in range(start, end + 1): print(arr[i], end=" ")print()print("largest sum=", max_so_far) # This code is contributed by amreshkumar3. using System; public class GFG { public static void Main(String[] args) { int[] arr = { 1, 4, -3, 9, 5, -6 }; int n = arr.Length; int max_so_far = 0, max_right_here = 0; int start = 0, end = 0, s = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; } } Console.Write("Sub Array : "); for (int i = start; i <= end; i++) { Console.Write(arr[i]); Console.Write(" "); } Console.WriteLine(); Console.Write("Largest Sum : "); Console.Write(max_so_far); }} // This code is contributed by umadevi9616 <script> let arr = [ 1, 4, -3, 9, 5, -6 ];let n = arr.length;let max_so_far = 0, max_right_here = 0;let start = 0, end = 0, s = 0;for(let i = 0; i < n; i++){ if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; }} // Driver codedocument.write("Sub Array : ");for(let i = start; i <= end; i++){ document.write(arr[i] + " ");} document.write("<br>");document.write("Largest Sum : " + max_so_far); // This code is contributed by Potta Lokesh </script> Sub Array : 9 5 Largest Sum : 14 Time Complexity: O(n) Space complexity: O(1) divyeshrabadiya07 sanjoy_62 ukasp mriduldas0226 famously SoumikMondal lokeshpotta20 kushsharma1001 amreshkumar3 umadevi9616 subarray subarray-sum Arrays Competitive Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Mar, 2022" }, { "code": null, "e": 185, "s": 54, "text": "Given an integer array arr[], the task is to find the largest sum contiguous subarray of non-negative elements and return its sum." }, { "code": null, "e": 196, "s": 185, "text": "Examples: " }, { "code": null, "e": 339, "s": 196, "text": "Input: arr[] = {1, 4, -3, 9, 5, -6} Output: 14 Explanation: Subarray [9, 5] is the subarray having maximum sum with all non-negative elements." }, { "code": null, "e": 386, "s": 339, "text": "Input: arr[] = {12, 0, 10, 3, 11} Output: 36 " }, { "code": null, "e": 596, "s": 386, "text": "Naive Approach: The simplest approach is to generate all subarrays having only non-negative elements while traversing the subarray and calculating the sum of every valid subarray and updating the maximum sum. " }, { "code": null, "e": 620, "s": 596, "text": "Time Complexity: O(N^2)" }, { "code": null, "e": 920, "s": 620, "text": "Efficient Approach: To optimize the above approach, traverse the array, and for every non-negative element encountered, keep calculating the sum. For every negative element encountered, update the maximum sum after comparison with the current sum. Reset the sum to 0 and proceed to the next element." }, { "code": null, "e": 972, "s": 920, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 976, "s": 972, "text": "C++" }, { "code": null, "e": 981, "s": 976, "text": "Java" }, { "code": null, "e": 989, "s": 981, "text": "Python3" }, { "code": null, "e": 992, "s": 989, "text": "C#" }, { "code": null, "e": 1003, "s": 992, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return Largest Sum Contiguous// Subarray having non-negative numberint maxNonNegativeSubArray(int A[], int N){ // Length of given array int l = N; int sum = 0, i = 0; int Max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum Max = max(Max, sum); } // Reset sum sum = 0; } // Return the maximum sum return Max;} // Driver codeint main(){ int arr[] = { 1, 4, -3, 9, 5, -6 }; int N = sizeof(arr) / sizeof(arr[0]); cout << maxNonNegativeSubArray(arr, N); return 0;} // This code is contributed by divyeshrabadiya07", "e": 2073, "s": 1003, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG { // Function to return Largest Sum Contiguous // Subarray having non-negative number static int maxNonNegativeSubArray(int[] A) { // Length of given array int l = A.length; int sum = 0, i = 0; int max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum max = Math.max(max, sum); } // Reset sum sum = 0; } // Return the maximum sum return max; } // Driver Code public static void main(String[] args) { int[] arr = { 1, 4, -3, 9, 5, -6 }; System.out.println(maxNonNegativeSubArray( arr)); }}", "e": 3198, "s": 2073, "text": null }, { "code": "# Python3 program for the above approachimport math # Function to return Largest Sum Contiguous# Subarray having non-negative numberdef maxNonNegativeSubArray(A, N): # Length of given array l = N sum = 0 i = 0 Max = -1 # Traversing array while (i < l): # Increment i counter to avoid # negative elements while (i < l and A[i] < 0): i += 1 continue # Calculating sum of contiguous # subarray of non-negative # elements while (i < l and 0 <= A[i]): sum += A[i] i += 1 # Update the maximum sum Max = max(Max, sum) # Reset sum sum = 0; # Return the maximum sum return Max # Driver codearr = [ 1, 4, -3, 9, 5, -6 ] # Length of arrayN = len(arr) print(maxNonNegativeSubArray(arr, N)) # This code is contributed by sanjoy_62 ", "e": 4135, "s": 3198, "text": null }, { "code": "// C# program to implement// the above approachusing System; class GFG{ // Function to return Largest Sum Contiguous// Subarray having non-negative numberstatic int maxNonNegativeSubArray(int[] A){ // Length of given array int l = A.Length; int sum = 0, i = 0; int max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum max = Math.Max(max, sum); } // Reset sum sum = 0; } // Return the maximum sum return max;} // Driver Codepublic static void Main(){ int[] arr = { 1, 4, -3, 9, 5, -6 }; Console.Write(maxNonNegativeSubArray(arr));}} // This code is contributed by chitranayal", "e": 5159, "s": 4135, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to return Largest Sum Contiguous// Subarray having non-negative numberfunction maxNonNegativeSubArray(A, N){ // Length of given array var l = N; var sum = 0, i = 0; var Max = -1; // Traversing array while (i < l) { // Increment i counter to avoid // negative elements while (i < l && A[i] < 0) { i++; continue; } // Calculating sum of contiguous // subarray of non-negative // elements while (i < l && 0 <= A[i]) { sum += A[i++]; // Update the maximum sum Max = Math.max(Max, sum); } // Reset sum sum = 0; } // Return the maximum sum return Max;} // Driver codevar arr = [1, 4, -3, 9, 5, -6];var N = arr.length;document.write( maxNonNegativeSubArray(arr, N)); // This code is contributed by famously.</script>", "e": 6142, "s": 5159, "text": null }, { "code": null, "e": 6145, "s": 6142, "text": "14" }, { "code": null, "e": 6167, "s": 6145, "text": "Time Complexity: O(N)" }, { "code": null, "e": 6189, "s": 6167, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6193, "s": 6189, "text": "C++" }, { "code": null, "e": 6198, "s": 6193, "text": "Java" }, { "code": null, "e": 6206, "s": 6198, "text": "Python3" }, { "code": null, "e": 6209, "s": 6206, "text": "C#" }, { "code": null, "e": 6220, "s": 6209, "text": "Javascript" }, { "code": "#include <iostream> using namespace std; int main(){ int arr[] = { 1, 4, -3, 9, 5, -6 }; int n = sizeof(arr) / sizeof(arr[0]); int max_so_far = 0, max_right_here = 0; int start = 0, end = 0, s = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; } } cout << (\"Sub Array : \"); for (int i = start; i <= end; i++) { cout << arr[i] << \" \"; } cout << endl; cout << \"Largest Sum : \" << max_so_far;} // This code is contributed by SoumikMondal", "e": 6960, "s": 6220, "text": null }, { "code": "import java.util.*; class GFG{ public static void main(String[] args){ int arr[] = { 1, 4, -3, 9, 5, -6 }; int n = arr.length; int max_so_far = 0, max_right_here = 0; int start = 0, end = 0, s = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; } } System.out.print(\"Sub Array : \"); for (int i = start; i <= end; i++) { System.out.print( arr[i]); System.out.print(\" \"); } System.out.println(); System.out.print(\"Largest Sum : \"); System.out.print( max_so_far);} } // This code is contributed by amreshkumar3.", "e": 7782, "s": 6960, "text": null }, { "code": "arr = [1, 4, -3, 9, 5, -6]n = len(arr)max_so_far = 0max_right_here = 0start = 0end = 0s = 0for i in range(0, n): if arr[i] < 0: s = i + 1 max_right_here = 0 else: max_right_here += arr[i] if max_right_here > max_so_far: max_so_far = max_right_here start = s end = i print(\"Sub Array : \")for i in range(start, end + 1): print(arr[i], end=\" \")print()print(\"largest sum=\", max_so_far) # This code is contributed by amreshkumar3.", "e": 8263, "s": 7782, "text": null }, { "code": "using System; public class GFG { public static void Main(String[] args) { int[] arr = { 1, 4, -3, 9, 5, -6 }; int n = arr.Length; int max_so_far = 0, max_right_here = 0; int start = 0, end = 0, s = 0; for (int i = 0; i < n; i++) { if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; } } Console.Write(\"Sub Array : \"); for (int i = start; i <= end; i++) { Console.Write(arr[i]); Console.Write(\" \"); } Console.WriteLine(); Console.Write(\"Largest Sum : \"); Console.Write(max_so_far); }} // This code is contributed by umadevi9616", "e": 9032, "s": 8263, "text": null }, { "code": "<script> let arr = [ 1, 4, -3, 9, 5, -6 ];let n = arr.length;let max_so_far = 0, max_right_here = 0;let start = 0, end = 0, s = 0;for(let i = 0; i < n; i++){ if (arr[i] < 0) { s = i + 1; max_right_here = 0; } else { max_right_here += arr[i]; } if (max_right_here > max_so_far) { max_so_far = max_right_here; start = s; end = i; }} // Driver codedocument.write(\"Sub Array : \");for(let i = start; i <= end; i++){ document.write(arr[i] + \" \");} document.write(\"<br>\");document.write(\"Largest Sum : \" + max_so_far); // This code is contributed by Potta Lokesh </script>", "e": 9671, "s": 9032, "text": null }, { "code": null, "e": 9705, "s": 9671, "text": "Sub Array : 9 5 \nLargest Sum : 14" }, { "code": null, "e": 9727, "s": 9705, "text": "Time Complexity: O(n)" }, { "code": null, "e": 9750, "s": 9727, "text": "Space complexity: O(1)" }, { "code": null, "e": 9768, "s": 9750, "text": "divyeshrabadiya07" }, { "code": null, "e": 9778, "s": 9768, "text": "sanjoy_62" }, { "code": null, "e": 9784, "s": 9778, "text": "ukasp" }, { "code": null, "e": 9798, "s": 9784, "text": "mriduldas0226" }, { "code": null, "e": 9807, "s": 9798, "text": "famously" }, { "code": null, "e": 9820, "s": 9807, "text": "SoumikMondal" }, { "code": null, "e": 9834, "s": 9820, "text": "lokeshpotta20" }, { "code": null, "e": 9849, "s": 9834, "text": "kushsharma1001" }, { "code": null, "e": 9862, "s": 9849, "text": "amreshkumar3" }, { "code": null, "e": 9874, "s": 9862, "text": "umadevi9616" }, { "code": null, "e": 9883, "s": 9874, "text": "subarray" }, { "code": null, "e": 9896, "s": 9883, "text": "subarray-sum" }, { "code": null, "e": 9903, "s": 9896, "text": "Arrays" }, { "code": null, "e": 9927, "s": 9903, "text": "Competitive Programming" }, { "code": null, "e": 9934, "s": 9927, "text": "Arrays" } ]
JavaScript Array map() Method
01 Nov, 2021 Below is an example of the Array map() method. Example: JavaScript <script> // JavaScript to illustrate map() method function func() { // Original array var arr = [14, 10, 11, 00]; // new mapped array var new_arr = arr.map(Math.sqrt); document.write(new_arr); } func();</script> Output: 3.7416573867739413,3.1622776601683795, 3.3166247903554,0 The arr.map() method creates a new array with the results of a called function for every array element. This function calls the argument function once for each element of the given array in order. Syntax: array.map(callback(element, index, arr), thisArg) Parameters: This method accepts five parameters as mentioned above and described below: callback: This parameter holds the function to be called for each element of the array. element: The parameter holds the value of the elements being processed currently. index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0. arr: This parameter is optional, it holds the complete array on which Array.every is called. thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default. Return value: This method returns a new array created by using the values modified by the arg_function using the value from the original array. This function does not modify the original array on which this function is implemented.Below examples illustrate the arr.map() method in JavaScript: Example 1: In this example, the method map() produces an array containing numbers obtained by dividing the numbers in the original array by 2. var arr = [2, 56, 78, 34, 65]; var new_arr = arr.map(function(num) { return num / 2; }); print(new_arr); Output: [1, 28, 39, 17, 32.5] Example 2: In this example, the method map() produces an array containing square roots of the numbers in the original array. var arr = [10, 64, 121, 23]; var new_arr = arr.map(Math.sqrt); print(new_arr); Output: [3.1622776601683795, 8, 11, 4.795831523312719] Codes for the above function are provided below:Program 1: JavaScript <script> // JavaScript to illustrate map() method function func() { // Original array var arr = [2, 56, 78, 34, 65]; // new mapped array var new_arr = arr.map(function (num) { return num / 2; }); document.write(new_arr); } func();</script> Output: 1, 28, 39, 17, 32.5 Program 2: JavaScript <script> // JavaScript to illustrate map() method function func() { // Original array var arr = [10, 64, 121, 23]; // new mapped array var new_arr = arr.map(Math.sqrt); document.write(new_arr); } func();</script> Output: 3.1622776601683795, 8, 11, 4.795831523312719 Supported Browsers: The browsers supported by the JavaScript Array map() method are listed below: Google Chrome 1 and above Microsoft Edge 12 and above Mozilla Firefox 1.5 and above Safari 3 and above Opera 9.5 and above Polyfills are the codes that are used instead of Any function that does not support old browsers. Suppose an old browser that is not up-to-date with new ES features then your code will break in that browser. Here we are creating a polyfill of Array.prototype.map( ) function. The steps are the following. Steps : Check is the browser supports the map( ) function or not. Now create a function expression and assign it into the Array.prototype.map and the function take an argument. Create an empty array. Iterate the value of this and using the for-of loop. ( Here the value of this is the array where you called the map function ) Now use the callback function on every iterated value and push it into that array ( which you created empty) return the array. Implementation: Javascript // Check if the map function is supported by the browser or notif(!Array.prototype.map){ Array.prototype.map = function(callback){ // create an empty array let newArr = []; // Iterate the value of this // Here the value of this is the array by // which you called the map function for(let item of this){ // Apply the callback function at every iteration // and push it into the newArr array newArr.push(callback(item)); } // return the newArr return newArr; }} let a = [ 1, 2, 3, 4, 5, 6] a.map((item)=>{ console.log(item)}) // This code is contributed by _saurabh_jaiswal Output : 1 2 3 4 5 6 _saurabh_jaiswal arorakashish0911 ysachin2314 javascript-array JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2021" }, { "code": null, "e": 77, "s": 28, "text": "Below is an example of the Array map() method. " }, { "code": null, "e": 88, "s": 77, "text": "Example: " }, { "code": null, "e": 99, "s": 88, "text": "JavaScript" }, { "code": "<script> // JavaScript to illustrate map() method function func() { // Original array var arr = [14, 10, 11, 00]; // new mapped array var new_arr = arr.map(Math.sqrt); document.write(new_arr); } func();</script>", "e": 359, "s": 99, "text": null }, { "code": null, "e": 370, "s": 359, "text": " Output: " }, { "code": null, "e": 427, "s": 370, "text": "3.7416573867739413,3.1622776601683795,\n3.3166247903554,0" }, { "code": null, "e": 634, "s": 427, "text": "The arr.map() method creates a new array with the results of a called function for every array element. This function calls the argument function once for each element of the given array in order. Syntax: " }, { "code": null, "e": 684, "s": 634, "text": "array.map(callback(element, index, arr), thisArg)" }, { "code": null, "e": 774, "s": 684, "text": "Parameters: This method accepts five parameters as mentioned above and described below: " }, { "code": null, "e": 862, "s": 774, "text": "callback: This parameter holds the function to be called for each element of the array." }, { "code": null, "e": 944, "s": 862, "text": "element: The parameter holds the value of the elements being processed currently." }, { "code": null, "e": 1056, "s": 944, "text": "index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0." }, { "code": null, "e": 1149, "s": 1056, "text": "arr: This parameter is optional, it holds the complete array on which Array.every is called." }, { "code": null, "e": 1416, "s": 1149, "text": "thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default." }, { "code": null, "e": 1711, "s": 1416, "text": "Return value: This method returns a new array created by using the values modified by the arg_function using the value from the original array. This function does not modify the original array on which this function is implemented.Below examples illustrate the arr.map() method in JavaScript: " }, { "code": null, "e": 1855, "s": 1711, "text": "Example 1: In this example, the method map() produces an array containing numbers obtained by dividing the numbers in the original array by 2. " }, { "code": null, "e": 1962, "s": 1855, "text": "var arr = [2, 56, 78, 34, 65];\nvar new_arr = arr.map(function(num) {\n return num / 2;\n});\nprint(new_arr);" }, { "code": null, "e": 1972, "s": 1962, "text": "Output: " }, { "code": null, "e": 1994, "s": 1972, "text": "[1, 28, 39, 17, 32.5]" }, { "code": null, "e": 2121, "s": 1994, "text": "Example 2: In this example, the method map() produces an array containing square roots of the numbers in the original array. " }, { "code": null, "e": 2200, "s": 2121, "text": "var arr = [10, 64, 121, 23];\nvar new_arr = arr.map(Math.sqrt);\nprint(new_arr);" }, { "code": null, "e": 2210, "s": 2200, "text": "Output: " }, { "code": null, "e": 2257, "s": 2210, "text": "[3.1622776601683795, 8, 11, 4.795831523312719]" }, { "code": null, "e": 2318, "s": 2257, "text": "Codes for the above function are provided below:Program 1: " }, { "code": null, "e": 2329, "s": 2318, "text": "JavaScript" }, { "code": "<script> // JavaScript to illustrate map() method function func() { // Original array var arr = [2, 56, 78, 34, 65]; // new mapped array var new_arr = arr.map(function (num) { return num / 2; }); document.write(new_arr); } func();</script>", "e": 2636, "s": 2329, "text": null }, { "code": null, "e": 2646, "s": 2636, "text": "Output: " }, { "code": null, "e": 2666, "s": 2646, "text": "1, 28, 39, 17, 32.5" }, { "code": null, "e": 2679, "s": 2666, "text": "Program 2: " }, { "code": null, "e": 2690, "s": 2679, "text": "JavaScript" }, { "code": "<script> // JavaScript to illustrate map() method function func() { // Original array var arr = [10, 64, 121, 23]; // new mapped array var new_arr = arr.map(Math.sqrt); document.write(new_arr); } func();</script>", "e": 2951, "s": 2690, "text": null }, { "code": null, "e": 2961, "s": 2951, "text": "Output: " }, { "code": null, "e": 3006, "s": 2961, "text": "3.1622776601683795, 8, 11, 4.795831523312719" }, { "code": null, "e": 3106, "s": 3006, "text": "Supported Browsers: The browsers supported by the JavaScript Array map() method are listed below: " }, { "code": null, "e": 3132, "s": 3106, "text": "Google Chrome 1 and above" }, { "code": null, "e": 3160, "s": 3132, "text": "Microsoft Edge 12 and above" }, { "code": null, "e": 3190, "s": 3160, "text": "Mozilla Firefox 1.5 and above" }, { "code": null, "e": 3209, "s": 3190, "text": "Safari 3 and above" }, { "code": null, "e": 3229, "s": 3209, "text": "Opera 9.5 and above" }, { "code": null, "e": 3328, "s": 3229, "text": "Polyfills are the codes that are used instead of Any function that does not support old browsers. " }, { "code": null, "e": 3438, "s": 3328, "text": "Suppose an old browser that is not up-to-date with new ES features then your code will break in that browser." }, { "code": null, "e": 3535, "s": 3438, "text": "Here we are creating a polyfill of Array.prototype.map( ) function. The steps are the following." }, { "code": null, "e": 3543, "s": 3535, "text": "Steps :" }, { "code": null, "e": 3601, "s": 3543, "text": "Check is the browser supports the map( ) function or not." }, { "code": null, "e": 3712, "s": 3601, "text": "Now create a function expression and assign it into the Array.prototype.map and the function take an argument." }, { "code": null, "e": 3735, "s": 3712, "text": "Create an empty array." }, { "code": null, "e": 3862, "s": 3735, "text": "Iterate the value of this and using the for-of loop. ( Here the value of this is the array where you called the map function )" }, { "code": null, "e": 3971, "s": 3862, "text": "Now use the callback function on every iterated value and push it into that array ( which you created empty)" }, { "code": null, "e": 3989, "s": 3971, "text": "return the array." }, { "code": null, "e": 4005, "s": 3989, "text": "Implementation:" }, { "code": null, "e": 4016, "s": 4005, "text": "Javascript" }, { "code": "// Check if the map function is supported by the browser or notif(!Array.prototype.map){ Array.prototype.map = function(callback){ // create an empty array let newArr = []; // Iterate the value of this // Here the value of this is the array by // which you called the map function for(let item of this){ // Apply the callback function at every iteration // and push it into the newArr array newArr.push(callback(item)); } // return the newArr return newArr; }} let a = [ 1, 2, 3, 4, 5, 6] a.map((item)=>{ console.log(item)}) // This code is contributed by _saurabh_jaiswal", "e": 4740, "s": 4016, "text": null }, { "code": null, "e": 4749, "s": 4740, "text": "Output :" }, { "code": null, "e": 4761, "s": 4749, "text": "1\n2\n3\n4\n5\n6" }, { "code": null, "e": 4778, "s": 4761, "text": "_saurabh_jaiswal" }, { "code": null, "e": 4795, "s": 4778, "text": "arorakashish0911" }, { "code": null, "e": 4807, "s": 4795, "text": "ysachin2314" }, { "code": null, "e": 4824, "s": 4807, "text": "javascript-array" }, { "code": null, "e": 4843, "s": 4824, "text": "JavaScript-Methods" }, { "code": null, "e": 4854, "s": 4843, "text": "JavaScript" }, { "code": null, "e": 4871, "s": 4854, "text": "Web Technologies" }, { "code": null, "e": 4969, "s": 4871, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5030, "s": 4969, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5102, "s": 5030, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5142, "s": 5102, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5183, "s": 5142, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5225, "s": 5183, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5287, "s": 5225, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5320, "s": 5287, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5381, "s": 5320, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5431, "s": 5381, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Date compareTo() method in Java with examples
07 Nov, 2019 The compareTo() method of Java Date class compares two dates and sort them for order. Syntax: public int compareTo(Date anotherDate) Parameters: The function accepts a single parameter anotherDate which specifies the date to be compared . Return Value: The function gives three return values specified below: It returns the value 0 if the argument Date is equal to this Date. It returns a value less than 0 if this Date is before the Date argument. It returns a value greater than 0 if this Date is after the Date argument. Exception: The function throws a single exception that is NullPointerException if anotherDate is null. Program below demonstrates the above mentioned function: // Java code to demonstrate// compareTo() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c.set(Calendar.MONTH, 11); // set Date c.set(Calendar.DATE, 05); // set Year c.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c.getTime(); System.out.println("Date 1: " + dateOne); // creating a date of object // storing the current date Date currentDate = new Date(); System.out.println("Date 2: " + currentDate); // compares System.out.println("On Comparison: " + currentDate .compareTo(dateOne)); }} Date 1: Thu Dec 05 08:17:55 UTC 1996 Date 2: Wed Jan 02 08:17:55 UTC 2019 On Comparison: 1 // Java code to demonstrate// compareTo() function of Date class import java.util.Date; public class GfG { // main method public static void main(String[] args) { // creating a date of object // stospecified datent date Date currentDate = new Date(); System.out.println("Date 1: " + currentDate); // specifiedDate is assigned to null. Date specifiedDate = null; System.out.println("Date 2: " + specifiedDate); System.out.println("Passing null as parameter: "); try { // throws NullPointerException System.out.println(currentDate .compareTo(specifiedDate)); } catch (Exception e) { System.out.println("Exception: " + e); } }} Date 1: Wed Jan 02 08:18:02 UTC 2019 Date 2: null Passing null as parameter: Exception: java.lang.NullPointerException ManasChhabra2 Java - util package Java-Functions Java-util-Date Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Nov, 2019" }, { "code": null, "e": 140, "s": 54, "text": "The compareTo() method of Java Date class compares two dates and sort them for order." }, { "code": null, "e": 148, "s": 140, "text": "Syntax:" }, { "code": null, "e": 188, "s": 148, "text": "public int compareTo(Date anotherDate)\n" }, { "code": null, "e": 294, "s": 188, "text": "Parameters: The function accepts a single parameter anotherDate which specifies the date to be compared ." }, { "code": null, "e": 364, "s": 294, "text": "Return Value: The function gives three return values specified below:" }, { "code": null, "e": 431, "s": 364, "text": "It returns the value 0 if the argument Date is equal to this Date." }, { "code": null, "e": 504, "s": 431, "text": "It returns a value less than 0 if this Date is before the Date argument." }, { "code": null, "e": 579, "s": 504, "text": "It returns a value greater than 0 if this Date is after the Date argument." }, { "code": null, "e": 682, "s": 579, "text": "Exception: The function throws a single exception that is NullPointerException if anotherDate is null." }, { "code": null, "e": 739, "s": 682, "text": "Program below demonstrates the above mentioned function:" }, { "code": "// Java code to demonstrate// compareTo() function of Date class import java.util.Date;import java.util.Calendar;public class GfG { // main method public static void main(String[] args) { // creating a Calendar object Calendar c = Calendar.getInstance(); // set Month // MONTH starts with 0 i.e. ( 0 - Jan) c.set(Calendar.MONTH, 11); // set Date c.set(Calendar.DATE, 05); // set Year c.set(Calendar.YEAR, 1996); // creating a date object with specified time. Date dateOne = c.getTime(); System.out.println(\"Date 1: \" + dateOne); // creating a date of object // storing the current date Date currentDate = new Date(); System.out.println(\"Date 2: \" + currentDate); // compares System.out.println(\"On Comparison: \" + currentDate .compareTo(dateOne)); }}", "e": 1757, "s": 739, "text": null }, { "code": null, "e": 1849, "s": 1757, "text": "Date 1: Thu Dec 05 08:17:55 UTC 1996\nDate 2: Wed Jan 02 08:17:55 UTC 2019\nOn Comparison: 1\n" }, { "code": "// Java code to demonstrate// compareTo() function of Date class import java.util.Date; public class GfG { // main method public static void main(String[] args) { // creating a date of object // stospecified datent date Date currentDate = new Date(); System.out.println(\"Date 1: \" + currentDate); // specifiedDate is assigned to null. Date specifiedDate = null; System.out.println(\"Date 2: \" + specifiedDate); System.out.println(\"Passing null as parameter: \"); try { // throws NullPointerException System.out.println(currentDate .compareTo(specifiedDate)); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 2649, "s": 1849, "text": null }, { "code": null, "e": 2770, "s": 2649, "text": "Date 1: Wed Jan 02 08:18:02 UTC 2019\nDate 2: null\nPassing null as parameter: \nException: java.lang.NullPointerException\n" }, { "code": null, "e": 2784, "s": 2770, "text": "ManasChhabra2" }, { "code": null, "e": 2804, "s": 2784, "text": "Java - util package" }, { "code": null, "e": 2819, "s": 2804, "text": "Java-Functions" }, { "code": null, "e": 2834, "s": 2819, "text": "Java-util-Date" }, { "code": null, "e": 2839, "s": 2834, "text": "Java" }, { "code": null, "e": 2844, "s": 2839, "text": "Java" }, { "code": null, "e": 2942, "s": 2844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2957, "s": 2942, "text": "Stream In Java" }, { "code": null, "e": 2978, "s": 2957, "text": "Introduction to Java" }, { "code": null, "e": 2999, "s": 2978, "text": "Constructors in Java" }, { "code": null, "e": 3018, "s": 2999, "text": "Exceptions in Java" }, { "code": null, "e": 3035, "s": 3018, "text": "Generics in Java" }, { "code": null, "e": 3065, "s": 3035, "text": "Functional Interfaces in Java" }, { "code": null, "e": 3091, "s": 3065, "text": "Java Programming Examples" }, { "code": null, "e": 3107, "s": 3091, "text": "Strings in Java" }, { "code": null, "e": 3144, "s": 3107, "text": "Differences between JDK, JRE and JVM" } ]