title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Playit
div#myBox { background-color:yellow; border: 1px solid red; padding:0px;}
[]
Python - AWS SAM Lambda Example - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws Here we are going to see the basic Python AWS Lambda Hello World example using SAM (Serverless Application Model) AWS Account Python AWS CLI SAM CLI SAM uses AWS-CLI so its required to install AWS CLI to work with SAM, after all the above installations, we have to set up the AWS credentials, it varies based on your OS type we have an exclusive article for this or you can configure the credentials directly like below. I am working on the below versions: $ sam --version SAM CLI, version 1.23.0 $ aws --version aws-cli/2.0.30 Python/3.7.4 Darwin/19.6.0 botocore/2.0.0dev34 The AWS configure command is used to map the AWS Account with the installed AWS CLI, that way the CLI can get access with your AWS Account. $ aws configure AWS Access Key ID [****************OE7N]: your_aws_access_key AWS Secret Access Key [****************7qwh]: your_aws_secret_access_key Default region name [None]: us-west-2 Default output format [None]: sam init command is used to generate the SAM project structure. For this example, I have generated the Sam project with python3.8 however, when implementing the code, we can change it to various versions of Python3x, .NET, Go, Node.js, Java or Ruby. $ sam init --runtime python3.8 Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location Choice: 1 What package type would you like to use? 1 - Zip (artifact is a zip uploaded to S3) 2 - Image (artifact is an image uploaded to an ECR image repository) Package type: 1 Project name [sam-app]: hello-world-sam Cloning app templates from https://github.com/aws/aws-sam-cli-app-templates AWS quick start application templates: 1 - Hello World Example 2 - EventBridge Hello World 3 - EventBridge App from scratch (100+ Event Schemas) 4 - Step Functions Sample App (Stock Trader) 5 - Elastic File System Sample App Template selection: 1 ----------------------- Generating application: ----------------------- Name: hello-world-sam Runtime: python3.8 Dependency Manager: pip Application Template: hello-world Output Directory: . Next steps can be found in the README file at ./hello-world-sam/README.md hello-world-sam $ . β”œβ”€β”€ README.md β”œβ”€β”€ __init__.py β”œβ”€β”€ events β”‚ └── event.json β”œβ”€β”€ hello_world β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ app.py β”‚ └── requirements.txt β”œβ”€β”€ template.yaml └── tests β”œβ”€β”€ __init__.py β”œβ”€β”€ integration β”‚ β”œβ”€β”€ __init__.py β”‚ └── test_api_gateway.py β”œβ”€β”€ requirements.txt └── unit β”œβ”€β”€ __init__.py └── test_handler.py Among all of the above files the most important file that we need to work on is app.py, it is the python lambda function. The template.yaml is the one that has the SAM template. The event.json has the sample event for testing. The requirement.txt specifies the lambda function dependencies. AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > hello-world-sam Sample SAM Template for hello-world-sam # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst Globals: Function: Timeout: 3 Resources: HelloWorldFunction: Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction Properties: CodeUri: hello_world/ Handler: app.lambda_handler Runtime: python3.8 Events: HelloWorld: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /hello Method: get Outputs: # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function # Find out more about other implicit resources you can reference within SAM # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api HelloWorldApi: Description: "API Gateway endpoint URL for Prod stage for Hello World function" Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" HelloWorldFunction: Description: "Hello World Lambda Function ARN" Value: !GetAtt HelloWorldFunction.Arn HelloWorldFunctionIamRole: Description: "Implicit IAM Role created for Hello World function" Value: !GetAtt HelloWorldFunctionRole.Arn The above simple template file used to build the AWS Lambda using SAM import json def lambda_handler(event, context): """Sample pure Lambda function return { "statusCode": 200, "body": json.dumps({ "message": "hello world", # "location": ip.text.replace("\n", "") }), } Build the application hello-world-sam $ sam build Building codeuri: /hello-world-sam/hello_world runtime: python3.8 metadata: {} functions: ['HelloWorldFunction'] Running PythonPipBuilder:ResolveDependencies Running PythonPipBuilder:CopySource Build Succeeded Built Artifacts : .aws-sam/build Built Template : .aws-sam/build/template.yaml Commands you can use next ========================= [*] Invoke Function: sam local invoke [*] Deploy: sam deploy --guided deploy the application $ sam deploy --guided Configuring SAM deploy ====================== Looking for config file [samconfig.toml] : Not found Setting default arguments for 'sam deploy' ========================================= Stack Name [sam-app]: hello-world-sam-application AWS Region [us-west-2]: us-west-2 #Shows you resources changes to be deployed and require a 'Y' to initiate deploy Confirm changes before deploy [y/N]: y #SAM needs permission to be able to create roles to connect to the resources in your template Allow SAM CLI IAM role creation [Y/n]: y HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y Save arguments to configuration file [Y/n]: y SAM configuration file [samconfig.toml]: SAM configuration environment [default]: dev Looking for resources needed for deployment: Found! Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-vlxz3w3to6ye A different default S3 bucket can be set in samconfig.toml Saved arguments to config file Running 'sam deploy' for future deployments will use the parameters saved above. The above parameters can be changed by modifying samconfig.toml Learn more about samconfig.toml syntax at https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html Uploading to hello-world-sam-application/58ec98812dacd95efee12c7e720890f1 585177 / 585177 (100.00%) Deploying with following values =============================== Stack name : hello-world-sam-application Region : us-west-2 Confirm changeset : True Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-vlxz3w3to6ye Capabilities : ["CAPABILITY_IAM"] Parameter overrides : {} Signing Profiles : {} Initiating deployment ===================== Uploading to hello-world-sam-application/b78c4ab547b82834a429f1f54a09b62f.template 1125 / 1125 (100.00%) Waiting for changeset to be created.. CloudFormation stack changeset ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Operation LogicalResourceId ResourceType Replacement ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + Add HelloWorldFunctionHelloWorldPermissionProd AWS::Lambda::Permission N/A + Add HelloWorldFunctionRole AWS::IAM::Role N/A + Add HelloWorldFunction AWS::Lambda::Function N/A + Add ServerlessRestApiDeployment47fc2d5f9d AWS::ApiGateway::Deployment N/A + Add ServerlessRestApiProdStage AWS::ApiGateway::Stage N/A + Add ServerlessRestApi AWS::ApiGateway::RestApi N/A ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Changeset created successfully. arn:aws:cloudformation:us-west-2:816569674899:changeSet/samcli-deploy1622384684/659cd0b5-e7fb-4767-a161-df496376c15e Previewing CloudFormation changeset before deployment ====================================================== Deploy this changeset? [y/N]: y 2021-05-30 19:55:02 - Waiting for stack create/update to complete CloudFormation events from changeset ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ResourceStatus ResourceType LogicalResourceId ResourceStatusReason ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole Resource creation Initiated CREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole - CREATE_COMPLETE AWS::IAM::Role HelloWorldFunctionRole - CREATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction - CREATE_COMPLETE AWS::Lambda::Function HelloWorldFunction - CREATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction Resource creation Initiated CREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi - CREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi Resource creation Initiated CREATE_COMPLETE AWS::ApiGateway::RestApi ServerlessRestApi - CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d Resource creation Initiated CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd Resource creation Initiated CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd - CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d - CREATE_COMPLETE AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d - CREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdStage Resource creation Initiated CREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdStage - CREATE_COMPLETE AWS::ApiGateway::Stage ServerlessRestApiProdStage - CREATE_COMPLETE AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd - CREATE_COMPLETE AWS::CloudFormation::Stack hello-world-sam-application - ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- CloudFormation outputs from deployed stack -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Outputs -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Key HelloWorldFunctionIamRole Description Implicit IAM Role created for Hello World function Value arn:aws:iam::816569674899:role/hello-world-sam-application-HelloWorldFunctionRole-NAYYRTABIVUF Key HelloWorldApi Description API Gateway endpoint URL for Prod stage for Hello World function Value https://6v73c82ade.execute-api.us-west-2.amazonaws.com/Prod/hello/ Key HelloWorldFunction Description Hello World Lambda Function ARN Value arn:aws:lambda:us-west-2:816569674899:function:hello-world-sam-application-HelloWorldFunction-dAjHSaNEq6pl -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Successfully created/updated stack - hello-world-sam-application in us-west-2 If everything went well you can see the above success message. Login to your AWS account-> Switch to Lambda-> Select the lambda-> Code Source-> Run Export AWS credentials More on AWS SAM Happy Learning πŸ™‚ How to install AWS CLI on Windows 10 How set AWS Access Keys in Windows or Mac Environment How to Copy Local Files to AWS EC2 instance Manually ? How to connect AWS EC2 Instance using PuTTY Lambda Expressions in Java What are Lambda Expressions in Java 8 Different ways to use Lambdas in Python AngularJs Directive Example Tutorials How add files to S3 Bucket using Shell Script Python Django Helloworld Example What are the different ways to Sort Objects in Python ? Angularjs Services Example Tutorials How to use *args and **kwargs in Python What are the List of Python Keywords Angularjs Custom Filter Example How to install AWS CLI on Windows 10 How set AWS Access Keys in Windows or Mac Environment How to Copy Local Files to AWS EC2 instance Manually ? How to connect AWS EC2 Instance using PuTTY Lambda Expressions in Java What are Lambda Expressions in Java 8 Different ways to use Lambdas in Python AngularJs Directive Example Tutorials How add files to S3 Bucket using Shell Script Python Django Helloworld Example What are the different ways to Sort Objects in Python ? Angularjs Services Example Tutorials How to use *args and **kwargs in Python What are the List of Python Keywords Angularjs Custom Filter Example Ξ” Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 512, "s": 398, "text": "Here we are going to see the basic Python AWS Lambda Hello World example using SAM (Serverless Application Model)" }, { "code": null, "e": 524, "s": 512, "text": "AWS Account" }, { "code": null, "e": 531, "s": 524, "text": "Python" }, { "code": null, "e": 539, "s": 531, "text": "AWS CLI" }, { "code": null, "e": 547, "s": 539, "text": "SAM CLI" }, { "code": null, "e": 819, "s": 547, "text": "SAM uses AWS-CLI so its required to install AWS CLI to work with SAM, after all the above installations, we have to set up the AWS credentials, it varies based on your OS type we have an exclusive article for this or you can configure the credentials directly like below." }, { "code": null, "e": 855, "s": 819, "text": "I am working on the below versions:" }, { "code": null, "e": 975, "s": 855, "text": "$ sam --version\nSAM CLI, version 1.23.0\n\n$ aws --version\naws-cli/2.0.30 Python/3.7.4 Darwin/19.6.0 botocore/2.0.0dev34\n" }, { "code": null, "e": 1115, "s": 975, "text": "The AWS configure command is used to map the AWS Account with the installed AWS CLI, that way the CLI can get access with your AWS Account." }, { "code": null, "e": 1336, "s": 1115, "text": "$ aws configure\nAWS Access Key ID [****************OE7N]: your_aws_access_key\nAWS Secret Access Key [****************7qwh]: your_aws_secret_access_key\nDefault region name [None]: us-west-2\nDefault output format [None]: \n" }, { "code": null, "e": 1586, "s": 1336, "text": "sam init command is used to generate the SAM project structure. For this example, I have generated the Sam project with python3.8 however, when implementing the code, we can change it to various versions of Python3x, .NET, Go, Node.js, Java or Ruby." }, { "code": null, "e": 2652, "s": 1586, "text": "$ sam init --runtime python3.8\nWhich template source would you like to use?\n 1 - AWS Quick Start Templates\n 2 - Custom Template Location\nChoice: 1\nWhat package type would you like to use?\n 1 - Zip (artifact is a zip uploaded to S3) \n 2 - Image (artifact is an image uploaded to an ECR image repository)\nPackage type: 1\n\nProject name [sam-app]: hello-world-sam\n\nCloning app templates from https://github.com/aws/aws-sam-cli-app-templates\n\nAWS quick start application templates:\n 1 - Hello World Example\n 2 - EventBridge Hello World\n 3 - EventBridge App from scratch (100+ Event Schemas)\n 4 - Step Functions Sample App (Stock Trader)\n 5 - Elastic File System Sample App\nTemplate selection: 1\n\n -----------------------\n Generating application:\n -----------------------\n Name: hello-world-sam\n Runtime: python3.8\n Dependency Manager: pip\n Application Template: hello-world\n Output Directory: .\n \n Next steps can be found in the README file at ./hello-world-sam/README.md\n" }, { "code": null, "e": 3024, "s": 2652, "text": "hello-world-sam $ \n.\nβ”œβ”€β”€ README.md\nβ”œβ”€β”€ __init__.py\nβ”œβ”€β”€ events\nβ”‚ └── event.json\nβ”œβ”€β”€ hello_world\nβ”‚ β”œβ”€β”€ __init__.py\nβ”‚ β”œβ”€β”€ app.py\nβ”‚ └── requirements.txt\nβ”œβ”€β”€ template.yaml\n└── tests\n β”œβ”€β”€ __init__.py\n β”œβ”€β”€ integration\n β”‚ β”œβ”€β”€ __init__.py\n β”‚ └── test_api_gateway.py\n β”œβ”€β”€ requirements.txt\n └── unit\n β”œβ”€β”€ __init__.py\n └── test_handler.py\n" }, { "code": null, "e": 3146, "s": 3024, "text": "Among all of the above files the most important file that we need to work on is app.py, it is the python lambda function." }, { "code": null, "e": 3202, "s": 3146, "text": "The template.yaml is the one that has the SAM template." }, { "code": null, "e": 3251, "s": 3202, "text": "The event.json has the sample event for testing." }, { "code": null, "e": 3315, "s": 3251, "text": "The requirement.txt specifies the lambda function dependencies." }, { "code": null, "e": 4955, "s": 3315, "text": "AWSTemplateFormatVersion: '2010-09-09'\nTransform: AWS::Serverless-2016-10-31\nDescription: >\n hello-world-sam\n\n Sample SAM Template for hello-world-sam\n\n# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst\nGlobals:\n Function:\n Timeout: 3\n\nResources:\n HelloWorldFunction:\n Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction\n Properties:\n CodeUri: hello_world/\n Handler: app.lambda_handler\n Runtime: python3.8\n Events:\n HelloWorld:\n Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api\n Properties:\n Path: /hello\n Method: get\n\nOutputs:\n # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function\n # Find out more about other implicit resources you can reference within SAM\n # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api\n HelloWorldApi:\n Description: \"API Gateway endpoint URL for Prod stage for Hello World function\"\n Value: !Sub \"https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/\"\n HelloWorldFunction:\n Description: \"Hello World Lambda Function ARN\"\n Value: !GetAtt HelloWorldFunction.Arn\n HelloWorldFunctionIamRole:\n Description: \"Implicit IAM Role created for Hello World function\"\n Value: !GetAtt HelloWorldFunctionRole.Arn\n" }, { "code": null, "e": 5025, "s": 4955, "text": "The above simple template file used to build the AWS Lambda using SAM" }, { "code": null, "e": 5288, "s": 5025, "text": "import json\n\ndef lambda_handler(event, context):\n \"\"\"Sample pure Lambda function\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\n \"message\": \"hello world\",\n # \"location\": ip.text.replace(\"\\n\", \"\")\n }),\n }\n" }, { "code": null, "e": 5310, "s": 5288, "text": "Build the application" }, { "code": null, "e": 5756, "s": 5310, "text": "hello-world-sam $ sam build\nBuilding codeuri: /hello-world-sam/hello_world runtime: python3.8 metadata: {} functions: ['HelloWorldFunction']\nRunning PythonPipBuilder:ResolveDependencies\nRunning PythonPipBuilder:CopySource\n\nBuild Succeeded\n\nBuilt Artifacts : .aws-sam/build\nBuilt Template : .aws-sam/build/template.yaml\n\nCommands you can use next\n=========================\n[*] Invoke Function: sam local invoke\n[*] Deploy: sam deploy --guided\n" }, { "code": null, "e": 5779, "s": 5756, "text": "deploy the application" }, { "code": null, "e": 19673, "s": 5779, "text": "$ sam deploy --guided\nConfiguring SAM deploy\n======================\nLooking for config file [samconfig.toml] : Not found\nSetting default arguments for 'sam deploy'\n=========================================\nStack Name [sam-app]: hello-world-sam-application\nAWS Region [us-west-2]: us-west-2\n#Shows you resources changes to be deployed and require a 'Y' to initiate deploy\nConfirm changes before deploy [y/N]: y\n#SAM needs permission to be able to create roles to connect to the resources in your template\nAllow SAM CLI IAM role creation [Y/n]: y\nHelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y\nSave arguments to configuration file [Y/n]: y\nSAM configuration file [samconfig.toml]: \nSAM configuration environment [default]: dev\nLooking for resources needed for deployment: Found!\nManaged S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-vlxz3w3to6ye\nA different default S3 bucket can be set in samconfig.toml\nSaved arguments to config file\nRunning 'sam deploy' for future deployments will use the parameters saved above.\nThe above parameters can be changed by modifying samconfig.toml\nLearn more about samconfig.toml syntax at \nhttps://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html\nUploading to hello-world-sam-application/58ec98812dacd95efee12c7e720890f1 585177 / 585177 (100.00%)\nDeploying with following values\n===============================\nStack name : hello-world-sam-application\nRegion : us-west-2\nConfirm changeset : True\nDeployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-vlxz3w3to6ye\nCapabilities : [\"CAPABILITY_IAM\"]\nParameter overrides : {}\nSigning Profiles : {}\nInitiating deployment\n=====================\nUploading to hello-world-sam-application/b78c4ab547b82834a429f1f54a09b62f.template 1125 / 1125 (100.00%)\nWaiting for changeset to be created..\nCloudFormation stack changeset\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nOperation LogicalResourceId ResourceType Replacement \n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n+ Add HelloWorldFunctionHelloWorldPermissionProd AWS::Lambda::Permission N/A \n+ Add HelloWorldFunctionRole AWS::IAM::Role N/A \n+ Add HelloWorldFunction AWS::Lambda::Function N/A \n+ Add ServerlessRestApiDeployment47fc2d5f9d AWS::ApiGateway::Deployment N/A \n+ Add ServerlessRestApiProdStage AWS::ApiGateway::Stage N/A \n+ Add ServerlessRestApi AWS::ApiGateway::RestApi N/A \n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nChangeset created successfully. arn:aws:cloudformation:us-west-2:816569674899:changeSet/samcli-deploy1622384684/659cd0b5-e7fb-4767-a161-df496376c15e\nPreviewing CloudFormation changeset before deployment\n======================================================\nDeploy this changeset? [y/N]: y\n2021-05-30 19:55:02 - Waiting for stack create/update to complete\nCloudFormation events from changeset\n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nResourceStatus ResourceType LogicalResourceId ResourceStatusReason \n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nCREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole Resource creation Initiated \nCREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole - \nCREATE_COMPLETE AWS::IAM::Role HelloWorldFunctionRole - \nCREATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction - \nCREATE_COMPLETE AWS::Lambda::Function HelloWorldFunction - \nCREATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction Resource creation Initiated \nCREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi - \nCREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi Resource creation Initiated \nCREATE_COMPLETE AWS::ApiGateway::RestApi ServerlessRestApi - \nCREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d Resource creation Initiated \nCREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd Resource creation Initiated \nCREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd - \nCREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d - \nCREATE_COMPLETE AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5f9d - \nCREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdStage Resource creation Initiated \nCREATE_IN_PROGRESS AWS::ApiGateway::Stage ServerlessRestApiProdStage - \nCREATE_COMPLETE AWS::ApiGateway::Stage ServerlessRestApiProdStage - \nCREATE_COMPLETE AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermissionProd - \nCREATE_COMPLETE AWS::CloudFormation::Stack hello-world-sam-application - \n-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nCloudFormation outputs from deployed stack\n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nOutputs \n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nKey HelloWorldFunctionIamRole \nDescription Implicit IAM Role created for Hello World function \nValue arn:aws:iam::816569674899:role/hello-world-sam-application-HelloWorldFunctionRole-NAYYRTABIVUF \nKey HelloWorldApi \nDescription API Gateway endpoint URL for Prod stage for Hello World function \nValue https://6v73c82ade.execute-api.us-west-2.amazonaws.com/Prod/hello/ \nKey HelloWorldFunction \nDescription Hello World Lambda Function ARN \nValue arn:aws:lambda:us-west-2:816569674899:function:hello-world-sam-application-HelloWorldFunction-dAjHSaNEq6pl \n--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\nSuccessfully created/updated stack - hello-world-sam-application in us-west-2\n" }, { "code": null, "e": 19736, "s": 19673, "text": "If everything went well you can see the above success message." }, { "code": null, "e": 19821, "s": 19736, "text": "Login to your AWS account-> Switch to Lambda-> Select the lambda-> Code Source-> Run" }, { "code": null, "e": 19844, "s": 19821, "text": "Export AWS credentials" }, { "code": null, "e": 19860, "s": 19844, "text": "More on AWS SAM" }, { "code": null, "e": 19877, "s": 19860, "text": "Happy Learning πŸ™‚" }, { "code": null, "e": 20493, "s": 19877, "text": "\nHow to install AWS CLI on Windows 10\nHow set AWS Access Keys in Windows or Mac Environment\nHow to Copy Local Files to AWS EC2 instance Manually ?\nHow to connect AWS EC2 Instance using PuTTY\nLambda Expressions in Java\nWhat are Lambda Expressions in Java 8\nDifferent ways to use Lambdas in Python\nAngularJs Directive Example Tutorials\nHow add files to S3 Bucket using Shell Script\nPython Django Helloworld Example\nWhat are the different ways to Sort Objects in Python ?\nAngularjs Services Example Tutorials\nHow to use *args and **kwargs in Python\nWhat are the List of Python Keywords\nAngularjs Custom Filter Example\n" }, { "code": null, "e": 20530, "s": 20493, "text": "How to install AWS CLI on Windows 10" }, { "code": null, "e": 20584, "s": 20530, "text": "How set AWS Access Keys in Windows or Mac Environment" }, { "code": null, "e": 20639, "s": 20584, "text": "How to Copy Local Files to AWS EC2 instance Manually ?" }, { "code": null, "e": 20683, "s": 20639, "text": "How to connect AWS EC2 Instance using PuTTY" }, { "code": null, "e": 20710, "s": 20683, "text": "Lambda Expressions in Java" }, { "code": null, "e": 20748, "s": 20710, "text": "What are Lambda Expressions in Java 8" }, { "code": null, "e": 20788, "s": 20748, "text": "Different ways to use Lambdas in Python" }, { "code": null, "e": 20826, "s": 20788, "text": "AngularJs Directive Example Tutorials" }, { "code": null, "e": 20872, "s": 20826, "text": "How add files to S3 Bucket using Shell Script" }, { "code": null, "e": 20905, "s": 20872, "text": "Python Django Helloworld Example" }, { "code": null, "e": 20961, "s": 20905, "text": "What are the different ways to Sort Objects in Python ?" }, { "code": null, "e": 20998, "s": 20961, "text": "Angularjs Services Example Tutorials" }, { "code": null, "e": 21038, "s": 20998, "text": "How to use *args and **kwargs in Python" }, { "code": null, "e": 21075, "s": 21038, "text": "What are the List of Python Keywords" }, { "code": null, "e": 21107, "s": 21075, "text": "Angularjs Custom Filter Example" }, { "code": null, "e": 21113, "s": 21111, "text": "Ξ”" }, { "code": null, "e": 21137, "s": 21113, "text": " Install Java on Mac OS" }, { "code": null, "e": 21165, "s": 21137, "text": " Install AWS CLI on Windows" }, { "code": null, "e": 21194, "s": 21165, "text": " Install Minikube on Windows" }, { "code": null, "e": 21229, "s": 21194, "text": " Install Docker Toolbox on Windows" }, { "code": null, "e": 21256, "s": 21229, "text": " Install SOAPUI on Windows" }, { "code": null, "e": 21283, "s": 21256, "text": " Install Gradle on Windows" }, { "code": null, "e": 21312, "s": 21283, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 21338, "s": 21312, "text": " Install PuTTY on windows" }, { "code": null, "e": 21364, "s": 21338, "text": " Install Mysql on Windows" }, { "code": null, "e": 21400, "s": 21364, "text": " Install Hibernate Tools in Eclipse" }, { "code": null, "e": 21434, "s": 21400, "text": " Install Elasticsearch on Windows" }, { "code": null, "e": 21460, "s": 21434, "text": " Install Maven on Windows" }, { "code": null, "e": 21485, "s": 21460, "text": " Install Maven on Ubuntu" }, { "code": null, "e": 21519, "s": 21485, "text": " Install Maven on Windows Command" }, { "code": null, "e": 21554, "s": 21519, "text": " Add OJDBC jar to Maven Repository" }, { "code": null, "e": 21578, "s": 21554, "text": " Install Ant on Windows" }, { "code": null, "e": 21607, "s": 21578, "text": " Install RabbitMQ on Windows" }, { "code": null, "e": 21639, "s": 21607, "text": " Install Apache Kafka on Ubuntu" } ]
WebSockets - Closing a Connection
Close event marks the end of a communication between the server and the client. Closing a connection is possible with the help of onclose event. After marking the end of communication with the help of onclose event, no messages can be further transferred between the server and the client. Closing the event can occur due to poor connectivity as well. The close() method stands for goodbye handshake. It terminates the connection and no data can be exchanged unless the connection opens again. Similar to the previous example, we call the close() method when the user clicks on the second button. var textView = document.getElementById("text-view"); var buttonStop = document.getElementById("stop-button"); buttonStop.onclick = function() { // Close the connection, if open. if (socket.readyState === WebSocket.OPEN) { socket.close(); } } It is also possible to pass the code and reason parameters we mentioned earlier as shown below. socket.close(1000, "Deliberate disconnection"); The following code gives a complete overview of how to close or disconnect a Web Socket connection βˆ’ <!DOCTYPE html> <html> <meta charset = "utf-8" /> <title>WebSocket Test</title> <script language = "javascript" type = "text/javascript"> var wsUri = "ws://echo.websocket.org/"; var output; function init() { output = document.getElementById("output"); testWebSocket(); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; } function onOpen(evt) { writeToScreen("CONNECTED"); doSend("WebSocket rocks"); } function onClose(evt) { writeToScreen("DISCONNECTED"); } function onMessage(evt) { writeToScreen('<span style = "color: blue;">RESPONSE: ' + evt.data+'</span>'); websocket.close(); } function onError(evt) { writeToScreen('<span style = "color: red;">ERROR:</span> ' + evt.data); } function doSend(message) { writeToScreen("SENT: " + message); websocket.send(message); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; output.appendChild(pre); } window.addEventListener("load", init, false); </script> <h2>WebSocket Test</h2> <div id = "output"></div> </html> The output is as follows βˆ’ Print Add Notes Bookmark this page
[ { "code": null, "e": 2471, "s": 2119, "text": "Close event marks the end of a communication between the server and the client. Closing a connection is possible with the help of onclose event. After marking the end of communication with the help of onclose event, no messages can be further transferred between the server and the client. Closing the event can occur due to poor connectivity as well." }, { "code": null, "e": 2613, "s": 2471, "text": "The close() method stands for goodbye handshake. It terminates the connection and no data can be exchanged unless the connection opens again." }, { "code": null, "e": 2716, "s": 2613, "text": "Similar to the previous example, we call the close() method when the user clicks on the second button." }, { "code": null, "e": 2974, "s": 2716, "text": "var textView = document.getElementById(\"text-view\");\nvar buttonStop = document.getElementById(\"stop-button\");\n\nbuttonStop.onclick = function() {\n // Close the connection, if open.\n if (socket.readyState === WebSocket.OPEN) {\n socket.close();\n }\n}" }, { "code": null, "e": 3070, "s": 2974, "text": "It is also possible to pass the code and reason parameters we mentioned earlier as shown below." }, { "code": null, "e": 3119, "s": 3070, "text": "socket.close(1000, \"Deliberate disconnection\");\n" }, { "code": null, "e": 3220, "s": 3119, "text": "The following code gives a complete overview of how to close or disconnect a Web Socket connection βˆ’" }, { "code": null, "e": 4921, "s": 3220, "text": "<!DOCTYPE html>\n<html>\n <meta charset = \"utf-8\" />\n <title>WebSocket Test</title>\n\n <script language = \"javascript\" type = \"text/javascript\">\n var wsUri = \"ws://echo.websocket.org/\";\n var output;\n\t\n function init() {\n output = document.getElementById(\"output\");\n testWebSocket();\n }\n\t\n function testWebSocket() {\n websocket = new WebSocket(wsUri);\n\t\t\n websocket.onopen = function(evt) {\n onOpen(evt)\n };\n\t\t\n websocket.onclose = function(evt) {\n onClose(evt)\n };\n\t\t\n websocket.onmessage = function(evt) {\n onMessage(evt)\n };\n\t\t\n websocket.onerror = function(evt) {\n onError(evt)\n };\n }\n\t\n function onOpen(evt) {\n writeToScreen(\"CONNECTED\");\n doSend(\"WebSocket rocks\");\n }\n\t\n function onClose(evt) {\n writeToScreen(\"DISCONNECTED\");\n }\n\t\n function onMessage(evt) {\n writeToScreen('<span style = \"color: blue;\">RESPONSE: ' + \n evt.data+'</span>'); websocket.close();\n }\n\t\n function onError(evt) {\n writeToScreen('<span style = \"color: red;\">ERROR:</span> '\n + evt.data);\n } \n\t\n function doSend(message) {\n writeToScreen(\"SENT: \" + message); websocket.send(message);\n }\n\t\n function writeToScreen(message) {\n var pre = document.createElement(\"p\"); \n pre.style.wordWrap = \"break-word\"; \n pre.innerHTML = message; \n output.appendChild(pre);\n }\n\t\n window.addEventListener(\"load\", init, false);\n </script>\n\t\n <h2>WebSocket Test</h2>\n <div id = \"output\"></div>\n\t\n</html>" }, { "code": null, "e": 4948, "s": 4921, "text": "The output is as follows βˆ’" }, { "code": null, "e": 4955, "s": 4948, "text": " Print" }, { "code": null, "e": 4966, "s": 4955, "text": " Add Notes" } ]
Find position of an element in a sorted array of infinite numbers - GeeksforGeeks
17 Aug, 2021 Suppose you have a sorted array of infinite numbers, how would you search an element in the array?Source: Amazon Interview Experience. Since array is sorted, the first thing clicks into mind is binary search, but the problem here is that we don’t know size of array. If the array is infinite, that means we don’t have proper bounds to apply binary search. So in order to find position of key, first we find bounds and then apply binary search algorithm.Let low be pointing to 1st element and high pointing to 2nd element of array, Now compare key with high index element, ->if it is greater than high index element then copy high index in low index and double the high index. ->if it is smaller, then apply binary search on high and low indices found. Below are implementations of above algorithm C++ Java Python3 C# PHP Javascript // C++ program to demonstrate working of an algorithm that finds// an element in an array of infinite size#include<bits/stdc++.h>using namespace std; // Simple binary search algorithmint binarySearch(int arr[], int l, int r, int x){ if (r>=l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1;} // function takes an infinite size array and a key to be// searched and returns its position if found else -1.// We don't know size of arr[] and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGint findPos(int arr[], int key){ int l = 0, h = 1; int val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high h = 2*h; // double high index val = arr[h]; // update new val } // at this point we have updated low and // high indices, Thus use binary search // between them return binarySearch(arr, l, h, key);} // Driver programint main(){ int arr[] = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int ans = findPos(arr, 10); if (ans==-1) cout << "Element not found"; else cout << "Element found at index " << ans; return 0;} // Java program to demonstrate working of// an algorithm that finds an element in an// array of infinite size class Test{ // Simple binary search algorithm static int binarySearch(int arr[], int l, int r, int x) { if (r>=l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1; } // Method takes an infinite size array and a key to be // searched and returns its position if found else -1. // We don't know size of arr[] and we can assume size to be // infinite in this function. // NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE // THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING static int findPos(int arr[],int key) { int l = 0, h = 1; int val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high //check that 2*h doesn't exceeds array //length to prevent ArrayOutOfBoundException if(2*h < arr.length-1) h = 2*h; else h = arr.length-1; val = arr[h]; // update new val } // at this point we have updated low // and high indices, thus use binary // search between them return binarySearch(arr, l, h, key); } // Driver method to test the above function public static void main(String[] args) { int arr[] = new int[]{3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int ans = findPos(arr,10); if (ans==-1) System.out.println("Element not found"); else System.out.println("Element found at index " + ans); }} # Python Program to demonstrate working of an algorithm that finds# an element in an array of infinite size # Binary search algorithm implementationdef binary_search(arr,l,r,x): if r >= l: mid = l+(r-l)//2 if arr[mid] == x: return mid if arr[mid] > x: return binary_search(arr,l,mid-1,x) return binary_search(arr,mid+1,r,x) return -1 # function takes an infinite size array and a key to be# searched and returns its position if found else -1.# We don't know size of a[] and we can assume size to be# infinite in this function.# NOTE THAT THIS FUNCTION ASSUMES a[] TO BE OF INFINITE SIZE# THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGdef findPos(a, key): l, h, val = 0, 1, arr[0] # Find h to do binary search while val < key: l = h #store previous high h = 2*h #double high index val = arr[h] #update new val # at this point we have updated low and high indices, # thus use binary search between them return binary_search(a, l, h, key) # Driver functionarr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]ans = findPos(arr,10)if ans == -1: print ("Element not found")else: print("Element found at index",ans) // C# program to demonstrate working of an// algorithm that finds an element in an// array of infinite sizeusing System; class GFG { // Simple binary search algorithm static int binarySearch(int []arr, int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1; } // Method takes an infinite size array // and a key to be searched and returns // its position if found else -1. We // don't know size of arr[] and we can // assume size to be infinite in this // function. // NOTE THAT THIS FUNCTION ASSUMES // arr[] TO BE OF INFINITE SIZE // THEREFORE, THERE IS NO INDEX OUT // OF BOUND CHECKING static int findPos(int []arr,int key) { int l = 0, h = 1; int val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high h = 2 * h;// double high index val = arr[h]; // update new val } // at this point we have updated low // and high indices, thus use binary // search between them return binarySearch(arr, l, h, key); } // Driver method to test the above // function public static void Main() { int []arr = new int[]{3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int ans = findPos(arr, 10); if (ans == -1) Console.Write("Element not found"); else Console.Write("Element found at " + "index " + ans); }} // This code is contributed by nitin mittal. <?php// PHP program to demonstrate working// of an algorithm that finds an// element in an array of infinite size // Simple binary search algorithmfunction binarySearch($arr, $l, $r, $x){ if ($r >= $l) { $mid = $l + ($r - $l)/2; if ($arr[$mid] == $x) return $mid; if ($arr[$mid] > $x) return binarySearch($arr, $l, $mid - 1, $x); return binarySearch($arr, $mid + 1, $r, $x); } return -1;} // function takes an infinite// size array and a key to be// searched and returns its// position if found else -1.// We don't know size of arr[]// and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES// arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX// OUT OF BOUND CHECKINGfunction findPos( $arr, $key){ $l = 0; $h = 1; $val = $arr[0]; // Find h to do binary search while ($val < $key) { // store previous high $l = $h; // double high index $h = 2 * $h; // update new val $val = $arr[$h]; } // at this point we have // updated low and high // indices, Thus use binary // search between them return binarySearch($arr, $l, $h, $key);} // Driver Code $arr = array(3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170); $ans = findPos($arr, 10); if ($ans==-1) echo "Element not found"; else echo "Element found at index " , $ans; // This code is contributed by anuj_67.?> <script>// JavaScript program to demonstrate working of an algorithm that finds// an element in an array of infinite size // Simple binary search algorithmfunction binarySearch(arr, l, r, x){ if (r>=l) { let mid = l + Math.floor((r - l)/2); if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1;} // function takes an infinite size array and a key to be// searched and returns its position if found else -1.// We don't know size of arr[] and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGfunction findPos(arr, key){ let l = 0, h = 1; let val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high h = 2*h; // double high index val = arr[h]; // update new val } // at this point we have updated low and // high indices, Thus use binary search // between them return binarySearch(arr, l, h, key);} // Driver program let arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]; let ans = findPos(arr, 10); if (ans==-1) document.write("Element not found"); else document.write("Element found at index " + ans); // This code is contributed by Surbhi Tyagi.</script> Output: Element found at index 4 Let p be the position of element to be searched. Number of steps for finding high index β€˜h’ is O(Log p). The value of β€˜h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal vt_m shivamgoel009 UnniKrishnan5 surbhityagi15 dibyasadhukhan Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find largest element in an array Given an array of size n and a number k, find all elements that appear more than n/k times Search an element in a sorted and rotated array k largest(or smallest) elements in an array Median of two sorted arrays of different sizes Find the index of an array element in Java Most frequent element in an array Count number of occurrences (or frequency) in a sorted array Two Pointers Technique Best First Search (Informed Search)
[ { "code": null, "e": 25044, "s": 25016, "text": "\n17 Aug, 2021" }, { "code": null, "e": 25798, "s": 25044, "text": "Suppose you have a sorted array of infinite numbers, how would you search an element in the array?Source: Amazon Interview Experience. Since array is sorted, the first thing clicks into mind is binary search, but the problem here is that we don’t know size of array. If the array is infinite, that means we don’t have proper bounds to apply binary search. So in order to find position of key, first we find bounds and then apply binary search algorithm.Let low be pointing to 1st element and high pointing to 2nd element of array, Now compare key with high index element, ->if it is greater than high index element then copy high index in low index and double the high index. ->if it is smaller, then apply binary search on high and low indices found. " }, { "code": null, "e": 25844, "s": 25798, "text": "Below are implementations of above algorithm " }, { "code": null, "e": 25848, "s": 25844, "text": "C++" }, { "code": null, "e": 25853, "s": 25848, "text": "Java" }, { "code": null, "e": 25861, "s": 25853, "text": "Python3" }, { "code": null, "e": 25864, "s": 25861, "text": "C#" }, { "code": null, "e": 25868, "s": 25864, "text": "PHP" }, { "code": null, "e": 25879, "s": 25868, "text": "Javascript" }, { "code": "// C++ program to demonstrate working of an algorithm that finds// an element in an array of infinite size#include<bits/stdc++.h>using namespace std; // Simple binary search algorithmint binarySearch(int arr[], int l, int r, int x){ if (r>=l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1;} // function takes an infinite size array and a key to be// searched and returns its position if found else -1.// We don't know size of arr[] and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGint findPos(int arr[], int key){ int l = 0, h = 1; int val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high h = 2*h; // double high index val = arr[h]; // update new val } // at this point we have updated low and // high indices, Thus use binary search // between them return binarySearch(arr, l, h, key);} // Driver programint main(){ int arr[] = {3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int ans = findPos(arr, 10); if (ans==-1) cout << \"Element not found\"; else cout << \"Element found at index \" << ans; return 0;}", "e": 27355, "s": 25879, "text": null }, { "code": "// Java program to demonstrate working of// an algorithm that finds an element in an// array of infinite size class Test{ // Simple binary search algorithm static int binarySearch(int arr[], int l, int r, int x) { if (r>=l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1; } // Method takes an infinite size array and a key to be // searched and returns its position if found else -1. // We don't know size of arr[] and we can assume size to be // infinite in this function. // NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE // THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING static int findPos(int arr[],int key) { int l = 0, h = 1; int val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high //check that 2*h doesn't exceeds array //length to prevent ArrayOutOfBoundException if(2*h < arr.length-1) h = 2*h; else h = arr.length-1; val = arr[h]; // update new val } // at this point we have updated low // and high indices, thus use binary // search between them return binarySearch(arr, l, h, key); } // Driver method to test the above function public static void main(String[] args) { int arr[] = new int[]{3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int ans = findPos(arr,10); if (ans==-1) System.out.println(\"Element not found\"); else System.out.println(\"Element found at index \" + ans); }}", "e": 29266, "s": 27355, "text": null }, { "code": "# Python Program to demonstrate working of an algorithm that finds# an element in an array of infinite size # Binary search algorithm implementationdef binary_search(arr,l,r,x): if r >= l: mid = l+(r-l)//2 if arr[mid] == x: return mid if arr[mid] > x: return binary_search(arr,l,mid-1,x) return binary_search(arr,mid+1,r,x) return -1 # function takes an infinite size array and a key to be# searched and returns its position if found else -1.# We don't know size of a[] and we can assume size to be# infinite in this function.# NOTE THAT THIS FUNCTION ASSUMES a[] TO BE OF INFINITE SIZE# THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGdef findPos(a, key): l, h, val = 0, 1, arr[0] # Find h to do binary search while val < key: l = h #store previous high h = 2*h #double high index val = arr[h] #update new val # at this point we have updated low and high indices, # thus use binary search between them return binary_search(a, l, h, key) # Driver functionarr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]ans = findPos(arr,10)if ans == -1: print (\"Element not found\")else: print(\"Element found at index\",ans)", "e": 30513, "s": 29266, "text": null }, { "code": "// C# program to demonstrate working of an// algorithm that finds an element in an// array of infinite sizeusing System; class GFG { // Simple binary search algorithm static int binarySearch(int []arr, int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1; } // Method takes an infinite size array // and a key to be searched and returns // its position if found else -1. We // don't know size of arr[] and we can // assume size to be infinite in this // function. // NOTE THAT THIS FUNCTION ASSUMES // arr[] TO BE OF INFINITE SIZE // THEREFORE, THERE IS NO INDEX OUT // OF BOUND CHECKING static int findPos(int []arr,int key) { int l = 0, h = 1; int val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high h = 2 * h;// double high index val = arr[h]; // update new val } // at this point we have updated low // and high indices, thus use binary // search between them return binarySearch(arr, l, h, key); } // Driver method to test the above // function public static void Main() { int []arr = new int[]{3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170}; int ans = findPos(arr, 10); if (ans == -1) Console.Write(\"Element not found\"); else Console.Write(\"Element found at \" + \"index \" + ans); }} // This code is contributed by nitin mittal.", "e": 32480, "s": 30513, "text": null }, { "code": "<?php// PHP program to demonstrate working// of an algorithm that finds an// element in an array of infinite size // Simple binary search algorithmfunction binarySearch($arr, $l, $r, $x){ if ($r >= $l) { $mid = $l + ($r - $l)/2; if ($arr[$mid] == $x) return $mid; if ($arr[$mid] > $x) return binarySearch($arr, $l, $mid - 1, $x); return binarySearch($arr, $mid + 1, $r, $x); } return -1;} // function takes an infinite// size array and a key to be// searched and returns its// position if found else -1.// We don't know size of arr[]// and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES// arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX// OUT OF BOUND CHECKINGfunction findPos( $arr, $key){ $l = 0; $h = 1; $val = $arr[0]; // Find h to do binary search while ($val < $key) { // store previous high $l = $h; // double high index $h = 2 * $h; // update new val $val = $arr[$h]; } // at this point we have // updated low and high // indices, Thus use binary // search between them return binarySearch($arr, $l, $h, $key);} // Driver Code $arr = array(3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170); $ans = findPos($arr, 10); if ($ans==-1) echo \"Element not found\"; else echo \"Element found at index \" , $ans; // This code is contributed by anuj_67.?>", "e": 34100, "s": 32480, "text": null }, { "code": "<script>// JavaScript program to demonstrate working of an algorithm that finds// an element in an array of infinite size // Simple binary search algorithmfunction binarySearch(arr, l, r, x){ if (r>=l) { let mid = l + Math.floor((r - l)/2); if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearch(arr, l, mid-1, x); return binarySearch(arr, mid+1, r, x); } return -1;} // function takes an infinite size array and a key to be// searched and returns its position if found else -1.// We don't know size of arr[] and we can assume size to be// infinite in this function.// NOTE THAT THIS FUNCTION ASSUMES arr[] TO BE OF INFINITE SIZE// THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKINGfunction findPos(arr, key){ let l = 0, h = 1; let val = arr[0]; // Find h to do binary search while (val < key) { l = h; // store previous high h = 2*h; // double high index val = arr[h]; // update new val } // at this point we have updated low and // high indices, Thus use binary search // between them return binarySearch(arr, l, h, key);} // Driver program let arr = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170]; let ans = findPos(arr, 10); if (ans==-1) document.write(\"Element not found\"); else document.write(\"Element found at index \" + ans); // This code is contributed by Surbhi Tyagi.</script>", "e": 35578, "s": 34100, "text": null }, { "code": null, "e": 35588, "s": 35578, "text": "Output: " }, { "code": null, "e": 35613, "s": 35588, "text": "Element found at index 4" }, { "code": null, "e": 36110, "s": 35613, "text": "Let p be the position of element to be searched. Number of steps for finding high index β€˜h’ is O(Log p). The value of β€˜h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36123, "s": 36110, "text": "nitin mittal" }, { "code": null, "e": 36128, "s": 36123, "text": "vt_m" }, { "code": null, "e": 36142, "s": 36128, "text": "shivamgoel009" }, { "code": null, "e": 36156, "s": 36142, "text": "UnniKrishnan5" }, { "code": null, "e": 36170, "s": 36156, "text": "surbhityagi15" }, { "code": null, "e": 36185, "s": 36170, "text": "dibyasadhukhan" }, { "code": null, "e": 36195, "s": 36185, "text": "Searching" }, { "code": null, "e": 36205, "s": 36195, "text": "Searching" }, { "code": null, "e": 36303, "s": 36205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36347, "s": 36303, "text": "Program to find largest element in an array" }, { "code": null, "e": 36438, "s": 36347, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 36486, "s": 36438, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 36530, "s": 36486, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 36577, "s": 36530, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 36620, "s": 36577, "text": "Find the index of an array element in Java" }, { "code": null, "e": 36654, "s": 36620, "text": "Most frequent element in an array" }, { "code": null, "e": 36715, "s": 36654, "text": "Count number of occurrences (or frequency) in a sorted array" }, { "code": null, "e": 36738, "s": 36715, "text": "Two Pointers Technique" } ]
Check if an array can be divided into pairs whose sum is divisible by k - GeeksforGeeks
02 Mar, 2022 Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k. Examples: Input: arr[] = {9, 7, 5, 3}, k = 6 Output: True We can divide the array into (9, 3) and (7, 5). Sum of both of these pairs is a multiple of 6. Input: arr[] = {92, 75, 65, 48, 45, 35}, k = 10 Output: True We can divide the array into (92, 48), (75, 65). and (45, 35). The sum of all these pairs is a multiple of 10. Input: arr[] = {91, 74, 66, 48}, k = 10 Output: False A Simple Solution is to iterate through every element arr[i]. Find if there is another not yet visited element that has a remainder like (k – arr[i]%k). If there is no such element, return false. If a pair is found, then mark both elements as visited. The time complexity of this solution is O(n2 and it requires O(n) extra space. An Efficient Solution is to use Hashing. 1) If length of given array is odd, return false. An odd length array cannot be divided into pairs. 2) Traverse input array and count occurrences of all remainders (use (arr[i] % k)+k)%k for handling the case of negative integers as well). freq[((arr[i] % k)+k)%k]++ 3) Traverse input array again. a) Find the remainder of the current element. b) If remainder divides k into two halves, then there must be even occurrences of it as it forms pair with itself only. c) If the remainder is 0, then there must be even occurrences. d) Else, number of occurrences of current the remainder must be equal to a number of occurrences of "k - current remainder". An efficient approach is to use hashing (unordered_map in C++ and HashMap in Java). The below image is a dry run of the above approach: Below is the implementation of the above approach: C++ Java Python3 C# Javascript // A C++ program to check if arr[0..n-1] can be divided// in pairs such that every pair is divisible by k.#include <bits/stdc++.h>using namespace std; // Returns true if arr[0..n-1] can be divided into pairs// with sum divisible by k.bool canPairs(int arr[], int n, int k){ // An odd length array cannot be divided into pairs if (n & 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. unordered_map<int, int> freq; // Count occurrences of all remainders for (int i = 0; i < n; i++) freq[((arr[i] % k) + k) % k]++; // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (int i = 0; i < n; i++) { // Remainder of current element int rem = ((arr[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (freq[rem] % 2 != 0) return false; } // If remainder is 0, then there must be even // number of elements with 0 remainder else if (rem == 0) { if (freq[rem] & 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else if (freq[rem] != freq[k - rem]) return false; } return true;} // Driver codeint main(){ int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call canPairs(arr, n, k) ? cout << "True" : cout << "False"; return 0;} // JAVA program to check if arr[0..n-1] can be divided// in pairs such that every pair is divisible by k.import java.util.HashMap;public class Divisiblepair { // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. static boolean canPairs(int ar[], int k) { // An odd length array cannot be divided into pairs if (ar.length % 2 == 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. HashMap<Integer, Integer> hm = new HashMap<>(); // Count occurrences of all remainders for (int i = 0; i < ar.length; i++) { int rem = ((ar[i] % k) + k) % k; if (!hm.containsKey(rem)) { hm.put(rem, 0); } hm.put(rem, hm.get(rem) + 1); } // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (int i = 0; i < ar.length; i++) { // Remainder of current element int rem = ((ar[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // If remainder is 0, then there must be two // elements with 0 remainder else if (rem == 0) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm.get(k - rem) != hm.get(rem)) return false; } } return true; } // Driver code public static void main(String[] args) { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; // Function call boolean ans = canPairs(arr, k); if (ans) System.out.println("True"); else System.out.println("False"); }} // This code is contributed by Rishabh Mahrsee # Python3 program to check if# arr[0..n-1] can be divided# in pairs such that every# pair is divisible by k.from collections import defaultdict # Returns true if arr[0..n-1] can be# divided into pairs with sum# divisible by k. def canPairs(arr, n, k): # An odd length array cannot # be divided into pairs if (n & 1): return 0 # Create a frequency array to # count occurrences of all # remainders when divided by k. freq = defaultdict(lambda: 0) # Count occurrences of all remainders for i in range(0, n): freq[((arr[i] % k) + k) % k] += 1 # Traverse input array and use # freq[] to decide if given array # can be divided in pairs for i in range(0, n): # Remainder of current element rem = ((arr[i] % k) + k) % k # If remainder with current element # divides k into two halves. if (2 * rem == k): # Then there must be even occurrences # of such remainder if (freq[rem] % 2 != 0): return 0 # If remainder is 0, then there # must be two elements with 0 remainder else if (rem == 0): if (freq[rem] & 1): return 0 # Else number of occurrences of # remainder must be equal to # number of occurrences of # k - remainder else if (freq[rem] != freq[k - rem]): return 0 return 1 # Driver codearr = [92, 75, 65, 48, 45, 35]k = 10n = len(arr) # Function callif (canPairs(arr, n, k)): print("True")else: print("False") # This code is contributed by Stream_Cipher // C# program to check if arr[0..n-1]// can be divided in pairs such that// every pair is divisible by k.using System.Collections.Generic;using System; class GFG { // Returns true if arr[0..n-1] can be // divided into pairs with sum // divisible by k. static bool canPairs(int[] ar, int k) { // An odd length array cannot // be divided into pairs if (ar.Length % 2 == 1) return false; // Create a frequency array to count // occurrences of all remainders when // divided by k. Dictionary<Double, int> hm = new Dictionary<Double, int>(); // Count occurrences of all remainders for (int i = 0; i < ar.Length; i++) { int rem = ((ar[i] % k) + k) % k; if (!hm.ContainsKey(rem)) { hm[rem] = 0; } hm[rem]++; } // Traverse input array and use freq[] // to decide if given array can be // divided in pairs for (int i = 0; i < ar.Length; i++) { // Remainder of current element int rem = ((ar[i] % k) + k) % k; // If remainder with current element // divides k into two halves. if (2 * rem == k) { // Then there must be even occurrences // of such remainder if (hm[rem] % 2 == 1) return false; } // If remainder is 0, then there // must be two elements with 0 // remainder else if (rem == 0) { // Then there must be even occurrences // of such remainder if (hm[rem] % 2 == 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm[k - rem] != hm[rem]) return false; } } return true; } // Driver code public static void Main() { int[] arr = { 92, 75, 65, 48, 45, 35 }; int k = 10; // Function call bool ans = canPairs(arr, k); if (ans) Console.WriteLine("True"); else Console.WriteLine("False"); }} // This code is contributed by Stream_Cipher <script> // Javascript program to check if arr[0..n-1] can be divided// in pairs such that every pair is divisible by k. // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. function canPairs(ar, k) { // An odd length array cannot be divided into pairs if (ar.length % 2 == 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. let hm = new Map(); // Count occurrences of all remainders for (let i = 0; i < ar.length; i++) { let rem = ((ar[i] % k) + k) % k; if (!hm.has(rem)) { hm.set(rem, 0); } hm.set(rem, hm.get(rem) + 1); } // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (let i = 0; i < ar.length; i++) { // Remainder of current element let rem = ((ar[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // If remainder is 0, then there must be two // elements with 0 remainder else if (rem == 0) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm.get(k - rem) != hm.get(rem)) return false; } } return true; } // Driver program let arr = [ 92, 75, 65, 48, 45, 35 ]; let k = 10; // Function call let ans = canPairs(arr, k); if (ans) document.write("True"); else document.write("False"); </script> True Time complexity: O(n). This article is contributed by Priyanka. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. bharatranjan Stream_Cipher palvaisaibharathreddy target_2 jacoboquinn374 takitachibana khushboogoyal499 simmytarika5 surinderdawra388 Amazon Directi STL Arrays Hash Amazon Directi Arrays Hash STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Introduction to Arrays Linear Search 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) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum
[ { "code": null, "e": 25172, "s": 25144, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25346, "s": 25172, "text": "Given an array of integers and a number k, write a function that returns true if the given array can be divided into pairs such that the sum of every pair is divisible by k." }, { "code": null, "e": 25357, "s": 25346, "text": "Examples: " }, { "code": null, "e": 25500, "s": 25357, "text": "Input: arr[] = {9, 7, 5, 3}, k = 6 Output: True We can divide the array into (9, 3) and (7, 5). Sum of both of these pairs is a multiple of 6." }, { "code": null, "e": 25672, "s": 25500, "text": "Input: arr[] = {92, 75, 65, 48, 45, 35}, k = 10 Output: True We can divide the array into (92, 48), (75, 65). and (45, 35). The sum of all these pairs is a multiple of 10." }, { "code": null, "e": 25727, "s": 25672, "text": "Input: arr[] = {91, 74, 66, 48}, k = 10 Output: False " }, { "code": null, "e": 26058, "s": 25727, "text": "A Simple Solution is to iterate through every element arr[i]. Find if there is another not yet visited element that has a remainder like (k – arr[i]%k). If there is no such element, return false. If a pair is found, then mark both elements as visited. The time complexity of this solution is O(n2 and it requires O(n) extra space." }, { "code": null, "e": 26099, "s": 26058, "text": "An Efficient Solution is to use Hashing." }, { "code": null, "e": 26815, "s": 26099, "text": "1) If length of given array is odd, return false. \n An odd length array cannot be divided into pairs.\n2) Traverse input array and count occurrences of \n all remainders (use (arr[i] % k)+k)%k for handling the case of negative integers as well). \n freq[((arr[i] % k)+k)%k]++\n3) Traverse input array again. \n a) Find the remainder of the current element.\n b) If remainder divides k into two halves, then\n there must be even occurrences of it as it \n forms pair with itself only.\n c) If the remainder is 0, then there must be \n even occurrences.\n d) Else, number of occurrences of current \n the remainder must be equal to a number of \n occurrences of \"k - current remainder\"." }, { "code": null, "e": 26899, "s": 26815, "text": "An efficient approach is to use hashing (unordered_map in C++ and HashMap in Java)." }, { "code": null, "e": 26951, "s": 26899, "text": "The below image is a dry run of the above approach:" }, { "code": null, "e": 27002, "s": 26951, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27006, "s": 27002, "text": "C++" }, { "code": null, "e": 27011, "s": 27006, "text": "Java" }, { "code": null, "e": 27019, "s": 27011, "text": "Python3" }, { "code": null, "e": 27022, "s": 27019, "text": "C#" }, { "code": null, "e": 27033, "s": 27022, "text": "Javascript" }, { "code": "// A C++ program to check if arr[0..n-1] can be divided// in pairs such that every pair is divisible by k.#include <bits/stdc++.h>using namespace std; // Returns true if arr[0..n-1] can be divided into pairs// with sum divisible by k.bool canPairs(int arr[], int n, int k){ // An odd length array cannot be divided into pairs if (n & 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. unordered_map<int, int> freq; // Count occurrences of all remainders for (int i = 0; i < n; i++) freq[((arr[i] % k) + k) % k]++; // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (int i = 0; i < n; i++) { // Remainder of current element int rem = ((arr[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (freq[rem] % 2 != 0) return false; } // If remainder is 0, then there must be even // number of elements with 0 remainder else if (rem == 0) { if (freq[rem] & 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else if (freq[rem] != freq[k - rem]) return false; } return true;} // Driver codeint main(){ int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call canPairs(arr, n, k) ? cout << \"True\" : cout << \"False\"; return 0;}", "e": 28747, "s": 27033, "text": null }, { "code": "// JAVA program to check if arr[0..n-1] can be divided// in pairs such that every pair is divisible by k.import java.util.HashMap;public class Divisiblepair { // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. static boolean canPairs(int ar[], int k) { // An odd length array cannot be divided into pairs if (ar.length % 2 == 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. HashMap<Integer, Integer> hm = new HashMap<>(); // Count occurrences of all remainders for (int i = 0; i < ar.length; i++) { int rem = ((ar[i] % k) + k) % k; if (!hm.containsKey(rem)) { hm.put(rem, 0); } hm.put(rem, hm.get(rem) + 1); } // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (int i = 0; i < ar.length; i++) { // Remainder of current element int rem = ((ar[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // If remainder is 0, then there must be two // elements with 0 remainder else if (rem == 0) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm.get(k - rem) != hm.get(rem)) return false; } } return true; } // Driver code public static void main(String[] args) { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; // Function call boolean ans = canPairs(arr, k); if (ans) System.out.println(\"True\"); else System.out.println(\"False\"); }} // This code is contributed by Rishabh Mahrsee", "e": 31075, "s": 28747, "text": null }, { "code": "# Python3 program to check if# arr[0..n-1] can be divided# in pairs such that every# pair is divisible by k.from collections import defaultdict # Returns true if arr[0..n-1] can be# divided into pairs with sum# divisible by k. def canPairs(arr, n, k): # An odd length array cannot # be divided into pairs if (n & 1): return 0 # Create a frequency array to # count occurrences of all # remainders when divided by k. freq = defaultdict(lambda: 0) # Count occurrences of all remainders for i in range(0, n): freq[((arr[i] % k) + k) % k] += 1 # Traverse input array and use # freq[] to decide if given array # can be divided in pairs for i in range(0, n): # Remainder of current element rem = ((arr[i] % k) + k) % k # If remainder with current element # divides k into two halves. if (2 * rem == k): # Then there must be even occurrences # of such remainder if (freq[rem] % 2 != 0): return 0 # If remainder is 0, then there # must be two elements with 0 remainder else if (rem == 0): if (freq[rem] & 1): return 0 # Else number of occurrences of # remainder must be equal to # number of occurrences of # k - remainder else if (freq[rem] != freq[k - rem]): return 0 return 1 # Driver codearr = [92, 75, 65, 48, 45, 35]k = 10n = len(arr) # Function callif (canPairs(arr, n, k)): print(\"True\")else: print(\"False\") # This code is contributed by Stream_Cipher", "e": 32692, "s": 31075, "text": null }, { "code": "// C# program to check if arr[0..n-1]// can be divided in pairs such that// every pair is divisible by k.using System.Collections.Generic;using System; class GFG { // Returns true if arr[0..n-1] can be // divided into pairs with sum // divisible by k. static bool canPairs(int[] ar, int k) { // An odd length array cannot // be divided into pairs if (ar.Length % 2 == 1) return false; // Create a frequency array to count // occurrences of all remainders when // divided by k. Dictionary<Double, int> hm = new Dictionary<Double, int>(); // Count occurrences of all remainders for (int i = 0; i < ar.Length; i++) { int rem = ((ar[i] % k) + k) % k; if (!hm.ContainsKey(rem)) { hm[rem] = 0; } hm[rem]++; } // Traverse input array and use freq[] // to decide if given array can be // divided in pairs for (int i = 0; i < ar.Length; i++) { // Remainder of current element int rem = ((ar[i] % k) + k) % k; // If remainder with current element // divides k into two halves. if (2 * rem == k) { // Then there must be even occurrences // of such remainder if (hm[rem] % 2 == 1) return false; } // If remainder is 0, then there // must be two elements with 0 // remainder else if (rem == 0) { // Then there must be even occurrences // of such remainder if (hm[rem] % 2 == 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm[k - rem] != hm[rem]) return false; } } return true; } // Driver code public static void Main() { int[] arr = { 92, 75, 65, 48, 45, 35 }; int k = 10; // Function call bool ans = canPairs(arr, k); if (ans) Console.WriteLine(\"True\"); else Console.WriteLine(\"False\"); }} // This code is contributed by Stream_Cipher", "e": 35041, "s": 32692, "text": null }, { "code": "<script> // Javascript program to check if arr[0..n-1] can be divided// in pairs such that every pair is divisible by k. // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. function canPairs(ar, k) { // An odd length array cannot be divided into pairs if (ar.length % 2 == 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. let hm = new Map(); // Count occurrences of all remainders for (let i = 0; i < ar.length; i++) { let rem = ((ar[i] % k) + k) % k; if (!hm.has(rem)) { hm.set(rem, 0); } hm.set(rem, hm.get(rem) + 1); } // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (let i = 0; i < ar.length; i++) { // Remainder of current element let rem = ((ar[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // If remainder is 0, then there must be two // elements with 0 remainder else if (rem == 0) { // Then there must be even occurrences of // such remainder if (hm.get(rem) % 2 == 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else { if (hm.get(k - rem) != hm.get(rem)) return false; } } return true; } // Driver program let arr = [ 92, 75, 65, 48, 45, 35 ]; let k = 10; // Function call let ans = canPairs(arr, k); if (ans) document.write(\"True\"); else document.write(\"False\"); </script>", "e": 37178, "s": 35041, "text": null }, { "code": null, "e": 37183, "s": 37178, "text": "True" }, { "code": null, "e": 37206, "s": 37183, "text": "Time complexity: O(n)." }, { "code": null, "e": 37372, "s": 37206, "text": "This article is contributed by Priyanka. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 37385, "s": 37372, "text": "bharatranjan" }, { "code": null, "e": 37399, "s": 37385, "text": "Stream_Cipher" }, { "code": null, "e": 37421, "s": 37399, "text": "palvaisaibharathreddy" }, { "code": null, "e": 37430, "s": 37421, "text": "target_2" }, { "code": null, "e": 37445, "s": 37430, "text": "jacoboquinn374" }, { "code": null, "e": 37459, "s": 37445, "text": "takitachibana" }, { "code": null, "e": 37476, "s": 37459, "text": "khushboogoyal499" }, { "code": null, "e": 37489, "s": 37476, "text": "simmytarika5" }, { "code": null, "e": 37506, "s": 37489, "text": "surinderdawra388" }, { "code": null, "e": 37513, "s": 37506, "text": "Amazon" }, { "code": null, "e": 37521, "s": 37513, "text": "Directi" }, { "code": null, "e": 37525, "s": 37521, "text": "STL" }, { "code": null, "e": 37532, "s": 37525, "text": "Arrays" }, { "code": null, "e": 37537, "s": 37532, "text": "Hash" }, { "code": null, "e": 37544, "s": 37537, "text": "Amazon" }, { "code": null, "e": 37552, "s": 37544, "text": "Directi" }, { "code": null, "e": 37559, "s": 37552, "text": "Arrays" }, { "code": null, "e": 37564, "s": 37559, "text": "Hash" }, { "code": null, "e": 37568, "s": 37564, "text": "STL" }, { "code": null, "e": 37666, "s": 37568, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37698, "s": 37666, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 37721, "s": 37698, "text": "Introduction to Arrays" }, { "code": null, "e": 37735, "s": 37721, "text": "Linear Search" }, { "code": null, "e": 37780, "s": 37735, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 37801, "s": 37780, "text": "Linked List vs Array" }, { "code": null, "e": 37886, "s": 37801, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 37922, "s": 37886, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 37953, "s": 37922, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 37987, "s": 37953, "text": "Hashing | Set 3 (Open Addressing)" } ]
Struts 2 - The Property Tag
The property tag is used to get the property of a value, which will default to the top of the stack if none is specified. This example shows you the usage of three simple data tags - namely set, push and property. For this exercise, let us reuse examples given in "Data Type Conversion" chapter but with little modifications. So let us start with creating classes. Consider the following POJO class Environment.java. package com.tutorialspoint.struts2; public class Environment { private String name; public Environment(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Let us have following action class βˆ’ package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class SystemDetails extends ActionSupport { private Environment environment = new Environment("Development"); private String operatingSystem = "Windows XP SP3"; public String execute() { return SUCCESS; } public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; } public String getOperatingSystem() { return operatingSystem; } public void setOperatingSystem(String operatingSystem) { this.operatingSystem = operatingSystem; } } Let us have System.jsp with the following content βˆ’ <%@ 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>System Details</title> </head> <body> <p>The environment name property can be accessed in three ways:</p> (Method 1) Environment Name: <s:property value = "environment.name"/><br/> (Method 2) Environment Name: <s:push value = "environment"> <s:property value = "name"/><br/> </s:push> (Method 3) Environment Name: <s:set name = "myenv" value = "environment.name"/> <s:property value = "myenv"/> </body> </html> Let us now go through the three options one by one βˆ’ In the first method, we use the property tag to get the value of the environment's name. Since, the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the property environment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add "environment." as the prefix. This is where the push tag comes in handy. In the first method, we use the property tag to get the value of the environment's name. Since, the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the property environment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add "environment." as the prefix. This is where the push tag comes in handy. In the second method, we push the "environment" property to the stack. Therefore, now within the body of the push tag, the environment property is available at the root of the stack. From now, you can refer to the property quite easily as shown in the example. In the second method, we push the "environment" property to the stack. Therefore, now within the body of the push tag, the environment property is available at the root of the stack. From now, you can refer to the property quite easily as shown in the example. In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name. In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name. Your struts.xml should look like βˆ’ <?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 = "system" class = "com.tutorialspoint.struts2.SystemDetails" method = "execute"> <result name = "success">/System.jsp</result> </action> </package> </struts> Your web.xml should look like βˆ’ <?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> 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/system.action. This will produce the following screen βˆ’ Print Add Notes Bookmark this page
[ { "code": null, "e": 2460, "s": 2246, "text": "The property tag is used to get the property of a value, which will default to the top of the stack if none is specified. This example shows you the usage of three simple data tags - namely set, push and property." }, { "code": null, "e": 2663, "s": 2460, "text": "For this exercise, let us reuse examples given in \"Data Type Conversion\" chapter but with little modifications. So let us start with creating classes. Consider the following POJO class Environment.java." }, { "code": null, "e": 2948, "s": 2663, "text": "package com.tutorialspoint.struts2;\n\npublic class Environment {\n private String name;\n public Environment(String name) {\n this.name = name;\n }\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n}" }, { "code": null, "e": 2985, "s": 2948, "text": "Let us have following action class βˆ’" }, { "code": null, "e": 3675, "s": 2985, "text": "package com.tutorialspoint.struts2;\nimport com.opensymphony.xwork2.ActionSupport;\n\npublic class SystemDetails extends ActionSupport {\n private Environment environment = new Environment(\"Development\");\n private String operatingSystem = \"Windows XP SP3\";\n\n public String execute() {\n return SUCCESS;\n }\n \n public Environment getEnvironment() {\n return environment;\n }\n \n public void setEnvironment(Environment environment) {\n this.environment = environment;\n }\n \n public String getOperatingSystem() {\n return operatingSystem;\n }\n \n public void setOperatingSystem(String operatingSystem) {\n this.operatingSystem = operatingSystem;\n }\n}" }, { "code": null, "e": 3728, "s": 3675, "text": "Let us have System.jsp with the following content βˆ’" }, { "code": null, "e": 4521, "s": 3728, "text": "<%@ page language = \"java\" contentType = \"text/html; charset = ISO-8859-1\"\n\tpageEncoding = \"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>System Details</title>\n </head>\n \n <body> \n <p>The environment name property can be accessed in three ways:</p>\n\n (Method 1) Environment Name: \n <s:property value = \"environment.name\"/><br/>\n\n (Method 2) Environment Name: \n <s:push value = \"environment\">\n <s:property value = \"name\"/><br/>\n </s:push>\n\n (Method 3) Environment Name:\n <s:set name = \"myenv\" value = \"environment.name\"/>\n <s:property value = \"myenv\"/>\n \n </body>\n</html>" }, { "code": null, "e": 4574, "s": 4521, "text": "Let us now go through the three options one by one βˆ’" }, { "code": null, "e": 5107, "s": 4574, "text": "In the first method, we use the property tag to get the value of the environment's name. Since, the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the property environment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add \"environment.\" as the prefix. This is where the push tag comes in handy." }, { "code": null, "e": 5640, "s": 5107, "text": "In the first method, we use the property tag to get the value of the environment's name. Since, the environment variable is in the action class, it is automatically available in the value stack. We can directly refer to it using the property environment.name. Method 1 works fine, when you have limited number of properties in a class. Imagine if you have 20 properties in the Environment class. Every time you need to refer to these variables you need to add \"environment.\" as the prefix. This is where the push tag comes in handy." }, { "code": null, "e": 5901, "s": 5640, "text": "In the second method, we push the \"environment\" property to the stack. Therefore, now within the body of the push tag, the environment property is available at the root of the stack. From now, you can refer to the property quite easily as shown in the example." }, { "code": null, "e": 6162, "s": 5901, "text": "In the second method, we push the \"environment\" property to the stack. Therefore, now within the body of the push tag, the environment property is available at the root of the stack. From now, you can refer to the property quite easily as shown in the example." }, { "code": null, "e": 6369, "s": 6162, "text": "In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name." }, { "code": null, "e": 6576, "s": 6369, "text": "In the final method, we use the set tag to create a new variable called myenv. This variable's value is set to environment.name. So, now we can use this variable wherever we refer to the environment's name." }, { "code": null, "e": 6611, "s": 6576, "text": "Your struts.xml should look like βˆ’" }, { "code": null, "e": 7139, "s": 6611, "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 <action name = \"system\" \n class = \"com.tutorialspoint.struts2.SystemDetails\" \n method = \"execute\">\n <result name = \"success\">/System.jsp</result>\n </action>\n </package>\n</struts>" }, { "code": null, "e": 7171, "s": 7139, "text": "Your web.xml should look like βˆ’" }, { "code": null, "e": 7985, "s": 7171, "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": 8271, "s": 7985, "text": "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/system.action. This will produce the following screen βˆ’" }, { "code": null, "e": 8278, "s": 8271, "text": " Print" }, { "code": null, "e": 8289, "s": 8278, "text": " Add Notes" } ]
How to define methods in C#?
A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows βˆ’ <Access Specifier> <Return Type> <Method Name>(Parameter List) { Method Body } Here, Access Specifier βˆ’ This determines the visibility of a variable or a method from another class. Access Specifier βˆ’ This determines the visibility of a variable or a method from another class. Return type βˆ’ A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void. Return type βˆ’ A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void. Method name βˆ’ Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Method name βˆ’ Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Parameter list βˆ’ Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Parameter list βˆ’ Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Method body βˆ’ This contains the set of instructions needed to complete the required activity. Method body βˆ’ This contains the set of instructions needed to complete the required activity. The following is an example of methods showing how to find that a string has unique words or not. Here, we have created a C# method CheckUnique() βˆ’ Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Demo { public bool CheckUnique(string str) { string one = ""; string two = ""; for (int i = 0; i < str.Length; i++) { one = str.Substring(i, 1); for (int j = 0; j < str.Length; j++) { two = str.Substring(j, 1); if ((one == two) && (i != j)) return false; } } return true; } static void Main(string[] args) { Demo d = new Demo(); bool b = d.CheckUnique("amit"); Console.WriteLine(b); Console.ReadKey(); } } True
[ { "code": null, "e": 1192, "s": 1062, "text": "A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main." }, { "code": null, "e": 1326, "s": 1192, "text": "When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows βˆ’" }, { "code": null, "e": 1408, "s": 1326, "text": "<Access Specifier> <Return Type> <Method Name>(Parameter List) {\n Method Body\n}" }, { "code": null, "e": 1414, "s": 1408, "text": "Here," }, { "code": null, "e": 1510, "s": 1414, "text": "Access Specifier βˆ’ This determines the visibility of a variable or a method from another class." }, { "code": null, "e": 1606, "s": 1510, "text": "Access Specifier βˆ’ This determines the visibility of a variable or a method from another class." }, { "code": null, "e": 1788, "s": 1606, "text": "Return type βˆ’ A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void." }, { "code": null, "e": 1970, "s": 1788, "text": "Return type βˆ’ A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void." }, { "code": null, "e": 2110, "s": 1970, "text": "Method name βˆ’ Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class." }, { "code": null, "e": 2250, "s": 2110, "text": "Method name βˆ’ Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class." }, { "code": null, "e": 2519, "s": 2250, "text": "Parameter list βˆ’ Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters." }, { "code": null, "e": 2788, "s": 2519, "text": "Parameter list βˆ’ Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters." }, { "code": null, "e": 2882, "s": 2788, "text": "Method body βˆ’ This contains the set of instructions needed to complete the required activity." }, { "code": null, "e": 2976, "s": 2882, "text": "Method body βˆ’ This contains the set of instructions needed to complete the required activity." }, { "code": null, "e": 3124, "s": 2976, "text": "The following is an example of methods showing how to find that a string has unique words or not. Here, we have created a C# method CheckUnique() βˆ’" }, { "code": null, "e": 3135, "s": 3124, "text": " Live Demo" }, { "code": null, "e": 3803, "s": 3135, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\npublic class Demo {\n\n public bool CheckUnique(string str) {\n string one = \"\";\n string two = \"\";\n\n for (int i = 0; i < str.Length; i++) {\n one = str.Substring(i, 1);\n for (int j = 0; j < str.Length; j++) {\n two = str.Substring(j, 1);\n if ((one == two) && (i != j))\n return false;\n }\n }\n return true;\n }\n static void Main(string[] args) {\n Demo d = new Demo();\n bool b = d.CheckUnique(\"amit\");\n Console.WriteLine(b);\n\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 3808, "s": 3803, "text": "True" } ]
Delete a node in a Doubly Linked List in C++
In this tutorial, we are going to learn how to delete a node in doubly linked list. Let's see the steps to solve the problem. Write struct with data, prev and next pointers. Write struct with data, prev and next pointers. Write a function to insert the node into the doubly linked list. Write a function to insert the node into the doubly linked list. Initialize the doubly linked list with dummy data. Initialize the doubly linked list with dummy data. Take a node to delete. Take a node to delete. Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link. Let's see the code. Write a function to delete the node. Consider the following three cases while deleting the node. If the node is head node, then move the head to next node. If the node is head node, then move the head to next node. If the node is middle node, then link the next node to the previous node If the node is middle node, then link the next node to the previous node If the node is end node, then remove the previous node link. Let's see the code. If the node is end node, then remove the previous node link. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; struct Node { int data; Node *prev, *next; }; void deleteNode(Node** head_ref, Node* del) { if (*head_ref == NULL || del == NULL) { return; } if (*head_ref == del) { *head_ref = del->next; } if (del->next != NULL) { del->next->prev = del->prev; } if (del->prev != NULL) { del->prev->next = del->next; } free(del); return; } void insertNode(Node** head_ref, int new_data) { Node* new_node = new Node(); new_node->data = new_data; new_node->prev = NULL; new_node->next = (*head_ref); if ((*head_ref) != NULL) { (*head_ref)->prev = new_node; } (*head_ref) = new_node; } void printLinkedList(Node* node) { while (node != NULL) { cout << node->data << " -> "; node = node->next; } } int main() { Node* head = NULL; insertNode(&head, 1); insertNode(&head, 2); insertNode(&head, 3); insertNode(&head, 4); insertNode(&head, 5); cout << "Linked List before deletion:" << endl; printLinkedList(head); deleteNode(&head, head->next); cout << "\nLinked List after deletion:" << endl; printLinkedList(head); return 0; } If you execute the above program, then you will get the following result. Linked List before deletion: 5 -> 4 -> 3 -> 2 -> 1 -> Linked List after deletion: 5 -> 3 -> 2 -> 1 -> If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1146, "s": 1062, "text": "In this tutorial, we are going to learn how to delete a node in doubly linked list." }, { "code": null, "e": 1188, "s": 1146, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1236, "s": 1188, "text": "Write struct with data, prev and next pointers." }, { "code": null, "e": 1284, "s": 1236, "text": "Write struct with data, prev and next pointers." }, { "code": null, "e": 1349, "s": 1284, "text": "Write a function to insert the node into the doubly linked list." }, { "code": null, "e": 1414, "s": 1349, "text": "Write a function to insert the node into the doubly linked list." }, { "code": null, "e": 1465, "s": 1414, "text": "Initialize the doubly linked list with dummy data." }, { "code": null, "e": 1516, "s": 1465, "text": "Initialize the doubly linked list with dummy data." }, { "code": null, "e": 1539, "s": 1516, "text": "Take a node to delete." }, { "code": null, "e": 1562, "s": 1539, "text": "Take a node to delete." }, { "code": null, "e": 1869, "s": 1562, "text": "Write a function to delete the node. Consider the following three cases while deleting the node.If the node is head node, then move the head to next node.If the node is middle node, then link the next node to the previous nodeIf the node is end node, then remove the previous node link.\nLet's see the code." }, { "code": null, "e": 1966, "s": 1869, "text": "Write a function to delete the node. Consider the following three cases while deleting the node." }, { "code": null, "e": 2025, "s": 1966, "text": "If the node is head node, then move the head to next node." }, { "code": null, "e": 2084, "s": 2025, "text": "If the node is head node, then move the head to next node." }, { "code": null, "e": 2157, "s": 2084, "text": "If the node is middle node, then link the next node to the previous node" }, { "code": null, "e": 2230, "s": 2157, "text": "If the node is middle node, then link the next node to the previous node" }, { "code": null, "e": 2311, "s": 2230, "text": "If the node is end node, then remove the previous node link.\nLet's see the code." }, { "code": null, "e": 2392, "s": 2311, "text": "If the node is end node, then remove the previous node link.\nLet's see the code." }, { "code": null, "e": 2403, "s": 2392, "text": " Live Demo" }, { "code": null, "e": 3596, "s": 2403, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int data;\n Node *prev, *next;\n};\nvoid deleteNode(Node** head_ref, Node* del) {\n if (*head_ref == NULL || del == NULL) {\n return;\n }\n if (*head_ref == del) {\n *head_ref = del->next;\n }\n if (del->next != NULL) {\n del->next->prev = del->prev;\n }\n if (del->prev != NULL) {\n del->prev->next = del->next;\n }\n free(del);\n return;\n}\nvoid insertNode(Node** head_ref, int new_data) {\n Node* new_node = new Node();\n new_node->data = new_data;\n new_node->prev = NULL;\n new_node->next = (*head_ref);\n if ((*head_ref) != NULL) {\n (*head_ref)->prev = new_node;\n }\n (*head_ref) = new_node;\n}\nvoid printLinkedList(Node* node) {\n while (node != NULL) {\n cout << node->data << \" -> \";\n node = node->next;\n }\n}\nint main() {\n Node* head = NULL;\n insertNode(&head, 1);\n insertNode(&head, 2);\n insertNode(&head, 3);\n insertNode(&head, 4);\n insertNode(&head, 5);\n cout << \"Linked List before deletion:\" << endl;\n printLinkedList(head);\n deleteNode(&head, head->next);\n cout << \"\\nLinked List after deletion:\" << endl;\n printLinkedList(head);\n return 0;\n}" }, { "code": null, "e": 3670, "s": 3596, "text": "If you execute the above program, then you will get the following result." }, { "code": null, "e": 3772, "s": 3670, "text": "Linked List before deletion:\n5 -> 4 -> 3 -> 2 -> 1 ->\nLinked List after deletion:\n5 -> 3 -> 2 -> 1 ->" }, { "code": null, "e": 3850, "s": 3772, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
Testing PyTorch Models | Towards Data Science
Have you ever had the experience of training a PyTorch model for long hours, only to find that you have typed one line wrong in the model’s forward method? Have you ever run into the situation that you obtained somewhat reasonable output from your model, but not sure if it indicated you had built the model right, or it was just because deep learning was so powerful that even wrong model architecture produced descent results? Speaking for myself, testing a deep learning model drives me crazy from time to time. The most outstanding pain points are: Its black box nature makes it hard to test. If not impossible, it requires much expertise to make sense of the intermediate results. The long training time greatly reduces the number of iterations. There is not a dedicated tool. Usually you will want to test your model on a small sample dataset, which involves repeatedly writing boilerplate code for setup optimizer, calculating loss, and backward propagation . To mitigate this overhead, I have done some research previously. I found a wonderful medium post on this topic by Chase Roberts. The core idea is that we can never be one hundred percent sure that our model is correct, but at least it should be able to pass some sanity checks. In other words, these sanity checks are necessary but may not be sufficient. To save your time, here is a summary of all the sanity checks he proposed: A model parameter should always change during the training procedure, if it is not frozen on purpose. This can be a weight tensor for a PyTorch linear layer. A model parameter should not change during the training procedure, if it is frozen. This can be a pre-trained layer you don’t want to update. The range of model outputs should obey certain conditions depending on your model property. For example, if it is a classification model, its outputs should not all be in the range (0, 1). Otherwise, it is highly likely that you incorrectly apply softmax function to the outputs before loss calculation. (This one actually is not from that post, but is a common one) A model parameter should not contain NaN(not a number) or Inf(infinite number) in most cases. Same applies to model outputs. In addition to proposing these checks, He also built a Python package that implemented them. It is a nice package, but still there are unsolved pain points. The package is built several years ago and is no longer being maintained. So, inspired by this idea of sanity check, aiming at creating an easy-to-use Python package, torcheck is created! Its major innovations are: Additional testing code is no longer needed. Just add a few lines of code specifying the checks before training, torcheck will take over, perform checks while the training happens, and raise an informative error message when checks fail. Checking your model on different levels is made possible. Instead of checking the whole model, you can specify checks for a submodule, a linear layer, or even the weight tensor! This enables more customization around the checks for complicated architecture. Next, we will give you a quick tutorial on torcheck. Here are some links you may find useful: Torcheck GitHub page Torcheck PyPI page Suppose we have coded up a ConvNet model for classifying the MNIST dataset. The full training routine looks like this: There is actually a subtle error in the model code. Some of you may have noticed: in line 16, we carelessly put x on the right hand side, which should be output instead. Now let’s see how torcheck help you detect this hidden error! Before we start, first install the package in one line. $ pip install torcheck Next we will add in code. Torcheck code always resides right before the training for loop, after your model and optimizer instantiation, as is shown below: First, register your optimizer(s) with torcheck: torcheck.register(optimizer) Next, add all the checks you want to perform in the four categories. For our example, we want all the model parameters to change during the training procedure. Adding the check is simple: # check all the model parameters will change# module_name is optional, but it makes error messages more informative when checks failtorcheck.add_module_changing_check(model, module_name="my_model") To demonstrate the full capability of torcheck, let’s say later you freeze the convolutional layers and only want to fine tune the linear layers. Adding checks in this situation would be like: # check the first convolutional layer's parameters won't changetorcheck.add_module_unchanging_check(model.conv1, module_name="conv_layer_1")# check the second convolutional layer's parameters won't changetorcheck.add_module_unchanging_check(model.conv2, module_name="conv_layer_2")# check the third convolutional layer's parameters won't changetorcheck.add_module_unchanging_check(model.conv3, module_name="conv_layer_3")# check the first linear layer's parameters will changetorcheck.add_module_changing_check(model.fc1, module_name="linear_layer_1")# check the second linear layer's parameters will changetorcheck.add_module_changing_check(model.fc2, module_name="linear_layer_2") Since our model is a classification model, we want to add the check mentioned earlier: model outputs should not all be in the range (0, 1). # check model outputs are not all within (0, 1)# aka softmax hasn't been applied before loss calculationtorcheck.add_module_output_range_check( model, output_range=(0, 1), negate_range=True,) The negate_range=True argument carries the meaning of β€œnot all”. If you simply want to check model outputs are all within a certain range, just remove that argument. Although not applicable to our example, torcheck enables you to check the intermediate outputs of submodules as well. We definitely want to make sure model parameters don’t become NaN during training, and model outputs don’t contain NaN. Adding the NaN check is simple: # check whether model parameters become NaN or outputs contain NaNtorcheck.add_module_nan_check(model) Similarly, add the Inf check: # check whether model parameters become infinite or outputs contain infinite valuetorcheck.add_module_inf_check(model) After adding all the checks of interest, the final training code looks like this: Now let’s run the training as usual and see what happens: $ python run.pyTraceback (most recent call last): (stack trace information here)RuntimeError: The following errors are detected while training:Module my_model's conv1.weight should change.Module my_model's conv1.bias should change. Bang! We immediately get an error message saying that our model’s conv1.weight and conv1.bias don’t change. There must be something wrong with model.conv1 . As expected, we head over to the model code, notice the error, fix it, and rerun the training. Now everything works like a charm :) Yay! Our model has passed all the checks. To get rid of them, we can simply call torcheck.disable() This is useful when you want to run your model on a validation set, or you just want to remove the checking overhead from your model training. If you ever want to turn on the checks again, just call torcheck.enable() And that’s pretty much all you need to start using torcheck. For a more comprehensive introduction, please refer to its GitHub page. As the package is still in early stage, there may be bugs here and there. Please do not hesitate to report them. Any contribution is welcome. Hope you find this package useful and make you more confident about your black box models!
[ { "code": null, "e": 475, "s": 46, "text": "Have you ever had the experience of training a PyTorch model for long hours, only to find that you have typed one line wrong in the model’s forward method? Have you ever run into the situation that you obtained somewhat reasonable output from your model, but not sure if it indicated you had built the model right, or it was just because deep learning was so powerful that even wrong model architecture produced descent results?" }, { "code": null, "e": 599, "s": 475, "text": "Speaking for myself, testing a deep learning model drives me crazy from time to time. The most outstanding pain points are:" }, { "code": null, "e": 732, "s": 599, "text": "Its black box nature makes it hard to test. If not impossible, it requires much expertise to make sense of the intermediate results." }, { "code": null, "e": 797, "s": 732, "text": "The long training time greatly reduces the number of iterations." }, { "code": null, "e": 1013, "s": 797, "text": "There is not a dedicated tool. Usually you will want to test your model on a small sample dataset, which involves repeatedly writing boilerplate code for setup optimizer, calculating loss, and backward propagation ." }, { "code": null, "e": 1368, "s": 1013, "text": "To mitigate this overhead, I have done some research previously. I found a wonderful medium post on this topic by Chase Roberts. The core idea is that we can never be one hundred percent sure that our model is correct, but at least it should be able to pass some sanity checks. In other words, these sanity checks are necessary but may not be sufficient." }, { "code": null, "e": 1443, "s": 1368, "text": "To save your time, here is a summary of all the sanity checks he proposed:" }, { "code": null, "e": 1601, "s": 1443, "text": "A model parameter should always change during the training procedure, if it is not frozen on purpose. This can be a weight tensor for a PyTorch linear layer." }, { "code": null, "e": 1743, "s": 1601, "text": "A model parameter should not change during the training procedure, if it is frozen. This can be a pre-trained layer you don’t want to update." }, { "code": null, "e": 2047, "s": 1743, "text": "The range of model outputs should obey certain conditions depending on your model property. For example, if it is a classification model, its outputs should not all be in the range (0, 1). Otherwise, it is highly likely that you incorrectly apply softmax function to the outputs before loss calculation." }, { "code": null, "e": 2235, "s": 2047, "text": "(This one actually is not from that post, but is a common one) A model parameter should not contain NaN(not a number) or Inf(infinite number) in most cases. Same applies to model outputs." }, { "code": null, "e": 2466, "s": 2235, "text": "In addition to proposing these checks, He also built a Python package that implemented them. It is a nice package, but still there are unsolved pain points. The package is built several years ago and is no longer being maintained." }, { "code": null, "e": 2607, "s": 2466, "text": "So, inspired by this idea of sanity check, aiming at creating an easy-to-use Python package, torcheck is created! Its major innovations are:" }, { "code": null, "e": 2845, "s": 2607, "text": "Additional testing code is no longer needed. Just add a few lines of code specifying the checks before training, torcheck will take over, perform checks while the training happens, and raise an informative error message when checks fail." }, { "code": null, "e": 3103, "s": 2845, "text": "Checking your model on different levels is made possible. Instead of checking the whole model, you can specify checks for a submodule, a linear layer, or even the weight tensor! This enables more customization around the checks for complicated architecture." }, { "code": null, "e": 3197, "s": 3103, "text": "Next, we will give you a quick tutorial on torcheck. Here are some links you may find useful:" }, { "code": null, "e": 3218, "s": 3197, "text": "Torcheck GitHub page" }, { "code": null, "e": 3237, "s": 3218, "text": "Torcheck PyPI page" }, { "code": null, "e": 3356, "s": 3237, "text": "Suppose we have coded up a ConvNet model for classifying the MNIST dataset. The full training routine looks like this:" }, { "code": null, "e": 3526, "s": 3356, "text": "There is actually a subtle error in the model code. Some of you may have noticed: in line 16, we carelessly put x on the right hand side, which should be output instead." }, { "code": null, "e": 3588, "s": 3526, "text": "Now let’s see how torcheck help you detect this hidden error!" }, { "code": null, "e": 3644, "s": 3588, "text": "Before we start, first install the package in one line." }, { "code": null, "e": 3667, "s": 3644, "text": "$ pip install torcheck" }, { "code": null, "e": 3823, "s": 3667, "text": "Next we will add in code. Torcheck code always resides right before the training for loop, after your model and optimizer instantiation, as is shown below:" }, { "code": null, "e": 3872, "s": 3823, "text": "First, register your optimizer(s) with torcheck:" }, { "code": null, "e": 3901, "s": 3872, "text": "torcheck.register(optimizer)" }, { "code": null, "e": 3970, "s": 3901, "text": "Next, add all the checks you want to perform in the four categories." }, { "code": null, "e": 4089, "s": 3970, "text": "For our example, we want all the model parameters to change during the training procedure. Adding the check is simple:" }, { "code": null, "e": 4287, "s": 4089, "text": "# check all the model parameters will change# module_name is optional, but it makes error messages more informative when checks failtorcheck.add_module_changing_check(model, module_name=\"my_model\")" }, { "code": null, "e": 4480, "s": 4287, "text": "To demonstrate the full capability of torcheck, let’s say later you freeze the convolutional layers and only want to fine tune the linear layers. Adding checks in this situation would be like:" }, { "code": null, "e": 5163, "s": 4480, "text": "# check the first convolutional layer's parameters won't changetorcheck.add_module_unchanging_check(model.conv1, module_name=\"conv_layer_1\")# check the second convolutional layer's parameters won't changetorcheck.add_module_unchanging_check(model.conv2, module_name=\"conv_layer_2\")# check the third convolutional layer's parameters won't changetorcheck.add_module_unchanging_check(model.conv3, module_name=\"conv_layer_3\")# check the first linear layer's parameters will changetorcheck.add_module_changing_check(model.fc1, module_name=\"linear_layer_1\")# check the second linear layer's parameters will changetorcheck.add_module_changing_check(model.fc2, module_name=\"linear_layer_2\")" }, { "code": null, "e": 5303, "s": 5163, "text": "Since our model is a classification model, we want to add the check mentioned earlier: model outputs should not all be in the range (0, 1)." }, { "code": null, "e": 5504, "s": 5303, "text": "# check model outputs are not all within (0, 1)# aka softmax hasn't been applied before loss calculationtorcheck.add_module_output_range_check( model, output_range=(0, 1), negate_range=True,)" }, { "code": null, "e": 5670, "s": 5504, "text": "The negate_range=True argument carries the meaning of β€œnot all”. If you simply want to check model outputs are all within a certain range, just remove that argument." }, { "code": null, "e": 5788, "s": 5670, "text": "Although not applicable to our example, torcheck enables you to check the intermediate outputs of submodules as well." }, { "code": null, "e": 5940, "s": 5788, "text": "We definitely want to make sure model parameters don’t become NaN during training, and model outputs don’t contain NaN. Adding the NaN check is simple:" }, { "code": null, "e": 6043, "s": 5940, "text": "# check whether model parameters become NaN or outputs contain NaNtorcheck.add_module_nan_check(model)" }, { "code": null, "e": 6073, "s": 6043, "text": "Similarly, add the Inf check:" }, { "code": null, "e": 6192, "s": 6073, "text": "# check whether model parameters become infinite or outputs contain infinite valuetorcheck.add_module_inf_check(model)" }, { "code": null, "e": 6274, "s": 6192, "text": "After adding all the checks of interest, the final training code looks like this:" }, { "code": null, "e": 6332, "s": 6274, "text": "Now let’s run the training as usual and see what happens:" }, { "code": null, "e": 6565, "s": 6332, "text": "$ python run.pyTraceback (most recent call last): (stack trace information here)RuntimeError: The following errors are detected while training:Module my_model's conv1.weight should change.Module my_model's conv1.bias should change." }, { "code": null, "e": 6722, "s": 6565, "text": "Bang! We immediately get an error message saying that our model’s conv1.weight and conv1.bias don’t change. There must be something wrong with model.conv1 ." }, { "code": null, "e": 6854, "s": 6722, "text": "As expected, we head over to the model code, notice the error, fix it, and rerun the training. Now everything works like a charm :)" }, { "code": null, "e": 6935, "s": 6854, "text": "Yay! Our model has passed all the checks. To get rid of them, we can simply call" }, { "code": null, "e": 6954, "s": 6935, "text": "torcheck.disable()" }, { "code": null, "e": 7097, "s": 6954, "text": "This is useful when you want to run your model on a validation set, or you just want to remove the checking overhead from your model training." }, { "code": null, "e": 7153, "s": 7097, "text": "If you ever want to turn on the checks again, just call" }, { "code": null, "e": 7171, "s": 7153, "text": "torcheck.enable()" }, { "code": null, "e": 7304, "s": 7171, "text": "And that’s pretty much all you need to start using torcheck. For a more comprehensive introduction, please refer to its GitHub page." }, { "code": null, "e": 7446, "s": 7304, "text": "As the package is still in early stage, there may be bugs here and there. Please do not hesitate to report them. Any contribution is welcome." } ]
C# While Loop
Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable. The while loop loops through a block of code as long as a specified condition is True: while (condition) { // code block to be executed } In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5: int i = 0; while (i < 5) { Console.WriteLine(i); i++; } Try it Yourself Β» Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end! The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. do { // code block to be executed } while (condition); The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested: int i = 0;do { Console.WriteLine(i); i++; } while (i < 5); Try it Yourself Β» Do not forget to increase the variable used in the condition, otherwise the loop will never end! Print i as long as i is less than 6. int i = 1; (i 6) { Console.WriteLine(i); ; } Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 79, "s": 0, "text": "Loops can execute a block of code as long as a specified condition is reached." }, { "code": null, "e": 168, "s": 79, "text": "Loops are handy because they save time, reduce errors, and they make code more readable." }, { "code": null, "e": 256, "s": 168, "text": "The while loop loops through a block of code as long as a specified condition is \nTrue:" }, { "code": null, "e": 311, "s": 256, "text": "while (condition) \n{\n // code block to be executed\n}\n" }, { "code": null, "e": 428, "s": 311, "text": "In the example below, the code in the loop will run, over and over again, as long as \na variable (i) is less than 5:" }, { "code": null, "e": 490, "s": 428, "text": "int i = 0;\nwhile (i < 5) \n{\n Console.WriteLine(i);\n i++;\n}\n" }, { "code": null, "e": 510, "s": 490, "text": "\nTry it Yourself Β»\n" }, { "code": null, "e": 614, "s": 510, "text": "Note: Do not forget to increase the variable used in the condition, otherwise \nthe loop will never end!" }, { "code": null, "e": 814, "s": 614, "text": "The do/while loop is a variant of the while loop. This loop will \nexecute the code block once, before checking if the condition is true, then it will\nrepeat the loop as long as the condition is true." }, { "code": null, "e": 873, "s": 814, "text": "do \n{\n // code block to be executed\n}\nwhile (condition);\n" }, { "code": null, "e": 1062, "s": 873, "text": "The example below uses a do/while loop. The loop will always be \nexecuted at least once, even if the condition is false, because the code block \nis executed before the condition is tested:" }, { "code": null, "e": 1127, "s": 1062, "text": "int i = 0;do \n{\n Console.WriteLine(i);\n i++;\n}\nwhile (i < 5);\n" }, { "code": null, "e": 1147, "s": 1127, "text": "\nTry it Yourself Β»\n" }, { "code": null, "e": 1245, "s": 1147, "text": "Do not forget to increase the variable used in the condition, otherwise \nthe loop will never end!" }, { "code": null, "e": 1282, "s": 1245, "text": "Print i as long as i is less than 6." }, { "code": null, "e": 1336, "s": 1282, "text": "int i = 1;\n (i 6) \n{\n Console.WriteLine(i); \n ;\n}\n" }, { "code": null, "e": 1355, "s": 1336, "text": "Start the Exercise" }, { "code": null, "e": 1388, "s": 1355, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1430, "s": 1388, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1537, "s": 1430, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1556, "s": 1537, "text": "[email protected]" } ]
How do I sort a two-dimensional array in C#
To sort a two-dimensional array in C#, in a nested for loop, add another for loop to check the following condition. for (int k = 0; k < j; k++) { if (arr[i, k] > arr[i, k + 1]) { int myTemp = arr[i, k]; arr[i, k] = arr[i, k + 1]; arr[i, k + 1] = myTemp; } } Till the outer loop loops through, use the GetLength() method as shown below. This is done to sort the array. for (int i = 0; i < arr.GetLength(0); i++) { for (int j = arr.GetLength(1) - 1; j > 0; j--) { for (int k = 0; k < j; k++) { if (arr[i, k] > arr[i, k + 1]) { int myTemp = arr[i, k]; arr[i, k] = arr[i, k + 1]; arr[i, k + 1] = myTemp; } } } Console.WriteLine(); }
[ { "code": null, "e": 1178, "s": 1062, "text": "To sort a two-dimensional array in C#, in a nested for loop, add another for loop to check the following condition." }, { "code": null, "e": 1344, "s": 1178, "text": "for (int k = 0; k < j; k++) {\n if (arr[i, k] > arr[i, k + 1]) {\n int myTemp = arr[i, k];\n arr[i, k] = arr[i, k + 1];\n arr[i, k + 1] = myTemp;\n }\n}" }, { "code": null, "e": 1454, "s": 1344, "text": "Till the outer loop loops through, use the GetLength() method as shown below. This is done to sort the array." }, { "code": null, "e": 1790, "s": 1454, "text": "for (int i = 0; i < arr.GetLength(0); i++) {\n for (int j = arr.GetLength(1) - 1; j > 0; j--) {\n for (int k = 0; k < j; k++) {\n if (arr[i, k] > arr[i, k + 1]) {\n int myTemp = arr[i, k];\n arr[i, k] = arr[i, k + 1];\n arr[i, k + 1] = myTemp;\n }\n }\n }\n Console.WriteLine();\n}" } ]
C program to calculate sum of series using predefined function
The program to calculate the sum of the following expression Sum=1-n^2/2!+n^4/4!-n^6/6!+n^8/8!-n^10/10! User has to enter the value of n at runtime to calculate the sum of the series by using the predefined function power present in math.h library function. It is explained below how to calculate sum of series using predefined function. Refer an algorithm given below to calculate sum of series by using the predefined function. Step 1 βˆ’ Read the num value Step 2 βˆ’ Initialize fact = 1, sum = 1 and n =5 Step 3 βˆ’ for i= 1 to n a. compute fact= fact*i b. if i %2 = 0 c. then if i=2 or i=10 or i=6 d. then sum+= -pow(num,i)/fact e. else sum+=pow(num,i)/fact 4. print sum Following is the C program to calculate sum of series by using the predefined function βˆ’ #include<stdio.h> #include<conio.h> #include<math.h> void main(){ int i,n=5,num; long int fact=1; float sum=1; printf("Enter the n value:"); scanf("%d", &num); for(i=1;i<=n;i++){ fact=fact*i; if(i%2==0){ if(i==2|i==10|i==6) sum+= -pow(num,i)/fact; else sum+=pow(num,i)/fact; } } printf("sum is %f", sum); } When the above program is executed, it produces the following result βˆ’ Enter the n value:10 sum is 367.666656
[ { "code": null, "e": 1123, "s": 1062, "text": "The program to calculate the sum of the following expression" }, { "code": null, "e": 1166, "s": 1123, "text": "Sum=1-n^2/2!+n^4/4!-n^6/6!+n^8/8!-n^10/10!" }, { "code": null, "e": 1320, "s": 1166, "text": "User has to enter the value of n at runtime to calculate the sum of the series by using the predefined function power present in math.h library function." }, { "code": null, "e": 1400, "s": 1320, "text": "It is explained below how to calculate sum of series using predefined function." }, { "code": null, "e": 1492, "s": 1400, "text": "Refer an algorithm given below to calculate sum of series by using the predefined function." }, { "code": null, "e": 1520, "s": 1492, "text": "Step 1 βˆ’ Read the num value" }, { "code": null, "e": 1567, "s": 1520, "text": "Step 2 βˆ’ Initialize fact = 1, sum = 1 and n =5" }, { "code": null, "e": 1590, "s": 1567, "text": "Step 3 βˆ’ for i= 1 to n" }, { "code": null, "e": 1750, "s": 1590, "text": " a. compute fact= fact*i\n b. if i %2 = 0\n c. then if i=2 or i=10 or i=6\n d. then sum+= -pow(num,i)/fact\n e. else sum+=pow(num,i)/fact\n 4. print sum" }, { "code": null, "e": 1839, "s": 1750, "text": "Following is the C program to calculate sum of series by using the predefined function βˆ’" }, { "code": null, "e": 2227, "s": 1839, "text": "#include<stdio.h>\n#include<conio.h>\n#include<math.h>\nvoid main(){\n int i,n=5,num;\n long int fact=1;\n float sum=1;\n printf(\"Enter the n value:\");\n scanf(\"%d\", &num);\n for(i=1;i<=n;i++){\n fact=fact*i;\n if(i%2==0){\n if(i==2|i==10|i==6)\n sum+= -pow(num,i)/fact;\n else\n sum+=pow(num,i)/fact;\n }\n }\n printf(\"sum is %f\", sum);\n}" }, { "code": null, "e": 2298, "s": 2227, "text": "When the above program is executed, it produces the following result βˆ’" }, { "code": null, "e": 2337, "s": 2298, "text": "Enter the n value:10\nsum is 367.666656" } ]
Create nested JSON object in PHP?
JSON structure can be created with the below code βˆ’ $json = json_encode(array( "client" => array( "build" => "1.0", "name" => "xxxx", "version" => "1.0" ), "protocolVersion" => 4, "data" => array( "distributorId" => "xxxx", "distributorPin" => "xxxx", "locale" => "en-US" ) ));
[ { "code": null, "e": 1114, "s": 1062, "text": "JSON structure can be created with the below code βˆ’" }, { "code": null, "e": 1391, "s": 1114, "text": "$json = json_encode(array(\n \"client\" => array(\n \"build\" => \"1.0\",\n \"name\" => \"xxxx\",\n \"version\" => \"1.0\"\n ),\n \"protocolVersion\" => 4,\n \"data\" => array(\n \"distributorId\" => \"xxxx\",\n \"distributorPin\" => \"xxxx\",\n \"locale\" => \"en-US\"\n )\n));" } ]
Transfer Learning for Segmentation Using DeepLabv3 in PyTorch | by Manpreet Singh Minhas | Towards Data Science
Back when I was researching segmentation using Deep Learning and wanted to run some experiments on DeepLabv3[1] using PyTorch, I couldn’t find any online tutorial. What added to the challenge was that torchvision not only does not provide a Segmentation dataset but also there is no detailed explanation available for the internal structure of the DeepLabv3 class. However, I did the transfer learning on my own, and want to share the procedure so that it may potentially be helpful for you. In this article, I’ll be covering how to use a pre-trained semantic segmentation DeepLabv3 model for the task of road crack detection in PyTorch by using transfer learning. The same procedure can be applied to fine-tune the network for your custom dataset. If you want to look at the results and repository link directly, please scroll to the bottom. Let us start with a brief introduction to image segmentation. The primary goal of a segmentation task is to output pixel-level output masks in which regions belonging to certain categories are assigned the same distinct pixel value. If you color-code these segmentation masks by assigning a different color for every category for visualizing them, then you’ll get something like an image from a coloring book for kids. An example is shown below. Segmentation has existed for a very long time in the domain of Computer Vision and Image processing. Some of the techniques are simple thresholding, clustering based methods such as k means clustering-segmentation, region growing methods, etc. [3] With recent advancements in deep learning and the success of convolutional neural networks in image-related tasks over the traditional methods, these techniques have also been applied to the task of image segmentation. One of these network architectures is DeepLabv3 by Google. Explaining how the model works is beyond the scope of this article. Instead, we shall focus on how to use a pre-trained DeepLabv3 network for our data-sets. We will discuss transfer learning briefly for this. Deep Learning models tend to struggle when limited data is available. And for most practical applications, getting access to a copious dataset can be very difficult if not impossible. Annotation is tedious and time-consuming. Even if you plan to outsource it, you would still have to shell out money. Efforts have been made to be able to train models from limited data. And of such techniques is called Transfer Learning. Transfer learning involves the use of a network pre-trained for a source domain and task (in which you hopefully have access to a large dataset) and adopting it for your intended/target domain and task (that is similar to the original task and domain)[4]. It can be conceptually represented by the following diagram. We change the target segmentation sub-network as per our own requirements and then either train a part of the network or the entire network.The learning rate chosen is lower than in the case of normal training. This is because the network already has good weights for the source task. We don’t want to change the weights too much too fast.Also sometimes the initial layers can be kept frozen since it is argued that these layers extract general features and can be potentially used without any changes. We change the target segmentation sub-network as per our own requirements and then either train a part of the network or the entire network. The learning rate chosen is lower than in the case of normal training. This is because the network already has good weights for the source task. We don’t want to change the weights too much too fast. Also sometimes the initial layers can be kept frozen since it is argued that these layers extract general features and can be potentially used without any changes. If you want to learn more about Transfer Learning, I talk about it in detail in my paper: Anomaly Detection in Images [4]. Next, I’ll talk about the dataset being used in this article before proceeding with the PyTorch related sections. For this tutorial, I’ll be using the CrackForest[5][6] dataset for road crack detection using segmentation. It consists of urban road surface images with cracks as defects. The images contain confounding regions such as shadows, oil spills, and water stains. The images were taken using an ordinary iPhone5 camera. The dataset contains 118 images and has corresponding pixel level masks for the cracks, all having a size of 320Γ—480. The additional confounders along with the limited number of samples available for training make CrackForest a challenging dataset [7]. Let us begin by constructing a dataset class for our model which will be used to get training samples. For segmentation, instead of a single valued numeric label that could be one hot encoded, we have a ground truth mask image as the label. The mask has pixel level annotations available as shown in Fig. 3. Therefore, the training tensors for both input and labels would be four dimensional. For PyTorch, these would be: batch_size x channels x height x width. We will be defining our segmentation dataset class now. The class definition is as follows. We use the VisionDataset class from torchvision as the base class for the Segmentation dataset. Following three method need to be overloaded. __init__: This method is where the dataset object would be initialized. Usually, you need to build your image file paths and corresponding labels which are mask file paths for segmentation. These paths are then used in the __len__ and __getitem__ method.__getitem__: This method is called whenever you would use object[index] to access any element. So we need to write the image and mask loading logic here. So in essence, you get one training sample from your dataset using dataset object from this method.__len__: This method is invoked whenever len(obj) would be used. This method simply returns the number of the training samples in the directory. __init__: This method is where the dataset object would be initialized. Usually, you need to build your image file paths and corresponding labels which are mask file paths for segmentation. These paths are then used in the __len__ and __getitem__ method. __getitem__: This method is called whenever you would use object[index] to access any element. So we need to write the image and mask loading logic here. So in essence, you get one training sample from your dataset using dataset object from this method. __len__: This method is invoked whenever len(obj) would be used. This method simply returns the number of the training samples in the directory. When creating your custom datasets for PyTorch please remember to use PIL library. This allows you to use the torchvision transforms directly without having to define your own.In the first version of this class, I was using OpenCV for just loading the image! (I would’ve met past me, I would have advised myself not to do so.) The library is not only extremely heavy but also not compatible with the torchvision transforms. I had to write my custom transforms and handle dimensional changes myself. When creating your custom datasets for PyTorch please remember to use PIL library. This allows you to use the torchvision transforms directly without having to define your own. In the first version of this class, I was using OpenCV for just loading the image! (I would’ve met past me, I would have advised myself not to do so.) The library is not only extremely heavy but also not compatible with the torchvision transforms. I had to write my custom transforms and handle dimensional changes myself. I’ve added additional functionality to allow you to keep your dataset in a single directory instead of splitting the Train, Val into separate folders because a lot of datasets I was using weren’t in this format and I didn’t want to restructure my folder structure every time. Now that we have the dataset class defined, the next step is to create a PyTorch data loader from this. Data loaders allow you to create batches of data samples and labels using multiprocessing. This makes the data loading process much faster and efficient. The DataLoader class available under torch.utils.data is used for this purpose. The creation process itself is straightforward. You create a DataLoader object by passing the dataset object to it. The supported arguments are shown below. DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, *, prefetch_factor=2, persistent_workers=False) Few useful arguments are explained below: dataset (Dataset): dataset from which to load the data. batch_size (int, optional): how many samples per batch to load (default: 1) batch_size (int, optional): how many samples per batch to load (default: 1). shuffle (bool, optional): set to True to have the data reshuffled at every epoch. (default: False) num_workers (int, optional): how many subprocesses to use for data loading. 0 means that the data will be loaded in the main process. (default: 0) Tip: You can set this value equal to the number of cores in your system’s processor as the optimal value. Setting a higher value may lead to degradation in performance. Additionally, I’ve written two helper functions that give you data loaders depending on your data directory structure and are available in datahandler.py file. get_dataloader_sep_folder: Create Train and Test data loaders from two separate Train and Test folders. The directory structure should be as follows. get_dataloader_sep_folder: Create Train and Test data loaders from two separate Train and Test folders. The directory structure should be as follows. data_dir --Train ------Image ---------Image1 ---------ImageN ------Mask ---------Mask1 ---------MaskN --Train ------Image ---------Image1 ---------ImageN ------Mask ---------Mask1 ---------MaskN 2. get_dataloader_single_folder: Create from a single folder. The structure should be as follows. --data_dir------Image---------Image1---------ImageN------Mask---------Mask1---------MaskN These give you training and validation data loaders that shall be used in the training process. Next, we discuss the crux of this tutorial i.e. how to load a pre-trained model and change the segmentation head according to our data requirements. Torchvision has pre-trained models available and we shall be using one of those models. I’ve written the following function which gives you a model that has a custom number of output channels. You can change this value if you have more than one class. First, we get the pre-trained model using the models.segmentation.deeplabv3_resnet101 method that downloads the pre-trained model into our system cache. Note resnet101 is the backbone for the deeplabv3 model obtained from this particular method. This decides the feature vector length that is passed onto the classifier.The second step is the major step of modifying the segmentation head i.e. the classifier. This classifier is the part of the network and is responsible for creating the final segmentation output. The change is done by replacing the classifier module of the model with a new DeepLabHead with a new number of output channels. 2048 is the feature vector size from the resnet101 backbone. If you decide to use another backbone, please change this value accordingly.Finally, we set the model is set to train mode. This step is optional since you can also do this in the training logic. First, we get the pre-trained model using the models.segmentation.deeplabv3_resnet101 method that downloads the pre-trained model into our system cache. Note resnet101 is the backbone for the deeplabv3 model obtained from this particular method. This decides the feature vector length that is passed onto the classifier. The second step is the major step of modifying the segmentation head i.e. the classifier. This classifier is the part of the network and is responsible for creating the final segmentation output. The change is done by replacing the classifier module of the model with a new DeepLabHead with a new number of output channels. 2048 is the feature vector size from the resnet101 backbone. If you decide to use another backbone, please change this value accordingly. Finally, we set the model is set to train mode. This step is optional since you can also do this in the training logic. So far we’ve covered how to create the data loaders and the DeepLabv3 model with the modified head. The next step is to train the model. I’ve defined the following train_model function that trains the model. It saves the training and validation loss and metric (if specified) values into a CSV log file for easy access. The training code is as follows. It is well documented to explain what is going on. However, I’ll share a few things to keep in mind. Ensure that you send the model as well as your inputs and label to the same device (which would be cpu or cuda).Remember to clear the gradients using optimizer.zero_grad() before you do forward and backward propagation and parameter update.When training, set the model to train mode by using mode.train()When doing inference, set the model to eval mode by using mode.eval(). This is really important since this ensures that the network parameters are adjusted to account for techniques such as batch norm, dropouts etc. which affect the network weights. Ensure that you send the model as well as your inputs and label to the same device (which would be cpu or cuda). Remember to clear the gradients using optimizer.zero_grad() before you do forward and backward propagation and parameter update. When training, set the model to train mode by using mode.train() When doing inference, set the model to eval mode by using mode.eval(). This is really important since this ensures that the network parameters are adjusted to account for techniques such as batch norm, dropouts etc. which affect the network weights. The best model is decided by the lowest loss value. You can select the best model based on an evaluation metric too. But you’ll have to modify the code a bit. I’ve used the mean squared error (MSE) loss function for this task. The reason I used MSE is that it is a simple function, provides better results and gives a better surface for calculating the gradients. The loss is calculated at the pixel level in our case and is defined as follows: Note: This loss function won’t work for datasets that have more than one channel. For those cases, you will have to use cross-entropy instead. https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html I’ve used the Adadelta optimizer with the default settings and a learning rate of 0.0001. The training was done for 25 epochs. To evaluate the quantitative performance of the models, two metrics were selected. The first metric was the area undercurve (AUC) measurement of the receiver operating characteristics (ROC) [8]. AUC or AUROC is a reliable measure of the degree or measure of the separability of any binary classifier (binary segmentation masks in this case). It provides an aggregate measure of the model’s performance across all possible classification thresholds. An excellent model has AUROC value near to the one and it means that the classifier is virtually agnostic to the choice of a particular threshold. The second metric used for the assessment was the F1 score. It is defined as the harmonic mean of precision (P) and recall (R) and is given by the following equation. F1 score reaches its best value at one and the worst score at zero. It is a robust choice for classification tasks since it takes both the false positives and false negatives into account. The best model achieved a testing AUROC value of 0.842. This is a great score and is also reflected by segmentation output obtained after a thresholding operation. I’ve shown the loss and evaluation metrics during the training in the following graph. We can observe that the loss value decreased throughout the training. The AUROC and F1 Score values improved with the training. However, we see that the F1 Score values are consistently lower for both training and validation. In fact, these are poor values. The reason for this observation is that I used a threshold of 0.1 for calculating this metric. This wasn’t selected based on the dataset. F1 Score value can change depending on the threshold. However, AUROC is a robust metric that takes into account all possible thresholds. So when you have a binary classification task, it is advisable to use the AUROC metric. Even though the model is performing well on the dataset, as can be seen from the Segmentation Output image, the masks are over dilated in comparison to the ground truth. Maybe since the model is deeper than required, we are observing this kind of behavior. If you have any comments about this phenomenon, please do comment, I would love to know your thoughts. With this, we have reached the end of the tutorial! We learnt how to do transfer learning for the task of semantic segmentation using DeepLabv3 in PyTorch on our custom dataset. First we gained understanding about image segmentation and transfer learning.Next, we saw how to create the dataset class for segmentation for training the model.This was followed by the most important step of how to change the segmentation head of the DeepLabv3 model as per our dataset.The approach was tested for road crack detection on the CrackForest dataset. It achieved an impressive AUROC score of 0.842 after just 25 epochs. First we gained understanding about image segmentation and transfer learning. Next, we saw how to create the dataset class for segmentation for training the model. This was followed by the most important step of how to change the segmentation head of the DeepLabv3 model as per our dataset. The approach was tested for road crack detection on the CrackForest dataset. It achieved an impressive AUROC score of 0.842 after just 25 epochs. The code is available at https://github.com/msminhas93/DeepLabv3FineTuning. Thank you for reading the article. Hope you learned something new from this article. If you found this useful please consider citing my work. Bibtex Entry: @misc{minhas_2019, title={Transfer Learning for Semantic Segmentation using PyTorch DeepLab v3}, url={https://github.com/msminhas93/DeepLabv3FineTuning}, journal={GitHub.com/msminhas93}, author={Minhas, Manpreet Singh}, year={2019}, month={Sep}} IEEE Format Citation: M. S. Minhas, β€œTransfer Learning for Semantic Segmentation using PyTorch DeepLab v3,” GitHub.com/msminhas93, 12-Sep-2019. [Online]. Available: https://github.com/msminhas93/DeepLabv3FineTuning. [1] Rethinking Atrous Convolution for Semantic Image Segmentation, arXiv:1706.05587, Available: https://arxiv.org/abs/1706.05587 [2] Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation, arXiv:1802.02611, Available: https://arxiv.org/abs/1802.02611 [3] https://scikit-image.org/docs/dev/user_guide/tutorial_segmentation.html [4] Anomaly Detection in Images, arXiv:1905.13147, Available: https://arxiv.org/abs/1905.13147 [5] Yong Shi, Limeng Cui, Zhiquan Qi, Fan Meng, and Zhensong Chen. Automatic road crack detection using randomstructured forests.IEEE Transactions on Intelligent Transportation Systems, 17(12):3434–3445, 2016. [6] https://github.com/cuilimeng/CrackForest-dataset [7] AnoNet: Weakly Supervised Anomaly Detection in Textured Surfaces, arXiv:1911.10608, Available: https://arxiv.org/abs/1911.10608 [8] Charles X. Ling, Jin Huang, and Harry Zhang. Auc: A statistically consistent and more discriminating measurethan accuracy. InProceedings of the 18th International Joint Conference on Artificial Intelligence, IJCAI’03,pages 519–524, San Francisco, CA, USA, 2003. Morgan Kaufmann Publishers Inc.
[ { "code": null, "e": 663, "s": 171, "text": "Back when I was researching segmentation using Deep Learning and wanted to run some experiments on DeepLabv3[1] using PyTorch, I couldn’t find any online tutorial. What added to the challenge was that torchvision not only does not provide a Segmentation dataset but also there is no detailed explanation available for the internal structure of the DeepLabv3 class. However, I did the transfer learning on my own, and want to share the procedure so that it may potentially be helpful for you." }, { "code": null, "e": 1014, "s": 663, "text": "In this article, I’ll be covering how to use a pre-trained semantic segmentation DeepLabv3 model for the task of road crack detection in PyTorch by using transfer learning. The same procedure can be applied to fine-tune the network for your custom dataset. If you want to look at the results and repository link directly, please scroll to the bottom." }, { "code": null, "e": 1460, "s": 1014, "text": "Let us start with a brief introduction to image segmentation. The primary goal of a segmentation task is to output pixel-level output masks in which regions belonging to certain categories are assigned the same distinct pixel value. If you color-code these segmentation masks by assigning a different color for every category for visualizing them, then you’ll get something like an image from a coloring book for kids. An example is shown below." }, { "code": null, "e": 1708, "s": 1460, "text": "Segmentation has existed for a very long time in the domain of Computer Vision and Image processing. Some of the techniques are simple thresholding, clustering based methods such as k means clustering-segmentation, region growing methods, etc. [3]" }, { "code": null, "e": 1927, "s": 1708, "text": "With recent advancements in deep learning and the success of convolutional neural networks in image-related tasks over the traditional methods, these techniques have also been applied to the task of image segmentation." }, { "code": null, "e": 2195, "s": 1927, "text": "One of these network architectures is DeepLabv3 by Google. Explaining how the model works is beyond the scope of this article. Instead, we shall focus on how to use a pre-trained DeepLabv3 network for our data-sets. We will discuss transfer learning briefly for this." }, { "code": null, "e": 2617, "s": 2195, "text": "Deep Learning models tend to struggle when limited data is available. And for most practical applications, getting access to a copious dataset can be very difficult if not impossible. Annotation is tedious and time-consuming. Even if you plan to outsource it, you would still have to shell out money. Efforts have been made to be able to train models from limited data. And of such techniques is called Transfer Learning." }, { "code": null, "e": 2934, "s": 2617, "text": "Transfer learning involves the use of a network pre-trained for a source domain and task (in which you hopefully have access to a large dataset) and adopting it for your intended/target domain and task (that is similar to the original task and domain)[4]. It can be conceptually represented by the following diagram." }, { "code": null, "e": 3437, "s": 2934, "text": "We change the target segmentation sub-network as per our own requirements and then either train a part of the network or the entire network.The learning rate chosen is lower than in the case of normal training. This is because the network already has good weights for the source task. We don’t want to change the weights too much too fast.Also sometimes the initial layers can be kept frozen since it is argued that these layers extract general features and can be potentially used without any changes." }, { "code": null, "e": 3578, "s": 3437, "text": "We change the target segmentation sub-network as per our own requirements and then either train a part of the network or the entire network." }, { "code": null, "e": 3778, "s": 3578, "text": "The learning rate chosen is lower than in the case of normal training. This is because the network already has good weights for the source task. We don’t want to change the weights too much too fast." }, { "code": null, "e": 3942, "s": 3778, "text": "Also sometimes the initial layers can be kept frozen since it is argued that these layers extract general features and can be potentially used without any changes." }, { "code": null, "e": 4179, "s": 3942, "text": "If you want to learn more about Transfer Learning, I talk about it in detail in my paper: Anomaly Detection in Images [4]. Next, I’ll talk about the dataset being used in this article before proceeding with the PyTorch related sections." }, { "code": null, "e": 4747, "s": 4179, "text": "For this tutorial, I’ll be using the CrackForest[5][6] dataset for road crack detection using segmentation. It consists of urban road surface images with cracks as defects. The images contain confounding regions such as shadows, oil spills, and water stains. The images were taken using an ordinary iPhone5 camera. The dataset contains 118 images and has corresponding pixel level masks for the cracks, all having a size of 320Γ—480. The additional confounders along with the limited number of samples available for training make CrackForest a challenging dataset [7]." }, { "code": null, "e": 5209, "s": 4747, "text": "Let us begin by constructing a dataset class for our model which will be used to get training samples. For segmentation, instead of a single valued numeric label that could be one hot encoded, we have a ground truth mask image as the label. The mask has pixel level annotations available as shown in Fig. 3. Therefore, the training tensors for both input and labels would be four dimensional. For PyTorch, these would be: batch_size x channels x height x width." }, { "code": null, "e": 5301, "s": 5209, "text": "We will be defining our segmentation dataset class now. The class definition is as follows." }, { "code": null, "e": 5443, "s": 5301, "text": "We use the VisionDataset class from torchvision as the base class for the Segmentation dataset. Following three method need to be overloaded." }, { "code": null, "e": 6095, "s": 5443, "text": "__init__: This method is where the dataset object would be initialized. Usually, you need to build your image file paths and corresponding labels which are mask file paths for segmentation. These paths are then used in the __len__ and __getitem__ method.__getitem__: This method is called whenever you would use object[index] to access any element. So we need to write the image and mask loading logic here. So in essence, you get one training sample from your dataset using dataset object from this method.__len__: This method is invoked whenever len(obj) would be used. This method simply returns the number of the training samples in the directory." }, { "code": null, "e": 6350, "s": 6095, "text": "__init__: This method is where the dataset object would be initialized. Usually, you need to build your image file paths and corresponding labels which are mask file paths for segmentation. These paths are then used in the __len__ and __getitem__ method." }, { "code": null, "e": 6604, "s": 6350, "text": "__getitem__: This method is called whenever you would use object[index] to access any element. So we need to write the image and mask loading logic here. So in essence, you get one training sample from your dataset using dataset object from this method." }, { "code": null, "e": 6749, "s": 6604, "text": "__len__: This method is invoked whenever len(obj) would be used. This method simply returns the number of the training samples in the directory." }, { "code": null, "e": 7248, "s": 6749, "text": "When creating your custom datasets for PyTorch please remember to use PIL library. This allows you to use the torchvision transforms directly without having to define your own.In the first version of this class, I was using OpenCV for just loading the image! (I would’ve met past me, I would have advised myself not to do so.) The library is not only extremely heavy but also not compatible with the torchvision transforms. I had to write my custom transforms and handle dimensional changes myself." }, { "code": null, "e": 7425, "s": 7248, "text": "When creating your custom datasets for PyTorch please remember to use PIL library. This allows you to use the torchvision transforms directly without having to define your own." }, { "code": null, "e": 7748, "s": 7425, "text": "In the first version of this class, I was using OpenCV for just loading the image! (I would’ve met past me, I would have advised myself not to do so.) The library is not only extremely heavy but also not compatible with the torchvision transforms. I had to write my custom transforms and handle dimensional changes myself." }, { "code": null, "e": 8024, "s": 7748, "text": "I’ve added additional functionality to allow you to keep your dataset in a single directory instead of splitting the Train, Val into separate folders because a lot of datasets I was using weren’t in this format and I didn’t want to restructure my folder structure every time." }, { "code": null, "e": 8519, "s": 8024, "text": "Now that we have the dataset class defined, the next step is to create a PyTorch data loader from this. Data loaders allow you to create batches of data samples and labels using multiprocessing. This makes the data loading process much faster and efficient. The DataLoader class available under torch.utils.data is used for this purpose. The creation process itself is straightforward. You create a DataLoader object by passing the dataset object to it. The supported arguments are shown below." }, { "code": null, "e": 8789, "s": 8519, "text": "DataLoader(dataset, batch_size=1, shuffle=False, sampler=None, batch_sampler=None, num_workers=0, collate_fn=None, pin_memory=False, drop_last=False, timeout=0, worker_init_fn=None, *, prefetch_factor=2, persistent_workers=False)" }, { "code": null, "e": 8831, "s": 8789, "text": "Few useful arguments are explained below:" }, { "code": null, "e": 8963, "s": 8831, "text": "dataset (Dataset): dataset from which to load the data. batch_size (int, optional): how many samples per batch to load (default: 1)" }, { "code": null, "e": 9040, "s": 8963, "text": "batch_size (int, optional): how many samples per batch to load (default: 1)." }, { "code": null, "e": 9139, "s": 9040, "text": "shuffle (bool, optional): set to True to have the data reshuffled at every epoch. (default: False)" }, { "code": null, "e": 9455, "s": 9139, "text": "num_workers (int, optional): how many subprocesses to use for data loading. 0 means that the data will be loaded in the main process. (default: 0) Tip: You can set this value equal to the number of cores in your system’s processor as the optimal value. Setting a higher value may lead to degradation in performance." }, { "code": null, "e": 9615, "s": 9455, "text": "Additionally, I’ve written two helper functions that give you data loaders depending on your data directory structure and are available in datahandler.py file." }, { "code": null, "e": 9765, "s": 9615, "text": "get_dataloader_sep_folder: Create Train and Test data loaders from two separate Train and Test folders. The directory structure should be as follows." }, { "code": null, "e": 9915, "s": 9765, "text": "get_dataloader_sep_folder: Create Train and Test data loaders from two separate Train and Test folders. The directory structure should be as follows." }, { "code": null, "e": 10110, "s": 9915, "text": "data_dir --Train ------Image ---------Image1 ---------ImageN ------Mask ---------Mask1 ---------MaskN --Train ------Image ---------Image1 ---------ImageN ------Mask ---------Mask1 ---------MaskN" }, { "code": null, "e": 10208, "s": 10110, "text": "2. get_dataloader_single_folder: Create from a single folder. The structure should be as follows." }, { "code": null, "e": 10298, "s": 10208, "text": "--data_dir------Image---------Image1---------ImageN------Mask---------Mask1---------MaskN" }, { "code": null, "e": 10394, "s": 10298, "text": "These give you training and validation data loaders that shall be used in the training process." }, { "code": null, "e": 10543, "s": 10394, "text": "Next, we discuss the crux of this tutorial i.e. how to load a pre-trained model and change the segmentation head according to our data requirements." }, { "code": null, "e": 10795, "s": 10543, "text": "Torchvision has pre-trained models available and we shall be using one of those models. I’ve written the following function which gives you a model that has a custom number of output channels. You can change this value if you have more than one class." }, { "code": null, "e": 11696, "s": 10795, "text": "First, we get the pre-trained model using the models.segmentation.deeplabv3_resnet101 method that downloads the pre-trained model into our system cache. Note resnet101 is the backbone for the deeplabv3 model obtained from this particular method. This decides the feature vector length that is passed onto the classifier.The second step is the major step of modifying the segmentation head i.e. the classifier. This classifier is the part of the network and is responsible for creating the final segmentation output. The change is done by replacing the classifier module of the model with a new DeepLabHead with a new number of output channels. 2048 is the feature vector size from the resnet101 backbone. If you decide to use another backbone, please change this value accordingly.Finally, we set the model is set to train mode. This step is optional since you can also do this in the training logic." }, { "code": null, "e": 12017, "s": 11696, "text": "First, we get the pre-trained model using the models.segmentation.deeplabv3_resnet101 method that downloads the pre-trained model into our system cache. Note resnet101 is the backbone for the deeplabv3 model obtained from this particular method. This decides the feature vector length that is passed onto the classifier." }, { "code": null, "e": 12479, "s": 12017, "text": "The second step is the major step of modifying the segmentation head i.e. the classifier. This classifier is the part of the network and is responsible for creating the final segmentation output. The change is done by replacing the classifier module of the model with a new DeepLabHead with a new number of output channels. 2048 is the feature vector size from the resnet101 backbone. If you decide to use another backbone, please change this value accordingly." }, { "code": null, "e": 12599, "s": 12479, "text": "Finally, we set the model is set to train mode. This step is optional since you can also do this in the training logic." }, { "code": null, "e": 12699, "s": 12599, "text": "So far we’ve covered how to create the data loaders and the DeepLabv3 model with the modified head." }, { "code": null, "e": 12736, "s": 12699, "text": "The next step is to train the model." }, { "code": null, "e": 13003, "s": 12736, "text": "I’ve defined the following train_model function that trains the model. It saves the training and validation loss and metric (if specified) values into a CSV log file for easy access. The training code is as follows. It is well documented to explain what is going on." }, { "code": null, "e": 13053, "s": 13003, "text": "However, I’ll share a few things to keep in mind." }, { "code": null, "e": 13607, "s": 13053, "text": "Ensure that you send the model as well as your inputs and label to the same device (which would be cpu or cuda).Remember to clear the gradients using optimizer.zero_grad() before you do forward and backward propagation and parameter update.When training, set the model to train mode by using mode.train()When doing inference, set the model to eval mode by using mode.eval(). This is really important since this ensures that the network parameters are adjusted to account for techniques such as batch norm, dropouts etc. which affect the network weights." }, { "code": null, "e": 13720, "s": 13607, "text": "Ensure that you send the model as well as your inputs and label to the same device (which would be cpu or cuda)." }, { "code": null, "e": 13849, "s": 13720, "text": "Remember to clear the gradients using optimizer.zero_grad() before you do forward and backward propagation and parameter update." }, { "code": null, "e": 13914, "s": 13849, "text": "When training, set the model to train mode by using mode.train()" }, { "code": null, "e": 14164, "s": 13914, "text": "When doing inference, set the model to eval mode by using mode.eval(). This is really important since this ensures that the network parameters are adjusted to account for techniques such as batch norm, dropouts etc. which affect the network weights." }, { "code": null, "e": 14323, "s": 14164, "text": "The best model is decided by the lowest loss value. You can select the best model based on an evaluation metric too. But you’ll have to modify the code a bit." }, { "code": null, "e": 14609, "s": 14323, "text": "I’ve used the mean squared error (MSE) loss function for this task. The reason I used MSE is that it is a simple function, provides better results and gives a better surface for calculating the gradients. The loss is calculated at the pixel level in our case and is defined as follows:" }, { "code": null, "e": 14825, "s": 14609, "text": "Note: This loss function won’t work for datasets that have more than one channel. For those cases, you will have to use cross-entropy instead. https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html" }, { "code": null, "e": 14952, "s": 14825, "text": "I’ve used the Adadelta optimizer with the default settings and a learning rate of 0.0001. The training was done for 25 epochs." }, { "code": null, "e": 15715, "s": 14952, "text": "To evaluate the quantitative performance of the models, two metrics were selected. The first metric was the area undercurve (AUC) measurement of the receiver operating characteristics (ROC) [8]. AUC or AUROC is a reliable measure of the degree or measure of the separability of any binary classifier (binary segmentation masks in this case). It provides an aggregate measure of the model’s performance across all possible classification thresholds. An excellent model has AUROC value near to the one and it means that the classifier is virtually agnostic to the choice of a particular threshold. The second metric used for the assessment was the F1 score. It is defined as the harmonic mean of precision (P) and recall (R) and is given by the following equation." }, { "code": null, "e": 15904, "s": 15715, "text": "F1 score reaches its best value at one and the worst score at zero. It is a robust choice for classification tasks since it takes both the false positives and false negatives into account." }, { "code": null, "e": 16068, "s": 15904, "text": "The best model achieved a testing AUROC value of 0.842. This is a great score and is also reflected by segmentation output obtained after a thresholding operation." }, { "code": null, "e": 16155, "s": 16068, "text": "I’ve shown the loss and evaluation metrics during the training in the following graph." }, { "code": null, "e": 17136, "s": 16155, "text": "We can observe that the loss value decreased throughout the training. The AUROC and F1 Score values improved with the training. However, we see that the F1 Score values are consistently lower for both training and validation. In fact, these are poor values. The reason for this observation is that I used a threshold of 0.1 for calculating this metric. This wasn’t selected based on the dataset. F1 Score value can change depending on the threshold. However, AUROC is a robust metric that takes into account all possible thresholds. So when you have a binary classification task, it is advisable to use the AUROC metric. Even though the model is performing well on the dataset, as can be seen from the Segmentation Output image, the masks are over dilated in comparison to the ground truth. Maybe since the model is deeper than required, we are observing this kind of behavior. If you have any comments about this phenomenon, please do comment, I would love to know your thoughts." }, { "code": null, "e": 17188, "s": 17136, "text": "With this, we have reached the end of the tutorial!" }, { "code": null, "e": 17314, "s": 17188, "text": "We learnt how to do transfer learning for the task of semantic segmentation using DeepLabv3 in PyTorch on our custom dataset." }, { "code": null, "e": 17748, "s": 17314, "text": "First we gained understanding about image segmentation and transfer learning.Next, we saw how to create the dataset class for segmentation for training the model.This was followed by the most important step of how to change the segmentation head of the DeepLabv3 model as per our dataset.The approach was tested for road crack detection on the CrackForest dataset. It achieved an impressive AUROC score of 0.842 after just 25 epochs." }, { "code": null, "e": 17826, "s": 17748, "text": "First we gained understanding about image segmentation and transfer learning." }, { "code": null, "e": 17912, "s": 17826, "text": "Next, we saw how to create the dataset class for segmentation for training the model." }, { "code": null, "e": 18039, "s": 17912, "text": "This was followed by the most important step of how to change the segmentation head of the DeepLabv3 model as per our dataset." }, { "code": null, "e": 18185, "s": 18039, "text": "The approach was tested for road crack detection on the CrackForest dataset. It achieved an impressive AUROC score of 0.842 after just 25 epochs." }, { "code": null, "e": 18261, "s": 18185, "text": "The code is available at https://github.com/msminhas93/DeepLabv3FineTuning." }, { "code": null, "e": 18403, "s": 18261, "text": "Thank you for reading the article. Hope you learned something new from this article. If you found this useful please consider citing my work." }, { "code": null, "e": 18417, "s": 18403, "text": "Bibtex Entry:" }, { "code": null, "e": 18663, "s": 18417, "text": "@misc{minhas_2019, title={Transfer Learning for Semantic Segmentation using PyTorch DeepLab v3}, url={https://github.com/msminhas93/DeepLabv3FineTuning}, journal={GitHub.com/msminhas93}, author={Minhas, Manpreet Singh}, year={2019}, month={Sep}}" }, { "code": null, "e": 18685, "s": 18663, "text": "IEEE Format Citation:" }, { "code": null, "e": 18879, "s": 18685, "text": "M. S. Minhas, β€œTransfer Learning for Semantic Segmentation using PyTorch DeepLab v3,” GitHub.com/msminhas93, 12-Sep-2019. [Online]. Available: https://github.com/msminhas93/DeepLabv3FineTuning." }, { "code": null, "e": 19008, "s": 18879, "text": "[1] Rethinking Atrous Convolution for Semantic Image Segmentation, arXiv:1706.05587, Available: https://arxiv.org/abs/1706.05587" }, { "code": null, "e": 19157, "s": 19008, "text": "[2] Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation, arXiv:1802.02611, Available: https://arxiv.org/abs/1802.02611" }, { "code": null, "e": 19233, "s": 19157, "text": "[3] https://scikit-image.org/docs/dev/user_guide/tutorial_segmentation.html" }, { "code": null, "e": 19328, "s": 19233, "text": "[4] Anomaly Detection in Images, arXiv:1905.13147, Available: https://arxiv.org/abs/1905.13147" }, { "code": null, "e": 19538, "s": 19328, "text": "[5] Yong Shi, Limeng Cui, Zhiquan Qi, Fan Meng, and Zhensong Chen. Automatic road crack detection using randomstructured forests.IEEE Transactions on Intelligent Transportation Systems, 17(12):3434–3445, 2016." }, { "code": null, "e": 19591, "s": 19538, "text": "[6] https://github.com/cuilimeng/CrackForest-dataset" }, { "code": null, "e": 19723, "s": 19591, "text": "[7] AnoNet: Weakly Supervised Anomaly Detection in Textured Surfaces, arXiv:1911.10608, Available: https://arxiv.org/abs/1911.10608" } ]
#pragma Directive in C/C++
The preprocessor directive #pragma is used to provide the additional information to the compiler in C/C++ language. This is used by the compiler to provide some special features. Here is the syntax of #pragma directive in C/C++ language, #pragma token_name The table of some of #pragma directives in C/C++ language is given as follows, Here is an example of #pragma directive in C language, #include<stdio.h> int display(); #pragma startup display #pragma exit display int main() { printf("\nI am in main function"); return 0; } int display() { printf("\nI am in display function"); return 0; }
[ { "code": null, "e": 1241, "s": 1062, "text": "The preprocessor directive #pragma is used to provide the additional information to the compiler in C/C++ language. This is used by the compiler to provide some special features." }, { "code": null, "e": 1300, "s": 1241, "text": "Here is the syntax of #pragma directive in C/C++ language," }, { "code": null, "e": 1319, "s": 1300, "text": "#pragma token_name" }, { "code": null, "e": 1398, "s": 1319, "text": "The table of some of #pragma directives in C/C++ language is given as follows," }, { "code": null, "e": 1453, "s": 1398, "text": "Here is an example of #pragma directive in C language," }, { "code": null, "e": 1672, "s": 1453, "text": "#include<stdio.h>\nint display();\n\n#pragma startup display\n#pragma exit display\n\nint main() {\n printf(\"\\nI am in main function\");\n return 0;\n}\n\nint display() {\n printf(\"\\nI am in display function\");\n return 0;\n}" } ]
C | Arrays | Question 14 - GeeksforGeeks
28 Jun, 2021 Which of the following is true about arrays in C.(A) For every type T, there can be an array of T.(B) For every type T except void and function type, there can be an array of T.(C) When an array is passed to a function, C compiler creates a copy of array.(D) 2D arrays are stored in column major formAnswer: (B)Explanation: In C, we cannot have an array of void type and function types. For example, below program throws compiler error int main() { void arr[100]; } But we can have array of void pointers and function pointers. The below program works fine. int main() { void *arr[100]; } See examples of function pointers for details of array function pointers. Quiz of this Question Arrays C-Arrays C Language C Quiz Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ 'this' pointer in C++ Multithreading in C Arrow operator -> in C/C++ with Examples Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Arrays | Question 7 C | Misc | Question 7
[ { "code": null, "e": 26028, "s": 26000, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26415, "s": 26028, "text": "Which of the following is true about arrays in C.(A) For every type T, there can be an array of T.(B) For every type T except void and function type, there can be an array of T.(C) When an array is passed to a function, C compiler creates a copy of array.(D) 2D arrays are stored in column major formAnswer: (B)Explanation: In C, we cannot have an array of void type and function types." }, { "code": null, "e": 26464, "s": 26415, "text": "For example, below program throws compiler error" }, { "code": null, "e": 26499, "s": 26464, "text": "int main()\n{\n void arr[100];\n}\n" }, { "code": null, "e": 26591, "s": 26499, "text": "But we can have array of void pointers and function pointers. The below program works fine." }, { "code": null, "e": 26627, "s": 26591, "text": "int main()\n{\n void *arr[100];\n}\n" }, { "code": null, "e": 26701, "s": 26627, "text": "See examples of function pointers for details of array function pointers." }, { "code": null, "e": 26723, "s": 26701, "text": "Quiz of this Question" }, { "code": null, "e": 26730, "s": 26723, "text": "Arrays" }, { "code": null, "e": 26739, "s": 26730, "text": "C-Arrays" }, { "code": null, "e": 26750, "s": 26739, "text": "C Language" }, { "code": null, "e": 26757, "s": 26750, "text": "C Quiz" }, { "code": null, "e": 26764, "s": 26757, "text": "Arrays" }, { "code": null, "e": 26862, "s": 26764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26900, "s": 26862, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26926, "s": 26900, "text": "Exception Handling in C++" }, { "code": null, "e": 26948, "s": 26926, "text": "'this' pointer in C++" }, { "code": null, "e": 26968, "s": 26948, "text": "Multithreading in C" }, { "code": null, "e": 27009, "s": 26968, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 27051, "s": 27009, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 27094, "s": 27051, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 27125, "s": 27094, "text": "C | File Handling | Question 1" }, { "code": null, "e": 27149, "s": 27125, "text": "C | Arrays | Question 7" } ]
Matplotlib.pyplot.plot_date() function in Python - GeeksforGeeks
05 Jan, 2022 Matplotlib is a module or package or library in python which is used for data visualization. Pyplot is an interface to a Matplotlib module that provides a MATLAB-like interface. This function used to add dates to the plot. Syntax: matplotlib.pyplot.plot_date(x, y, fmt=’o’, tz=None, xdate=True, ydate=False, data=None, **kwargs) This is the syntax of date function. It contains various parameters or arguments which are explained below. 1. x, y x and y both are the coordinates of the data i.e. x-axis horizontally and y-axis vertically. 2. fmt It is a optional string parameter that contains the corresponding plot details like color, style etc. 3. tz tz stands for timezone used to label dates, default(UTC). 4. xdate xdate parameter contains boolean value. If xdate is true then x-axis is interpreted as date in matplotlib. By default xdate is true. 5. ydate If ydate is true then y-axis is interpreted as date in matplotlib. By default ydate is false. 6. data The data which is going to be used in plot. The last parameter **kwargs is the Keyword arguments control the Line2D properties like animation, dash_ joint-style, colors, linewidth, linestyle, marker, etc. Example 1: Python3 # importing librariesimport matplotlib.pyplot as pltfrom datetime import datetime # creating array of dates for x axisdates = [ datetime(2020, 6, 30), datetime(2020, 7, 22), datetime(2020, 8, 3), datetime(2020, 9, 14)] # for y axisx = [0, 1, 2, 3] plt.plot_date(dates, x, 'g')plt.xticks(rotation=70)plt.show() Output: Example 2: Creating a plot using dataset. Python3 # importing librariesimport pandas as pdimport matplotlib.pyplot as pltfrom datetime import datetime # creating a dataframedata = pd.DataFrame({'Date': [datetime(2020, 6, 30), datetime(2020, 7, 22), datetime(2020, 8, 3), datetime(2020, 9, 14)], 'Close': [8800, 2600, 8500, 7400]}) # x-axisprice_date = data['Date'] # y-axisprice_close = data['Close'] plt.plot_date(price_date, price_close, linestyle='--', color='r')plt.title('Market', fontweight="bold")plt.xlabel('Date of Closing')plt.ylabel('Closing Amount') plt.show() Example 3: Changing the format of the date: Python3 # importing librariesimport pandas as pdimport matplotlib.pyplot as pltfrom datetime import datetime # creating a dataframedata = pd.DataFrame({'Date': [datetime(2020, 6, 30), datetime(2020, 7, 22), datetime(2020, 8, 3), datetime(2020, 9, 14)], 'Close': [8800, 2600, 8500, 7400]}) # x-axisprice_date = data['Date'] # y-axisprice_close = data['Close'] plt.plot_date(price_date, price_close, linestyle='--', color='r')plt.title('Market', fontweight="bold")plt.xlabel('Date of Closing')plt.ylabel('Closing Amount') # Changing the format of the date using# dateformatter classformat_date = mpl_dates.DateFormatter('%d-%m-%Y') # getting the accurate current axes using gca()plt.gca().xaxis.set_major_formatter(format_date) plt.show() Output: The format of the date changed to dd-mm-yyyy. To know more about dataformatter and gca() click here. clintra Matplotlib Pyplot-class Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n05 Jan, 2022" }, { "code": null, "e": 24471, "s": 24292, "text": "Matplotlib is a module or package or library in python which is used for data visualization. Pyplot is an interface to a Matplotlib module that provides a MATLAB-like interface. " }, { "code": null, "e": 24517, "s": 24471, "text": "This function used to add dates to the plot." }, { "code": null, "e": 24525, "s": 24517, "text": "Syntax:" }, { "code": null, "e": 24624, "s": 24525, "text": "matplotlib.pyplot.plot_date(x, y, fmt=’o’, tz=None, xdate=True, ydate=False, data=None, **kwargs)" }, { "code": null, "e": 24732, "s": 24624, "text": "This is the syntax of date function. It contains various parameters or arguments which are explained below." }, { "code": null, "e": 24735, "s": 24732, "text": "1." }, { "code": null, "e": 24740, "s": 24735, "text": "x, y" }, { "code": null, "e": 24833, "s": 24740, "text": "x and y both are the coordinates of the data i.e. x-axis horizontally and y-axis vertically." }, { "code": null, "e": 24836, "s": 24833, "text": "2." }, { "code": null, "e": 24840, "s": 24836, "text": "fmt" }, { "code": null, "e": 24943, "s": 24840, "text": "It is a optional string parameter that contains the corresponding plot details like color, style etc. " }, { "code": null, "e": 24946, "s": 24943, "text": "3." }, { "code": null, "e": 24949, "s": 24946, "text": "tz" }, { "code": null, "e": 25007, "s": 24949, "text": "tz stands for timezone used to label dates, default(UTC)." }, { "code": null, "e": 25010, "s": 25007, "text": "4." }, { "code": null, "e": 25016, "s": 25010, "text": "xdate" }, { "code": null, "e": 25149, "s": 25016, "text": "xdate parameter contains boolean value. If xdate is true then x-axis is interpreted as date in matplotlib. By default xdate is true." }, { "code": null, "e": 25152, "s": 25149, "text": "5." }, { "code": null, "e": 25158, "s": 25152, "text": "ydate" }, { "code": null, "e": 25252, "s": 25158, "text": "If ydate is true then y-axis is interpreted as date in matplotlib. By default ydate is false." }, { "code": null, "e": 25255, "s": 25252, "text": "6." }, { "code": null, "e": 25260, "s": 25255, "text": "data" }, { "code": null, "e": 25304, "s": 25260, "text": "The data which is going to be used in plot." }, { "code": null, "e": 25465, "s": 25304, "text": "The last parameter **kwargs is the Keyword arguments control the Line2D properties like animation, dash_ joint-style, colors, linewidth, linestyle, marker, etc." }, { "code": null, "e": 25476, "s": 25465, "text": "Example 1:" }, { "code": null, "e": 25484, "s": 25476, "text": "Python3" }, { "code": "# importing librariesimport matplotlib.pyplot as pltfrom datetime import datetime # creating array of dates for x axisdates = [ datetime(2020, 6, 30), datetime(2020, 7, 22), datetime(2020, 8, 3), datetime(2020, 9, 14)] # for y axisx = [0, 1, 2, 3] plt.plot_date(dates, x, 'g')plt.xticks(rotation=70)plt.show()", "e": 25806, "s": 25484, "text": null }, { "code": null, "e": 25814, "s": 25806, "text": "Output:" }, { "code": null, "e": 25856, "s": 25814, "text": "Example 2: Creating a plot using dataset." }, { "code": null, "e": 25864, "s": 25856, "text": "Python3" }, { "code": "# importing librariesimport pandas as pdimport matplotlib.pyplot as pltfrom datetime import datetime # creating a dataframedata = pd.DataFrame({'Date': [datetime(2020, 6, 30), datetime(2020, 7, 22), datetime(2020, 8, 3), datetime(2020, 9, 14)], 'Close': [8800, 2600, 8500, 7400]}) # x-axisprice_date = data['Date'] # y-axisprice_close = data['Close'] plt.plot_date(price_date, price_close, linestyle='--', color='r')plt.title('Market', fontweight=\"bold\")plt.xlabel('Date of Closing')plt.ylabel('Closing Amount') plt.show()", "e": 26516, "s": 25864, "text": null }, { "code": null, "e": 26560, "s": 26516, "text": "Example 3: Changing the format of the date:" }, { "code": null, "e": 26568, "s": 26560, "text": "Python3" }, { "code": "# importing librariesimport pandas as pdimport matplotlib.pyplot as pltfrom datetime import datetime # creating a dataframedata = pd.DataFrame({'Date': [datetime(2020, 6, 30), datetime(2020, 7, 22), datetime(2020, 8, 3), datetime(2020, 9, 14)], 'Close': [8800, 2600, 8500, 7400]}) # x-axisprice_date = data['Date'] # y-axisprice_close = data['Close'] plt.plot_date(price_date, price_close, linestyle='--', color='r')plt.title('Market', fontweight=\"bold\")plt.xlabel('Date of Closing')plt.ylabel('Closing Amount') # Changing the format of the date using# dateformatter classformat_date = mpl_dates.DateFormatter('%d-%m-%Y') # getting the accurate current axes using gca()plt.gca().xaxis.set_major_formatter(format_date) plt.show()", "e": 27426, "s": 26568, "text": null }, { "code": null, "e": 27434, "s": 27426, "text": "Output:" }, { "code": null, "e": 27535, "s": 27434, "text": "The format of the date changed to dd-mm-yyyy. To know more about dataformatter and gca() click here." }, { "code": null, "e": 27543, "s": 27535, "text": "clintra" }, { "code": null, "e": 27567, "s": 27543, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 27574, "s": 27567, "text": "Picked" }, { "code": null, "e": 27592, "s": 27574, "text": "Python-matplotlib" }, { "code": null, "e": 27599, "s": 27592, "text": "Python" }, { "code": null, "e": 27697, "s": 27599, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27706, "s": 27697, "text": "Comments" }, { "code": null, "e": 27719, "s": 27706, "text": "Old Comments" }, { "code": null, "e": 27751, "s": 27719, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27806, "s": 27751, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 27862, "s": 27806, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27904, "s": 27862, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27946, "s": 27904, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27985, "s": 27946, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28007, "s": 27985, "text": "Defaultdict in Python" }, { "code": null, "e": 28028, "s": 28007, "text": "Python OOPs Concepts" }, { "code": null, "e": 28059, "s": 28028, "text": "Python | os.path.join() method" } ]
PHP | Palindrome Check - GeeksforGeeks
12 Jul, 2021 In this article, we will learn how to check whether a number and a string is a palindrome or not in PHP. A number or string is said to be a palindrome if it remains same even after reversing the digits or letters respectively.Examples for Palindrome Number: Input : 1441 Output : Palindrome Explanation: Reversing 1441 will also get 1441 Input : 12521 Output : Palindrome Explanation remains same Check for Palindrome number Here we have simply used the iterative way to check for the palindrome number. Each digit is extracted in an iteration and formed the reverse number and finally, it is checked, whether it is same as the original number. PHP <?php// PHP code to check for Palindrome number in PHP// Function to check for Palindromefunction Palindrome($number){ $temp = $number; $new = 0; while (floor($temp)) { $d = $temp % 10; $new = $new * 10 + $d; $temp = $temp/10; } if ($new == $number){ return 1; } else{ return 0; }} // Driver Code$original = 1441;if (Palindrome($original)){ echo "Palindrome"; }else { echo "Not a Palindrome"; } ?> Output: Palindrome Check for Palindrome String Examples for Palindrome String: Input : "MALAYALAM" Output : Palindrome Explanation: Reversing "MALAYALAM" will also get "MALAYALAM" Input : "14441" Output : Palindrome Explanation remains same Method 1: Using strrev() The strrev() function is used in PHP to reverse a string. We can simply use this method to reverse the string and match it with the previous value. If it is a match, then the string is palindrome else not. Example: PHP <?php// PHP code to check for Palindrome string in PHP// Using strrev()function Palindrome($string){ if (strrev($string) == $string){ return 1; } else{ return 0; }} // Driver Code$original = "DAD";if(Palindrome($original)){ echo "Palindrome"; }else { echo "Not a Palindrome"; }?> Output: Palindrome Method 2: Recursive way using substr() The substr() method is used to return a part of a string, referred to as the substring. Using this method, there is a recursive way to check for Palindrome or not. In this method no new string is formed and the original string is modified in each recursive call. Example: PHP <?php// PHP code to check for Palindrome string in PHP// Recursive way using substr()function Palindrome($string){ // Base condition to end the recursive process if ((strlen($string) == 1) || (strlen($string) == 0)){ echo "Palindrome"; } else{ // First character is compared with the last one if (substr($string,0,1) == substr($string,(strlen($string) - 1),1)){ // Checked letters are discarded and passed for next call return Palindrome(substr($string,1,strlen($string) -2)); } else{ echo " Not a Palindrome"; } }} $string = "MALAYALAM";Palindrome($string);?> Output: Palindrome Working: The first character is matched with the last character of the string during each recursive call and if it matches, then both the characters are discarded during the next call. This goes on until the length of the string reduces to 0 or 1. In the following example where the word β€œMALAYALAM”, is taken, let’s see the working. In the first step both the M’s at both, the end is compared. Since it matches, both of them are discarded and the next string to be passed is β€œALAYALA”. Again both the A matched at both the end, so next string to be passed is β€œLAYAL”. This goes on until only β€œY” remains. simranarora5sos simmytarika5 PHP-string PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26305, "s": 26277, "text": "\n12 Jul, 2021" }, { "code": null, "e": 26565, "s": 26305, "text": "In this article, we will learn how to check whether a number and a string is a palindrome or not in PHP. A number or string is said to be a palindrome if it remains same even after reversing the digits or letters respectively.Examples for Palindrome Number: " }, { "code": null, "e": 26705, "s": 26565, "text": "Input : 1441\nOutput : Palindrome\nExplanation: Reversing 1441 will also get 1441\n\nInput : 12521\nOutput : Palindrome\nExplanation remains same" }, { "code": null, "e": 26737, "s": 26709, "text": "Check for Palindrome number" }, { "code": null, "e": 26959, "s": 26737, "text": "Here we have simply used the iterative way to check for the palindrome number. Each digit is extracted in an iteration and formed the reverse number and finally, it is checked, whether it is same as the original number. " }, { "code": null, "e": 26963, "s": 26959, "text": "PHP" }, { "code": "<?php// PHP code to check for Palindrome number in PHP// Function to check for Palindromefunction Palindrome($number){ $temp = $number; $new = 0; while (floor($temp)) { $d = $temp % 10; $new = $new * 10 + $d; $temp = $temp/10; } if ($new == $number){ return 1; } else{ return 0; }} // Driver Code$original = 1441;if (Palindrome($original)){ echo \"Palindrome\"; }else { echo \"Not a Palindrome\"; } ?> ", "e": 27436, "s": 26963, "text": null }, { "code": null, "e": 27446, "s": 27436, "text": "Output: " }, { "code": null, "e": 27457, "s": 27446, "text": "Palindrome" }, { "code": null, "e": 27487, "s": 27459, "text": "Check for Palindrome String" }, { "code": null, "e": 27521, "s": 27487, "text": "Examples for Palindrome String: " }, { "code": null, "e": 27684, "s": 27521, "text": "Input : \"MALAYALAM\"\nOutput : Palindrome\nExplanation: Reversing \"MALAYALAM\" will also get \"MALAYALAM\"\n\nInput : \"14441\"\nOutput : Palindrome\nExplanation remains same" }, { "code": null, "e": 27926, "s": 27684, "text": "Method 1: Using strrev() The strrev() function is used in PHP to reverse a string. We can simply use this method to reverse the string and match it with the previous value. If it is a match, then the string is palindrome else not. Example: " }, { "code": null, "e": 27930, "s": 27926, "text": "PHP" }, { "code": "<?php// PHP code to check for Palindrome string in PHP// Using strrev()function Palindrome($string){ if (strrev($string) == $string){ return 1; } else{ return 0; }} // Driver Code$original = \"DAD\";if(Palindrome($original)){ echo \"Palindrome\"; }else { echo \"Not a Palindrome\"; }?> ", "e": 28245, "s": 27930, "text": null }, { "code": null, "e": 28255, "s": 28245, "text": "Output: " }, { "code": null, "e": 28266, "s": 28255, "text": "Palindrome" }, { "code": null, "e": 28578, "s": 28266, "text": "Method 2: Recursive way using substr() The substr() method is used to return a part of a string, referred to as the substring. Using this method, there is a recursive way to check for Palindrome or not. In this method no new string is formed and the original string is modified in each recursive call. Example: " }, { "code": null, "e": 28582, "s": 28578, "text": "PHP" }, { "code": "<?php// PHP code to check for Palindrome string in PHP// Recursive way using substr()function Palindrome($string){ // Base condition to end the recursive process if ((strlen($string) == 1) || (strlen($string) == 0)){ echo \"Palindrome\"; } else{ // First character is compared with the last one if (substr($string,0,1) == substr($string,(strlen($string) - 1),1)){ // Checked letters are discarded and passed for next call return Palindrome(substr($string,1,strlen($string) -2)); } else{ echo \" Not a Palindrome\"; } }} $string = \"MALAYALAM\";Palindrome($string);?> ", "e": 29255, "s": 28582, "text": null }, { "code": null, "e": 29265, "s": 29255, "text": "Output: " }, { "code": null, "e": 29276, "s": 29265, "text": "Palindrome" }, { "code": null, "e": 29883, "s": 29276, "text": "Working: The first character is matched with the last character of the string during each recursive call and if it matches, then both the characters are discarded during the next call. This goes on until the length of the string reduces to 0 or 1. In the following example where the word β€œMALAYALAM”, is taken, let’s see the working. In the first step both the M’s at both, the end is compared. Since it matches, both of them are discarded and the next string to be passed is β€œALAYALA”. Again both the A matched at both the end, so next string to be passed is β€œLAYAL”. This goes on until only β€œY” remains. " }, { "code": null, "e": 29899, "s": 29883, "text": "simranarora5sos" }, { "code": null, "e": 29912, "s": 29899, "text": "simmytarika5" }, { "code": null, "e": 29923, "s": 29912, "text": "PHP-string" }, { "code": null, "e": 29927, "s": 29923, "text": "PHP" }, { "code": null, "e": 29944, "s": 29927, "text": "Web Technologies" }, { "code": null, "e": 29948, "s": 29944, "text": "PHP" }, { "code": null, "e": 30046, "s": 29948, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30096, "s": 30046, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 30136, "s": 30096, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 30197, "s": 30136, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 30247, "s": 30197, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 30292, "s": 30247, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 30332, "s": 30292, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30365, "s": 30332, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30410, "s": 30365, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30453, "s": 30410, "text": "How to fetch data from an API in ReactJS ?" } ]
Java - Variable Types
A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. You must declare all variables before they can be used. Following is the basic form of a variable declaration βˆ’ data type variable [ = value][, variable [ = value] ...] ; Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list. Following are valid examples of variable declaration and initialization in Java βˆ’ int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char a = 'a'; // the char variable a iis initialized with value 'a' This chapter will explain various variable types available in Java Language. There are three kinds of variables in Java βˆ’ Local variables Instance variables Class/Static variables Local variables are declared in methods, constructors, or blocks. Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block. Access modifiers cannot be used for local variables. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor, or block. Local variables are visible only within the declared method, constructor, or block. Local variables are implemented at stack level internally. Local variables are implemented at stack level internally. There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use. There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use. Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method. public class Test { public void pupAge() { int age = 0; age = age + 7; System.out.println("Puppy age is : " + age); } public static void main(String args[]) { Test test = new Test(); test.pupAge(); } } This will produce the following result βˆ’ Puppy age is: 7 Following example uses age without initializing it, so it would give an error at the time of compilation. public class Test { public void pupAge() { int age; age = age + 7; System.out.println("Puppy age is : " + age); } public static void main(String args[]) { Test test = new Test(); test.pupAge(); } } This will produce the following error while compiling it βˆ’ Test.java:4:variable number might not have been initialized age = age + 7; ^ 1 error Instance variables are declared in a class, but outside a method, constructor or any block. Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared in class level before or after use. Instance variables can be declared in class level before or after use. Access modifiers can be given for instance variables. Access modifiers can be given for instance variables. The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers. The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers. Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName. Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName. import java.io.*; public class Employee { // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empName) { name = empName; } // The salary variable is assigned a value. public void setSalary(double empSal) { salary = empSal; } // This method prints the employee details. public void printEmp() { System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]) { Employee empOne = new Employee("Ransika"); empOne.setSalary(1000); empOne.printEmp(); } } This will produce the following result βˆ’ name : Ransika salary :1000.0 Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value. Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops. Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks. Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks. Static variables can be accessed by calling with the class name ClassName.VariableName. Static variables can be accessed by calling with the class name ClassName.VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables. import java.io.*; public class Employee { // salary variable is a private static variable private static double salary; // DEPARTMENT is a constant public static final String DEPARTMENT = "Development "; public static void main(String args[]) { salary = 1000; System.out.println(DEPARTMENT + "average salary:" + salary); } } This will produce the following result βˆ’ Development average salary:1000 Note βˆ’ If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT You already have used access modifiers (public & private) in this chapter. The next chapter will explain Access Modifiers and Non-Access Modifiers in detail. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2681, "s": 2377, "text": "A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable." }, { "code": null, "e": 2793, "s": 2681, "text": "You must declare all variables before they can be used. Following is the basic form of a variable declaration βˆ’" }, { "code": null, "e": 2853, "s": 2793, "text": "data type variable [ = value][, variable [ = value] ...] ;\n" }, { "code": null, "e": 3030, "s": 2853, "text": "Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list." }, { "code": null, "e": 3112, "s": 3030, "text": "Following are valid examples of variable declaration and initialization in Java βˆ’" }, { "code": null, "e": 3415, "s": 3112, "text": "int a, b, c; // Declares three ints, a, b, and c.\nint a = 10, b = 10; // Example of initialization\nbyte B = 22; // initializes a byte type variable B.\ndouble pi = 3.14159; // declares and assigns a value of PI.\nchar a = 'a'; // the char variable a iis initialized with value 'a'" }, { "code": null, "e": 3537, "s": 3415, "text": "This chapter will explain various variable types available in Java Language. There are three kinds of variables in Java βˆ’" }, { "code": null, "e": 3553, "s": 3537, "text": "Local variables" }, { "code": null, "e": 3572, "s": 3553, "text": "Instance variables" }, { "code": null, "e": 3595, "s": 3572, "text": "Class/Static variables" }, { "code": null, "e": 3661, "s": 3595, "text": "Local variables are declared in methods, constructors, or blocks." }, { "code": null, "e": 3727, "s": 3661, "text": "Local variables are declared in methods, constructors, or blocks." }, { "code": null, "e": 3888, "s": 3727, "text": "Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block." }, { "code": null, "e": 4049, "s": 3888, "text": "Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block." }, { "code": null, "e": 4102, "s": 4049, "text": "Access modifiers cannot be used for local variables." }, { "code": null, "e": 4155, "s": 4102, "text": "Access modifiers cannot be used for local variables." }, { "code": null, "e": 4239, "s": 4155, "text": "Local variables are visible only within the declared method, constructor, or block." }, { "code": null, "e": 4323, "s": 4239, "text": "Local variables are visible only within the declared method, constructor, or block." }, { "code": null, "e": 4382, "s": 4323, "text": "Local variables are implemented at stack level internally." }, { "code": null, "e": 4441, "s": 4382, "text": "Local variables are implemented at stack level internally." }, { "code": null, "e": 4588, "s": 4441, "text": "There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use." }, { "code": null, "e": 4735, "s": 4588, "text": "There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use." }, { "code": null, "e": 4851, "s": 4735, "text": "Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method." }, { "code": null, "e": 5096, "s": 4851, "text": "public class Test {\n public void pupAge() {\n int age = 0;\n age = age + 7;\n System.out.println(\"Puppy age is : \" + age);\n }\n\n public static void main(String args[]) {\n Test test = new Test();\n test.pupAge();\n }\n}" }, { "code": null, "e": 5137, "s": 5096, "text": "This will produce the following result βˆ’" }, { "code": null, "e": 5154, "s": 5137, "text": "Puppy age is: 7\n" }, { "code": null, "e": 5260, "s": 5154, "text": "Following example uses age without initializing it, so it would give an error at the time of compilation." }, { "code": null, "e": 5501, "s": 5260, "text": "public class Test {\n public void pupAge() {\n int age;\n age = age + 7;\n System.out.println(\"Puppy age is : \" + age);\n }\n\n public static void main(String args[]) {\n Test test = new Test();\n test.pupAge();\n }\n}" }, { "code": null, "e": 5560, "s": 5501, "text": "This will produce the following error while compiling it βˆ’" }, { "code": null, "e": 5655, "s": 5560, "text": "Test.java:4:variable number might not have been initialized\nage = age + 7;\n ^\n1 error\n" }, { "code": null, "e": 5747, "s": 5655, "text": "Instance variables are declared in a class, but outside a method, constructor or any block." }, { "code": null, "e": 5839, "s": 5747, "text": "Instance variables are declared in a class, but outside a method, constructor or any block." }, { "code": null, "e": 5944, "s": 5839, "text": "When a space is allocated for an object in the heap, a slot for each instance variable value is created." }, { "code": null, "e": 6049, "s": 5944, "text": "When a space is allocated for an object in the heap, a slot for each instance variable value is created." }, { "code": null, "e": 6184, "s": 6049, "text": "Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed." }, { "code": null, "e": 6319, "s": 6184, "text": "Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed." }, { "code": null, "e": 6504, "s": 6319, "text": "Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class." }, { "code": null, "e": 6689, "s": 6504, "text": "Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class." }, { "code": null, "e": 6760, "s": 6689, "text": "Instance variables can be declared in class level before or after use." }, { "code": null, "e": 6831, "s": 6760, "text": "Instance variables can be declared in class level before or after use." }, { "code": null, "e": 6885, "s": 6831, "text": "Access modifiers can be given for instance variables." }, { "code": null, "e": 6939, "s": 6885, "text": "Access modifiers can be given for instance variables." }, { "code": null, "e": 7206, "s": 6939, "text": "The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers." }, { "code": null, "e": 7473, "s": 7206, "text": "The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers." }, { "code": null, "e": 7687, "s": 7473, "text": "Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor." }, { "code": null, "e": 7901, "s": 7687, "text": "Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor." }, { "code": null, "e": 8158, "s": 7901, "text": "Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName." }, { "code": null, "e": 8415, "s": 8158, "text": "Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName." }, { "code": null, "e": 9197, "s": 8415, "text": "import java.io.*;\npublic class Employee {\n\n // this instance variable is visible for any child class.\n public String name;\n\n // salary variable is visible in Employee class only.\n private double salary;\n\n // The name variable is assigned in the constructor.\n public Employee (String empName) {\n name = empName;\n }\n\n // The salary variable is assigned a value.\n public void setSalary(double empSal) {\n salary = empSal;\n }\n\n // This method prints the employee details.\n public void printEmp() {\n System.out.println(\"name : \" + name );\n System.out.println(\"salary :\" + salary);\n }\n\n public static void main(String args[]) {\n Employee empOne = new Employee(\"Ransika\");\n empOne.setSalary(1000);\n empOne.printEmp();\n }\n}" }, { "code": null, "e": 9238, "s": 9197, "text": "This will produce the following result βˆ’" }, { "code": null, "e": 9270, "s": 9238, "text": "name : Ransika\nsalary :1000.0\n" }, { "code": null, "e": 9412, "s": 9270, "text": "Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block." }, { "code": null, "e": 9554, "s": 9412, "text": "Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block." }, { "code": null, "e": 9669, "s": 9554, "text": "There would only be one copy of each class variable per class, regardless of how many objects are created from it." }, { "code": null, "e": 9784, "s": 9669, "text": "There would only be one copy of each class variable per class, regardless of how many objects are created from it." }, { "code": null, "e": 9995, "s": 9784, "text": "Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value." }, { "code": null, "e": 10206, "s": 9995, "text": "Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value." }, { "code": null, "e": 10365, "s": 10206, "text": "Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants." }, { "code": null, "e": 10524, "s": 10365, "text": "Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants." }, { "code": null, "e": 10615, "s": 10524, "text": "Static variables are created when the program starts and destroyed when the program stops." }, { "code": null, "e": 10706, "s": 10615, "text": "Static variables are created when the program starts and destroyed when the program stops." }, { "code": null, "e": 10855, "s": 10706, "text": "Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class." }, { "code": null, "e": 11004, "s": 10855, "text": "Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class." }, { "code": null, "e": 11302, "s": 11004, "text": "Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks." }, { "code": null, "e": 11600, "s": 11302, "text": "Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks." }, { "code": null, "e": 11688, "s": 11600, "text": "Static variables can be accessed by calling with the class name ClassName.VariableName." }, { "code": null, "e": 11776, "s": 11688, "text": "Static variables can be accessed by calling with the class name ClassName.VariableName." }, { "code": null, "e": 11999, "s": 11776, "text": "When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables." }, { "code": null, "e": 12222, "s": 11999, "text": "When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables." }, { "code": null, "e": 12581, "s": 12222, "text": "import java.io.*;\npublic class Employee {\n\n // salary variable is a private static variable\n private static double salary;\n\n // DEPARTMENT is a constant\n public static final String DEPARTMENT = \"Development \";\n\n public static void main(String args[]) {\n salary = 1000;\n System.out.println(DEPARTMENT + \"average salary:\" + salary);\n }\n}" }, { "code": null, "e": 12622, "s": 12581, "text": "This will produce the following result βˆ’" }, { "code": null, "e": 12655, "s": 12622, "text": "Development average salary:1000\n" }, { "code": null, "e": 12770, "s": 12655, "text": "Note βˆ’ If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT" }, { "code": null, "e": 12928, "s": 12770, "text": "You already have used access modifiers (public & private) in this chapter. The next chapter will explain Access Modifiers and Non-Access Modifiers in detail." }, { "code": null, "e": 12961, "s": 12928, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 12977, "s": 12961, "text": " Malhar Lathkar" }, { "code": null, "e": 13010, "s": 12977, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 13026, "s": 13010, "text": " Malhar Lathkar" }, { "code": null, "e": 13061, "s": 13026, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 13075, "s": 13061, "text": " Anadi Sharma" }, { "code": null, "e": 13109, "s": 13075, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 13123, "s": 13109, "text": " Tushar Kale" }, { "code": null, "e": 13160, "s": 13123, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 13175, "s": 13160, "text": " Monica Mittal" }, { "code": null, "e": 13208, "s": 13175, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 13227, "s": 13208, "text": " Arnab Chakraborty" }, { "code": null, "e": 13234, "s": 13227, "text": " Print" }, { "code": null, "e": 13245, "s": 13234, "text": " Add Notes" } ]
How to make a new folder using askdirectory dialog in Tkinter?
To make a new folder using askdirectory dialog in Tkinter, we can take the following steps βˆ’ Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method. Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method. Create an instance of tkinter frame. Create an instance of tkinter frame. Set the size of the frame using win.geometry method. Set the size of the frame using win.geometry method. Define a user-defined method "create_subfolder". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path. Define a user-defined method "create_subfolder". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path. We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable. We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable. Then, use os.path.join and makedirs to create a sub-folder inside the parent directory. Then, use os.path.join and makedirs to create a sub-folder inside the parent directory. Create a button to call the create_subfolder method. Create a button to call the create_subfolder method. # Import the required libraries from tkinter import * from tkinter import ttk from tkinter import filedialog import os # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") def create_subfolder(): source_path = filedialog.askdirectory(title='Select the Parent Directory') path = os.path.join(source_path, 'Images') os.makedirs(path) button1 = ttk.Button(win, text="Select a Folder", command=create_subfolder) button1.pack(pady=5) win.mainloop() When we execute the above code, it will first show the following window βˆ’ Now, click the "Select a Folder" button to select a parent folder. It will automatically create a sub-folder called "Images" in the selected parent folder.
[ { "code": null, "e": 1155, "s": 1062, "text": "To make a new folder using askdirectory dialog in Tkinter, we can take the following steps βˆ’" }, { "code": null, "e": 1282, "s": 1155, "text": "Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method." }, { "code": null, "e": 1409, "s": 1282, "text": "Import the required modules. filedialog module is required for askdirectory method. os module is required for makedirs method." }, { "code": null, "e": 1446, "s": 1409, "text": "Create an instance of tkinter frame." }, { "code": null, "e": 1483, "s": 1446, "text": "Create an instance of tkinter frame." }, { "code": null, "e": 1536, "s": 1483, "text": "Set the size of the frame using win.geometry method." }, { "code": null, "e": 1589, "s": 1536, "text": "Set the size of the frame using win.geometry method." }, { "code": null, "e": 1751, "s": 1589, "text": "Define a user-defined method \"create_subfolder\". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path." }, { "code": null, "e": 1913, "s": 1751, "text": "Define a user-defined method \"create_subfolder\". Inside the method, call filedialog.askdirectory to select a folder and save the path in a variable, source_path." }, { "code": null, "e": 2041, "s": 1913, "text": "We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable." }, { "code": null, "e": 2169, "s": 2041, "text": "We can use askdirectory method of filedialog to open a directory. Save the path of the selected directory in a 'path' variable." }, { "code": null, "e": 2257, "s": 2169, "text": "Then, use os.path.join and makedirs to create a sub-folder inside the parent directory." }, { "code": null, "e": 2345, "s": 2257, "text": "Then, use os.path.join and makedirs to create a sub-folder inside the parent directory." }, { "code": null, "e": 2398, "s": 2345, "text": "Create a button to call the create_subfolder method." }, { "code": null, "e": 2451, "s": 2398, "text": "Create a button to call the create_subfolder method." }, { "code": null, "e": 2969, "s": 2451, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import filedialog\nimport os\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\ndef create_subfolder():\n source_path = filedialog.askdirectory(title='Select the Parent Directory')\n path = os.path.join(source_path, 'Images')\n os.makedirs(path)\n\nbutton1 = ttk.Button(win, text=\"Select a Folder\", command=create_subfolder)\n\nbutton1.pack(pady=5)\n\nwin.mainloop()" }, { "code": null, "e": 3043, "s": 2969, "text": "When we execute the above code, it will first show the following window βˆ’" }, { "code": null, "e": 3199, "s": 3043, "text": "Now, click the \"Select a Folder\" button to select a parent folder. It will automatically create a sub-folder called \"Images\" in the selected parent folder." } ]
Machine Learning Basics: Simple Linear Regression | by Gurucharan M K | Towards Data Science
One would perhaps come across the term β€œRegression” during their initial days of Data Science programming. In this story, I would like explain the program code for the very basic β€œSimple Linear Regression” with a common example. In statistics, Linear Regression is a linear approach to modeling the relationship between a scalar response (or dependent variable) and one or more explanatory variables (or independent variables). In our example, we will go through the Simple Linear Regression. Simple Linear Regression is of the form y = wx + b, where y is the dependent variable, x is the independent variable, w and b are the training parameters which are to be optimized during training process to get accurate predictions. Let us now apply Machine Learning to train a dataset to predict the Salary from Years of Experience. In this first step, we shall import the pandas library that will be used to store the data in a Pandas DataFrame. The matplotlib is used to plot graphs. import numpy as npimport matplotlib.pyplot as pltimport pandas as pd In this step, we shall download the dataset from my github repositary which contains the data as β€œSalary_Data.csv”. The variable X will store the β€œYears of Experience” and the variable Y will store the β€œSalary”. The dataset.head(5)is used to visualize the first 5 rows of the data. dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/Salary_Data.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, -1].valuesdataset.head(5)>>YearsExperience Salary1.1 39343.01.3 46205.01.5 37731.02.0 43525.02.2 39891.0 In this step, we have to split the dataset into the Training set, on which the Linear Regression model will be trained and the Test set, on which the trained model will be applied to visualize the results. In this the test_size=0.2 denotes that 20% of the data will be kept as the Test set and the remaining 80% will be used for training as the Training set. 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 the fourth step, the class LinearRegression is imported and is assigned to the variable β€œregressor”. The regressor.fit() function is fitted with X_train and Y_train on which the model will be trained. from sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train) In this step, the regressor.predict() function is used to predict the values for the Test set and the values are stored to the variable y_pred. y_pred = regressor.predict(X_test) In this step, a Pandas DataFrame is created to compare the Salary values of both the original Test set (y_test) and the predicted results (y_pred). df = pd.DataFrame({'Real Values':y_test, 'Predicted Values':y_pred})df>> Real Values Predicted Values109431.0 107621.91710781363.0 81508.21711293940.0 82440.84925555794.0 63788.20640166029.0 74047.15997091738.0 89901.906396 We can see that the predicted salaries are very close to the real salary values and it can be concluded that the model has been well trained. In this last step, we visualize the results of the Real and the Predicted Salary values along with the Linear Regression Line on a graph that is plotted. plt.scatter(X_test, y_test, color = 'red')plt.scatter(X_test, y_pred, color = 'green')plt.plot(X_train, regressor.predict(X_train), color = 'black')plt.title('Salary vs Experience (Result)')plt.xlabel('YearsExperience')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 Linear Regression line that is generated is drawn in β€œBlack” color. Thus in this story, we have successfully been able to build a Simple Linear Regression model that predicts the β€˜Salary’ of an employee based on their β€˜Years of Experience’ and visualize the results. I am also attaching the link to my github repository where you can download this Google Colab notebook and the data files for your reference. github.com 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": 401, "s": 172, "text": "One would perhaps come across the term β€œRegression” during their initial days of Data Science programming. In this story, I would like explain the program code for the very basic β€œSimple Linear Regression” with a common example." }, { "code": null, "e": 665, "s": 401, "text": "In statistics, Linear Regression is a linear approach to modeling the relationship between a scalar response (or dependent variable) and one or more explanatory variables (or independent variables). In our example, we will go through the Simple Linear Regression." }, { "code": null, "e": 898, "s": 665, "text": "Simple Linear Regression is of the form y = wx + b, where y is the dependent variable, x is the independent variable, w and b are the training parameters which are to be optimized during training process to get accurate predictions." }, { "code": null, "e": 999, "s": 898, "text": "Let us now apply Machine Learning to train a dataset to predict the Salary from Years of Experience." }, { "code": null, "e": 1152, "s": 999, "text": "In this first step, we shall import the pandas library that will be used to store the data in a Pandas DataFrame. The matplotlib is used to plot graphs." }, { "code": null, "e": 1221, "s": 1152, "text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd" }, { "code": null, "e": 1503, "s": 1221, "text": "In this step, we shall download the dataset from my github repositary which contains the data as β€œSalary_Data.csv”. The variable X will store the β€œYears of Experience” and the variable Y will store the β€œSalary”. The dataset.head(5)is used to visualize the first 5 rows of the data." }, { "code": null, "e": 1825, "s": 1503, "text": "dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Regression/master/Salary_Data.csv')X = dataset.iloc[:, :-1].valuesy = dataset.iloc[:, -1].valuesdataset.head(5)>>YearsExperience Salary1.1 39343.01.3 46205.01.5 37731.02.0 43525.02.2 39891.0" }, { "code": null, "e": 2184, "s": 1825, "text": "In this step, we have to split the dataset into the Training set, on which the Linear Regression model will be trained and the Test set, on which the trained model will be applied to visualize the results. In this the test_size=0.2 denotes that 20% of the data will be kept as the Test set and the remaining 80% will be used for training as the Training set." }, { "code": null, "e": 2311, "s": 2184, "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": 2515, "s": 2311, "text": "In the fourth step, the class LinearRegression is imported and is assigned to the variable β€œregressor”. The regressor.fit() function is fitted with X_train and Y_train on which the model will be trained." }, { "code": null, "e": 2626, "s": 2515, "text": "from sklearn.linear_model import LinearRegressionregressor = LinearRegression()regressor.fit(X_train, y_train)" }, { "code": null, "e": 2770, "s": 2626, "text": "In this step, the regressor.predict() function is used to predict the values for the Test set and the values are stored to the variable y_pred." }, { "code": null, "e": 2805, "s": 2770, "text": "y_pred = regressor.predict(X_test)" }, { "code": null, "e": 2953, "s": 2805, "text": "In this step, a Pandas DataFrame is created to compare the Salary values of both the original Test set (y_test) and the predicted results (y_pred)." }, { "code": null, "e": 3221, "s": 2953, "text": "df = pd.DataFrame({'Real Values':y_test, 'Predicted Values':y_pred})df>> Real Values Predicted Values109431.0 107621.91710781363.0 81508.21711293940.0 82440.84925555794.0 63788.20640166029.0 74047.15997091738.0 89901.906396" }, { "code": null, "e": 3363, "s": 3221, "text": "We can see that the predicted salaries are very close to the real salary values and it can be concluded that the model has been well trained." }, { "code": null, "e": 3517, "s": 3363, "text": "In this last step, we visualize the results of the Real and the Predicted Salary values along with the Linear Regression Line on a graph that is plotted." }, { "code": null, "e": 3767, "s": 3517, "text": "plt.scatter(X_test, y_test, color = 'red')plt.scatter(X_test, y_pred, color = 'green')plt.plot(X_train, regressor.predict(X_train), color = 'black')plt.title('Salary vs Experience (Result)')plt.xlabel('YearsExperience')plt.ylabel('Salary')plt.show()" }, { "code": null, "e": 3952, "s": 3767, "text": "In this graph, the Real values are plotted in β€œRed” color and the Predicted values are plotted in β€œGreen” color. The Linear Regression line that is generated is drawn in β€œBlack” color." }, { "code": null, "e": 4151, "s": 3952, "text": "Thus in this story, we have successfully been able to build a Simple Linear Regression model that predicts the β€˜Salary’ of an employee based on their β€˜Years of Experience’ and visualize the results." }, { "code": null, "e": 4293, "s": 4151, "text": "I am also attaching the link to my github repository where you can download this Google Colab notebook and the data files for your reference." }, { "code": null, "e": 4304, "s": 4293, "text": "github.com" }, { "code": null, "e": 4388, "s": 4304, "text": "You can also find the explanation of the program for other Regression models below:" }, { "code": null, "e": 4413, "s": 4388, "text": "Simple Linear Regression" }, { "code": null, "e": 4440, "s": 4413, "text": "Multiple Linear Regression" }, { "code": null, "e": 4462, "s": 4440, "text": "Polynomial Regression" }, { "code": null, "e": 4488, "s": 4462, "text": "Support Vector Regression" }, { "code": null, "e": 4513, "s": 4488, "text": "Decision Tree Regression" }, { "code": null, "e": 4538, "s": 4513, "text": "Random Forest Regression" } ]
Counting number of words in text file using java
We can read words in a file using BufferedReader class of Java and splitting the read data based on space character. See the example below: Consider the following text file in classpath. This is Line 1 This is Line 2 This is Line 3 This is Line 4 This is Line 5 This is Line 6 This is Line 7 This is Line 8 This is Line 9 This is Line 10 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; public class Tester { private static final String FILE_PATH = "data.txt"; public static void main(String args[]) throws IOException { FileUtil fileUtil = new FileUtil(FILE_PATH); System.out.println("No. of words in file: " + fileUtil.getWordCount()); } } class FileUtil { static BufferedReader reader = null; public FileUtil(String filePath) throws FileNotFoundException { File file = new File(filePath); FileInputStream fileStream = new FileInputStream(file); InputStreamReader input = new InputStreamReader(fileStream); reader = new BufferedReader(input); } public static int getWordCount() throws IOException { int wordCount = 0; String data; while((data = reader.readLine()) != null){ // \\s+ regex for space delimiter String[] words = data.split("\\s+"); wordCount += words.length; } return wordCount; } } This will produce the following result βˆ’ No. of words in file: 40
[ { "code": null, "e": 1202, "s": 1062, "text": "We can read words in a file using BufferedReader class of Java and splitting the read data based on space character. See the example below:" }, { "code": null, "e": 1249, "s": 1202, "text": "Consider the following text file in classpath." }, { "code": null, "e": 1400, "s": 1249, "text": "This is Line 1\nThis is Line 2\nThis is Line 3\nThis is Line 4\nThis is Line 5\nThis is Line 6\nThis is Line 7\nThis is Line 8\nThis is Line 9\nThis is Line 10" }, { "code": null, "e": 2517, "s": 1400, "text": "import java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class Tester {\n\n private static final String FILE_PATH = \"data.txt\";\n public static void main(String args[]) throws IOException {\n FileUtil fileUtil = new FileUtil(FILE_PATH);\n System.out.println(\"No. of words in file: \" + fileUtil.getWordCount());\n }\n}\n\nclass FileUtil {\n static BufferedReader reader = null;\n public FileUtil(String filePath) throws FileNotFoundException {\n File file = new File(filePath);\n FileInputStream fileStream = new FileInputStream(file);\n InputStreamReader input = new InputStreamReader(fileStream);\n reader = new BufferedReader(input);\n }\n\n public static int getWordCount() throws IOException {\n int wordCount = 0;\n String data;\n while((data = reader.readLine()) != null){\n\n // \\\\s+ regex for space delimiter\n String[] words = data.split(\"\\\\s+\");\n wordCount += words.length;\n }\n return wordCount;\n }\n}" }, { "code": null, "e": 2558, "s": 2517, "text": "This will produce the following result βˆ’" }, { "code": null, "e": 2583, "s": 2558, "text": "No. of words in file: 40" } ]
What is increment (++) operator in JavaScript?
The increment operator increases an integer value by one. Here’s an example where the value of a is incremented twice using the increment operator twice Live Demo <html> <body> <script> var a = 33; a = ++a; document.write("++a = "); result = ++a; document.write(result); </script> </body> </html>
[ { "code": null, "e": 1215, "s": 1062, "text": "The increment operator increases an integer value by one. Here’s an example where the value of a is incremented twice using the increment operator twice" }, { "code": null, "e": 1225, "s": 1215, "text": "Live Demo" }, { "code": null, "e": 1422, "s": 1225, "text": "<html>\n <body>\n <script>\n var a = 33;\n a = ++a;\n document.write(\"++a = \");\n result = ++a;\n document.write(result);\n </script>\n </body>\n</html>" } ]
How to create transparent statusbar and ActionBar in Android?
This example demonstrates how to create a transparent statusbar and ActionBar 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"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:background="#222222"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3 βˆ’ Add the following code to src/MainActivity.java package com.app.sample; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } Step 4 βˆ’ Add the following code to res/values/styles.xml <resources> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent<item> </style> <style name="AppTheme.ActionBar.Transparent" parent="AppTheme"> <item name="android:windowContentOverlay">@null</item> <item name="windowActionBarOverlay">true</item> <item name="colorPrimary">@android:color/transparent</item> </style> </resources> Step 4 βˆ’ Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:theme="@style/AppTheme.ActionBar.Transparent"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the 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": 1152, "s": 1062, "text": "This example demonstrates how to create a transparent statusbar and ActionBar in Android." }, { "code": null, "e": 1281, "s": 1152, "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": 1346, "s": 1281, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2140, "s": 1346, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\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:background=\"#222222\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</androidx.constraintlayout.widget.ConstraintLayout>" }, { "code": null, "e": 2197, "s": 2140, "text": "Step 3 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 2514, "s": 2197, "text": "package com.app.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}" }, { "code": null, "e": 2571, "s": 2514, "text": "Step 4 βˆ’ Add the following code to res/values/styles.xml" }, { "code": null, "e": 3122, "s": 2571, "text": "<resources>\n <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n <item name=\"colorPrimary\">@color/colorPrimary</item>\n <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n <item name=\"colorAccent\">@color/colorAccent<item>\n </style>\n <style name=\"AppTheme.ActionBar.Transparent\" parent=\"AppTheme\">\n <item name=\"android:windowContentOverlay\">@null</item>\n <item name=\"windowActionBarOverlay\">true</item>\n <item name=\"colorPrimary\">@android:color/transparent</item>\n </style>\n</resources>" }, { "code": null, "e": 3187, "s": 3122, "text": "Step 4 βˆ’ Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 3911, "s": 3187, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.app.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\" android:theme=\"@style/AppTheme.ActionBar.Transparent\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4262, "s": 3911, "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 the 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": 4303, "s": 4262, "text": "Click here to download the project code." } ]
PyTorch - Implementing First Neural Network
PyTorch includes a special feature of creating and implementing neural networks. In this chapter, we will create a simple neural network with one hidden layer developing a single output unit. We shall use following steps to implement the first neural network using PyTorch βˆ’ First, we need to import the PyTorch library using the below command βˆ’ import torch import torch.nn as nn Define all the layers and the batch size to start executing the neural network as shown below βˆ’ # Defining input size, hidden layer size, output size and batch size respectively n_in, n_h, n_out, batch_size = 10, 5, 1, 10 As neural network includes a combination of input data to get the respective output data, we will be following the same procedure as given below βˆ’ # Create dummy input and target tensors (data) x = torch.randn(batch_size, n_in) y = torch.tensor([[1.0], [0.0], [0.0], [1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]]) Create a sequential model with the help of in-built functions. Using the below lines of code, create a sequential model βˆ’ # Create a model model = nn.Sequential(nn.Linear(n_in, n_h), nn.ReLU(), nn.Linear(n_h, n_out), nn.Sigmoid()) Construct the loss function with the help of Gradient Descent optimizer as shown below βˆ’ Construct the loss function criterion = torch.nn.MSELoss() # Construct the optimizer (Stochastic Gradient Descent in this case) optimizer = torch.optim.SGD(model.parameters(), lr = 0.01) Implement the gradient descent model with the iterating loop with the given lines of code βˆ’ # Gradient Descent for epoch in range(50): # Forward pass: Compute predicted y by passing x to the model y_pred = model(x) # Compute and print loss loss = criterion(y_pred, y) print('epoch: ', epoch,' loss: ', loss.item()) # Zero gradients, perform a backward pass, and update the weights. optimizer.zero_grad() # perform a backward pass (backpropagation) loss.backward() # Update the parameters optimizer.step() The output generated is as follows βˆ’ epoch: 0 loss: 0.2545787990093231 epoch: 1 loss: 0.2545052170753479 epoch: 2 loss: 0.254431813955307 epoch: 3 loss: 0.25435858964920044 epoch: 4 loss: 0.2542854845523834 epoch: 5 loss: 0.25421255826950073 epoch: 6 loss: 0.25413978099823 epoch: 7 loss: 0.25406715273857117 epoch: 8 loss: 0.2539947032928467 epoch: 9 loss: 0.25392240285873413 epoch: 10 loss: 0.25385022163391113 epoch: 11 loss: 0.25377824902534485 epoch: 12 loss: 0.2537063956260681 epoch: 13 loss: 0.2536346912384033 epoch: 14 loss: 0.25356316566467285 epoch: 15 loss: 0.25349172949790955 epoch: 16 loss: 0.25342053174972534 epoch: 17 loss: 0.2533493936061859 epoch: 18 loss: 0.2532784342765808 epoch: 19 loss: 0.25320762395858765 epoch: 20 loss: 0.2531369626522064 epoch: 21 loss: 0.25306645035743713 epoch: 22 loss: 0.252996027469635 epoch: 23 loss: 0.2529257833957672 epoch: 24 loss: 0.25285571813583374 epoch: 25 loss: 0.25278574228286743 epoch: 26 loss: 0.25271597504615784 epoch: 27 loss: 0.25264623761177063 epoch: 28 loss: 0.25257670879364014 epoch: 29 loss: 0.2525072991847992 epoch: 30 loss: 0.2524380087852478 epoch: 31 loss: 0.2523689270019531 epoch: 32 loss: 0.25229987502098083 epoch: 33 loss: 0.25223103165626526 epoch: 34 loss: 0.25216227769851685 epoch: 35 loss: 0.252093642950058 epoch: 36 loss: 0.25202515721321106 epoch: 37 loss: 0.2519568204879761 epoch: 38 loss: 0.251888632774353 epoch: 39 loss: 0.25182053446769714 epoch: 40 loss: 0.2517525553703308 epoch: 41 loss: 0.2516847252845764 epoch: 42 loss: 0.2516169846057892 epoch: 43 loss: 0.2515493929386139 epoch: 44 loss: 0.25148195028305054 epoch: 45 loss: 0.25141456723213196 epoch: 46 loss: 0.2513473629951477 epoch: 47 loss: 0.2512802183628082 epoch: 48 loss: 0.2512132525444031 epoch: 49 loss: 0.2511464059352875 Print Add Notes Bookmark this page
[ { "code": null, "e": 2451, "s": 2259, "text": "PyTorch includes a special feature of creating and implementing neural networks. In this chapter, we will create a simple neural network with one hidden layer developing a single output unit." }, { "code": null, "e": 2534, "s": 2451, "text": "We shall use following steps to implement the first neural network using PyTorch βˆ’" }, { "code": null, "e": 2605, "s": 2534, "text": "First, we need to import the PyTorch library using the below command βˆ’" }, { "code": null, "e": 2642, "s": 2605, "text": "import torch \nimport torch.nn as nn\n" }, { "code": null, "e": 2738, "s": 2642, "text": "Define all the layers and the batch size to start executing the neural network as shown below βˆ’" }, { "code": null, "e": 2864, "s": 2738, "text": "# Defining input size, hidden layer size, output size and batch size respectively\nn_in, n_h, n_out, batch_size = 10, 5, 1, 10" }, { "code": null, "e": 3011, "s": 2864, "text": "As neural network includes a combination of input data to get the respective output data, we will be following the same procedure as given below βˆ’" }, { "code": null, "e": 3182, "s": 3011, "text": "# Create dummy input and target tensors (data)\nx = torch.randn(batch_size, n_in)\ny = torch.tensor([[1.0], [0.0], [0.0], \n[1.0], [1.0], [1.0], [0.0], [0.0], [1.0], [1.0]])" }, { "code": null, "e": 3304, "s": 3182, "text": "Create a sequential model with the help of in-built functions. Using the below lines of code, create a sequential model βˆ’" }, { "code": null, "e": 3422, "s": 3304, "text": "# Create a model\nmodel = nn.Sequential(nn.Linear(n_in, n_h),\n nn.ReLU(),\n nn.Linear(n_h, n_out),\n nn.Sigmoid())" }, { "code": null, "e": 3511, "s": 3422, "text": "Construct the loss function with the help of Gradient Descent optimizer as shown below βˆ’" }, { "code": null, "e": 3698, "s": 3511, "text": "Construct the loss function\ncriterion = torch.nn.MSELoss()\n# Construct the optimizer (Stochastic Gradient Descent in this case)\noptimizer = torch.optim.SGD(model.parameters(), lr = 0.01)" }, { "code": null, "e": 3790, "s": 3698, "text": "Implement the gradient descent model with the iterating loop with the given lines of code βˆ’" }, { "code": null, "e": 4240, "s": 3790, "text": "# Gradient Descent\nfor epoch in range(50):\n # Forward pass: Compute predicted y by passing x to the model\n y_pred = model(x)\n\n # Compute and print loss\n loss = criterion(y_pred, y)\n print('epoch: ', epoch,' loss: ', loss.item())\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad()\n\n # perform a backward pass (backpropagation)\n loss.backward()\n\n # Update the parameters\n optimizer.step()" }, { "code": null, "e": 4277, "s": 4240, "text": "The output generated is as follows βˆ’" }, { "code": null, "e": 6034, "s": 4277, "text": "epoch: 0 loss: 0.2545787990093231\nepoch: 1 loss: 0.2545052170753479\nepoch: 2 loss: 0.254431813955307\nepoch: 3 loss: 0.25435858964920044\nepoch: 4 loss: 0.2542854845523834\nepoch: 5 loss: 0.25421255826950073\nepoch: 6 loss: 0.25413978099823\nepoch: 7 loss: 0.25406715273857117\nepoch: 8 loss: 0.2539947032928467\nepoch: 9 loss: 0.25392240285873413\nepoch: 10 loss: 0.25385022163391113\nepoch: 11 loss: 0.25377824902534485\nepoch: 12 loss: 0.2537063956260681\nepoch: 13 loss: 0.2536346912384033\nepoch: 14 loss: 0.25356316566467285\nepoch: 15 loss: 0.25349172949790955\nepoch: 16 loss: 0.25342053174972534\nepoch: 17 loss: 0.2533493936061859\nepoch: 18 loss: 0.2532784342765808\nepoch: 19 loss: 0.25320762395858765\nepoch: 20 loss: 0.2531369626522064\nepoch: 21 loss: 0.25306645035743713\nepoch: 22 loss: 0.252996027469635\nepoch: 23 loss: 0.2529257833957672\nepoch: 24 loss: 0.25285571813583374\nepoch: 25 loss: 0.25278574228286743\nepoch: 26 loss: 0.25271597504615784\nepoch: 27 loss: 0.25264623761177063\nepoch: 28 loss: 0.25257670879364014\nepoch: 29 loss: 0.2525072991847992\nepoch: 30 loss: 0.2524380087852478\nepoch: 31 loss: 0.2523689270019531\nepoch: 32 loss: 0.25229987502098083\nepoch: 33 loss: 0.25223103165626526\nepoch: 34 loss: 0.25216227769851685\nepoch: 35 loss: 0.252093642950058\nepoch: 36 loss: 0.25202515721321106\nepoch: 37 loss: 0.2519568204879761\nepoch: 38 loss: 0.251888632774353\nepoch: 39 loss: 0.25182053446769714\nepoch: 40 loss: 0.2517525553703308\nepoch: 41 loss: 0.2516847252845764\nepoch: 42 loss: 0.2516169846057892\nepoch: 43 loss: 0.2515493929386139\nepoch: 44 loss: 0.25148195028305054\nepoch: 45 loss: 0.25141456723213196\nepoch: 46 loss: 0.2513473629951477\nepoch: 47 loss: 0.2512802183628082\nepoch: 48 loss: 0.2512132525444031\nepoch: 49 loss: 0.2511464059352875" }, { "code": null, "e": 6041, "s": 6034, "text": " Print" }, { "code": null, "e": 6052, "s": 6041, "text": " Add Notes" } ]
Cross-Entropy for Dummies. A simple and intuitive explanation of... | by Viraj Kulkarni | Towards Data Science
Cross-entropy is commonly used as a loss function for classification problems, but due to historical reasons, most explanations of cross-entropy are based on communication theory which data scientists may not be familiar with. You cannot understand cross-entropy without understanding entropy, and you cannot understand entropy without knowing what information is. This article builds the concept of cross-entropy in an easy-to-understand manner without relying on its communication theory background. Let’s consider three illustrative experiments. (1) I toss a coin, and I give you a message that the coin came up heads. The message conveyed some information to you. How much information? Let’s say you got one bit of information from this message. Coin came up heads (probability=0.5) | Information = 1 bit (2) I woke you up in the morning and told you that the sun rose. You shrugged and angrily went back to sleep, because this message was obvious and gave you no new information. Sun rose (probability=1) | Information = 0 bits (3) I woke you up in the morning and told you the sun did not rise. You came out shocked and saw the world had gone crazy. This was breaking news β€” lots of information. Sun did not rise (probability=0) | Information = ∞ bits From the above examples, you might have deduced that the information contained in a message about an event is related to the uncertainty and surprise-value of the event. An occurrence of an unlikely event gives you more information than the occurrence of a likely event. Claude Shannon formalised this intuition behind information in his seminal work on Information Theory. He defined information as: I(x) = -log2P(x) ..where P(x) is probability of occurrence of x Information quantifies the uncertainty in one single event. What if you are interested not in one single event but in a sequence of events? Consider the following example. A bin contains 2 red, 3 green, and 4 blue balls. Now, instead of tossing a coin, I pick out one ball at random and give it to you. What is the expected amount of information you will receive every time I pick one ball? We model picking out a ball as a stochastic process represented by a random variable X. The entropy of X is then defined as the expected value of the information conveyed by an outcome in X. Using our above definition of information, we get: P(red ball) = 2/9; I(red ball) = -log2(2/9)P(green ball) = 3/9; I(green ball) = -log2(3/9)P(blue ball) = 4/9; I(blue ball) = -log2(4/9)Entropy = E[I(all balls)] = -[(2/9)*log2(2/9) + (3/9)*log2(3/9) + (4/9)*log2(4/9)]= 1.53 bits. * Expected Value or Expectation of random variable X, written as E[X], is the average of all values of X weighted by the probability of their occurrence. In other words, you can expect to get 1.53 bits of information on average every time I pick out a ball from the bin. Formally, the entropy H of a probability distribution of a random variable is defined as: The x~P in the above equation means that the values x takes are from the distribution P. In our example, P = (2 red, 3 green, 4 blue). Cross-entropy measures the relative entropy between two probability distributions over the same set of events. Intuitively, to calculate cross-entropy between P and Q, you simply calculate entropy for Q using probability weights from P. Formally: Let’s consider the same bin example with two bins. Bin P = {2 red, 3 green, 4 blue} Bin Q = {4 red, 4 green, 1 blue} H(P, Q) = -[(2/9)*log2(4/9) + (3/9)*log2(4/9) + (4/9)*log2(1/9)] Instead of the contrived example above, let’s take a machine learning example where we use cross-entropy as a loss function. Suppose we build a classifier that predicts samples in three classes: A, B, C. Let P be the true label distribution and Q be the predicted label distribution. Suppose the true label of one particular sample is B and our classifier predicts probabilities for A, B, C as (0.15, 0.60, 0.25) Cross-entropy H(P, Q) will be: H(P, Q) = -[0 * log2(0.15) + 1 * log2(0.6) + 0 * log2(0.25)] = 0.736 On the other hand, if our classifier is more confident and predicts probabilities as (0.05, 0.90, 0.05), we would get cross-entropy as 0.15, which is lower than the above example. For classification problems, using cross-entropy as a loss function is equivalent to maximising log likelihood. Consider the below case of binary classification where a, b, c, d represent probabilities: H(True, Predicted)= -[a*log(b) + c*log(d)]= -[a*log(b) + (1-a)*log(1-b)]= -[y*log(yΜ‚) + (1-y)*log(1-yΜ‚)]..where y is true label and yΜ‚ is predicted label This is the same equation for maximum likelihood estimation. Due to historical reasons, you will often find cross-entropy defined in the context of communication theory such as: cross-entropy is the average number of bits needed to encode data coming from a source with distribution p when we use model q. Most data scientists have never studied communication theory. I hope they find the above article useful. If you liked the article, check out my other pieces on Medium, follow me on LinkedIn or Twitter, view my personal webpage, or email me at [email protected].
[ { "code": null, "e": 674, "s": 172, "text": "Cross-entropy is commonly used as a loss function for classification problems, but due to historical reasons, most explanations of cross-entropy are based on communication theory which data scientists may not be familiar with. You cannot understand cross-entropy without understanding entropy, and you cannot understand entropy without knowing what information is. This article builds the concept of cross-entropy in an easy-to-understand manner without relying on its communication theory background." }, { "code": null, "e": 721, "s": 674, "text": "Let’s consider three illustrative experiments." }, { "code": null, "e": 922, "s": 721, "text": "(1) I toss a coin, and I give you a message that the coin came up heads. The message conveyed some information to you. How much information? Let’s say you got one bit of information from this message." }, { "code": null, "e": 981, "s": 922, "text": "Coin came up heads (probability=0.5) | Information = 1 bit" }, { "code": null, "e": 1157, "s": 981, "text": "(2) I woke you up in the morning and told you that the sun rose. You shrugged and angrily went back to sleep, because this message was obvious and gave you no new information." }, { "code": null, "e": 1205, "s": 1157, "text": "Sun rose (probability=1) | Information = 0 bits" }, { "code": null, "e": 1374, "s": 1205, "text": "(3) I woke you up in the morning and told you the sun did not rise. You came out shocked and saw the world had gone crazy. This was breaking news β€” lots of information." }, { "code": null, "e": 1430, "s": 1374, "text": "Sun did not rise (probability=0) | Information = ∞ bits" }, { "code": null, "e": 1831, "s": 1430, "text": "From the above examples, you might have deduced that the information contained in a message about an event is related to the uncertainty and surprise-value of the event. An occurrence of an unlikely event gives you more information than the occurrence of a likely event. Claude Shannon formalised this intuition behind information in his seminal work on Information Theory. He defined information as:" }, { "code": null, "e": 1895, "s": 1831, "text": "I(x) = -log2P(x) ..where P(x) is probability of occurrence of x" }, { "code": null, "e": 1955, "s": 1895, "text": "Information quantifies the uncertainty in one single event." }, { "code": null, "e": 2528, "s": 1955, "text": "What if you are interested not in one single event but in a sequence of events? Consider the following example. A bin contains 2 red, 3 green, and 4 blue balls. Now, instead of tossing a coin, I pick out one ball at random and give it to you. What is the expected amount of information you will receive every time I pick one ball? We model picking out a ball as a stochastic process represented by a random variable X. The entropy of X is then defined as the expected value of the information conveyed by an outcome in X. Using our above definition of information, we get:" }, { "code": null, "e": 2758, "s": 2528, "text": "P(red ball) = 2/9; I(red ball) = -log2(2/9)P(green ball) = 3/9; I(green ball) = -log2(3/9)P(blue ball) = 4/9; I(blue ball) = -log2(4/9)Entropy = E[I(all balls)] = -[(2/9)*log2(2/9) + (3/9)*log2(3/9) + (4/9)*log2(4/9)]= 1.53 bits." }, { "code": null, "e": 2912, "s": 2758, "text": "* Expected Value or Expectation of random variable X, written as E[X], is the average of all values of X weighted by the probability of their occurrence." }, { "code": null, "e": 3029, "s": 2912, "text": "In other words, you can expect to get 1.53 bits of information on average every time I pick out a ball from the bin." }, { "code": null, "e": 3119, "s": 3029, "text": "Formally, the entropy H of a probability distribution of a random variable is defined as:" }, { "code": null, "e": 3254, "s": 3119, "text": "The x~P in the above equation means that the values x takes are from the distribution P. In our example, P = (2 red, 3 green, 4 blue)." }, { "code": null, "e": 3501, "s": 3254, "text": "Cross-entropy measures the relative entropy between two probability distributions over the same set of events. Intuitively, to calculate cross-entropy between P and Q, you simply calculate entropy for Q using probability weights from P. Formally:" }, { "code": null, "e": 3552, "s": 3501, "text": "Let’s consider the same bin example with two bins." }, { "code": null, "e": 3585, "s": 3552, "text": "Bin P = {2 red, 3 green, 4 blue}" }, { "code": null, "e": 3618, "s": 3585, "text": "Bin Q = {4 red, 4 green, 1 blue}" }, { "code": null, "e": 3683, "s": 3618, "text": "H(P, Q) = -[(2/9)*log2(4/9) + (3/9)*log2(4/9) + (4/9)*log2(1/9)]" }, { "code": null, "e": 3887, "s": 3683, "text": "Instead of the contrived example above, let’s take a machine learning example where we use cross-entropy as a loss function. Suppose we build a classifier that predicts samples in three classes: A, B, C." }, { "code": null, "e": 4096, "s": 3887, "text": "Let P be the true label distribution and Q be the predicted label distribution. Suppose the true label of one particular sample is B and our classifier predicts probabilities for A, B, C as (0.15, 0.60, 0.25)" }, { "code": null, "e": 4127, "s": 4096, "text": "Cross-entropy H(P, Q) will be:" }, { "code": null, "e": 4196, "s": 4127, "text": "H(P, Q) = -[0 * log2(0.15) + 1 * log2(0.6) + 0 * log2(0.25)] = 0.736" }, { "code": null, "e": 4376, "s": 4196, "text": "On the other hand, if our classifier is more confident and predicts probabilities as (0.05, 0.90, 0.05), we would get cross-entropy as 0.15, which is lower than the above example." }, { "code": null, "e": 4579, "s": 4376, "text": "For classification problems, using cross-entropy as a loss function is equivalent to maximising log likelihood. Consider the below case of binary classification where a, b, c, d represent probabilities:" }, { "code": null, "e": 4733, "s": 4579, "text": "H(True, Predicted)= -[a*log(b) + c*log(d)]= -[a*log(b) + (1-a)*log(1-b)]= -[y*log(yΜ‚) + (1-y)*log(1-yΜ‚)]..where y is true label and yΜ‚ is predicted label" }, { "code": null, "e": 4794, "s": 4733, "text": "This is the same equation for maximum likelihood estimation." }, { "code": null, "e": 5144, "s": 4794, "text": "Due to historical reasons, you will often find cross-entropy defined in the context of communication theory such as: cross-entropy is the average number of bits needed to encode data coming from a source with distribution p when we use model q. Most data scientists have never studied communication theory. I hope they find the above article useful." } ]
Maximum Length of a Concatenated String with Unique Characters in C++
Suppose we have an array of strings arr. The string s is a concatenation of a sub-sequence of arr which have unique characters. Find the maximum possible length of s. If the input is like [β€œcha”, β€œr”, β€œact”, β€œers”], then the output will be 6, possible solutions are β€œchaers” and β€œacters”. To solve this, we will follow these steps βˆ’ make one method called ok() and this will take strings s and t. This will act like below make one map x for i in range 0 to size of sincrease x[s[i]] by 1if x[s[i]] > 1, then return false increase x[s[i]] by 1 if x[s[i]] > 1, then return false for i in range 0 to size of tincrease x[t[i]] by 1if x[t[i]] > 1, then return false increase x[t[i]] by 1 if x[t[i]] > 1, then return false return true the actual method will be look like below βˆ’ make an array of strings called v, and ans := 0, insert one empty string into v for i in range 0 to size of arrn := size of vfor j in range 0 to n – 1if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t n := size of v for j in range 0 to n – 1if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t t := v[j] + arr[i] insert t into v ans := max of ans and size of t return ans Let us see the following implementation to get better understanding βˆ’ Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: bool ok(string s, string t){ map <char, int > x; for(int i = 0; i < s.size(); i++){ x[s[i]]++; if(x[s[i]] >1)return false; } for(int i = 0; i < t.size(); i++){ x[t[i]]++; if(x[t[i]]>1)return false; } return true; } int maxLength(vector<string>& arr) { vector <string> v; int ans = 0; v.push_back(""); for(int i = 0; i < arr.size(); i++){ int n = v.size(); for(int j = 0; j < n; j++){ if(ok(v[j],arr[i])){ string t = v[j]+arr[i]; v.push_back(t); ans = max(ans,(int)t.size()); } } } return ans; } }; main(){ vector<string> v = {"cha","r","act","ers"}; Solution ob; cout << (ob.maxLength(v)); } ["cha","r","act","ers"] 6
[ { "code": null, "e": 1351, "s": 1062, "text": "Suppose we have an array of strings arr. The string s is a concatenation of a sub-sequence of arr which have unique characters. Find the maximum possible length of s. If the input is like [β€œcha”, β€œr”, β€œact”, β€œers”], then the output will be 6, possible solutions are β€œchaers” and β€œacters”." }, { "code": null, "e": 1395, "s": 1351, "text": "To solve this, we will follow these steps βˆ’" }, { "code": null, "e": 1484, "s": 1395, "text": "make one method called ok() and this will take strings s and t. This will act like below" }, { "code": null, "e": 1499, "s": 1484, "text": "make one map x" }, { "code": null, "e": 1583, "s": 1499, "text": "for i in range 0 to size of sincrease x[s[i]] by 1if x[s[i]] > 1, then return false" }, { "code": null, "e": 1605, "s": 1583, "text": "increase x[s[i]] by 1" }, { "code": null, "e": 1639, "s": 1605, "text": "if x[s[i]] > 1, then return false" }, { "code": null, "e": 1723, "s": 1639, "text": "for i in range 0 to size of tincrease x[t[i]] by 1if x[t[i]] > 1, then return false" }, { "code": null, "e": 1745, "s": 1723, "text": "increase x[t[i]] by 1" }, { "code": null, "e": 1779, "s": 1745, "text": "if x[t[i]] > 1, then return false" }, { "code": null, "e": 1791, "s": 1779, "text": "return true" }, { "code": null, "e": 1835, "s": 1791, "text": "the actual method will be look like below βˆ’" }, { "code": null, "e": 1915, "s": 1835, "text": "make an array of strings called v, and ans := 0, insert one empty string into v" }, { "code": null, "e": 2083, "s": 1915, "text": "for i in range 0 to size of arrn := size of vfor j in range 0 to n – 1if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t" }, { "code": null, "e": 2098, "s": 2083, "text": "n := size of v" }, { "code": null, "e": 2221, "s": 2098, "text": "for j in range 0 to n – 1if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t" }, { "code": null, "e": 2319, "s": 2221, "text": "if ok(v[j], arr[i]) is true, thent := v[j] + arr[i]insert t into vans := max of ans and size of t" }, { "code": null, "e": 2338, "s": 2319, "text": "t := v[j] + arr[i]" }, { "code": null, "e": 2354, "s": 2338, "text": "insert t into v" }, { "code": null, "e": 2386, "s": 2354, "text": "ans := max of ans and size of t" }, { "code": null, "e": 2397, "s": 2386, "text": "return ans" }, { "code": null, "e": 2467, "s": 2397, "text": "Let us see the following implementation to get better understanding βˆ’" }, { "code": null, "e": 2478, "s": 2467, "text": " Live Demo" }, { "code": null, "e": 3369, "s": 2478, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n bool ok(string s, string t){\n map <char, int > x;\n for(int i = 0; i < s.size(); i++){\n x[s[i]]++;\n if(x[s[i]] >1)return false;\n }\n for(int i = 0; i < t.size(); i++){\n x[t[i]]++;\n if(x[t[i]]>1)return false;\n }\n return true;\n }\n int maxLength(vector<string>& arr) {\n vector <string> v;\n int ans = 0;\n v.push_back(\"\");\n for(int i = 0; i < arr.size(); i++){\n int n = v.size();\n for(int j = 0; j < n; j++){\n if(ok(v[j],arr[i])){\n string t = v[j]+arr[i];\n v.push_back(t);\n ans = max(ans,(int)t.size());\n }\n }\n }\n return ans;\n }\n};\nmain(){\n vector<string> v = {\"cha\",\"r\",\"act\",\"ers\"};\n Solution ob;\n cout << (ob.maxLength(v));\n}" }, { "code": null, "e": 3393, "s": 3369, "text": "[\"cha\",\"r\",\"act\",\"ers\"]" }, { "code": null, "e": 3395, "s": 3393, "text": "6" } ]
Get value from div with JavaScript resulting undefined?
Use document.getElementById().innerHTML for this. Following is the JavaScript code βˆ’ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <div class='getValueFromDiv' id='getValue' contenteditable="true" onkeyUp='display()' style="color: red"></div> <script> function display(){ var storedValue = document.getElementById('getValue').innerHTML.value="This is the value"; console.log("The value is==="+storedValue); } </script> </body> </html> To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS Code editor. Following is the output. When you will click the mouse and place the arrow key, you will get the following output. The snapshot is as follows βˆ’
[ { "code": null, "e": 1147, "s": 1062, "text": "Use document.getElementById().innerHTML for this. Following is the JavaScript code βˆ’" }, { "code": null, "e": 1869, "s": 1147, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<div class='getValueFromDiv' id='getValue' contenteditable=\"true\" onkeyUp='display()'\nstyle=\"color: red\"></div>\n<script>\n function display(){\n var storedValue = document.getElementById('getValue').innerHTML.value=\"This is the\n value\";\n console.log(\"The value is===\"+storedValue);\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 2030, "s": 1869, "text": "To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS Code editor." }, { "code": null, "e": 2145, "s": 2030, "text": "Following is the output. When you will click the mouse and place the arrow key, you will get the\nfollowing output." }, { "code": null, "e": 2174, "s": 2145, "text": "The snapshot is as follows βˆ’" } ]
How to declare a two-dimensional array in C#
A 2-dimensional array is a list of one-dimensional arrays. Declare it like the two dimensional array shown below βˆ’ int [,] a Two-dimensional arrays may be initialized by specifying bracketed values for each row. int [,] a = new int [4,4] { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} , {12, 13, 14, 15} }; The following is an example showing how to work with two-dimensional arrays in C# βˆ’ Live Demo using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { /* an array with 3 rows and 2 columns*/ int[,] a = new int[3, 2] {{0,0}, {1,2}, {2,4} }; int i, j; /* output each array element's value */ for (i = 0; i < 3; i++) { for (j = 0; j < 2; j++) { Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]); } } Console.ReadKey(); } } } a[0,0] = 0 a[0,1] = 0 a[1,0] = 1 a[1,1] = 2 a[2,0] = 2 a[2,1] = 4
[ { "code": null, "e": 1177, "s": 1062, "text": "A 2-dimensional array is a list of one-dimensional arrays. Declare it like the two dimensional array shown below βˆ’" }, { "code": null, "e": 1187, "s": 1177, "text": "int [,] a" }, { "code": null, "e": 1274, "s": 1187, "text": "Two-dimensional arrays may be initialized by specifying bracketed values for each row." }, { "code": null, "e": 1369, "s": 1274, "text": "int [,] a = new int [4,4] {\n{0, 1, 2, 3} ,\n{4, 5, 6, 7} ,\n{8, 9, 10, 11} ,\n{12, 13, 14, 15}\n};" }, { "code": null, "e": 1453, "s": 1369, "text": "The following is an example showing how to work with two-dimensional arrays in C# βˆ’" }, { "code": null, "e": 1464, "s": 1453, "text": " Live Demo" }, { "code": null, "e": 1953, "s": 1464, "text": "using System;\n\nnamespace ArrayApplication {\n class MyArray {\n static void Main(string[] args) {\n /* an array with 3 rows and 2 columns*/\n int[,] a = new int[3, 2] {{0,0}, {1,2}, {2,4} };\n int i, j;\n\n /* output each array element's value */\n for (i = 0; i < 3; i++) {\n\n for (j = 0; j < 2; j++) {\n Console.WriteLine(\"a[{0},{1}] = {2}\", i, j, a[i,j]);\n }\n }\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 2019, "s": 1953, "text": "a[0,0] = 0\na[0,1] = 0\na[1,0] = 1\na[1,1] = 2\na[2,0] = 2\na[2,1] = 4" } ]
Eggs dropping puzzle (Binomial Coefficient and Binary Search Solution) - GeeksforGeeks
09 Jul, 2021 Given n eggs and k floors, find the minimum number of trials needed in worst case to find the floor below which all floors are safe. A floor is safe if dropping an egg from it does not break the egg. Please see n eggs and k floors. for complete statements Example Input : n = 2, k = 10 Output : 4 We first try from 4-th floor. Two cases arise, (1) If egg breaks, we have one egg left so we need three more trials. (2) If egg does not break, we try next from 7-th floor. Again two cases arise. We can notice that if we choose 4th floor as first floor, 7-th as next floor and 9 as next of next floor, we never exceed more than 4 trials. Input : n = 2. k = 100 Output : 14 We have discussed the problem for 2 eggs and k floors. We have also discussed a dynamic programming solution to find the solution. The dynamic programming solution is based on below recursive nature of the problem. Let us look at the discussed recursive formula from a different perspective. How many floors we can cover with x trials? When we drop an egg, two cases arise. If egg breaks, then we are left with x-1 trials and n-1 eggs.If egg does not break, then we are left with x-1 trials and n eggs If egg breaks, then we are left with x-1 trials and n-1 eggs. If egg does not break, then we are left with x-1 trials and n eggs Let maxFloors(x, n) be the maximum number of floors that we can cover with x trials and n eggs. From above two cases, we can write. maxFloors(x, n) = maxFloors(x-1, n-1) + maxFloors(x-1, n) + 1 For all x >= 1 and n >= 1 Base cases : We can't cover any floor with 0 trials or 0 eggs maxFloors(0, n) = 0 maxFloors(x, 0) = 0 Since we need to cover k floors, maxFloors(x, n) >= k ----------(1) The above recurrence simplifies to following, Refer this for proof. maxFloors(x, n) = &Sum;xCi 1 <= i <= n ----------(2) Here C represents Binomial Coefficient. From above two equations, we can say. &Sum;xCj >= k 1 <= i <= n Basically we need to find minimum value of x that satisfies above inequality. We can find such x using Binary Search. C++ Java Python3 C# PHP Javascript // C++ program to find minimum// number of trials in worst case.#include <bits/stdc++.h> using namespace std; // Find sum of binomial coefficients xCi// (where i varies from 1 to n).int binomialCoeff(int x, int n, int k){ int sum = 0, term = 1; for (int i = 1; i <= n; ++i) { term *= x - i + 1; term /= i; sum += term; if(sum>k) return sum; } return sum;} // Do binary search to find minimum// number of trials in worst case.int minTrials(int n, int k){ // Initialize low and high as 1st // and last floors int low = 1, high = k; // Do binary search, for every mid, // find sum of binomial coefficients and // check if the sum is greater than k or not. while (low < high) { int mid = (low + high) / 2; if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} /* Driver code*/int main(){ cout << minTrials(2, 10); return 0;} // Java program to find minimum// number of trials in worst case.class Geeks { // Find sum of binomial coefficients xCi// (where i varies from 1 to n). If the sum// becomes more than Kstatic int binomialCoeff(int x, int n, int k){ int sum = 0, term = 1; for (int i = 1; i <= n && sum < k; ++i) { term *= x - i + 1; term /= i; sum += term; } return sum;} // Do binary search to find minimum// number of trials in worst case.static int minTrials(int n, int k){ // Initialize low and high as 1st //and last floors int low = 1, high = k; // Do binary search, for every mid, // find sum of binomial coefficients and // check if the sum is greater than k or not. while (low < high) { int mid = (low + high) / 2; if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} /* Driver code*/public static void main(String args[]){ System.out.println(minTrials(2, 10));}} // This code is contributed by ankita_saini # Python3 program to find minimum# number of trials in worst case. # Find sum of binomial coefficients# xCi (where i varies from 1 to n).# If the sum becomes more than Kdef binomialCoeff(x, n, k): sum = 0; term = 1; i = 1; while(i <= n and sum < k): term *= x - i + 1; term /= i; sum += term; i += 1; return sum; # Do binary search to find minimum# number of trials in worst case.def minTrials(n, k): # Initialize low and high as # 1st and last floors low = 1; high = k; # Do binary search, for every # mid, find sum of binomial # coefficients and check if # the sum is greater than k or not. while (low < high): mid = int((low + high) / 2); if (binomialCoeff(mid, n, k) < k): low = mid + 1; else: high = mid; return int(low); # Driver Codeprint(minTrials(2, 10)); # This code is contributed# by mits // C# program to find minimum// number of trials in worst case.using System; class GFG{ // Find sum of binomial coefficients// xCi (where i varies from 1 to n).// If the sum becomes more than Kstatic int binomialCoeff(int x, int n, int k){ int sum = 0, term = 1; for (int i = 1; i <= n && sum < k; ++i) { term *= x - i + 1; term /= i; sum += term; } return sum;} // Do binary search to find minimum// number of trials in worst case.static int minTrials(int n, int k){ // Initialize low and high // as 1st and last floors int low = 1, high = k; // Do binary search, for every // mid, find sum of binomial // coefficients and check if the // sum is greater than k or not. while (low < high) { int mid = (low + high) / 2; if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} // Driver Codepublic static void Main(){ Console.WriteLine(minTrials(2, 10));}} // This code is contributed// by Akanksha Rai(Abby_akku) <?php// PHP program to find minimum// number of trials in worst case. // Find sum of binomial coefficients// xCi (where i varies from 1 to n).// If the sum becomes more than Kfunction binomialCoeff($x, $n, $k){ $sum = 0; $term = 1; for ($i = 1; $i <= $n && $sum < $k; ++$i) { $term *= $x - $i + 1; $term /= $i; $sum += $term; } return $sum;} // Do binary search to find minimum// number of trials in worst case.function minTrials($n, $k){ // Initialize low and high as // 1st and last floors $low = 1; $high = $k; // Do binary search, for every // mid, find sum of binomial // coefficients and check if // the sum is greater than k or not. while ($low < $high) { $mid = ($low + $high) / 2; if (binomialCoeff($mid, $n, $k) < $k) $low = $mid + 1; else $high = $mid; } return (int)$low;} // Driver Codeecho minTrials(2, 10); // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // Javascript program to find minimum// number of trials in worst case. // Find sum of binomial coefficients xCi// (where i varies from 1 to n). If the sum// becomes more than Kfunction binomialCoeff(x, n, k){ var sum = 0, term = 1; for(var i = 1; i <= n && sum < k; ++i) { term *= x - i + 1; term /= i; sum += term; } return sum;} // Do binary search to find minimum// number of trials in worst case.function minTrials(n, k){ // Initialize low and high as 1st //and last floors var low = 1, high = k; // Do binary search, for every mid, // find sum of binomial coefficients and // check if the sum is greater than k or not. while (low < high) { var mid = parseInt((low + high) / 2); if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} // Driver codedocument.write(minTrials(2, 10)); // This code is contributed by shivanisinghss2110 </script> 4 Time Complexity : O(n Log k) ankita_saini Akanksha_Rai Mithun Kumar yashjaiswal10 dkp1903 studyrockers5 infinitetsukiyome shivanisinghss2110 Binary Search binomial coefficient Egg-Dropping programming-puzzle Mathematical Mathematical Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Sieve of Eratosthenes Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 24968, "s": 24940, "text": "\n09 Jul, 2021" }, { "code": null, "e": 25224, "s": 24968, "text": "Given n eggs and k floors, find the minimum number of trials needed in worst case to find the floor below which all floors are safe. A floor is safe if dropping an egg from it does not break the egg. Please see n eggs and k floors. for complete statements" }, { "code": null, "e": 25232, "s": 25224, "text": "Example" }, { "code": null, "e": 25647, "s": 25232, "text": "Input : n = 2, k = 10\nOutput : 4\nWe first try from 4-th floor. Two cases arise,\n(1) If egg breaks, we have one egg left so we\n need three more trials.\n(2) If egg does not break, we try next from 7-th\n floor. Again two cases arise.\nWe can notice that if we choose 4th floor as first\nfloor, 7-th as next floor and 9 as next of next floor,\nwe never exceed more than 4 trials.\n\nInput : n = 2. k = 100\nOutput : 14" }, { "code": null, "e": 25939, "s": 25647, "text": "We have discussed the problem for 2 eggs and k floors. We have also discussed a dynamic programming solution to find the solution. The dynamic programming solution is based on below recursive nature of the problem. Let us look at the discussed recursive formula from a different perspective." }, { "code": null, "e": 26022, "s": 25939, "text": "How many floors we can cover with x trials? When we drop an egg, two cases arise. " }, { "code": null, "e": 26150, "s": 26022, "text": "If egg breaks, then we are left with x-1 trials and n-1 eggs.If egg does not break, then we are left with x-1 trials and n eggs" }, { "code": null, "e": 26212, "s": 26150, "text": "If egg breaks, then we are left with x-1 trials and n-1 eggs." }, { "code": null, "e": 26279, "s": 26212, "text": "If egg does not break, then we are left with x-1 trials and n eggs" }, { "code": null, "e": 27053, "s": 26279, "text": "Let maxFloors(x, n) be the maximum number of floors \nthat we can cover with x trials and n eggs. From above \ntwo cases, we can write.\n\nmaxFloors(x, n) = maxFloors(x-1, n-1) + maxFloors(x-1, n) + 1\nFor all x >= 1 and n >= 1\n\nBase cases : \nWe can't cover any floor with 0 trials or 0 eggs\nmaxFloors(0, n) = 0\nmaxFloors(x, 0) = 0\n\nSince we need to cover k floors, \nmaxFloors(x, n) >= k ----------(1)\n\nThe above recurrence simplifies to following,\nRefer this for proof.\n\nmaxFloors(x, n) = &Sum;xCi\n 1 <= i <= n ----------(2)\nHere C represents Binomial Coefficient.\n\nFrom above two equations, we can say.\n&Sum;xCj >= k\n1 <= i <= n\nBasically we need to find minimum value of x\nthat satisfies above inequality. We can find\nsuch x using Binary Search." }, { "code": null, "e": 27057, "s": 27053, "text": "C++" }, { "code": null, "e": 27062, "s": 27057, "text": "Java" }, { "code": null, "e": 27070, "s": 27062, "text": "Python3" }, { "code": null, "e": 27073, "s": 27070, "text": "C#" }, { "code": null, "e": 27077, "s": 27073, "text": "PHP" }, { "code": null, "e": 27088, "s": 27077, "text": "Javascript" }, { "code": "// C++ program to find minimum// number of trials in worst case.#include <bits/stdc++.h> using namespace std; // Find sum of binomial coefficients xCi// (where i varies from 1 to n).int binomialCoeff(int x, int n, int k){ int sum = 0, term = 1; for (int i = 1; i <= n; ++i) { term *= x - i + 1; term /= i; sum += term; if(sum>k) return sum; } return sum;} // Do binary search to find minimum// number of trials in worst case.int minTrials(int n, int k){ // Initialize low and high as 1st // and last floors int low = 1, high = k; // Do binary search, for every mid, // find sum of binomial coefficients and // check if the sum is greater than k or not. while (low < high) { int mid = (low + high) / 2; if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} /* Driver code*/int main(){ cout << minTrials(2, 10); return 0;}", "e": 28065, "s": 27088, "text": null }, { "code": "// Java program to find minimum// number of trials in worst case.class Geeks { // Find sum of binomial coefficients xCi// (where i varies from 1 to n). If the sum// becomes more than Kstatic int binomialCoeff(int x, int n, int k){ int sum = 0, term = 1; for (int i = 1; i <= n && sum < k; ++i) { term *= x - i + 1; term /= i; sum += term; } return sum;} // Do binary search to find minimum// number of trials in worst case.static int minTrials(int n, int k){ // Initialize low and high as 1st //and last floors int low = 1, high = k; // Do binary search, for every mid, // find sum of binomial coefficients and // check if the sum is greater than k or not. while (low < high) { int mid = (low + high) / 2; if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} /* Driver code*/public static void main(String args[]){ System.out.println(minTrials(2, 10));}} // This code is contributed by ankita_saini", "e": 29100, "s": 28065, "text": null }, { "code": "# Python3 program to find minimum# number of trials in worst case. # Find sum of binomial coefficients# xCi (where i varies from 1 to n).# If the sum becomes more than Kdef binomialCoeff(x, n, k): sum = 0; term = 1; i = 1; while(i <= n and sum < k): term *= x - i + 1; term /= i; sum += term; i += 1; return sum; # Do binary search to find minimum# number of trials in worst case.def minTrials(n, k): # Initialize low and high as # 1st and last floors low = 1; high = k; # Do binary search, for every # mid, find sum of binomial # coefficients and check if # the sum is greater than k or not. while (low < high): mid = int((low + high) / 2); if (binomialCoeff(mid, n, k) < k): low = mid + 1; else: high = mid; return int(low); # Driver Codeprint(minTrials(2, 10)); # This code is contributed# by mits", "e": 30022, "s": 29100, "text": null }, { "code": "// C# program to find minimum// number of trials in worst case.using System; class GFG{ // Find sum of binomial coefficients// xCi (where i varies from 1 to n).// If the sum becomes more than Kstatic int binomialCoeff(int x, int n, int k){ int sum = 0, term = 1; for (int i = 1; i <= n && sum < k; ++i) { term *= x - i + 1; term /= i; sum += term; } return sum;} // Do binary search to find minimum// number of trials in worst case.static int minTrials(int n, int k){ // Initialize low and high // as 1st and last floors int low = 1, high = k; // Do binary search, for every // mid, find sum of binomial // coefficients and check if the // sum is greater than k or not. while (low < high) { int mid = (low + high) / 2; if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} // Driver Codepublic static void Main(){ Console.WriteLine(minTrials(2, 10));}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 31112, "s": 30022, "text": null }, { "code": "<?php// PHP program to find minimum// number of trials in worst case. // Find sum of binomial coefficients// xCi (where i varies from 1 to n).// If the sum becomes more than Kfunction binomialCoeff($x, $n, $k){ $sum = 0; $term = 1; for ($i = 1; $i <= $n && $sum < $k; ++$i) { $term *= $x - $i + 1; $term /= $i; $sum += $term; } return $sum;} // Do binary search to find minimum// number of trials in worst case.function minTrials($n, $k){ // Initialize low and high as // 1st and last floors $low = 1; $high = $k; // Do binary search, for every // mid, find sum of binomial // coefficients and check if // the sum is greater than k or not. while ($low < $high) { $mid = ($low + $high) / 2; if (binomialCoeff($mid, $n, $k) < $k) $low = $mid + 1; else $high = $mid; } return (int)$low;} // Driver Codeecho minTrials(2, 10); // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 32115, "s": 31112, "text": null }, { "code": "<script> // Javascript program to find minimum// number of trials in worst case. // Find sum of binomial coefficients xCi// (where i varies from 1 to n). If the sum// becomes more than Kfunction binomialCoeff(x, n, k){ var sum = 0, term = 1; for(var i = 1; i <= n && sum < k; ++i) { term *= x - i + 1; term /= i; sum += term; } return sum;} // Do binary search to find minimum// number of trials in worst case.function minTrials(n, k){ // Initialize low and high as 1st //and last floors var low = 1, high = k; // Do binary search, for every mid, // find sum of binomial coefficients and // check if the sum is greater than k or not. while (low < high) { var mid = parseInt((low + high) / 2); if (binomialCoeff(mid, n, k) < k) low = mid + 1; else high = mid; } return low;} // Driver codedocument.write(minTrials(2, 10)); // This code is contributed by shivanisinghss2110 </script>", "e": 33112, "s": 32115, "text": null }, { "code": null, "e": 33114, "s": 33112, "text": "4" }, { "code": null, "e": 33144, "s": 33114, "text": "Time Complexity : O(n Log k) " }, { "code": null, "e": 33157, "s": 33144, "text": "ankita_saini" }, { "code": null, "e": 33170, "s": 33157, "text": "Akanksha_Rai" }, { "code": null, "e": 33183, "s": 33170, "text": "Mithun Kumar" }, { "code": null, "e": 33197, "s": 33183, "text": "yashjaiswal10" }, { "code": null, "e": 33205, "s": 33197, "text": "dkp1903" }, { "code": null, "e": 33219, "s": 33205, "text": "studyrockers5" }, { "code": null, "e": 33237, "s": 33219, "text": "infinitetsukiyome" }, { "code": null, "e": 33256, "s": 33237, "text": "shivanisinghss2110" }, { "code": null, "e": 33270, "s": 33256, "text": "Binary Search" }, { "code": null, "e": 33291, "s": 33270, "text": "binomial coefficient" }, { "code": null, "e": 33304, "s": 33291, "text": "Egg-Dropping" }, { "code": null, "e": 33323, "s": 33304, "text": "programming-puzzle" }, { "code": null, "e": 33336, "s": 33323, "text": "Mathematical" }, { "code": null, "e": 33349, "s": 33336, "text": "Mathematical" }, { "code": null, "e": 33363, "s": 33349, "text": "Binary Search" }, { "code": null, "e": 33461, "s": 33363, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33485, "s": 33461, "text": "Merge two sorted arrays" }, { "code": null, "e": 33527, "s": 33485, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 33570, "s": 33527, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33584, "s": 33570, "text": "Prime Numbers" }, { "code": null, "e": 33633, "s": 33584, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 33655, "s": 33633, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33696, "s": 33655, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 33730, "s": 33696, "text": "Program for factorial of a number" }, { "code": null, "e": 33751, "s": 33730, "text": "Operators in C / C++" } ]
Database Testing – Interview Questions
Database testing includes performing the data validity, data Integrity testing, performance check related to database and testing of Procedures, triggers and functions in the database. There are multiple reasons why database testing is performed. There is a need to perform data integrity, validation and data consistency check on database as the backend system is responsible to store the data and is accessed for multiple purpose. Some of the common reasons why one needs to perform Database testing are as follows βˆ’ To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures. To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures. These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels. These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels. Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system. Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system. In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly. In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly. The steps that you need to follow while performing database testing are as follows βˆ’ The data that is being in the database must be verified. Verify if the constraints are maintained. The performance of the procedures and execution of triggers must be checked. Roll back and commit of transaction must be checked. On the basis of function and structure of a database, DB testing can be categorized into the following categories βˆ’ Structural Database testing βˆ’ It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc. Structural Database testing βˆ’ It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc. Functional Testing βˆ’ It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing. Functional Testing βˆ’ It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing. Nonfunctional Testing βˆ’ It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database. Nonfunctional Testing βˆ’ It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database. The most common tools that are used to perform stored procedures testing are LINQ, SP Test tool, etc. Joins are used to connect two or more tables in some logical manner. Common types of joins include: Inner join, Non-equijoin, Outer join, Self-join, and Cross join. You can join a single table to itself. In this case, you are using the same table twice. Step 1 βˆ’ Connect to the database db_connect(query1 DRIVER {drivername};SERVER server_name;UID uidname; PWD password;DBQ database_name ); Step 2 βˆ’ Execute the query of the database βˆ’ db_excecute_query (write the required query that is to execute); Specify the appropriate condition Step 3 βˆ’ Disconnect the database connection by using db_disconnect(query); Using Output database checkpoints, SQL manual queries options must be selected. Here, the select query can be written. First, check the requirement of the stored procedure. The next step is to check if indexes, joins, deletions, update are correct in comparison with tables mentioned in stored procedure. Next, perform the following tasks βˆ’ Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters. Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters. Execute the procedure with TOAD or MySQL or Query Analyzer. Execute the procedure with TOAD or MySQL or Query Analyzer. Re-execute the available procedures by sending different parameters, and check the results against expected values. Re-execute the available procedures by sending different parameters, and check the results against expected values. Concluding to the process, automate the tests with WinRunner. Concluding to the process, automate the tests with WinRunner. The tester should call the stored procedure in the database using the EXEC command. If any parameters are required, they must be passed. Different values of parameters must be passed to confirm if the stored procedure is executed or not. On calling this command it must check and verify the nature and behavior of the database. Example βˆ’ If the stored procedure is written to populate some table, the table values must be checked. We have three types of SQL statements βˆ’ Data Manipulation Language (DML) Data Definition Language (DDL) Data Control Language (DCL) DDL statements are used to define the database structure or schema. Some examples βˆ’ CREATE βˆ’ to create objects in the database CREATE βˆ’ to create objects in the database ALTER βˆ’ alters the structure of the database ALTER βˆ’ alters the structure of the database DROP βˆ’ delete objects from the database DROP βˆ’ delete objects from the database Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement. Arithmetic Operators Comparison/Relational Operators Logical Operators Set Operators Operators used to negate conditions Union is used to combine the results of two or more Select statements. However it will eliminate the duplicate rows. Union is a set operator. Union is used to combine the results of two or more Select statements. However it will eliminate duplicate rows Union All operation is similar to Union, but it also shows the duplicate rows. Triggers are used to maintain the Integrity of database. To check Trigger is fired or not you can check in audit logs. Triggers can’t be invoked on demand. They are invoked when an associated action (insert, delete & update) happens on the table on which they are defined. Triggers are used to apply business rules, auditing and also for the referential integrity checks. First, get the functional requirement. Then, understand the table structure, Joins, Cursors and Triggers, Stored procedure used, and other parameters. Next, you can write a test-case with different values as input to these objects. DB testing involves testing of back-end components which are not visible to users. It includes database components and DBMS systems such as MySQL and Oracle. Front-end testing involves checking functionalities of an application and its components like forms, graphs, menus, reports, etc. These components are created using front-end development tools like VB.net, C#, Delphi, etc. The process to perform database testing is similar to testing of other applications. DB testing can be described with the following key processes βˆ’ Setting up the environment Run a test Check the test result Validating according to the expected results Report the findings to the respective stakeholders Various SQL statements are used to develop the Test cases. Most common SQL statement which is used to perform DB testing is select statement. Apart from this various DDL, DML, DCL statements can also be used. Example βˆ’ Create, Insert, Select, Update, etc. A view is a table that does not really exist in its own right but is instead derived from one or more base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the changes in the database. Hence accounts for logical data independence. It specifies user views and their mappings to the conceptual schema. It is a process of decomposing a table into multiple tables without losing any information. Normalization is done to achieve the following goals βˆ’ To minimize redundancy. To minimize insertion, deletion and update anomalies. Indexing is a technique for determining how quickly specific data can be found. It is used for query performance optimization. Indexing can be of the following types βˆ’ Binary search style indexing B-Tree indexing Inverted list indexing Memory resident table Table indexing SQL is a Structured Query language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. Stored procedures are used to perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors βˆ’ implicit and explicit. Cold Backup βˆ’ Cold back is known as taking back up of database files, redo logs, and control file when the instance is shut down. This is a file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All the changes that are performed after the last backup is lost. Hot Backup βˆ’ Some databases can’t shut down while making a backup copy of the files, so cold backup is not an available option. For these types of database we use hot backup. SQL subquery is a means of querying two or more tables at the same time. The subquery itself is an SQL SELECT statement contained within the WHERE clause of another SQL SELECT statement, and separated by being enclosed in parenthesis. Some subqueries have equivalent SQL join structures, but correlated subqueries cannot be duplicated by a join In such a case, you need to test the following aspects βˆ’ Multivalued dependencies Functional dependencies Candidate keys Primary keys Foreign keys You can go to the database and run a relevant SQL query. In WinRunner, you can use database checkpoint function. If the application provides view function, then you can verify the same from the front-end. Data-driven testing is defined as an automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface. Once you execute the test-cases and find the defects that has been already detected and fixed. Re-execution of the same test with different input values to confirm the original defect has been successfully removed is called Re-testing. Retesting is also called Data Driven Testing with a small difference βˆ’ Retesting βˆ’ It is a manual testing process whereas application testing done with entire new set of data. Retesting βˆ’ It is a manual testing process whereas application testing done with entire new set of data. Data-driven Testing βˆ’ It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface. Data-driven Testing βˆ’ It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface. There are four types of data driven testing βˆ’ Dynamic test data submission through keyboard Data Driven Tests via .txt, .doc flat files Data Driven Tests via front-end objects Data Driven Tests via excel sheet Performance testing is a software testing technique to determine how a system performs in terms of speed, sensitivity and stability under a heavy workload. The following key points are to be considered while performing database recovery testing βˆ’ Time span when changes or modifications occurs in database system. Time span when changes or modifications occurs in database system. The period by which you want your recovery plan conducted. The period by which you want your recovery plan conducted. The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software. The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software. The following tools are used to generate test data βˆ’ Data Factory DTM Data Generator Turbo Data There are two types of backup that can be used βˆ’ Physical Backups βˆ’ Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities. Physical Backups βˆ’ Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities. Logical Backups βˆ’ Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc. Logical Backups βˆ’ Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc. A common tool to take data backup is Oracle Recovery Manager (RMAN) that is an Oracle utility to take database backup. The following actions are performed in database recovery testing βˆ’ Testing of database system Testing of the SQL files Testing of partial files Testing of data backup Testing of Backup tool Testing log backups Database security testing is performed to find the loop holes in security mechanisms and also about finding the vulnerabilities or weaknesses of database system. Database security testing is performed to check the following aspects βˆ’ Authentication Authorization Confidentiality Availability Integrity Resilience SQL Injection threat is the most common type of attack in a database system where malicious SQL statements are inserted in database system and executed to get critical information from database system. This attack takes advantage of loopholes in implementation of user applications. To prevent this user inputs fields should be carefully handled. The following tools can be used to perform database security testing: Zed Attack Proxy, Paros, Social Engineer Toolkit, Skipfish, Vega, Wapiti, and Web Scarab. The common challenges that one faces while performing database testing are as follows βˆ’ Testing scope is too large Scaled-down test database Changes in database structure Complex Test Plans Good understanding of SQL 33 Lectures 7.5 hours Syed Raza 31 Lectures 6 hours Eduonix Learning Solutions 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 17 Lectures 1.5 hours Pranjal Srivastava 19 Lectures 2 hours Harshit Srivastava 19 Lectures 5 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2255, "s": 2070, "text": "Database testing includes performing the data validity, data Integrity testing, performance check related to database and testing of Procedures, triggers and functions in the database." }, { "code": null, "e": 2503, "s": 2255, "text": "There are multiple reasons why database testing is performed. There is a need to perform data integrity, validation and data consistency check on database as the backend system is responsible to store the data and is accessed for multiple purpose." }, { "code": null, "e": 2589, "s": 2503, "text": "Some of the common reasons why one needs to perform Database testing are as follows βˆ’" }, { "code": null, "e": 2701, "s": 2589, "text": "To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures." }, { "code": null, "e": 2813, "s": 2701, "text": "To ease the complexity of calls to database backend, developers increase the use of View and Stored Procedures." }, { "code": null, "e": 3004, "s": 2813, "text": "These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels." }, { "code": null, "e": 3195, "s": 3004, "text": "These Stored procedures and Views contain critical tasks such as inserting customer details (name, contact information, etc.) and sales data. These tasks need to be tested at several levels." }, { "code": null, "e": 3427, "s": 3195, "text": "Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system." }, { "code": null, "e": 3659, "s": 3427, "text": "Black box testing performed on front-end is important, but makes it difficult to isolate the problem. Testing at the backend system increases the robustness of the data. That is why database testing is performed on back end system." }, { "code": null, "e": 3937, "s": 3659, "text": "In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly." }, { "code": null, "e": 4215, "s": 3937, "text": "In a database, data comes from multiple applications and there is a possibility that harmful or incorrect data is stored in the database. Therefore, there is a need to check database components regularly. In addition, data integrity and consistency should be checked regularly." }, { "code": null, "e": 4300, "s": 4215, "text": "The steps that you need to follow while performing database testing are as follows βˆ’" }, { "code": null, "e": 4357, "s": 4300, "text": "The data that is being in the database must be verified." }, { "code": null, "e": 4399, "s": 4357, "text": "Verify if the constraints are maintained." }, { "code": null, "e": 4476, "s": 4399, "text": "The performance of the procedures and execution of triggers must be checked." }, { "code": null, "e": 4529, "s": 4476, "text": "Roll back and commit of transaction must be checked." }, { "code": null, "e": 4645, "s": 4529, "text": "On the basis of function and structure of a database, DB testing can be categorized into the following categories βˆ’" }, { "code": null, "e": 4792, "s": 4645, "text": "Structural Database testing βˆ’ It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc." }, { "code": null, "e": 4939, "s": 4792, "text": "Structural Database testing βˆ’ It deals with table and column testing, schema testing, stored procedures and views testing, checking triggers, etc." }, { "code": null, "e": 5108, "s": 4939, "text": "Functional Testing βˆ’ It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing." }, { "code": null, "e": 5277, "s": 5108, "text": "Functional Testing βˆ’ It involves checking functionality of database from user point of view. Most common type of Functional testing are White box and black box testing." }, { "code": null, "e": 5440, "s": 5277, "text": "Nonfunctional Testing βˆ’ It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database." }, { "code": null, "e": 5603, "s": 5440, "text": "Nonfunctional Testing βˆ’ It involves load testing, risk testing in database, stress testing, minimum system requirement, and deals wot performance of the database." }, { "code": null, "e": 5705, "s": 5603, "text": "The most common tools that are used to perform stored procedures testing are LINQ, SP Test tool, etc." }, { "code": null, "e": 5870, "s": 5705, "text": "Joins are used to connect two or more tables in some logical manner. Common types of joins include: Inner join, Non-equijoin, Outer join, Self-join, and Cross join." }, { "code": null, "e": 5959, "s": 5870, "text": "You can join a single table to itself. In this case, you are using the same table twice." }, { "code": null, "e": 5992, "s": 5959, "text": "Step 1 βˆ’ Connect to the database" }, { "code": null, "e": 6099, "s": 5992, "text": "db_connect(query1 DRIVER {drivername};SERVER server_name;UID uidname;\n PWD password;DBQ database_name );" }, { "code": null, "e": 6144, "s": 6099, "text": "Step 2 βˆ’ Execute the query of the database βˆ’" }, { "code": null, "e": 6243, "s": 6144, "text": "db_excecute_query (write the required query that is to execute); Specify the appropriate condition" }, { "code": null, "e": 6296, "s": 6243, "text": "Step 3 βˆ’ Disconnect the database connection by using" }, { "code": null, "e": 6318, "s": 6296, "text": "db_disconnect(query);" }, { "code": null, "e": 6437, "s": 6318, "text": "Using Output database checkpoints, SQL manual queries options must be selected. Here, the select query can be written." }, { "code": null, "e": 6623, "s": 6437, "text": "First, check the requirement of the stored procedure. The next step is to check if indexes, joins, deletions, update are correct in comparison with tables mentioned in stored procedure." }, { "code": null, "e": 6659, "s": 6623, "text": "Next, perform the following tasks βˆ’" }, { "code": null, "e": 6778, "s": 6659, "text": "Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters." }, { "code": null, "e": 6897, "s": 6778, "text": "Validate the calling procedure name, calling parameters and expected responses for different sets of input parameters." }, { "code": null, "e": 6957, "s": 6897, "text": "Execute the procedure with TOAD or MySQL or Query Analyzer." }, { "code": null, "e": 7017, "s": 6957, "text": "Execute the procedure with TOAD or MySQL or Query Analyzer." }, { "code": null, "e": 7133, "s": 7017, "text": "Re-execute the available procedures by sending different parameters, and check the results against expected values." }, { "code": null, "e": 7249, "s": 7133, "text": "Re-execute the available procedures by sending different parameters, and check the results against expected values." }, { "code": null, "e": 7311, "s": 7249, "text": "Concluding to the process, automate the tests with WinRunner." }, { "code": null, "e": 7373, "s": 7311, "text": "Concluding to the process, automate the tests with WinRunner." }, { "code": null, "e": 7701, "s": 7373, "text": "The tester should call the stored procedure in the database using the EXEC command. If any parameters are required, they must be passed. Different values of parameters must be passed to confirm if the stored procedure is executed or not. On calling this command it must check and verify the nature and behavior of the database." }, { "code": null, "e": 7804, "s": 7701, "text": "Example βˆ’ If the stored procedure is written to populate some table, the table values must be checked." }, { "code": null, "e": 7844, "s": 7804, "text": "We have three types of SQL statements βˆ’" }, { "code": null, "e": 7877, "s": 7844, "text": "Data Manipulation Language (DML)" }, { "code": null, "e": 7908, "s": 7877, "text": "Data Definition Language (DDL)" }, { "code": null, "e": 7936, "s": 7908, "text": "Data Control Language (DCL)" }, { "code": null, "e": 8020, "s": 7936, "text": "DDL statements are used to define the database structure or schema. Some examples βˆ’" }, { "code": null, "e": 8063, "s": 8020, "text": "CREATE βˆ’ to create objects in the database" }, { "code": null, "e": 8106, "s": 8063, "text": "CREATE βˆ’ to create objects in the database" }, { "code": null, "e": 8151, "s": 8106, "text": "ALTER βˆ’ alters the structure of the database" }, { "code": null, "e": 8196, "s": 8151, "text": "ALTER βˆ’ alters the structure of the database" }, { "code": null, "e": 8236, "s": 8196, "text": "DROP βˆ’ delete objects from the database" }, { "code": null, "e": 8276, "s": 8236, "text": "DROP βˆ’ delete objects from the database" }, { "code": null, "e": 8406, "s": 8276, "text": "Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple conditions in a statement." }, { "code": null, "e": 8427, "s": 8406, "text": "Arithmetic Operators" }, { "code": null, "e": 8459, "s": 8427, "text": "Comparison/Relational Operators" }, { "code": null, "e": 8477, "s": 8459, "text": "Logical Operators" }, { "code": null, "e": 8491, "s": 8477, "text": "Set Operators" }, { "code": null, "e": 8527, "s": 8491, "text": "Operators used to negate conditions" }, { "code": null, "e": 8669, "s": 8527, "text": "Union is used to combine the results of two or more Select statements. However it will eliminate the duplicate rows. Union is a set operator." }, { "code": null, "e": 8781, "s": 8669, "text": "Union is used to combine the results of two or more Select statements. However it will eliminate duplicate rows" }, { "code": null, "e": 8860, "s": 8781, "text": "Union All operation is similar to Union, but it also shows the duplicate rows." }, { "code": null, "e": 8979, "s": 8860, "text": "Triggers are used to maintain the Integrity of database. To check Trigger is fired or not you can check in audit logs." }, { "code": null, "e": 9232, "s": 8979, "text": "Triggers can’t be invoked on demand. They are invoked when an associated action (insert, delete & update) happens on the table on which they are defined. Triggers are used to apply business rules, auditing and also for the referential integrity checks." }, { "code": null, "e": 9464, "s": 9232, "text": "First, get the functional requirement. Then, understand the table structure, Joins, Cursors and Triggers, Stored procedure used, and other parameters. Next, you can write a test-case with different values as input to these objects." }, { "code": null, "e": 9622, "s": 9464, "text": "DB testing involves testing of back-end components which are not visible to users. It includes database components and DBMS systems such as MySQL and Oracle." }, { "code": null, "e": 9845, "s": 9622, "text": "Front-end testing involves checking functionalities of an application and its components like forms, graphs, menus, reports, etc. These components are created using front-end development tools like VB.net, C#, Delphi, etc." }, { "code": null, "e": 9993, "s": 9845, "text": "The process to perform database testing is similar to testing of other applications. DB testing can be described with the following key processes βˆ’" }, { "code": null, "e": 10020, "s": 9993, "text": "Setting up the environment" }, { "code": null, "e": 10031, "s": 10020, "text": "Run a test" }, { "code": null, "e": 10053, "s": 10031, "text": "Check the test result" }, { "code": null, "e": 10098, "s": 10053, "text": "Validating according to the expected results" }, { "code": null, "e": 10149, "s": 10098, "text": "Report the findings to the respective stakeholders" }, { "code": null, "e": 10358, "s": 10149, "text": "Various SQL statements are used to develop the Test cases. Most common SQL statement which is used to perform DB testing is select statement. Apart from this various DDL, DML, DCL statements can also be used." }, { "code": null, "e": 10405, "s": 10358, "text": "Example βˆ’ Create, Insert, Select, Update, etc." }, { "code": null, "e": 10650, "s": 10405, "text": "A view is a table that does not really exist in its own right but is instead derived from one or more base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary." }, { "code": null, "e": 10830, "s": 10650, "text": "Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the changes in the database. Hence accounts for logical data independence." }, { "code": null, "e": 10899, "s": 10830, "text": "It specifies user views and their mappings to the conceptual schema." }, { "code": null, "e": 11046, "s": 10899, "text": "It is a process of decomposing a table into multiple tables without losing any information. Normalization is done to achieve the following goals βˆ’" }, { "code": null, "e": 11070, "s": 11046, "text": "To minimize redundancy." }, { "code": null, "e": 11124, "s": 11070, "text": "To minimize insertion, deletion and update anomalies." }, { "code": null, "e": 11292, "s": 11124, "text": "Indexing is a technique for determining how quickly specific data can be found. It is used for query performance optimization. Indexing can be of the following types βˆ’" }, { "code": null, "e": 11321, "s": 11292, "text": "Binary search style indexing" }, { "code": null, "e": 11337, "s": 11321, "text": "B-Tree indexing" }, { "code": null, "e": 11360, "s": 11337, "text": "Inverted list indexing" }, { "code": null, "e": 11382, "s": 11360, "text": "Memory resident table" }, { "code": null, "e": 11397, "s": 11382, "text": "Table indexing" }, { "code": null, "e": 11535, "s": 11397, "text": "SQL is a Structured Query language that is designed specifically for data access operations on normalized relational database structures." }, { "code": null, "e": 11720, "s": 11535, "text": "The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them." }, { "code": null, "e": 11929, "s": 11720, "text": "Stored procedures are used to perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client." }, { "code": null, "e": 12075, "s": 11929, "text": "PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors βˆ’ implicit and explicit." }, { "code": null, "e": 12330, "s": 12075, "text": "Cold Backup βˆ’ Cold back is known as taking back up of database files, redo logs, and control file when the instance is shut down. This is a file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy." }, { "code": null, "e": 12535, "s": 12330, "text": "If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All the changes that are performed after the last backup is lost." }, { "code": null, "e": 12710, "s": 12535, "text": "Hot Backup βˆ’ Some databases can’t shut down while making a backup copy of the files, so cold backup is not an available option. For these types of database we use hot backup." }, { "code": null, "e": 13055, "s": 12710, "text": "SQL subquery is a means of querying two or more tables at the same time. The subquery itself is an SQL SELECT statement contained within the WHERE clause of another SQL SELECT statement, and separated by being enclosed in parenthesis. Some subqueries have equivalent SQL join structures, but correlated subqueries cannot be duplicated by a join" }, { "code": null, "e": 13112, "s": 13055, "text": "In such a case, you need to test the following aspects βˆ’" }, { "code": null, "e": 13137, "s": 13112, "text": "Multivalued dependencies" }, { "code": null, "e": 13161, "s": 13137, "text": "Functional dependencies" }, { "code": null, "e": 13176, "s": 13161, "text": "Candidate keys" }, { "code": null, "e": 13189, "s": 13176, "text": "Primary keys" }, { "code": null, "e": 13202, "s": 13189, "text": "Foreign keys" }, { "code": null, "e": 13407, "s": 13202, "text": "You can go to the database and run a relevant SQL query. In WinRunner, you can use database checkpoint function. If the application provides view function, then you can verify the same from the front-end." }, { "code": null, "e": 13679, "s": 13407, "text": "Data-driven testing is defined as an automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface." }, { "code": null, "e": 13915, "s": 13679, "text": "Once you execute the test-cases and find the defects that has been already detected and fixed. Re-execution of the same test with different input values to confirm the original defect has been successfully removed is called Re-testing." }, { "code": null, "e": 13986, "s": 13915, "text": "Retesting is also called Data Driven Testing with a small difference βˆ’" }, { "code": null, "e": 14091, "s": 13986, "text": "Retesting βˆ’ It is a manual testing process whereas application testing done with entire new set of data." }, { "code": null, "e": 14196, "s": 14091, "text": "Retesting βˆ’ It is a manual testing process whereas application testing done with entire new set of data." }, { "code": null, "e": 14462, "s": 14196, "text": "Data-driven Testing βˆ’ It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface." }, { "code": null, "e": 14728, "s": 14462, "text": "Data-driven Testing βˆ’ It is an Automation testing process where application will be tested with multiple test data. It is simple and easy than retesting where tester just sit in front of system and enter different new input values manually from front-end interface." }, { "code": null, "e": 14774, "s": 14728, "text": "There are four types of data driven testing βˆ’" }, { "code": null, "e": 14820, "s": 14774, "text": "Dynamic test data submission through keyboard" }, { "code": null, "e": 14864, "s": 14820, "text": "Data Driven Tests via .txt, .doc flat files" }, { "code": null, "e": 14904, "s": 14864, "text": "Data Driven Tests via front-end objects" }, { "code": null, "e": 14938, "s": 14904, "text": "Data Driven Tests via excel sheet" }, { "code": null, "e": 15094, "s": 14938, "text": "Performance testing is a software testing technique to determine how a system performs in terms of speed, sensitivity and stability under a heavy workload." }, { "code": null, "e": 15185, "s": 15094, "text": "The following key points are to be considered while performing database recovery testing βˆ’" }, { "code": null, "e": 15252, "s": 15185, "text": "Time span when changes or modifications occurs in database system." }, { "code": null, "e": 15319, "s": 15252, "text": "Time span when changes or modifications occurs in database system." }, { "code": null, "e": 15378, "s": 15319, "text": "The period by which you want your recovery plan conducted." }, { "code": null, "e": 15437, "s": 15378, "text": "The period by which you want your recovery plan conducted." }, { "code": null, "e": 15563, "s": 15437, "text": "The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software." }, { "code": null, "e": 15689, "s": 15563, "text": "The sensitivity of data in database system. More critical the data is, the more regularly you will need to test the software." }, { "code": null, "e": 15742, "s": 15689, "text": "The following tools are used to generate test data βˆ’" }, { "code": null, "e": 15755, "s": 15742, "text": "Data Factory" }, { "code": null, "e": 15774, "s": 15755, "text": "DTM Data Generator" }, { "code": null, "e": 15785, "s": 15774, "text": "Turbo Data" }, { "code": null, "e": 15834, "s": 15785, "text": "There are two types of backup that can be used βˆ’" }, { "code": null, "e": 16008, "s": 15834, "text": "Physical Backups βˆ’ Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities." }, { "code": null, "e": 16182, "s": 16008, "text": "Physical Backups βˆ’ Physical backup includes taking back up using 3rd party backup tools like Veritas net back, IBM Tivoli Manager or user manager backups using OS utilities." }, { "code": null, "e": 16309, "s": 16182, "text": "Logical Backups βˆ’ Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc." }, { "code": null, "e": 16436, "s": 16309, "text": "Logical Backups βˆ’ Logical backup of database includes taking back up of logical objects like tables, indexes, procedures, etc." }, { "code": null, "e": 16555, "s": 16436, "text": "A common tool to take data backup is Oracle Recovery Manager (RMAN) that is an Oracle utility to take database backup." }, { "code": null, "e": 16622, "s": 16555, "text": "The following actions are performed in database recovery testing βˆ’" }, { "code": null, "e": 16649, "s": 16622, "text": "Testing of database system" }, { "code": null, "e": 16674, "s": 16649, "text": "Testing of the SQL files" }, { "code": null, "e": 16699, "s": 16674, "text": "Testing of partial files" }, { "code": null, "e": 16722, "s": 16699, "text": "Testing of data backup" }, { "code": null, "e": 16745, "s": 16722, "text": "Testing of Backup tool" }, { "code": null, "e": 16765, "s": 16745, "text": "Testing log backups" }, { "code": null, "e": 16927, "s": 16765, "text": "Database security testing is performed to find the loop holes in security mechanisms and also about finding the vulnerabilities or weaknesses of database system." }, { "code": null, "e": 16999, "s": 16927, "text": "Database security testing is performed to check the following aspects βˆ’" }, { "code": null, "e": 17014, "s": 16999, "text": "Authentication" }, { "code": null, "e": 17028, "s": 17014, "text": "Authorization" }, { "code": null, "e": 17044, "s": 17028, "text": "Confidentiality" }, { "code": null, "e": 17057, "s": 17044, "text": "Availability" }, { "code": null, "e": 17067, "s": 17057, "text": "Integrity" }, { "code": null, "e": 17078, "s": 17067, "text": "Resilience" }, { "code": null, "e": 17425, "s": 17078, "text": "SQL Injection threat is the most common type of attack in a database system where malicious SQL statements are inserted in database system and executed to get critical information from database system. This attack takes advantage of loopholes in implementation of user applications. To prevent this user inputs fields should be carefully handled." }, { "code": null, "e": 17585, "s": 17425, "text": "The following tools can be used to perform database security testing: Zed Attack Proxy, Paros, Social Engineer Toolkit, Skipfish, Vega, Wapiti, and Web Scarab." }, { "code": null, "e": 17673, "s": 17585, "text": "The common challenges that one faces while performing database testing are as follows βˆ’" }, { "code": null, "e": 17700, "s": 17673, "text": "Testing scope is too large" }, { "code": null, "e": 17726, "s": 17700, "text": "Scaled-down test database" }, { "code": null, "e": 17756, "s": 17726, "text": "Changes in database structure" }, { "code": null, "e": 17775, "s": 17756, "text": "Complex Test Plans" }, { "code": null, "e": 17801, "s": 17775, "text": "Good understanding of SQL" }, { "code": null, "e": 17836, "s": 17801, "text": "\n 33 Lectures \n 7.5 hours \n" }, { "code": null, "e": 17847, "s": 17836, "text": " Syed Raza" }, { "code": null, "e": 17880, "s": 17847, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 17908, "s": 17880, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 17942, "s": 17908, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 17977, "s": 17942, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 18012, "s": 17977, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 18032, "s": 18012, "text": " Pranjal Srivastava" }, { "code": null, "e": 18065, "s": 18032, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 18085, "s": 18065, "text": " Harshit Srivastava" }, { "code": null, "e": 18118, "s": 18085, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 18136, "s": 18118, "text": " Trevoir Williams" }, { "code": null, "e": 18143, "s": 18136, "text": " Print" }, { "code": null, "e": 18154, "s": 18143, "text": " Add Notes" } ]
Find the minimum capacity of the train required to hold the passengers - GeeksforGeeks
24 May, 2021 Given the number of passengers entering and exiting the train, the task is to find the minimum capacity of the train to keep all the passengers in throughout the journey.Examples: Input: enter[] = {3, 5, 2, 0}, exit[] = {0, 2, 4, 4} Output: 6 Station 1: Train capacity = 3 Station 2: Train capacity = 3 + 5 – 2 = 6 Station 3: Train capacity = 6 + 2 – 4 = 4 Station 4: Train capacity = 4 – 4 = 0 The maximum passengers that can be in the train at any instance of time is 6.Input: enter[] = {5, 2, 2, 0}, exit[] = {0, 2, 2, 5} Output: 5 Approach: The current capacity of the train at a particular station can be calculated by adding the number of people entering the train and subtracting the number of people exiting the train. The minimum capacity required will be the maximum of all the values of current capacities at all the stations.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum capacity requiredint minCapacity(int enter[], int exit[], int n){ // To store the minimum capacity int minCap = 0; // To store the current capacity // of the train int currCap = 0; // For every station for (int i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = max(minCap, currCap); } return minCap;} // Driver codeint main(){ int enter[] = { 3, 5, 2, 0 }; int exit[] = { 0, 2, 4, 4 }; int n = sizeof(enter) / sizeof(enter[0]); cout << minCapacity(enter, exit, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimum capacity requiredstatic int minCapacity(int enter[], int exit[], int n){ // To store the minimum capacity int minCap = 0; // To store the current capacity // of the train int currCap = 0; // For every station for (int i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = Math.max(minCap, currCap); } return minCap;} // Driver codepublic static void main(String[] args){ int enter[] = { 3, 5, 2, 0 }; int exit[] = { 0, 2, 4, 4 }; int n = enter.length; System.out.println(minCapacity(enter, exit, n));}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function to return the# minimum capacity requireddef minCapacity(enter, exit, n): # To store the minimum capacity minCap = 0; # To store the current capacity # of the train currCap = 0; # For every station for i in range(n): # Add the number of people entering the # train and subtract the number of people # exiting the train to get the # current capacity of the train currCap = currCap + enter[i] - exit[i]; # Update the minimum capacity minCap = max(minCap, currCap); return minCap; # Driver codeif __name__ == '__main__': enter = [3, 5, 2, 0]; exit = [0, 2, 4, 4]; n = len(enter); print(minCapacity(enter, exit, n)); # This code is contributed by Princi Singh // C# implementation of the approachusing System; class GFG{ // Function to return the minimum// capacity requiredstatic int minCapacity(int []enter, int []exit, int n){ // To store the minimum capacity int minCap = 0; // To store the current capacity // of the train int currCap = 0; // For every station for (int i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = Math.Max(minCap, currCap); } return minCap;} // Driver codepublic static void Main(String[] args){ int []enter = { 3, 5, 2, 0 }; int []exit = { 0, 2, 4, 4 }; int n = enter.Length; Console.WriteLine(minCapacity(enter, exit, n));}} // This code is contributed by PrinciRaj1992 <script>// Javascript implementation of the approach // Function to return the minimum capacity requiredfunction minCapacity(enter, exit, n) { // To store the minimum capacity let minCap = 0; // To store the current capacity // of the train let currCap = 0; // For every station for (let i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = Math.max(minCap, currCap); } return minCap;} // Driver code let enter = [3, 5, 2, 0];let exit = [0, 2, 4, 4];let n = enter.length; document.write(minCapacity(enter, exit, n)); // This code is contributed by _saurabh_jaiswal.</script> 6 Time Complexity: O(n) 29AjayKumar princiraj1992 princi singh _saurabh_jaiswal Arrays Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Window Sliding Technique Program to find sum of elements in a given array Reversal algorithm for array rotation Trapping Rain Water Find duplicates in O(n) time and O(1) extra space | Set 1 Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3 Write a program to print all permutations of a given string
[ { "code": null, "e": 24740, "s": 24712, "text": "\n24 May, 2021" }, { "code": null, "e": 24922, "s": 24740, "text": "Given the number of passengers entering and exiting the train, the task is to find the minimum capacity of the train to keep all the passengers in throughout the journey.Examples: " }, { "code": null, "e": 25279, "s": 24922, "text": "Input: enter[] = {3, 5, 2, 0}, exit[] = {0, 2, 4, 4} Output: 6 Station 1: Train capacity = 3 Station 2: Train capacity = 3 + 5 – 2 = 6 Station 3: Train capacity = 6 + 2 – 4 = 4 Station 4: Train capacity = 4 – 4 = 0 The maximum passengers that can be in the train at any instance of time is 6.Input: enter[] = {5, 2, 2, 0}, exit[] = {0, 2, 2, 5} Output: 5 " }, { "code": null, "e": 25636, "s": 25281, "text": "Approach: The current capacity of the train at a particular station can be calculated by adding the number of people entering the train and subtracting the number of people exiting the train. The minimum capacity required will be the maximum of all the values of current capacities at all the stations.Below is the implementation of the above approach: " }, { "code": null, "e": 25640, "s": 25636, "text": "C++" }, { "code": null, "e": 25645, "s": 25640, "text": "Java" }, { "code": null, "e": 25653, "s": 25645, "text": "Python3" }, { "code": null, "e": 25656, "s": 25653, "text": "C#" }, { "code": null, "e": 25667, "s": 25656, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum capacity requiredint minCapacity(int enter[], int exit[], int n){ // To store the minimum capacity int minCap = 0; // To store the current capacity // of the train int currCap = 0; // For every station for (int i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = max(minCap, currCap); } return minCap;} // Driver codeint main(){ int enter[] = { 3, 5, 2, 0 }; int exit[] = { 0, 2, 4, 4 }; int n = sizeof(enter) / sizeof(enter[0]); cout << minCapacity(enter, exit, n); return 0;}", "e": 26558, "s": 25667, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimum capacity requiredstatic int minCapacity(int enter[], int exit[], int n){ // To store the minimum capacity int minCap = 0; // To store the current capacity // of the train int currCap = 0; // For every station for (int i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = Math.max(minCap, currCap); } return minCap;} // Driver codepublic static void main(String[] args){ int enter[] = { 3, 5, 2, 0 }; int exit[] = { 0, 2, 4, 4 }; int n = enter.length; System.out.println(minCapacity(enter, exit, n));}} // This code is contributed by Rajput-Ji", "e": 27520, "s": 26558, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the# minimum capacity requireddef minCapacity(enter, exit, n): # To store the minimum capacity minCap = 0; # To store the current capacity # of the train currCap = 0; # For every station for i in range(n): # Add the number of people entering the # train and subtract the number of people # exiting the train to get the # current capacity of the train currCap = currCap + enter[i] - exit[i]; # Update the minimum capacity minCap = max(minCap, currCap); return minCap; # Driver codeif __name__ == '__main__': enter = [3, 5, 2, 0]; exit = [0, 2, 4, 4]; n = len(enter); print(minCapacity(enter, exit, n)); # This code is contributed by Princi Singh", "e": 28330, "s": 27520, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the minimum// capacity requiredstatic int minCapacity(int []enter, int []exit, int n){ // To store the minimum capacity int minCap = 0; // To store the current capacity // of the train int currCap = 0; // For every station for (int i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = Math.Max(minCap, currCap); } return minCap;} // Driver codepublic static void Main(String[] args){ int []enter = { 3, 5, 2, 0 }; int []exit = { 0, 2, 4, 4 }; int n = enter.Length; Console.WriteLine(minCapacity(enter, exit, n));}} // This code is contributed by PrinciRaj1992", "e": 29289, "s": 28330, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to return the minimum capacity requiredfunction minCapacity(enter, exit, n) { // To store the minimum capacity let minCap = 0; // To store the current capacity // of the train let currCap = 0; // For every station for (let i = 0; i < n; i++) { // Add the number of people entering the // train and subtract the number of people // exiting the train to get the // current capacity of the train currCap = currCap + enter[i] - exit[i]; // Update the minimum capacity minCap = Math.max(minCap, currCap); } return minCap;} // Driver code let enter = [3, 5, 2, 0];let exit = [0, 2, 4, 4];let n = enter.length; document.write(minCapacity(enter, exit, n)); // This code is contributed by _saurabh_jaiswal.</script>", "e": 30144, "s": 29289, "text": null }, { "code": null, "e": 30146, "s": 30144, "text": "6" }, { "code": null, "e": 30171, "s": 30148, "text": "Time Complexity: O(n) " }, { "code": null, "e": 30183, "s": 30171, "text": "29AjayKumar" }, { "code": null, "e": 30197, "s": 30183, "text": "princiraj1992" }, { "code": null, "e": 30210, "s": 30197, "text": "princi singh" }, { "code": null, "e": 30227, "s": 30210, "text": "_saurabh_jaiswal" }, { "code": null, "e": 30234, "s": 30227, "text": "Arrays" }, { "code": null, "e": 30241, "s": 30234, "text": "Greedy" }, { "code": null, "e": 30248, "s": 30241, "text": "Arrays" }, { "code": null, "e": 30255, "s": 30248, "text": "Greedy" }, { "code": null, "e": 30353, "s": 30255, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30362, "s": 30353, "text": "Comments" }, { "code": null, "e": 30375, "s": 30362, "text": "Old Comments" }, { "code": null, "e": 30400, "s": 30375, "text": "Window Sliding Technique" }, { "code": null, "e": 30449, "s": 30400, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30487, "s": 30449, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30507, "s": 30487, "text": "Trapping Rain Water" }, { "code": null, "e": 30565, "s": 30507, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30616, "s": 30565, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 30667, "s": 30616, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 30725, "s": 30667, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 30756, "s": 30725, "text": "Huffman Coding | Greedy Algo-3" } ]
C# | Get an enumerator that iterates through the SortedDictionary - GeeksforGeeks
01 Feb, 2019 SortedDictionary<TKey, TValue>.GetEnumerator Method is used to get an enumerator that iterates through the SortedDictionary<TKey, TValue>. Syntax: public System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator GetEnumerator (); Return Value: This method returns an SortedDictionary<TKey, TValue>.Enumerator for the SortedDictionary<TKey, TValue>. Below programs illustrate the above-discussed method: Below programs illustrate thabove-discusseddiscussed method: Example 1: // C# code to get an IDictionaryEnumerator// that iterates through the SortedDictionaryusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedDictionary named myDict SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // To get an IDictionaryEnumerator // for the SortedDictionary IDictionaryEnumerator myEnumerator = myDict.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the collection // and MoveNext returns false. while (myEnumerator.MoveNext()) Console.WriteLine(myEnumerator.Key + " --> " + myEnumerator.Value); }} Australia --> Canberra Belgium --> Brussels China --> Beijing India --> New Delhi Netherlands --> Amsterdam Russia --> Moscow Example 2: // C# code to get an IDictionaryEnumerator// that iterates through the SortedDictionaryusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedDictionary named myDict SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("I", "C"); myDict.Add("II", "C++"); myDict.Add("III", "Java"); myDict.Add("IV", "Python"); myDict.Add("V", "C#"); // To get an IDictionaryEnumerator // for the Dictionary IDictionaryEnumerator myEnumerator = myDict.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the collection // and MoveNext returns false. while (myEnumerator.MoveNext()) Console.WriteLine(myEnumerator.Key + " --> " + myEnumerator.Value); }} I --> C II --> C++ III --> Java IV --> Python V --> C# Note: The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator. Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection. Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element. An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined. This method is an O(1) operation. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2.getenumerator?view=netframework-4.7.2 CSharp SortedDictionary Class CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Constructors C# | Delegates Introduction to .NET Framework Difference between Ref and Out keywords in C# C# | Data Types Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
[ { "code": null, "e": 24718, "s": 24690, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24857, "s": 24718, "text": "SortedDictionary<TKey, TValue>.GetEnumerator Method is used to get an enumerator that iterates through the SortedDictionary<TKey, TValue>." }, { "code": null, "e": 24865, "s": 24857, "text": "Syntax:" }, { "code": null, "e": 24959, "s": 24865, "text": "public System.Collections.Generic.SortedDictionary<TKey, TValue>.Enumerator GetEnumerator ();" }, { "code": null, "e": 25078, "s": 24959, "text": "Return Value: This method returns an SortedDictionary<TKey, TValue>.Enumerator for the SortedDictionary<TKey, TValue>." }, { "code": null, "e": 25132, "s": 25078, "text": "Below programs illustrate the above-discussed method:" }, { "code": null, "e": 25193, "s": 25132, "text": "Below programs illustrate thabove-discusseddiscussed method:" }, { "code": null, "e": 25204, "s": 25193, "text": "Example 1:" }, { "code": "// C# code to get an IDictionaryEnumerator// that iterates through the SortedDictionaryusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedDictionary named myDict SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // To get an IDictionaryEnumerator // for the SortedDictionary IDictionaryEnumerator myEnumerator = myDict.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the collection // and MoveNext returns false. while (myEnumerator.MoveNext()) Console.WriteLine(myEnumerator.Key + \" --> \" + myEnumerator.Value); }}", "e": 26345, "s": 25204, "text": null }, { "code": null, "e": 26472, "s": 26345, "text": "Australia --> Canberra\nBelgium --> Brussels\nChina --> Beijing\nIndia --> New Delhi\nNetherlands --> Amsterdam\nRussia --> Moscow\n" }, { "code": null, "e": 26483, "s": 26472, "text": "Example 2:" }, { "code": "// C# code to get an IDictionaryEnumerator// that iterates through the SortedDictionaryusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a SortedDictionary named myDict SortedDictionary<string, string> myDict = new SortedDictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"I\", \"C\"); myDict.Add(\"II\", \"C++\"); myDict.Add(\"III\", \"Java\"); myDict.Add(\"IV\", \"Python\"); myDict.Add(\"V\", \"C#\"); // To get an IDictionaryEnumerator // for the Dictionary IDictionaryEnumerator myEnumerator = myDict.GetEnumerator(); // If MoveNext passes the end of the // collection, the enumerator is positioned // after the last element in the collection // and MoveNext returns false. while (myEnumerator.MoveNext()) Console.WriteLine(myEnumerator.Key + \" --> \" + myEnumerator.Value); }}", "e": 27568, "s": 26483, "text": null }, { "code": null, "e": 27624, "s": 27568, "text": "I --> C\nII --> C++\nIII --> Java\nIV --> Python\nV --> C#\n" }, { "code": null, "e": 27630, "s": 27624, "text": "Note:" }, { "code": null, "e": 27802, "s": 27630, "text": "The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator." }, { "code": null, "e": 27923, "s": 27802, "text": "Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection." }, { "code": null, "e": 28040, "s": 27923, "text": "Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element." }, { "code": null, "e": 28276, "s": 28040, "text": "An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined." }, { "code": null, "e": 28310, "s": 28276, "text": "This method is an O(1) operation." }, { "code": null, "e": 28321, "s": 28310, "text": "Reference:" }, { "code": null, "e": 28449, "s": 28321, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2.getenumerator?view=netframework-4.7.2" }, { "code": null, "e": 28479, "s": 28449, "text": "CSharp SortedDictionary Class" }, { "code": null, "e": 28504, "s": 28479, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 28518, "s": 28504, "text": "CSharp-method" }, { "code": null, "e": 28521, "s": 28518, "text": "C#" }, { "code": null, "e": 28619, "s": 28521, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28628, "s": 28619, "text": "Comments" }, { "code": null, "e": 28641, "s": 28628, "text": "Old Comments" }, { "code": null, "e": 28664, "s": 28641, "text": "C# | Method Overriding" }, { "code": null, "e": 28686, "s": 28664, "text": "C# | Class and Object" }, { "code": null, "e": 28726, "s": 28686, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28749, "s": 28726, "text": "Extension Method in C#" }, { "code": null, "e": 28767, "s": 28749, "text": "C# | Constructors" }, { "code": null, "e": 28782, "s": 28767, "text": "C# | Delegates" }, { "code": null, "e": 28813, "s": 28782, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28859, "s": 28813, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28875, "s": 28859, "text": "C# | Data Types" } ]
Music Genre Classification with Python | by Parul Pandey | Towards Data Science
Music is like a mirror, and it tells people a lot about who you are and what you care about, whether you like it or not. We love to say β€œyou are what you stream,”:Spotify Spotify, with a net worth of $26 billion, is reigning the music streaming platform today. It currently has millions of songs in its database and claims to have the right music score for everyone. Spotify’s Discover Weekly service has become a hit with the millennials. Needless to say, Spotify has invested a lot in research to improve the way users find and listen to music. Machine Learning is at the core of their research. From NLP to Collaborative filtering to Deep Learning, Spotify uses them all. Songs are analyzed based on their digital signatures for some factors, including tempo, acoustics, energy, danceability, etc., to answer that impossible old first-date query: What kind of music are you into? Companies nowadays use music classification, either to be able to place recommendations to their customers (such as Spotify, Soundcloud) or simply as a product (for example, Shazam). Determining music genres is the first step in that direction. Machine Learning techniques have proved to be quite successful in extracting trends and patterns from a large data pool. The same principles are applied in Music Analysis also. In this article, we shall study how to analyze an audio/music signal in Python. We shall then utilize the skills learnt to classify music clips into different genres. Sound is represented in the form of an audio signal having parameters such as frequency, bandwidth, decibel, etc. A typical audio signal can be expressed as a function of Amplitude and Time. These sounds are available in many formats, making it possible for the computer to read and analyze them. Some examples are: mp3 format WMA (Windows Media Audio) format wav (Waveform Audio File) format Python has some great libraries for audio processing like Librosa and PyAudio.There are also built-in modules for some basic audio functionalities. We will mainly use two libraries for audio acquisition and playback: It is a Python module to analyze audio signals in general but geared more towards music. It includes the nuts and bolts to build a MIR(Music information retrieval) system. It has been very well documented, along with a lot of examples and tutorials. For a more advanced introduction that describes the package design principles, please refer to the librosa paper at SciPy 2015. Installation pip install librosaorconda install -c conda-forge librosa To fuel more audio-decoding power, you can install FFmpeg, which ships with many audio decoders. IPython.display.Audio lets you play audio directly in a jupyter notebook. import librosaaudio_path = '../T08-violin.wav'x , sr = librosa.load(audio_path)print(type(x), type(sr))<class 'numpy.ndarray'> <class 'int'>print(x.shape, sr)(396688,) 22050 This returns an audio time series as a numpy array with a default sampling rate(sr) of 22KHZ mono. We can change this behavior by saying: librosa.load(audio_path, sr=44100) to resample at 44.1KHz, or librosa.load(audio_path, sr=None) to disable resampling. The sample rate is the number of samples of audio carried per second, measured in Hz or kHz. Using,IPython.display.Audio to play the audio import IPython.display as ipdipd.Audio(audio_path) This returns an audio widget in the jupyter notebook as follows: This widget won’t work here, but it will work in your notebooks. I have uploaded the same to SoundCloud so that we can listen to it. 7.4K plays7.4K You can even use an mp3 or a WMA format for the audio example. We can plot the audio array using librosa.display.waveplot: %matplotlib inlineimport matplotlib.pyplot as pltimport librosa.displayplt.figure(figsize=(14, 5))librosa.display.waveplot(x, sr=sr) Here, we have the plot of the amplitude envelope of a waveform. A spectrogram is a visual representation of the spectrum of frequencies of sound or other signals as they vary with time. Spectrograms are sometimes called sonographs, voiceprints, or voicegrams. When the data is represented in a 3D plot, they may be called waterfalls. In 2-dimensional arrays, the first axis is frequency while the second axis is time. We can display a spectrogram using. librosa.display.specshow. X = librosa.stft(x)Xdb = librosa.amplitude_to_db(abs(X))plt.figure(figsize=(14, 5))librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')plt.colorbar() The vertical axis shows frequencies (from 0 to 10kHz), and the horizontal axis shows the time of the clip. Since all action is taking place at the bottom of the spectrum, we can convert the frequency axis to a logarithmic one. librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='log')plt.colorbar() librosa.output.write_wav saves a NumPy array to a WAV file. librosa.output.write_wav('example.wav', x, sr) Let us now create an audio signal at 220Hz. An audio signal is a numpy array, so we shall create one and pass it into the audio function. import numpy as npsr = 22050 # sample rateT = 5.0 # secondst = np.linspace(0, T, int(T*sr), endpoint=False) # time variablex = 0.5*np.sin(2*np.pi*220*t)# pure sine wave at 220 HzPlaying the audioipd.Audio(x, rate=sr) # load a NumPy arraySaving the audiolibrosa.output.write_wav('tone_220.wav', x, sr) So, here it is- the first sound signal created by you.πŸ™Œ Every audio signal consists of many features. However, we must extract the characteristics that are relevant to the problem we are trying to solve. The process of extracting features to use them for analysis is called feature extraction. Let us study about few of the features in detail. Zero-Crossing Rate The zero-crossing rate is the rate of sign-changes along with a signal, i.e., the rate at which the signal changes from positive to negative or back. This feature has been used heavily in both speech recognition and music information retrieval. It usually has higher values for highly percussive sounds like those in metal and rock. Let us calculate the zero-crossing rate for our example audio clip. # Load the signalx, sr = librosa.load('../T08-violin.wav')#Plot the signal:plt.figure(figsize=(14, 5))librosa.display.waveplot(x, sr=sr) # Zooming inn0 = 9000n1 = 9100plt.figure(figsize=(14, 5))plt.plot(x[n0:n1])plt.grid() There appear to be 6 zero crossings. Let’s verify with librosa. zero_crossings = librosa.zero_crossings(x[n0:n1], pad=False)print(sum(zero_crossings))6 Spectral Centroid It indicates where the ” center of mass” for a sound is located and is calculated as the weighted mean of the frequencies present in the sound. Consider two songs, one from a blues genre and the other belonging to metal. Now, as compared to the blues genre song, which is the same throughout its length, the metal song has more frequencies towards the end. So spectral centroid for blues song will lie somewhere near the middle of its spectrum while that for a metal song would be towards its end. librosa.feature.spectral_centroid computes the spectral centroid for each frame in a signal: spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]spectral_centroids.shape(775,)# Computing the time variable for visualizationframes = range(len(spectral_centroids))t = librosa.frames_to_time(frames)# Normalising the spectral centroid for visualisationdef normalize(x, axis=0): return sklearn.preprocessing.minmax_scale(x, axis=axis)#Plotting the Spectral Centroid along the waveformlibrosa.display.waveplot(x, sr=sr, alpha=0.4)plt.plot(t, normalize(spectral_centroids), color='r') There is a rise in the spectral centroid towards the end. Spectral Rolloff It is a measure of the shape of the signal. It represents the frequency below which a specified percentage of the total spectral energy, e.g., 85%, lies. librosa.feature.spectral_rolloff computes the roll-off frequency for each frame in a signal: spectral_rolloff = librosa.feature.spectral_rolloff(x+0.01, sr=sr)[0]librosa.display.waveplot(x, sr=sr, alpha=0.4)plt.plot(t, normalize(spectral_rolloff), color='r') Mel-Frequency Cepstral Coefficients The Mel frequency cepstral coefficients (MFCCs) of a signal are a small set of features (usually about 10–20) that concisely describe the overall shape of a spectral envelope. It models the characteristics of the human voice. Let’ work with a simple loop wave this time. x, fs = librosa.load('../simple_loop.wav')librosa.display.waveplot(x, sr=sr) librosa.feature.mfcc computes MFCCs across an audio signal: mfccs = librosa.feature.mfcc(x, sr=fs)print mfccs.shape(20, 97)#Displaying the MFCCs:librosa.display.specshow(mfccs, sr=sr, x_axis='time') Here mfcc calculated 20 MFCC s over 97 frames. We can also perform feature scaling such that each coefficient dimension has zero mean and unit variance: import sklearnmfccs = sklearn.preprocessing.scale(mfccs, axis=1)print(mfccs.mean(axis=1))print(mfccs.var(axis=1))librosa.display.specshow(mfccs, sr=sr, x_axis='time') Chroma Frequencies Chroma features are an interesting and powerful representation for music audio in which the entire spectrum is projected onto 12 bins representing the 12 distinct semitones (or chroma) of the musical octave. librosa.feature.chroma_stft is used for computation # Loadign the filex, sr = librosa.load('../simple_piano.wav')hop_length = 512chromagram = librosa.feature.chroma_stft(x, sr=sr, hop_length=hop_length)plt.figure(figsize=(15, 5))librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', hop_length=hop_length, cmap='coolwarm') After having an overview of the acoustic signal, its features, and its feature extraction process, it is time to utilize our newly developed skill to work on a Machine Learning Problem. In his section, we will try to model a classifier to classify songs into different genres. Let us assume a scenario in which, for some reason, we find a bunch of randomly named MP3 files on our hard disk, which are assumed to contain music. Our task is to sort them according to the music genre into different folders such as jazz, classical, country, pop, rock, and metal. We will be using the famous GITZAN dataset for our case study. This dataset was used for the well-known paper in genre classification β€œ Musical genre classification of audio signals β€œ by G. Tzanetakis and P. Cook in IEEE Transactions on Audio and Speech Processing 2002. The dataset consists of 1000 audio tracks, each 30 seconds long. It contains ten genres: blues, classical, country, disco, hip-hop, jazz, reggae, rock, metal, and pop. Each genre consists of 100 sound clips. Before training the classification model, we have to transform raw data from audio samples into more meaningful representations. The audio clips need to be converted from .au format to .wav format to make it compatible with python’s wave module for reading audio files. I used the open-source SoX module for the conversion. Here is a handy cheat sheet for SoX conversion. sox input.au output.wav Feature Extraction We then need to extract meaningful features from audio files. We will choose five features to classify our audio clips, i.e., Mel-Frequency Cepstral Coefficients, Spectral Centroid, Zero Crossing Rate, Chroma Frequencies, Spectral Roll-off. All the features are then appended into a .csv file so that classification algorithms can be used. Classification Once the features have been extracted, we can use existing classification algorithms to classify the songs into different genres. You can either use the spectrogram images directly for classification or can extract the features and use the classification models on them. Music Genre Classification is one of the many branches of Music Information Retrieval. From here, you can perform other tasks on musical data like beat tracking, music generation, recommender systems, track separation and instrument recognition, etc. Music analysis is a diverse field and also an interesting one. A music session somehow represents a moment for the user. Finding these moments and describing them is an interesting challenge in the field of Data Science.
[ { "code": null, "e": 343, "s": 172, "text": "Music is like a mirror, and it tells people a lot about who you are and what you care about, whether you like it or not. We love to say β€œyou are what you stream,”:Spotify" }, { "code": null, "e": 1055, "s": 343, "text": "Spotify, with a net worth of $26 billion, is reigning the music streaming platform today. It currently has millions of songs in its database and claims to have the right music score for everyone. Spotify’s Discover Weekly service has become a hit with the millennials. Needless to say, Spotify has invested a lot in research to improve the way users find and listen to music. Machine Learning is at the core of their research. From NLP to Collaborative filtering to Deep Learning, Spotify uses them all. Songs are analyzed based on their digital signatures for some factors, including tempo, acoustics, energy, danceability, etc., to answer that impossible old first-date query: What kind of music are you into?" }, { "code": null, "e": 1477, "s": 1055, "text": "Companies nowadays use music classification, either to be able to place recommendations to their customers (such as Spotify, Soundcloud) or simply as a product (for example, Shazam). Determining music genres is the first step in that direction. Machine Learning techniques have proved to be quite successful in extracting trends and patterns from a large data pool. The same principles are applied in Music Analysis also." }, { "code": null, "e": 1644, "s": 1477, "text": "In this article, we shall study how to analyze an audio/music signal in Python. We shall then utilize the skills learnt to classify music clips into different genres." }, { "code": null, "e": 1835, "s": 1644, "text": "Sound is represented in the form of an audio signal having parameters such as frequency, bandwidth, decibel, etc. A typical audio signal can be expressed as a function of Amplitude and Time." }, { "code": null, "e": 1960, "s": 1835, "text": "These sounds are available in many formats, making it possible for the computer to read and analyze them. Some examples are:" }, { "code": null, "e": 1971, "s": 1960, "text": "mp3 format" }, { "code": null, "e": 2004, "s": 1971, "text": "WMA (Windows Media Audio) format" }, { "code": null, "e": 2037, "s": 2004, "text": "wav (Waveform Audio File) format" }, { "code": null, "e": 2185, "s": 2037, "text": "Python has some great libraries for audio processing like Librosa and PyAudio.There are also built-in modules for some basic audio functionalities." }, { "code": null, "e": 2254, "s": 2185, "text": "We will mainly use two libraries for audio acquisition and playback:" }, { "code": null, "e": 2504, "s": 2254, "text": "It is a Python module to analyze audio signals in general but geared more towards music. It includes the nuts and bolts to build a MIR(Music information retrieval) system. It has been very well documented, along with a lot of examples and tutorials." }, { "code": null, "e": 2632, "s": 2504, "text": "For a more advanced introduction that describes the package design principles, please refer to the librosa paper at SciPy 2015." }, { "code": null, "e": 2645, "s": 2632, "text": "Installation" }, { "code": null, "e": 2703, "s": 2645, "text": "pip install librosaorconda install -c conda-forge librosa" }, { "code": null, "e": 2800, "s": 2703, "text": "To fuel more audio-decoding power, you can install FFmpeg, which ships with many audio decoders." }, { "code": null, "e": 2874, "s": 2800, "text": "IPython.display.Audio lets you play audio directly in a jupyter notebook." }, { "code": null, "e": 3048, "s": 2874, "text": "import librosaaudio_path = '../T08-violin.wav'x , sr = librosa.load(audio_path)print(type(x), type(sr))<class 'numpy.ndarray'> <class 'int'>print(x.shape, sr)(396688,) 22050" }, { "code": null, "e": 3186, "s": 3048, "text": "This returns an audio time series as a numpy array with a default sampling rate(sr) of 22KHZ mono. We can change this behavior by saying:" }, { "code": null, "e": 3221, "s": 3186, "text": "librosa.load(audio_path, sr=44100)" }, { "code": null, "e": 3248, "s": 3221, "text": "to resample at 44.1KHz, or" }, { "code": null, "e": 3282, "s": 3248, "text": "librosa.load(audio_path, sr=None)" }, { "code": null, "e": 3305, "s": 3282, "text": "to disable resampling." }, { "code": null, "e": 3398, "s": 3305, "text": "The sample rate is the number of samples of audio carried per second, measured in Hz or kHz." }, { "code": null, "e": 3444, "s": 3398, "text": "Using,IPython.display.Audio to play the audio" }, { "code": null, "e": 3495, "s": 3444, "text": "import IPython.display as ipdipd.Audio(audio_path)" }, { "code": null, "e": 3560, "s": 3495, "text": "This returns an audio widget in the jupyter notebook as follows:" }, { "code": null, "e": 3693, "s": 3560, "text": "This widget won’t work here, but it will work in your notebooks. I have uploaded the same to SoundCloud so that we can listen to it." }, { "code": null, "e": 3712, "s": 3693, "text": "\n\n7.4K plays7.4K\n\n" }, { "code": null, "e": 3775, "s": 3712, "text": "You can even use an mp3 or a WMA format for the audio example." }, { "code": null, "e": 3835, "s": 3775, "text": "We can plot the audio array using librosa.display.waveplot:" }, { "code": null, "e": 3968, "s": 3835, "text": "%matplotlib inlineimport matplotlib.pyplot as pltimport librosa.displayplt.figure(figsize=(14, 5))librosa.display.waveplot(x, sr=sr)" }, { "code": null, "e": 4032, "s": 3968, "text": "Here, we have the plot of the amplitude envelope of a waveform." }, { "code": null, "e": 4386, "s": 4032, "text": "A spectrogram is a visual representation of the spectrum of frequencies of sound or other signals as they vary with time. Spectrograms are sometimes called sonographs, voiceprints, or voicegrams. When the data is represented in a 3D plot, they may be called waterfalls. In 2-dimensional arrays, the first axis is frequency while the second axis is time." }, { "code": null, "e": 4448, "s": 4386, "text": "We can display a spectrogram using. librosa.display.specshow." }, { "code": null, "e": 4610, "s": 4448, "text": "X = librosa.stft(x)Xdb = librosa.amplitude_to_db(abs(X))plt.figure(figsize=(14, 5))librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='hz')plt.colorbar()" }, { "code": null, "e": 4837, "s": 4610, "text": "The vertical axis shows frequencies (from 0 to 10kHz), and the horizontal axis shows the time of the clip. Since all action is taking place at the bottom of the spectrum, we can convert the frequency axis to a logarithmic one." }, { "code": null, "e": 4917, "s": 4837, "text": "librosa.display.specshow(Xdb, sr=sr, x_axis='time', y_axis='log')plt.colorbar()" }, { "code": null, "e": 4977, "s": 4917, "text": "librosa.output.write_wav saves a NumPy array to a WAV file." }, { "code": null, "e": 5024, "s": 4977, "text": "librosa.output.write_wav('example.wav', x, sr)" }, { "code": null, "e": 5162, "s": 5024, "text": "Let us now create an audio signal at 220Hz. An audio signal is a numpy array, so we shall create one and pass it into the audio function." }, { "code": null, "e": 5466, "s": 5162, "text": "import numpy as npsr = 22050 # sample rateT = 5.0 # secondst = np.linspace(0, T, int(T*sr), endpoint=False) # time variablex = 0.5*np.sin(2*np.pi*220*t)# pure sine wave at 220 HzPlaying the audioipd.Audio(x, rate=sr) # load a NumPy arraySaving the audiolibrosa.output.write_wav('tone_220.wav', x, sr)" }, { "code": null, "e": 5522, "s": 5466, "text": "So, here it is- the first sound signal created by you.πŸ™Œ" }, { "code": null, "e": 5810, "s": 5522, "text": "Every audio signal consists of many features. However, we must extract the characteristics that are relevant to the problem we are trying to solve. The process of extracting features to use them for analysis is called feature extraction. Let us study about few of the features in detail." }, { "code": null, "e": 5829, "s": 5810, "text": "Zero-Crossing Rate" }, { "code": null, "e": 6162, "s": 5829, "text": "The zero-crossing rate is the rate of sign-changes along with a signal, i.e., the rate at which the signal changes from positive to negative or back. This feature has been used heavily in both speech recognition and music information retrieval. It usually has higher values for highly percussive sounds like those in metal and rock." }, { "code": null, "e": 6230, "s": 6162, "text": "Let us calculate the zero-crossing rate for our example audio clip." }, { "code": null, "e": 6367, "s": 6230, "text": "# Load the signalx, sr = librosa.load('../T08-violin.wav')#Plot the signal:plt.figure(figsize=(14, 5))librosa.display.waveplot(x, sr=sr)" }, { "code": null, "e": 6453, "s": 6367, "text": "# Zooming inn0 = 9000n1 = 9100plt.figure(figsize=(14, 5))plt.plot(x[n0:n1])plt.grid()" }, { "code": null, "e": 6517, "s": 6453, "text": "There appear to be 6 zero crossings. Let’s verify with librosa." }, { "code": null, "e": 6605, "s": 6517, "text": "zero_crossings = librosa.zero_crossings(x[n0:n1], pad=False)print(sum(zero_crossings))6" }, { "code": null, "e": 6623, "s": 6605, "text": "Spectral Centroid" }, { "code": null, "e": 7121, "s": 6623, "text": "It indicates where the ” center of mass” for a sound is located and is calculated as the weighted mean of the frequencies present in the sound. Consider two songs, one from a blues genre and the other belonging to metal. Now, as compared to the blues genre song, which is the same throughout its length, the metal song has more frequencies towards the end. So spectral centroid for blues song will lie somewhere near the middle of its spectrum while that for a metal song would be towards its end." }, { "code": null, "e": 7214, "s": 7121, "text": "librosa.feature.spectral_centroid computes the spectral centroid for each frame in a signal:" }, { "code": null, "e": 7717, "s": 7214, "text": "spectral_centroids = librosa.feature.spectral_centroid(x, sr=sr)[0]spectral_centroids.shape(775,)# Computing the time variable for visualizationframes = range(len(spectral_centroids))t = librosa.frames_to_time(frames)# Normalising the spectral centroid for visualisationdef normalize(x, axis=0): return sklearn.preprocessing.minmax_scale(x, axis=axis)#Plotting the Spectral Centroid along the waveformlibrosa.display.waveplot(x, sr=sr, alpha=0.4)plt.plot(t, normalize(spectral_centroids), color='r')" }, { "code": null, "e": 7775, "s": 7717, "text": "There is a rise in the spectral centroid towards the end." }, { "code": null, "e": 7792, "s": 7775, "text": "Spectral Rolloff" }, { "code": null, "e": 7946, "s": 7792, "text": "It is a measure of the shape of the signal. It represents the frequency below which a specified percentage of the total spectral energy, e.g., 85%, lies." }, { "code": null, "e": 8039, "s": 7946, "text": "librosa.feature.spectral_rolloff computes the roll-off frequency for each frame in a signal:" }, { "code": null, "e": 8205, "s": 8039, "text": "spectral_rolloff = librosa.feature.spectral_rolloff(x+0.01, sr=sr)[0]librosa.display.waveplot(x, sr=sr, alpha=0.4)plt.plot(t, normalize(spectral_rolloff), color='r')" }, { "code": null, "e": 8241, "s": 8205, "text": "Mel-Frequency Cepstral Coefficients" }, { "code": null, "e": 8467, "s": 8241, "text": "The Mel frequency cepstral coefficients (MFCCs) of a signal are a small set of features (usually about 10–20) that concisely describe the overall shape of a spectral envelope. It models the characteristics of the human voice." }, { "code": null, "e": 8512, "s": 8467, "text": "Let’ work with a simple loop wave this time." }, { "code": null, "e": 8589, "s": 8512, "text": "x, fs = librosa.load('../simple_loop.wav')librosa.display.waveplot(x, sr=sr)" }, { "code": null, "e": 8649, "s": 8589, "text": "librosa.feature.mfcc computes MFCCs across an audio signal:" }, { "code": null, "e": 8789, "s": 8649, "text": "mfccs = librosa.feature.mfcc(x, sr=fs)print mfccs.shape(20, 97)#Displaying the MFCCs:librosa.display.specshow(mfccs, sr=sr, x_axis='time')" }, { "code": null, "e": 8836, "s": 8789, "text": "Here mfcc calculated 20 MFCC s over 97 frames." }, { "code": null, "e": 8942, "s": 8836, "text": "We can also perform feature scaling such that each coefficient dimension has zero mean and unit variance:" }, { "code": null, "e": 9109, "s": 8942, "text": "import sklearnmfccs = sklearn.preprocessing.scale(mfccs, axis=1)print(mfccs.mean(axis=1))print(mfccs.var(axis=1))librosa.display.specshow(mfccs, sr=sr, x_axis='time')" }, { "code": null, "e": 9128, "s": 9109, "text": "Chroma Frequencies" }, { "code": null, "e": 9336, "s": 9128, "text": "Chroma features are an interesting and powerful representation for music audio in which the entire spectrum is projected onto 12 bins representing the 12 distinct semitones (or chroma) of the musical octave." }, { "code": null, "e": 9388, "s": 9336, "text": "librosa.feature.chroma_stft is used for computation" }, { "code": null, "e": 9674, "s": 9388, "text": "# Loadign the filex, sr = librosa.load('../simple_piano.wav')hop_length = 512chromagram = librosa.feature.chroma_stft(x, sr=sr, hop_length=hop_length)plt.figure(figsize=(15, 5))librosa.display.specshow(chromagram, x_axis='time', y_axis='chroma', hop_length=hop_length, cmap='coolwarm')" }, { "code": null, "e": 9860, "s": 9674, "text": "After having an overview of the acoustic signal, its features, and its feature extraction process, it is time to utilize our newly developed skill to work on a Machine Learning Problem." }, { "code": null, "e": 10234, "s": 9860, "text": "In his section, we will try to model a classifier to classify songs into different genres. Let us assume a scenario in which, for some reason, we find a bunch of randomly named MP3 files on our hard disk, which are assumed to contain music. Our task is to sort them according to the music genre into different folders such as jazz, classical, country, pop, rock, and metal." }, { "code": null, "e": 10505, "s": 10234, "text": "We will be using the famous GITZAN dataset for our case study. This dataset was used for the well-known paper in genre classification β€œ Musical genre classification of audio signals β€œ by G. Tzanetakis and P. Cook in IEEE Transactions on Audio and Speech Processing 2002." }, { "code": null, "e": 10713, "s": 10505, "text": "The dataset consists of 1000 audio tracks, each 30 seconds long. It contains ten genres: blues, classical, country, disco, hip-hop, jazz, reggae, rock, metal, and pop. Each genre consists of 100 sound clips." }, { "code": null, "e": 11085, "s": 10713, "text": "Before training the classification model, we have to transform raw data from audio samples into more meaningful representations. The audio clips need to be converted from .au format to .wav format to make it compatible with python’s wave module for reading audio files. I used the open-source SoX module for the conversion. Here is a handy cheat sheet for SoX conversion." }, { "code": null, "e": 11109, "s": 11085, "text": "sox input.au output.wav" }, { "code": null, "e": 11128, "s": 11109, "text": "Feature Extraction" }, { "code": null, "e": 11468, "s": 11128, "text": "We then need to extract meaningful features from audio files. We will choose five features to classify our audio clips, i.e., Mel-Frequency Cepstral Coefficients, Spectral Centroid, Zero Crossing Rate, Chroma Frequencies, Spectral Roll-off. All the features are then appended into a .csv file so that classification algorithms can be used." }, { "code": null, "e": 11483, "s": 11468, "text": "Classification" }, { "code": null, "e": 11754, "s": 11483, "text": "Once the features have been extracted, we can use existing classification algorithms to classify the songs into different genres. You can either use the spectrogram images directly for classification or can extract the features and use the classification models on them." } ]
Check whether a character is Lowercase or not in Java
To check whether a character is in Lowercase or not in Java, use the Character.isLowerCase() method. We have a character to be checked. char val = 'q'; Now let us use the Character.isLowerCase() method. if (Character.isLowerCase(val)) { System.out.println("Character is in Lowercase!"); }else { System.out.println("Character is in Uppercase!"); } Let us see the complete example now to check for Lowercase in Java. Live Demo public class Demo { public static void main(String []args) { System.out.println("Checking for Lowercase character..."); char val = 'q'; System.out.println("Character: "+val); if (Character.isLowerCase(val)) { System.out.println("Character is in Lowercase!"); } else { System.out.println("Character is in Uppercase!"); } } } Checking for Lowercase character... Character: q Character is in Lowercase!
[ { "code": null, "e": 1163, "s": 1062, "text": "To check whether a character is in Lowercase or not in Java, use the Character.isLowerCase() method." }, { "code": null, "e": 1198, "s": 1163, "text": "We have a character to be checked." }, { "code": null, "e": 1214, "s": 1198, "text": "char val = 'q';" }, { "code": null, "e": 1265, "s": 1214, "text": "Now let us use the Character.isLowerCase() method." }, { "code": null, "e": 1415, "s": 1265, "text": "if (Character.isLowerCase(val)) {\n System.out.println(\"Character is in Lowercase!\");\n}else {\n System.out.println(\"Character is in Uppercase!\");\n}" }, { "code": null, "e": 1483, "s": 1415, "text": "Let us see the complete example now to check for Lowercase in Java." }, { "code": null, "e": 1494, "s": 1483, "text": " Live Demo" }, { "code": null, "e": 1878, "s": 1494, "text": "public class Demo {\n public static void main(String []args) {\n System.out.println(\"Checking for Lowercase character...\");\n char val = 'q';\n System.out.println(\"Character: \"+val);\n if (Character.isLowerCase(val)) {\n System.out.println(\"Character is in Lowercase!\");\n } else {\n System.out.println(\"Character is in Uppercase!\");\n }\n }\n}" }, { "code": null, "e": 1954, "s": 1878, "text": "Checking for Lowercase character...\nCharacter: q\nCharacter is in Lowercase!" } ]
Default method vs static method in an interface in Java?
An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static. Since Java8 static methods and default methods are introduced in interfaces. Default Methods - Unlike other abstract methods these are the methods can have a default implementation. If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface. In short, you can access the default methods of an interface using the objects of the implementing classes. interface MyInterface{ public static int num = 100; public default void display() { System.out.println("display method of MyInterface"); } } public class InterfaceExample implements MyInterface{ public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); } } display method of MyInterface Static methods - They are declared using the static keyword and will be loaded into the memory along with the interface. You can access static methods using the interface name. If your interface has a static method you need to call it 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. 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 You can call a static method using the name of an interface. To call a default method you need to use the object of the implementing class. If you want, you can override a default method of an interface from the implementing class. interface MyInterface{ public static int num = 100; public default void display() { System.out.println("display method of MyInterface"); } } public class InterfaceExample implements MyInterface{ public void display() { System.out.println("display method of class"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.display(); } } display method of class You cannot override the static method of the interface; you can just access them using the name of the interface. If you try to override a static method of an interface by defining a similar method in the implementing interface, it will be considered as another (static) method of the class. interface MyInterface{ public static void display() { System.out.println("Static method of the interface"); } } public class InterfaceExample{ public static void display() { System.out.println("Static method of the class"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); MyInterface.display(); InterfaceExample.display(); } } Static method of the interface Static method of the class
[ { "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": 1258, "s": 1181, "text": "Since Java8 static methods and default methods are introduced in interfaces." }, { "code": null, "e": 1518, "s": 1258, "text": "Default Methods - Unlike other abstract methods these are the methods can have a default implementation. If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface." }, { "code": null, "e": 1626, "s": 1518, "text": "In short, you can access the default methods of an interface using the objects of the implementing classes." }, { "code": null, "e": 1961, "s": 1626, "text": "interface MyInterface{\n public static int num = 100;\n public default void display() {\n System.out.println(\"display method of MyInterface\");\n }\n}\npublic class InterfaceExample implements MyInterface{\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.display();\n }\n}" }, { "code": null, "e": 1991, "s": 1961, "text": "display method of MyInterface" }, { "code": null, "e": 2168, "s": 1991, "text": "Static methods - They are declared using the static keyword and will be loaded into the memory along with the interface. You can access static methods using the interface name." }, { "code": null, "e": 2296, "s": 2168, "text": "If your interface has a static method you need to call it using the name of the interface, just like static methods of a class." }, { "code": null, "e": 2428, "s": 2296, "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": 2854, "s": 2428, "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": 2924, "s": 2854, "text": "This is the implementation of the demo method\nThis is a static method" }, { "code": null, "e": 2985, "s": 2924, "text": "You can call a static method using the name of an interface." }, { "code": null, "e": 3064, "s": 2985, "text": "To call a default method you need to use the object of the implementing class." }, { "code": null, "e": 3156, "s": 3064, "text": "If you want, you can override a default method of an interface from the implementing class." }, { "code": null, "e": 3576, "s": 3156, "text": "interface MyInterface{\n public static int num = 100;\n public default void display() {\n System.out.println(\"display method of MyInterface\");\n }\n}\npublic class InterfaceExample implements MyInterface{\n public void display() {\n System.out.println(\"display method of class\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n obj.display();\n }\n}" }, { "code": null, "e": 3600, "s": 3576, "text": "display method of class" }, { "code": null, "e": 3892, "s": 3600, "text": "You cannot override the static method of the interface; you can just access them using the name of the interface. If you try to override a static method of an interface by defining a similar method in the implementing interface, it will be considered as another (static) method of the class." }, { "code": null, "e": 4309, "s": 3892, "text": "interface MyInterface{\n public static void display() {\n System.out.println(\"Static method of the interface\");\n }\n}\npublic class InterfaceExample{\n public static void display() {\n System.out.println(\"Static method of the class\");\n }\n public static void main(String args[]) {\n InterfaceExample obj = new InterfaceExample();\n MyInterface.display();\n InterfaceExample.display();\n }\n}" }, { "code": null, "e": 4367, "s": 4309, "text": "Static method of the interface\nStatic method of the class" } ]
6 SQL Tricks Every Data Scientist Should Know | by Kat Li | Towards Data Science
Data scientists/analysts should know SQL, in fact, all professionals working with data and analytics should know SQL. To some extent, SQL is an under-rated skill for data science because it has been taken for granted as a necessary yet uncool way of extracting data out from the database to feed into pandas and {tidyverse} β€” fancier ways to wrangle your data. However, with massive data being collected and churned out every day in the industries, as long as the data reside in a SQL compliant database, SQL is still the most proficient tool to help you investigate, filter and aggregate to get a thorough understanding of your data. By slicing and dicing with SQL, analysts are allowed to possibly identify patterns that worth further looking into, which oftentimes leads to redefining the analysis population and variables to be considerably smaller (than the initial scope). Hence rather than transferring huge datasets into Python or R, the first step of analytics should be using SQL to gain informative insights from our data. Working in real-world relational databases, SQL is way more than just SELECT, JOIN, ORDER BY statements. In this blog, I will discuss 6 tips (and one Bonus tip) to make your analytics work more efficient with SQL and its integrating with other programming languages like Python and R. For this exercise, we will work with Oracle SQL on the toy data table below, which consists of multiple types of data elements, COALESCE() to recode NULL / missing data COALESCE() to recode NULL / missing data When it comes to re-coding missing values, the COALESCE() function is our secret sauce, which, under this circumstance, re-codes the NULL to whatever value specified in the second argument. For our example, we can re-code the NULL_VAR to a character value β€˜MISSING’, this code snippet returns, One important note, however, is that in databases, missing values can be encoded in various ways besides NULL. For instance, they could be empty string/blank space (e.g., EMPTY_STR_VAR in our table), or a character string β€˜NA’ (e.g., NA_STR_VAR in our table). In these cases, COALESCE( ) would not work, but they can be handled with the CASE WHEN statement, *** Update 2022: You can also watch the video version of this blog on my channel here, 2. Compute running total and cumulative frequency Running total can be useful when we are interested in the total sum (but not individual value) at a given point for potential analysis population segmentation and outlier identification. The following showcases how to calculate the running total and cumulative frequency for the variable NUM_VAR, Here is our output (on the left). Two tricks here, (1) SUM over ROWS UNBOUNDED PRECEDING will calculate the sum of all prior values to this point; (2) create a JOIN_ID to calculate the total sum. We use the window function for this calculation, and from the cumulative frequency, it is not hard to spot the last record as an outlier. 3. Find the record(s) with extreme values without self joining So our task is to return the row(s) with the largest NUM_VAR value for each unique ID. An intuitive query is to first find the max value for each ID using group by, and then self join on ID and the max value. Yet a more concise way would be, this query should give us the following output, showing rows having the max NUM_VAR grouped by ID, 4. Conditional WHERE clause Everyone knows the WHERE clause in SQL for subsetting. In fact, I find myself using conditional WHERE clause more often. With the toy table, for instance, we want only to keep the rows satisfying the following logic, β€” if SEQ_VAR in (1, 2, 3) & diff(DATE_VAR2, DATE_VAR1)β‰₯ 0 β€” elif SEQ_VAR in (4, 5, 6) & diff(DATE_VAR2, DATE_VAR1) β‰₯1 β€” else diff(DATE_VAR2, DATE_VAR1) β‰₯2 Now the conditional WHERE clause comes in handy, The logic aforementioned should eliminate the sequences 4, 5 of ID = 19064 because the difference between date2 and date1 = 0, and this is exactly what the query returns above. 5. Lag() and Lead() to work with consecutive rows Lag (looking at the previous row) and Lead (looking at the next row) probably are two of the most used analytic functions in my day-to-day work. In a nutshell, these two functions allow users to query more than one row at a time without self-joining. More detailed explanations can be found here. Let’s say, we want to compute the difference in NUM_VAR between two consecutive rows (sorted by sequences), The LAG() function returns the prior row, and if there is none (i.e., the first row of each ID), the PREV_NUM is coded as 0 to compute the difference shown as NUM_DIFF below, 6. Integrate SQL query with Python and R The prerequisite of integrating SQL queries into Python and R is to establish the database connections via ODBC or JDBC. Since this is beyond the scope of this blog, I will not discuss it here, however, more details regarding how to (create ODBC or JDBC connections) can be found here. Now, assuming that we already connected Python and R to our database, the most straightforward way of using query in, say Python, is to copy and paste it as a string, then call pandas.read_sql(), my_query = "SELECT * FROM CURRENT_TABLE"sql_data = pandas.read_sql(my_query, connection) Well, as long as our queries are short and finalized with no further changes, this method works well. However, what if our query has 1000 lines, or we need to constantly update it? For these scenarios, we would want to read .sql files directly into Python or R. The following demonstrates how to implement a getSQL function in Python, and the idea is the same in R, Here, the first arg sql_query takes in a separate standalone .sql file that can be easily maintained, like this, The β€œID_LIST” is a placeholder string for the values we are about to put in, and the getSQL( ) can be called using the following code, Bonus tip, regular expression in SQL Even though I do not use regular expression in SQL all the time, it sometimes can be convenient for text extraction. For instance, the following code shows a simple example of how to use REGEXP_INSTR( ) to find and extract numbers (see here for more details), I hope you find this blog helpful, and the full code along with the toy dataset is available in my github. πŸ˜€ Want more data science and programming tips? Use my link to sign up to Medium and gain full access to all my content. Also subscribe to my newly created YouTube channel β€œData Talk with Kat”, Also, head over to Part 2 of this mini-series for more SQL analytics tips.
[ { "code": null, "e": 533, "s": 172, "text": "Data scientists/analysts should know SQL, in fact, all professionals working with data and analytics should know SQL. To some extent, SQL is an under-rated skill for data science because it has been taken for granted as a necessary yet uncool way of extracting data out from the database to feed into pandas and {tidyverse} β€” fancier ways to wrangle your data." }, { "code": null, "e": 1051, "s": 533, "text": "However, with massive data being collected and churned out every day in the industries, as long as the data reside in a SQL compliant database, SQL is still the most proficient tool to help you investigate, filter and aggregate to get a thorough understanding of your data. By slicing and dicing with SQL, analysts are allowed to possibly identify patterns that worth further looking into, which oftentimes leads to redefining the analysis population and variables to be considerably smaller (than the initial scope)." }, { "code": null, "e": 1206, "s": 1051, "text": "Hence rather than transferring huge datasets into Python or R, the first step of analytics should be using SQL to gain informative insights from our data." }, { "code": null, "e": 1491, "s": 1206, "text": "Working in real-world relational databases, SQL is way more than just SELECT, JOIN, ORDER BY statements. In this blog, I will discuss 6 tips (and one Bonus tip) to make your analytics work more efficient with SQL and its integrating with other programming languages like Python and R." }, { "code": null, "e": 1619, "s": 1491, "text": "For this exercise, we will work with Oracle SQL on the toy data table below, which consists of multiple types of data elements," }, { "code": null, "e": 1660, "s": 1619, "text": "COALESCE() to recode NULL / missing data" }, { "code": null, "e": 1701, "s": 1660, "text": "COALESCE() to recode NULL / missing data" }, { "code": null, "e": 1968, "s": 1701, "text": "When it comes to re-coding missing values, the COALESCE() function is our secret sauce, which, under this circumstance, re-codes the NULL to whatever value specified in the second argument. For our example, we can re-code the NULL_VAR to a character value β€˜MISSING’," }, { "code": null, "e": 1995, "s": 1968, "text": "this code snippet returns," }, { "code": null, "e": 2353, "s": 1995, "text": "One important note, however, is that in databases, missing values can be encoded in various ways besides NULL. For instance, they could be empty string/blank space (e.g., EMPTY_STR_VAR in our table), or a character string β€˜NA’ (e.g., NA_STR_VAR in our table). In these cases, COALESCE( ) would not work, but they can be handled with the CASE WHEN statement," }, { "code": null, "e": 2440, "s": 2353, "text": "*** Update 2022: You can also watch the video version of this blog on my channel here," }, { "code": null, "e": 2490, "s": 2440, "text": "2. Compute running total and cumulative frequency" }, { "code": null, "e": 2677, "s": 2490, "text": "Running total can be useful when we are interested in the total sum (but not individual value) at a given point for potential analysis population segmentation and outlier identification." }, { "code": null, "e": 2787, "s": 2677, "text": "The following showcases how to calculate the running total and cumulative frequency for the variable NUM_VAR," }, { "code": null, "e": 2821, "s": 2787, "text": "Here is our output (on the left)." }, { "code": null, "e": 2983, "s": 2821, "text": "Two tricks here, (1) SUM over ROWS UNBOUNDED PRECEDING will calculate the sum of all prior values to this point; (2) create a JOIN_ID to calculate the total sum." }, { "code": null, "e": 3121, "s": 2983, "text": "We use the window function for this calculation, and from the cumulative frequency, it is not hard to spot the last record as an outlier." }, { "code": null, "e": 3184, "s": 3121, "text": "3. Find the record(s) with extreme values without self joining" }, { "code": null, "e": 3426, "s": 3184, "text": "So our task is to return the row(s) with the largest NUM_VAR value for each unique ID. An intuitive query is to first find the max value for each ID using group by, and then self join on ID and the max value. Yet a more concise way would be," }, { "code": null, "e": 3525, "s": 3426, "text": "this query should give us the following output, showing rows having the max NUM_VAR grouped by ID," }, { "code": null, "e": 3553, "s": 3525, "text": "4. Conditional WHERE clause" }, { "code": null, "e": 3770, "s": 3553, "text": "Everyone knows the WHERE clause in SQL for subsetting. In fact, I find myself using conditional WHERE clause more often. With the toy table, for instance, we want only to keep the rows satisfying the following logic," }, { "code": null, "e": 3828, "s": 3770, "text": "β€” if SEQ_VAR in (1, 2, 3) & diff(DATE_VAR2, DATE_VAR1)β‰₯ 0" }, { "code": null, "e": 3888, "s": 3828, "text": "β€” elif SEQ_VAR in (4, 5, 6) & diff(DATE_VAR2, DATE_VAR1) β‰₯1" }, { "code": null, "e": 3925, "s": 3888, "text": "β€” else diff(DATE_VAR2, DATE_VAR1) β‰₯2" }, { "code": null, "e": 3974, "s": 3925, "text": "Now the conditional WHERE clause comes in handy," }, { "code": null, "e": 4151, "s": 3974, "text": "The logic aforementioned should eliminate the sequences 4, 5 of ID = 19064 because the difference between date2 and date1 = 0, and this is exactly what the query returns above." }, { "code": null, "e": 4201, "s": 4151, "text": "5. Lag() and Lead() to work with consecutive rows" }, { "code": null, "e": 4498, "s": 4201, "text": "Lag (looking at the previous row) and Lead (looking at the next row) probably are two of the most used analytic functions in my day-to-day work. In a nutshell, these two functions allow users to query more than one row at a time without self-joining. More detailed explanations can be found here." }, { "code": null, "e": 4606, "s": 4498, "text": "Let’s say, we want to compute the difference in NUM_VAR between two consecutive rows (sorted by sequences)," }, { "code": null, "e": 4781, "s": 4606, "text": "The LAG() function returns the prior row, and if there is none (i.e., the first row of each ID), the PREV_NUM is coded as 0 to compute the difference shown as NUM_DIFF below," }, { "code": null, "e": 4822, "s": 4781, "text": "6. Integrate SQL query with Python and R" }, { "code": null, "e": 5108, "s": 4822, "text": "The prerequisite of integrating SQL queries into Python and R is to establish the database connections via ODBC or JDBC. Since this is beyond the scope of this blog, I will not discuss it here, however, more details regarding how to (create ODBC or JDBC connections) can be found here." }, { "code": null, "e": 5304, "s": 5108, "text": "Now, assuming that we already connected Python and R to our database, the most straightforward way of using query in, say Python, is to copy and paste it as a string, then call pandas.read_sql()," }, { "code": null, "e": 5393, "s": 5304, "text": "my_query = \"SELECT * FROM CURRENT_TABLE\"sql_data = pandas.read_sql(my_query, connection)" }, { "code": null, "e": 5759, "s": 5393, "text": "Well, as long as our queries are short and finalized with no further changes, this method works well. However, what if our query has 1000 lines, or we need to constantly update it? For these scenarios, we would want to read .sql files directly into Python or R. The following demonstrates how to implement a getSQL function in Python, and the idea is the same in R," }, { "code": null, "e": 5872, "s": 5759, "text": "Here, the first arg sql_query takes in a separate standalone .sql file that can be easily maintained, like this," }, { "code": null, "e": 6007, "s": 5872, "text": "The β€œID_LIST” is a placeholder string for the values we are about to put in, and the getSQL( ) can be called using the following code," }, { "code": null, "e": 6044, "s": 6007, "text": "Bonus tip, regular expression in SQL" }, { "code": null, "e": 6304, "s": 6044, "text": "Even though I do not use regular expression in SQL all the time, it sometimes can be convenient for text extraction. For instance, the following code shows a simple example of how to use REGEXP_INSTR( ) to find and extract numbers (see here for more details)," }, { "code": null, "e": 6413, "s": 6304, "text": "I hope you find this blog helpful, and the full code along with the toy dataset is available in my github. πŸ˜€" }, { "code": null, "e": 6531, "s": 6413, "text": "Want more data science and programming tips? Use my link to sign up to Medium and gain full access to all my content." }, { "code": null, "e": 6604, "s": 6531, "text": "Also subscribe to my newly created YouTube channel β€œData Talk with Kat”," } ]
Can we call methods using this keyword in java?
The "this" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it. But, you should call them only from instance methods (non-static). In the following example, the Student class has a private variable name, with setter and getter methods, using the setter method we have assigned value to the name variable from the main method and then, we have invoked the getter (getName) method using "this" keyword from the instance method. public class ThisExample_Method { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void display() { System.out.println("name: "+this.getName()); } public static void main(String args[]) { ThisExample_Method obj = new ThisExample_Method(); Scanner sc = new Scanner(System.in); System.out.println("Enter the name of the student: "); String name = sc.nextLine(); obj.setName(name); obj.display(); } } Enter the name of the student: Krishna name: Krishna
[ { "code": null, "e": 1282, "s": 1062, "text": "The \"this\" keyword in Java is used as a reference to the current object, within an instance method or a constructor. Yes, you can call methods using it. But, you should call them only from instance methods (non-static)." }, { "code": null, "e": 1577, "s": 1282, "text": "In the following example, the Student class has a private variable name, with setter and getter methods, using the setter method we have assigned value to the name variable from the main method and then, we have invoked the getter (getName) method using \"this\" keyword from the instance method." }, { "code": null, "e": 2131, "s": 1577, "text": "public class ThisExample_Method {\n private String name;\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void display() {\n System.out.println(\"name: \"+this.getName());\n }\n public static void main(String args[]) {\n ThisExample_Method obj = new ThisExample_Method();\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the name of the student: \");\n String name = sc.nextLine();\n obj.setName(name);\n obj.display();\n }\n}" }, { "code": null, "e": 2184, "s": 2131, "text": "Enter the name of the student:\nKrishna\nname: Krishna" } ]
Difference between single-quoted and double-quoted strings in JavaScript - GeeksforGeeks
10 Apr, 2022 Both single-quoted and double-quoted strings in JavaScript are used for creating string literals. But the basic difference between them comes into play when the character which needed to be escaped is itself a single-quoted or double-quoted string. You need to escape single quote when the literal is enclosed in single code using the backslash(\) or need to escape double quotes when the literal is enclosed in a double code using a backslash(\). . Using Single-Quoted strings: While using single-quoted strings for defining string literals, we only need to escape the single quote inside the string. While there is no need to escape double-quote and can be written exactly. Example: Javascript <script> const geeks = 'We will visit \'GeeksforGeeks\' student.'; const hello = 'Hello, I am an "Engineer"'; document.write(geeks + "<br>"); document.write(hello)</script> Output: In this example, GeeksforGeeks has to be written within single quotes. Since, for defining string literal, we are using a single-quote string, that’s why we need to escape the single-quote(β€˜ β€˜) using a backslash(\) within the string. The engineer is quoted in a double-quoted string. Since for defining string literal, we are using a single-quote string, therefore, we do not need to escape the double-quotes(” β€œ) within the string. We will visit 'GeeksforGeeks' student. Hello, I am an "Engineer" Using Double-Quoted strings: While using double-quoted strings for defining string literals, we only need to escape the double-quote inside the string. While there is no need to escape single-quote and can be written exactly.Example: Javascript <script> const geeks = "We will visit \"GeeksforGeeks\" student." const hello = "Hello, I am an 'Engineer'" document.write(geeks+"<br>") document.write(hello)</script> Output: In this example, GeeksforGeeks has to be written within double quotes. Since, for defining string literal, we are using a double-quoted string, that’s why we need to escape the double-quotes(β€œβ€) using a backslash(\) within the string. The engineer is quoted in a single-quoted string. Since for defining string literal, we are using a double-quoted string, therefore, we do not need to escape the single-quote(”) within the string. We will visit "GeeksforGeeks" student. Hello, I am an 'Engineer' Whether the string is enclosed in a single quote or in a double quote, they behave in exactly the same manner except for the behavior of escaping characters. That means a string enclosed in the single quote is equal to the same string enclosed in the double quote provided that necessary characters are escaped. 'GeeksforGeeks' === "GeeksforGeeks" Example 1: Here, we have declared two constants namely a and b. In both the constants, we have stored the same literal GeeksforGeeks but they both are enclosed differently. the literals in constant a are being enclosed in double-quotes while the literals in constant b are being enclosed in single quotes. Then we are comparing constants a and b using a triple equal sign(===) and then write the output of it. Here, a===b will compare the string stored in constants a and b and will return true if they are strictly and exactly equal. If not equal, it will return false. Here the output comes true means that whether the string is enclosed in a single quote or in a double quote, they are strictly and exactly equal with the same value. That simply means Double quotes or Single quotes do not affect the enclosed string. Javascript <script> const a = "GeeksforGeeks" const b = 'GeeksforGeeks' document.write(a===b)</script> Output: true Example 2: Using a back-tic or a diacritic sign (`) is the alternative to using a single quote or double quote. In this, you don’t need to escape any single quote or double quote. So, it is an error-free choice. Again the string enclosed in back-tic would be strictly and exactly equal to the strings enclosed in single or double-quotes. Javascript <script> const geeks = `We will visit "GeeksforGeeks" student.` const hello = `Hello, I am an 'Engineer'` document.write(geeks+"<br>") document.write(hello)</script> Output: Here, as you can see that we have not escaped any double-quote or single while we are enclosing the string in back-tic(`) and this yields us the same output. We will visit "GeeksforGeeks" student. Hello, I am an 'Engineer' Points to remember: While back-tic(`) can be used anywhere and have fewer errors when handling JSON files from within JavaScript, the stringify() and parse() functions have to be enclosed only within double quotes as it knows about the double quotes already. Out of double quote and single quote, which one is preferred: Both quotes can be used anywhere but then, you have to consider the characters which are needed to be escaped. When you have to write double quotes(β€œ) inside the string, preferably choose a single quote string, or even if you are choosing a double-quoted string, don’t forget to escape the double quote inside the string. When you have to write single quotes(β€˜) inside the string, preferably choose a double-quoted string, or even if you are choosing a single quote string, don’t forget to escape the single quote inside the string. While you can use back-tics(`) in both the above cases and you don’t need to escape anything. Let us understand the differences in a Tabular Form -: Syntax -: β€˜string’ Syntax -: β€œstring” Example -: β€˜GeeksforGeeks’ Example -: β€œGeeksforGeeks” mayank007rawa javascript-string Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to get selected value in dropdown list using JavaScript ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24909, "s": 24881, "text": "\n10 Apr, 2022" }, { "code": null, "e": 25585, "s": 24909, "text": "Both single-quoted and double-quoted strings in JavaScript are used for creating string literals. But the basic difference between them comes into play when the character which needed to be escaped is itself a single-quoted or double-quoted string. You need to escape single quote when the literal is enclosed in single code using the backslash(\\) or need to escape double quotes when the literal is enclosed in a double code using a backslash(\\). . Using Single-Quoted strings: While using single-quoted strings for defining string literals, we only need to escape the single quote inside the string. While there is no need to escape double-quote and can be written exactly." }, { "code": null, "e": 25595, "s": 25585, "text": "Example: " }, { "code": null, "e": 25606, "s": 25595, "text": "Javascript" }, { "code": "<script> const geeks = 'We will visit \\'GeeksforGeeks\\' student.'; const hello = 'Hello, I am an \"Engineer\"'; document.write(geeks + \"<br>\"); document.write(hello)</script> ", "e": 25794, "s": 25606, "text": null }, { "code": null, "e": 26235, "s": 25794, "text": "Output: In this example, GeeksforGeeks has to be written within single quotes. Since, for defining string literal, we are using a single-quote string, that’s why we need to escape the single-quote(β€˜ β€˜) using a backslash(\\) within the string. The engineer is quoted in a double-quoted string. Since for defining string literal, we are using a single-quote string, therefore, we do not need to escape the double-quotes(” β€œ) within the string." }, { "code": null, "e": 26300, "s": 26235, "text": "We will visit 'GeeksforGeeks' student.\nHello, I am an \"Engineer\"" }, { "code": null, "e": 26535, "s": 26300, "text": "Using Double-Quoted strings: While using double-quoted strings for defining string literals, we only need to escape the double-quote inside the string. While there is no need to escape single-quote and can be written exactly.Example: " }, { "code": null, "e": 26546, "s": 26535, "text": "Javascript" }, { "code": "<script> const geeks = \"We will visit \\\"GeeksforGeeks\\\" student.\" const hello = \"Hello, I am an 'Engineer'\" document.write(geeks+\"<br>\") document.write(hello)</script> ", "e": 26729, "s": 26546, "text": null }, { "code": null, "e": 27170, "s": 26729, "text": "Output: In this example, GeeksforGeeks has to be written within double quotes. Since, for defining string literal, we are using a double-quoted string, that’s why we need to escape the double-quotes(β€œβ€) using a backslash(\\) within the string. The engineer is quoted in a single-quoted string. Since for defining string literal, we are using a double-quoted string, therefore, we do not need to escape the single-quote(”) within the string. " }, { "code": null, "e": 27235, "s": 27170, "text": "We will visit \"GeeksforGeeks\" student.\nHello, I am an 'Engineer'" }, { "code": null, "e": 27547, "s": 27235, "text": "Whether the string is enclosed in a single quote or in a double quote, they behave in exactly the same manner except for the behavior of escaping characters. That means a string enclosed in the single quote is equal to the same string enclosed in the double quote provided that necessary characters are escaped." }, { "code": null, "e": 27584, "s": 27547, "text": "'GeeksforGeeks' === \"GeeksforGeeks\" " }, { "code": null, "e": 28405, "s": 27584, "text": "Example 1: Here, we have declared two constants namely a and b. In both the constants, we have stored the same literal GeeksforGeeks but they both are enclosed differently. the literals in constant a are being enclosed in double-quotes while the literals in constant b are being enclosed in single quotes. Then we are comparing constants a and b using a triple equal sign(===) and then write the output of it. Here, a===b will compare the string stored in constants a and b and will return true if they are strictly and exactly equal. If not equal, it will return false. Here the output comes true means that whether the string is enclosed in a single quote or in a double quote, they are strictly and exactly equal with the same value. That simply means Double quotes or Single quotes do not affect the enclosed string." }, { "code": null, "e": 28416, "s": 28405, "text": "Javascript" }, { "code": "<script> const a = \"GeeksforGeeks\" const b = 'GeeksforGeeks' document.write(a===b)</script> ", "e": 28520, "s": 28416, "text": null }, { "code": null, "e": 28529, "s": 28520, "text": "Output: " }, { "code": null, "e": 28534, "s": 28529, "text": "true" }, { "code": null, "e": 28874, "s": 28534, "text": "Example 2: Using a back-tic or a diacritic sign (`) is the alternative to using a single quote or double quote. In this, you don’t need to escape any single quote or double quote. So, it is an error-free choice. Again the string enclosed in back-tic would be strictly and exactly equal to the strings enclosed in single or double-quotes. " }, { "code": null, "e": 28885, "s": 28874, "text": "Javascript" }, { "code": "<script> const geeks = `We will visit \"GeeksforGeeks\" student.` const hello = `Hello, I am an 'Engineer'` document.write(geeks+\"<br>\") document.write(hello)</script> ", "e": 29066, "s": 28885, "text": null }, { "code": null, "e": 29232, "s": 29066, "text": "Output: Here, as you can see that we have not escaped any double-quote or single while we are enclosing the string in back-tic(`) and this yields us the same output." }, { "code": null, "e": 29297, "s": 29232, "text": "We will visit \"GeeksforGeeks\" student.\nHello, I am an 'Engineer'" }, { "code": null, "e": 29558, "s": 29297, "text": "Points to remember: While back-tic(`) can be used anywhere and have fewer errors when handling JSON files from within JavaScript, the stringify() and parse() functions have to be enclosed only within double quotes as it knows about the double quotes already. " }, { "code": null, "e": 29733, "s": 29558, "text": "Out of double quote and single quote, which one is preferred: Both quotes can be used anywhere but then, you have to consider the characters which are needed to be escaped. " }, { "code": null, "e": 29944, "s": 29733, "text": "When you have to write double quotes(β€œ) inside the string, preferably choose a single quote string, or even if you are choosing a double-quoted string, don’t forget to escape the double quote inside the string." }, { "code": null, "e": 30155, "s": 29944, "text": "When you have to write single quotes(β€˜) inside the string, preferably choose a double-quoted string, or even if you are choosing a single quote string, don’t forget to escape the single quote inside the string." }, { "code": null, "e": 30249, "s": 30155, "text": "While you can use back-tics(`) in both the above cases and you don’t need to escape anything." }, { "code": null, "e": 30304, "s": 30249, "text": "Let us understand the differences in a Tabular Form -:" }, { "code": null, "e": 30314, "s": 30304, "text": "Syntax -:" }, { "code": null, "e": 30323, "s": 30314, "text": "β€˜string’" }, { "code": null, "e": 30333, "s": 30323, "text": "Syntax -:" }, { "code": null, "e": 30342, "s": 30333, "text": "β€œstring”" }, { "code": null, "e": 30353, "s": 30342, "text": "Example -:" }, { "code": null, "e": 30369, "s": 30353, "text": "β€˜GeeksforGeeks’" }, { "code": null, "e": 30380, "s": 30369, "text": "Example -:" }, { "code": null, "e": 30396, "s": 30380, "text": "β€œGeeksforGeeks”" }, { "code": null, "e": 30410, "s": 30396, "text": "mayank007rawa" }, { "code": null, "e": 30428, "s": 30410, "text": "javascript-string" }, { "code": null, "e": 30435, "s": 30428, "text": "Picked" }, { "code": null, "e": 30446, "s": 30435, "text": "JavaScript" }, { "code": null, "e": 30463, "s": 30446, "text": "Web Technologies" }, { "code": null, "e": 30490, "s": 30463, "text": "Web technologies Questions" }, { "code": null, "e": 30588, "s": 30490, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30597, "s": 30588, "text": "Comments" }, { "code": null, "e": 30610, "s": 30597, "text": "Old Comments" }, { "code": null, "e": 30671, "s": 30610, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30712, "s": 30671, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30766, "s": 30712, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 30806, "s": 30766, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30868, "s": 30806, "text": "How to get selected value in dropdown list using JavaScript ?" }, { "code": null, "e": 30924, "s": 30868, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 30957, "s": 30924, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31019, "s": 30957, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31062, "s": 31019, "text": "How to fetch data from an API in ReactJS ?" } ]
How to convert a value to a number in JavaScript?
Javascript has introduced Number() method to convert a value into a number. This method can convert number strings to numbers and boolean values to 1's or 0's. Let's discuss it briefly. var num = Number(value); In the following example, Number() method has converted number strings and boolean values to numbers and displayed the output as shown. Live Demo <html> <body> <script> document.write(Number("10.5") + "</br>"); document.write(Number(" 123 ") + "</br>"); document.write(Number(true) + "</br>"); document.write(Number(false) + "</br>"); document.write(Number(null)); </script> </body> </html> 10.5 123 1 0 0 This method not only converts a normal value to a number but also converts a hexadecimal value to a number as shown below. Live Demo <html> <body> <script> document.write(Number(" ") + "<br>"); document.write(Number("") + "<br>"); document.write(Number("123e-1") + "<br>"); document.write(Number("0xFF") + "<br>"); </script> </body> </html> 0 0 12.3 255
[ { "code": null, "e": 1248, "s": 1062, "text": "Javascript has introduced Number() method to convert a value into a number. This method can convert number strings to numbers and boolean values to 1's or 0's. Let's discuss it briefly." }, { "code": null, "e": 1273, "s": 1248, "text": "var num = Number(value);" }, { "code": null, "e": 1410, "s": 1273, "text": "In the following example, Number() method has converted number strings and boolean values to numbers and displayed the output as shown. " }, { "code": null, "e": 1420, "s": 1410, "text": "Live Demo" }, { "code": null, "e": 1680, "s": 1420, "text": "<html>\n<body>\n<script>\n document.write(Number(\"10.5\") + \"</br>\");\n document.write(Number(\" 123 \") + \"</br>\");\n document.write(Number(true) + \"</br>\");\n document.write(Number(false) + \"</br>\");\n document.write(Number(null));\n</script>\n</body>\n</html>" }, { "code": null, "e": 1695, "s": 1680, "text": "10.5\n123\n1\n0\n0" }, { "code": null, "e": 1818, "s": 1695, "text": "This method not only converts a normal value to a number but also converts a hexadecimal value to a number as shown below." }, { "code": null, "e": 1829, "s": 1818, "text": " Live Demo" }, { "code": null, "e": 2055, "s": 1829, "text": "<html>\n<body>\n<script>\n document.write(Number(\" \") + \"<br>\"); \n document.write(Number(\"\") + \"<br>\"); \n document.write(Number(\"123e-1\") + \"<br>\"); \n document.write(Number(\"0xFF\") + \"<br>\");\n</script>\n</body>\n</html>" }, { "code": null, "e": 2068, "s": 2055, "text": "0\n0\n12.3\n255" } ]
Round float and double numbers in Java
In order to round float and double numbers in Java, we use the java.lang.Math.round() method. The method accepts either double or float values and returns an integer value. It returns the closest integer to number. This is computed by adding 1⁄2 to the number and then flooring it. Declaration - The java.lang.Math.round() method is declared as follows βˆ’ public static int round(float a) public static int round(double a) where a is the value to be rounded. Let us see a program where float and double numbers are rounded in Java. Live Demo import java.lang.Math; public class Example { public static void main(String[] args) { // declaring and initializing some double and values double x = 25.5; float y = 8.1f; // printing the rounded values System.out.println("The round-off of "+ x + " is "+ Math.round(x)); System.out.println("The round-off of "+ y + " is "+ Math.round(y)); } } The round-off of 25.5 is 26 The round-off of 8.1 is 8
[ { "code": null, "e": 1344, "s": 1062, "text": "In order to round float and double numbers in Java, we use the java.lang.Math.round() method. The method accepts either double or float values and returns an integer value. It returns the closest integer to number. This is computed by adding 1⁄2 to the number and then flooring it." }, { "code": null, "e": 1417, "s": 1344, "text": "Declaration - The java.lang.Math.round() method is declared as follows βˆ’" }, { "code": null, "e": 1484, "s": 1417, "text": "public static int round(float a)\npublic static int round(double a)" }, { "code": null, "e": 1520, "s": 1484, "text": "where a is the value to be rounded." }, { "code": null, "e": 1593, "s": 1520, "text": "Let us see a program where float and double numbers are rounded in Java." }, { "code": null, "e": 1604, "s": 1593, "text": " Live Demo" }, { "code": null, "e": 1990, "s": 1604, "text": "import java.lang.Math;\npublic class Example {\n public static void main(String[] args) {\n // declaring and initializing some double and values\n double x = 25.5;\n float y = 8.1f;\n // printing the rounded values\n System.out.println(\"The round-off of \"+ x + \" is \"+ Math.round(x));\n System.out.println(\"The round-off of \"+ y + \" is \"+ Math.round(y));\n }\n}" }, { "code": null, "e": 2044, "s": 1990, "text": "The round-off of 25.5 is 26\nThe round-off of 8.1 is 8" } ]
Flutter - Installation
This chapter will guide you through the installation of Flutter on your local computer in detail. In this section, let us see how to install Flutter SDK and its requirement in a windows system. Step 1 βˆ’ Go to URL, https://flutter.dev/docs/get-started/install/windows and download the latest Flutter SDK. As of April 2019, the version is 1.2.1 and the file is flutter_windows_v1.2.1-stable.zip. Step 2 βˆ’ Unzip the zip archive in a folder, say C:\flutter\ Step 3 βˆ’ Update the system path to include flutter bin directory. Step 4 βˆ’ Flutter provides a tool, flutter doctor to check that all the requirement of flutter development is met. flutter doctor Step 5 βˆ’ Running the above command will analyze the system and show its report as shown below βˆ’ Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [Version 10.0.17134.706], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK version 28.0.3) [√] Android Studio (version 3.2) [√] VS Code, 64-bit edition (version 1.29.1) [!] Connected device ! No devices available ! Doctor found issues in 1 category. The report says that all development tools are available but the device is not connected. We can fix this by connecting an android device through USB or starting an android emulator. Step 6 βˆ’ Install the latest Android SDK, if reported by flutter doctor Step 7 βˆ’ Install the latest Android Studio, if reported by flutter doctor Step 8 βˆ’ Start an android emulator or connect a real android device to the system. Step 9 βˆ’ Install Flutter and Dart plugin for Android Studio. It provides startup template to create new Flutter application, an option to run and debug Flutter application in the Android studio itself, etc., Open Android Studio. Open Android Studio. Click File β†’ Settings β†’ Plugins. Click File β†’ Settings β†’ Plugins. Select the Flutter plugin and click Install. Select the Flutter plugin and click Install. Click Yes when prompted to install the Dart plugin. Click Yes when prompted to install the Dart plugin. Restart Android studio. Restart Android studio. To install Flutter on MacOS, you will have to follow the following steps βˆ’ Step 1 βˆ’ Go to URL, https://flutter.dev/docs/get-started/install/macos and download latest Flutter SDK. As of April 2019, the version is 1.2.1 and the file is flutter_macos_v1.2.1- stable.zip. Step 2 βˆ’ Unzip the zip archive in a folder, say /path/to/flutter Step 3 βˆ’ Update the system path to include flutter bin directory (in ~/.bashrc file). > export PATH = "$PATH:/path/to/flutter/bin" Step 4 βˆ’ Enable the updated path in the current session using below command and then verify it as well. source ~/.bashrc source $HOME/.bash_profile echo $PATH Flutter provides a tool, flutter doctor to check that all the requirement of flutter development is met. It is similar to the Windows counterpart. Step 5 βˆ’ Install latest XCode, if reported by flutter doctor Step 6 βˆ’ Install latest Android SDK, if reported by flutter doctor Step 7 βˆ’ Install latest Android Studio, if reported by flutter doctor Step 8 βˆ’ Start an android emulator or connect a real android device to the system to develop android application. Step 9 βˆ’ Open iOS simulator or connect a real iPhone device to the system to develop iOS application. Step 10 βˆ’ Install Flutter and Dart plugin for Android Studio. It provides the startup template to create a new Flutter application, option to run and debug Flutter application in the Android studio itself, etc., Open Android Studio Open Android Studio Click Preferences β†’ Plugins Click Preferences β†’ Plugins Select the Flutter plugin and click Install Select the Flutter plugin and click Install Click Yes when prompted to install the Dart plugin. Click Yes when prompted to install the Dart plugin. Restart Android studio. Restart Android studio. 34 Lectures 4 hours Sriyank Siddhartha 117 Lectures 10 hours Frahaan Hussain 27 Lectures 1 hours Skillbakerystudios 17 Lectures 51 mins Harsh Kumar Khatri 17 Lectures 1.5 hours Pramila Rawat 85 Lectures 16.5 hours Rahul Agarwal Print Add Notes Bookmark this page
[ { "code": null, "e": 2316, "s": 2218, "text": "This chapter will guide you through the installation of Flutter on your local computer in detail." }, { "code": null, "e": 2412, "s": 2316, "text": "In this section, let us see how to install Flutter SDK and its requirement in a windows system." }, { "code": null, "e": 2612, "s": 2412, "text": "Step 1 βˆ’ Go to URL, https://flutter.dev/docs/get-started/install/windows and download the latest Flutter SDK. As of April 2019, the version is 1.2.1 and the file is flutter_windows_v1.2.1-stable.zip." }, { "code": null, "e": 2672, "s": 2612, "text": "Step 2 βˆ’ Unzip the zip archive in a folder, say C:\\flutter\\" }, { "code": null, "e": 2738, "s": 2672, "text": "Step 3 βˆ’ Update the system path to include flutter bin directory." }, { "code": null, "e": 2852, "s": 2738, "text": "Step 4 βˆ’ Flutter provides a tool, flutter doctor to check that all the requirement of flutter development is met." }, { "code": null, "e": 2868, "s": 2852, "text": "flutter doctor\n" }, { "code": null, "e": 2964, "s": 2868, "text": "Step 5 βˆ’ Running the above command will analyze the system and show its report as shown below βˆ’" }, { "code": null, "e": 3363, "s": 2964, "text": "Doctor summary (to see all details, run flutter doctor -v):\n[√] Flutter (Channel stable, v1.2.1, on Microsoft Windows [Version\n10.0.17134.706], locale en-US)\n[√] Android toolchain - develop for Android devices (Android SDK version\n28.0.3)\n[√] Android Studio (version 3.2)\n[√] VS Code, 64-bit edition (version 1.29.1)\n[!] Connected device\n! No devices available\n! Doctor found issues in 1 category.\n" }, { "code": null, "e": 3546, "s": 3363, "text": "The report says that all development tools are available but the device is not connected. We can fix this by connecting an android device through USB or starting an android emulator." }, { "code": null, "e": 3617, "s": 3546, "text": "Step 6 βˆ’ Install the latest Android SDK, if reported by flutter doctor" }, { "code": null, "e": 3691, "s": 3617, "text": "Step 7 βˆ’ Install the latest Android Studio, if reported by flutter doctor" }, { "code": null, "e": 3774, "s": 3691, "text": "Step 8 βˆ’ Start an android emulator or connect a real android device to the system." }, { "code": null, "e": 3982, "s": 3774, "text": "Step 9 βˆ’ Install Flutter and Dart plugin for Android Studio. It provides startup template to create new Flutter application, an option to run and debug Flutter application in the Android studio itself, etc.," }, { "code": null, "e": 4003, "s": 3982, "text": "Open Android Studio." }, { "code": null, "e": 4024, "s": 4003, "text": "Open Android Studio." }, { "code": null, "e": 4057, "s": 4024, "text": "Click File β†’ Settings β†’ Plugins." }, { "code": null, "e": 4090, "s": 4057, "text": "Click File β†’ Settings β†’ Plugins." }, { "code": null, "e": 4135, "s": 4090, "text": "Select the Flutter plugin and click Install." }, { "code": null, "e": 4180, "s": 4135, "text": "Select the Flutter plugin and click Install." }, { "code": null, "e": 4232, "s": 4180, "text": "Click Yes when prompted to install the Dart plugin." }, { "code": null, "e": 4284, "s": 4232, "text": "Click Yes when prompted to install the Dart plugin." }, { "code": null, "e": 4308, "s": 4284, "text": "Restart Android studio." }, { "code": null, "e": 4332, "s": 4308, "text": "Restart Android studio." }, { "code": null, "e": 4407, "s": 4332, "text": "To install Flutter on MacOS, you will have to follow the following steps βˆ’" }, { "code": null, "e": 4600, "s": 4407, "text": "Step 1 βˆ’ Go to URL, https://flutter.dev/docs/get-started/install/macos and download latest Flutter SDK. As of April 2019, the version is 1.2.1 and the file is flutter_macos_v1.2.1- stable.zip." }, { "code": null, "e": 4665, "s": 4600, "text": "Step 2 βˆ’ Unzip the zip archive in a folder, say /path/to/flutter" }, { "code": null, "e": 4751, "s": 4665, "text": "Step 3 βˆ’ Update the system path to include flutter bin directory (in ~/.bashrc file)." }, { "code": null, "e": 4797, "s": 4751, "text": "> export PATH = \"$PATH:/path/to/flutter/bin\"\n" }, { "code": null, "e": 4901, "s": 4797, "text": "Step 4 βˆ’ Enable the updated path in the current session using below command and then verify it as well." }, { "code": null, "e": 4957, "s": 4901, "text": "source ~/.bashrc\nsource $HOME/.bash_profile\necho $PATH\n" }, { "code": null, "e": 5104, "s": 4957, "text": "Flutter provides a tool, flutter doctor to check that all the requirement of flutter development is met. It is similar to the Windows counterpart." }, { "code": null, "e": 5165, "s": 5104, "text": "Step 5 βˆ’ Install latest XCode, if reported by flutter doctor" }, { "code": null, "e": 5232, "s": 5165, "text": "Step 6 βˆ’ Install latest Android SDK, if reported by flutter doctor" }, { "code": null, "e": 5302, "s": 5232, "text": "Step 7 βˆ’ Install latest Android Studio, if reported by flutter doctor" }, { "code": null, "e": 5416, "s": 5302, "text": "Step 8 βˆ’ Start an android emulator or connect a real android device to the system to develop android application." }, { "code": null, "e": 5518, "s": 5416, "text": "Step 9 βˆ’ Open iOS simulator or connect a real iPhone device to the system to develop iOS application." }, { "code": null, "e": 5730, "s": 5518, "text": "Step 10 βˆ’ Install Flutter and Dart plugin for Android Studio. It provides the startup template to create a new Flutter application, option to run and debug Flutter application in the Android studio itself, etc.," }, { "code": null, "e": 5750, "s": 5730, "text": "Open Android Studio" }, { "code": null, "e": 5770, "s": 5750, "text": "Open Android Studio" }, { "code": null, "e": 5798, "s": 5770, "text": "Click Preferences β†’ Plugins" }, { "code": null, "e": 5826, "s": 5798, "text": "Click Preferences β†’ Plugins" }, { "code": null, "e": 5870, "s": 5826, "text": "Select the Flutter plugin and click Install" }, { "code": null, "e": 5914, "s": 5870, "text": "Select the Flutter plugin and click Install" }, { "code": null, "e": 5966, "s": 5914, "text": "Click Yes when prompted to install the Dart plugin." }, { "code": null, "e": 6018, "s": 5966, "text": "Click Yes when prompted to install the Dart plugin." }, { "code": null, "e": 6042, "s": 6018, "text": "Restart Android studio." }, { "code": null, "e": 6066, "s": 6042, "text": "Restart Android studio." }, { "code": null, "e": 6099, "s": 6066, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 6119, "s": 6099, "text": " Sriyank Siddhartha" }, { "code": null, "e": 6154, "s": 6119, "text": "\n 117 Lectures \n 10 hours \n" }, { "code": null, "e": 6171, "s": 6154, "text": " Frahaan Hussain" }, { "code": null, "e": 6204, "s": 6171, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 6224, "s": 6204, "text": " Skillbakerystudios" }, { "code": null, "e": 6256, "s": 6224, "text": "\n 17 Lectures \n 51 mins\n" }, { "code": null, "e": 6276, "s": 6256, "text": " Harsh Kumar Khatri" }, { "code": null, "e": 6311, "s": 6276, "text": "\n 17 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6326, "s": 6311, "text": " Pramila Rawat" }, { "code": null, "e": 6362, "s": 6326, "text": "\n 85 Lectures \n 16.5 hours \n" }, { "code": null, "e": 6377, "s": 6362, "text": " Rahul Agarwal" }, { "code": null, "e": 6384, "s": 6377, "text": " Print" }, { "code": null, "e": 6395, "s": 6384, "text": " Add Notes" } ]
VueJS - Introduction
Vue is a JavaScript framework for building user interfaces. Its core part is focused mainly on the view layer and it is very easy to understand. The version of Vue that we are going to use in this tutorial is 2.0. As Vue is basically built for frontend development, we are going to deal with lot of HTML, JavaScript and CSS files in the upcoming chapters. To understand the details, let us start with a simple example. In this example, we are going to use the development verison of vuejs. <html> <head> <title>VueJs Introduction</title> <script type = "text/javascript" src = "js/vue.js"></script> </head> <body> <div id = "intro" style = "text-align:center;"> <h1>{{ message }}</h1> </div> <script type = "text/javascript"> var vue_det = new Vue({ el: '#intro', data: { message: 'My first VueJS Task' } }); </script> </body> </html> This is the first app we have created using VueJS. As seen in the above code, we have included vue.js at the start of the .html file. <script type = "text/javascript" src = "js/vue.js"></script> There is a div which is added in the body that prints β€œMy first VueJS Task” in the browser. <div id = "intro" style = "text-align:center;"> <h1>{{ message }}</h1> </div> We have also added a message in a interpolation, i.e. {{}}. This interacts with VueJS and prints the data in the browser. To get the value of the message in the DOM, we are creating an instance of vuejs as follows βˆ’ var vue_det = new Vue({ el: '#intro', data: { message: 'My first VueJS Task' } }) In the above code snippet, we are calling Vue instance, which takes the id of the DOM element i.e. e1:’#intro’, it is the id of the div. There is data with the message which is assigned the value β€˜My first VueJS Task’. VueJS interacts with DOM and changes the value in the DOM {{message}} with ’My first VueJS Task’. If we happen to change the value of the message in the console, the same will be reflected in the browser. For example βˆ’ In the above console, we have printed the vue_det object, which is an instance of Vue. We are updating the message with β€œVueJs is interesting” and the same is changed in the browser immediately as seen in the above screenshot. This is just a basic example showing the linking of VueJS with DOM, and how we can manipulate it. In the next few chapters, we will learn about directives, components, conditional loops, etc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2150, "s": 1936, "text": "Vue is a JavaScript framework for building user interfaces. Its core part is focused mainly on the view layer and it is very easy to understand. The version of Vue that we are going to use in this tutorial is 2.0." }, { "code": null, "e": 2355, "s": 2150, "text": "As Vue is basically built for frontend development, we are going to deal with lot of HTML, JavaScript and CSS files in the upcoming chapters. To understand the details, let us start with a simple example." }, { "code": null, "e": 2426, "s": 2355, "text": "In this example, we are going to use the development verison of vuejs." }, { "code": null, "e": 2897, "s": 2426, "text": "<html>\n <head>\n <title>VueJs Introduction</title>\n <script type = \"text/javascript\" src = \"js/vue.js\"></script>\n </head>\n <body>\n <div id = \"intro\" style = \"text-align:center;\">\n <h1>{{ message }}</h1>\n </div>\n <script type = \"text/javascript\">\n var vue_det = new Vue({\n el: '#intro',\n data: {\n message: 'My first VueJS Task'\n }\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 3031, "s": 2897, "text": "This is the first app we have created using VueJS. As seen in the above code, we have included vue.js at the start of the .html file." }, { "code": null, "e": 3092, "s": 3031, "text": "<script type = \"text/javascript\" src = \"js/vue.js\"></script>" }, { "code": null, "e": 3184, "s": 3092, "text": "There is a div which is added in the body that prints β€œMy first VueJS Task” in the browser." }, { "code": null, "e": 3265, "s": 3184, "text": "<div id = \"intro\" style = \"text-align:center;\">\n <h1>{{ message }}</h1>\n</div>" }, { "code": null, "e": 3481, "s": 3265, "text": "We have also added a message in a interpolation, i.e. {{}}. This interacts with VueJS and prints the data in the browser. To get the value of the message in the DOM, we are creating an instance of vuejs as follows βˆ’" }, { "code": null, "e": 3578, "s": 3481, "text": "var vue_det = new Vue({\n el: '#intro',\n data: {\n message: 'My first VueJS Task'\n }\n})" }, { "code": null, "e": 3895, "s": 3578, "text": "In the above code snippet, we are calling Vue instance, which takes the id of the DOM element i.e. e1:’#intro’, it is the id of the div. There is data with the message which is assigned the value β€˜My first VueJS Task’. VueJS interacts with DOM and changes the value in the DOM {{message}} with ’My first VueJS Task’." }, { "code": null, "e": 4016, "s": 3895, "text": "If we happen to change the value of the message in the console, the same will be reflected in the browser. For example βˆ’" }, { "code": null, "e": 4243, "s": 4016, "text": "In the above console, we have printed the vue_det object, which is an instance of Vue. We are updating the message with β€œVueJs is interesting” and the same is changed in the browser immediately as seen in the above screenshot." }, { "code": null, "e": 4435, "s": 4243, "text": "This is just a basic example showing the linking of VueJS with DOM, and how we can manipulate it. In the next few chapters, we will learn about directives, components, conditional loops, etc." }, { "code": null, "e": 4442, "s": 4435, "text": " Print" }, { "code": null, "e": 4453, "s": 4442, "text": " Add Notes" } ]
C# - Preprocessor Directives
The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts. All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;). C# compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In C# the preprocessor directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros. A preprocessor directive must be the only instruction on a line. The following table lists the preprocessor directives available in C# βˆ’ #define It defines a sequence of characters, called symbol. #undef It allows you to undefine a symbol. #if It allows testing a symbol or symbols to see if they evaluate to true. #else It allows to create a compound conditional directive, along with #if. #elif It allows creating a compound conditional directive. #endif Specifies the end of a conditional directive. #line It lets you modify the compiler's line number and (optionally) the file name output for errors and warnings. #error It allows generating an error from a specific location in your code. #warning It allows generating a level one warning from a specific location in your code. #region It lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor. #endregion It marks the end of a #region block. The #define preprocessor directive creates symbolic constants. #define lets you define a symbol such that, by using the symbol as the expression passed to the #if directive, the expression evaluates to true. Its syntax is as follows βˆ’ #define symbol The following program illustrates this βˆ’ #define PI using System; namespace PreprocessorDAppl { class Program { static void Main(string[] args) { #if (PI) Console.WriteLine("PI is defined"); #else Console.WriteLine("PI is not defined"); #endif Console.ReadKey(); } } } When the above code is compiled and executed, it produces the following result βˆ’ PI is defined You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive. Syntax for conditional directive is βˆ’ #if symbol [operator symbol]... Where, symbol is the name of the symbol you want to test. You can also use true and false or prepend the symbol with the negation operator. The operator symbol is the operator used for evaluating the symbol. Operators could be either of the following βˆ’ == (equality) != (inequality) && (and) || (or) You can also group symbols and operators with parentheses. Conditional directives are used for compiling code for a debug build or when compiling for a specific configuration. A conditional directive beginning with a #if directive must explicitly be terminated with a #endif directive. The following program demonstrates use of conditional directives βˆ’ #define DEBUG #define VC_V10 using System; public class TestClass { public static void Main() { #if (DEBUG && !VC_V10) Console.WriteLine("DEBUG is defined"); #elif (!DEBUG && VC_V10) Console.WriteLine("VC_V10 is defined"); #elif (DEBUG && VC_V10) Console.WriteLine("DEBUG and VC_V10 are defined"); #else Console.WriteLine("DEBUG and VC_V10 are not defined"); #endif Console.ReadKey(); } } When the above code is compiled and executed, it produces the following result βˆ’ DEBUG and VC_V10 are defined 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": 2395, "s": 2270, "text": "The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts." }, { "code": null, "e": 2608, "s": 2395, "text": "All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;)." }, { "code": null, "e": 2927, "s": 2608, "text": "C# compiler does not have a separate preprocessor; however, the directives are processed as if there was one. In C# the preprocessor directives are used to help in conditional compilation. Unlike C and C++ directives, they are not used to create macros. A preprocessor directive must be the only instruction on a line." }, { "code": null, "e": 2999, "s": 2927, "text": "The following table lists the preprocessor directives available in C# βˆ’" }, { "code": null, "e": 3007, "s": 2999, "text": "#define" }, { "code": null, "e": 3059, "s": 3007, "text": "It defines a sequence of characters, called symbol." }, { "code": null, "e": 3066, "s": 3059, "text": "#undef" }, { "code": null, "e": 3102, "s": 3066, "text": "It allows you to undefine a symbol." }, { "code": null, "e": 3106, "s": 3102, "text": "#if" }, { "code": null, "e": 3177, "s": 3106, "text": "It allows testing a symbol or symbols to see if they evaluate to true." }, { "code": null, "e": 3183, "s": 3177, "text": "#else" }, { "code": null, "e": 3253, "s": 3183, "text": "It allows to create a compound conditional directive, along with #if." }, { "code": null, "e": 3259, "s": 3253, "text": "#elif" }, { "code": null, "e": 3312, "s": 3259, "text": "It allows creating a compound conditional directive." }, { "code": null, "e": 3319, "s": 3312, "text": "#endif" }, { "code": null, "e": 3365, "s": 3319, "text": "Specifies the end of a conditional directive." }, { "code": null, "e": 3371, "s": 3365, "text": "#line" }, { "code": null, "e": 3480, "s": 3371, "text": "It lets you modify the compiler's line number and (optionally) the file name output for errors and warnings." }, { "code": null, "e": 3487, "s": 3480, "text": "#error" }, { "code": null, "e": 3556, "s": 3487, "text": "It allows generating an error from a specific location in your code." }, { "code": null, "e": 3565, "s": 3556, "text": "#warning" }, { "code": null, "e": 3645, "s": 3565, "text": "It allows generating a level one warning from a specific location in your code." }, { "code": null, "e": 3653, "s": 3645, "text": "#region" }, { "code": null, "e": 3788, "s": 3653, "text": "It lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor." }, { "code": null, "e": 3799, "s": 3788, "text": "#endregion" }, { "code": null, "e": 3836, "s": 3799, "text": "It marks the end of a #region block." }, { "code": null, "e": 3899, "s": 3836, "text": "The #define preprocessor directive creates symbolic constants." }, { "code": null, "e": 4071, "s": 3899, "text": "#define lets you define a symbol such that, by using the symbol as the expression passed to the #if directive, the expression evaluates to true. Its syntax is as follows βˆ’" }, { "code": null, "e": 4087, "s": 4071, "text": "#define symbol\n" }, { "code": null, "e": 4128, "s": 4087, "text": "The following program illustrates this βˆ’" }, { "code": null, "e": 4436, "s": 4128, "text": "#define PI \nusing System;\n\nnamespace PreprocessorDAppl {\n class Program {\n static void Main(string[] args) {\n #if (PI)\n Console.WriteLine(\"PI is defined\");\n #else\n Console.WriteLine(\"PI is not defined\");\n #endif\n Console.ReadKey();\n }\n }\n}" }, { "code": null, "e": 4517, "s": 4436, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 4532, "s": 4517, "text": "PI is defined\n" }, { "code": null, "e": 4803, "s": 4532, "text": "You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive." }, { "code": null, "e": 4841, "s": 4803, "text": "Syntax for conditional directive is βˆ’" }, { "code": null, "e": 4874, "s": 4841, "text": "#if symbol [operator symbol]...\n" }, { "code": null, "e": 5014, "s": 4874, "text": "Where, symbol is the name of the symbol you want to test. You can also use true and false or prepend the symbol with the negation operator." }, { "code": null, "e": 5127, "s": 5014, "text": "The operator symbol is the operator used for evaluating the symbol. Operators could be either of the following βˆ’" }, { "code": null, "e": 5141, "s": 5127, "text": "== (equality)" }, { "code": null, "e": 5157, "s": 5141, "text": "!= (inequality)" }, { "code": null, "e": 5166, "s": 5157, "text": "&& (and)" }, { "code": null, "e": 5174, "s": 5166, "text": "|| (or)" }, { "code": null, "e": 5460, "s": 5174, "text": "You can also group symbols and operators with parentheses. Conditional directives are used for compiling code for a debug build or when compiling for a specific configuration. A conditional directive beginning with a #if directive must explicitly be terminated with a #endif directive." }, { "code": null, "e": 5527, "s": 5460, "text": "The following program demonstrates use of conditional directives βˆ’" }, { "code": null, "e": 5995, "s": 5527, "text": "#define DEBUG\n#define VC_V10\nusing System;\n\npublic class TestClass {\n public static void Main() {\n #if (DEBUG && !VC_V10)\n Console.WriteLine(\"DEBUG is defined\");\n #elif (!DEBUG && VC_V10)\n Console.WriteLine(\"VC_V10 is defined\");\n #elif (DEBUG && VC_V10)\n Console.WriteLine(\"DEBUG and VC_V10 are defined\");\n #else\n Console.WriteLine(\"DEBUG and VC_V10 are not defined\");\n #endif\n Console.ReadKey();\n }\n}" }, { "code": null, "e": 6076, "s": 5995, "text": "When the above code is compiled and executed, it produces the following result βˆ’" }, { "code": null, "e": 6106, "s": 6076, "text": "DEBUG and VC_V10 are defined\n" }, { "code": null, "e": 6143, "s": 6106, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 6156, "s": 6143, "text": " Raja Biswas" }, { "code": null, "e": 6190, "s": 6156, "text": "\n 37 Lectures \n 13 hours \n" }, { "code": null, "e": 6208, "s": 6190, "text": " Trevoir Williams" }, { "code": null, "e": 6241, "s": 6208, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6255, "s": 6241, "text": " Peter Jepson" }, { "code": null, "e": 6292, "s": 6255, "text": "\n 159 Lectures \n 21.5 hours \n" }, { "code": null, "e": 6307, "s": 6292, "text": " Ebenezer Ogbu" }, { "code": null, "e": 6342, "s": 6307, "text": "\n 193 Lectures \n 17 hours \n" }, { "code": null, "e": 6357, "s": 6342, "text": " Arnold Higuit" }, { "code": null, "e": 6392, "s": 6357, "text": "\n 24 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6404, "s": 6392, "text": " Eric Frick" }, { "code": null, "e": 6411, "s": 6404, "text": " Print" }, { "code": null, "e": 6422, "s": 6411, "text": " Add Notes" } ]
Deploying a Prophet Forecasting Model with Streamlit to Heroku | by Edward Krueger | Towards Data Science
By: Edward Krueger and Douglas Franklin. Streamlit and Facebook Prophet give us the ability to create a clean forecasting dashboard with minimal effort and no cost. This makes for a solid proof of concept workflow. In this project, we create a dashboard using Streamlit and Prophet to showcase data and make forecasts and then deploy our app to Heroku. Here is a link to the GitHub repository with our code for the project. Note that we use Pipenv to manage our dependencies. github.com Streamlit is a free and open-source app framework that presents an easy way for data scientists and machine learning engineers to create great Python apps quickly. Streamlit’s opinioned nature makes building frontends easy. Lastly, Streamlit can make experimentation and production of data apps and machine learning analysis easier to do and to iterate on. Check it out on GitHub. github.com Streamlit is excellent because it embraces Python scripting, treats widgets as variables, and caches data and computation for reuse. This allows us to have custom complex visualizations that only need to load once. Additionally, Streamlit can be used locally or run on the cloud. Before you get started, you’re going to need Python 3.6 or later. First, let’s install streamlit. If you have issues getting your machine set up, feel free to use our Pipfile from the project repository. $ pip install streamlit Now run the hello world app to make sure everything it’s working: $ streamlit hello This command opens a web server on your computer where you can play around with some demos! The first time you run this command, you may be prompted for an email that is added to ~/.streamlit/config.toml . It is not necessary to add your email to use to the software. It’s worth noting that this email prompt will appear each time you run Streamlit without a complete config.toml file. To get around this, we use this bash script to input our email and the port we want to run on. Once we run this setup.sh script, we have our email and port set. Facebook Prophet or FB Prophet is, fittingly, a prediction tool. In lieu of predicting the end-times, we are going to forecast time series COVID data. FB Prophet uses pandas and takes in and outputs a Dataframe. The Dataframes passed to FB prophet must have a β€œds” and β€œy” column. We then feed a Dataframe containing only dates into FB Prophet and the forecast fills the missing values. We had some issues getting this set up locally on a windows 10 machine and within a docker container. However, we had no complications at all when using GCP AI Platform notebooks. You will need to install pystanbefore installing fbprophet . pip install pystan Then you should be able to run: pip install fbprophet Note that you might get an error with FB Prophet that states it can’t be found. We ran into this error and the package was found. If you have issues with setup, this try a cloud VM or using our Pipfile! Now that we have Streamlit and a basic understanding of what it does let’s get started with our forecasting app. Pandas works well with Streamlit and is already a dependency for FB Prophet, so we are using it in the load_data.py file to make our lives a little easier. All of our data is in the data.json file; we need to load it into Pandas and transform it into a Dataframe. The rest of our app code is relatively simple and presents us with the dropdown options and select functions. This allows our app to get data and generate plots when a user selects an option from the dropdown. Check out the app.py code here. github.com Streamlit lets us write apps like they are Python scripts. This means that when a new selection is picked in our dropdown, the entire app file runs again to generate the plot. Let run our app and see the default view. Use the following line to run your streamlit app on local port 8000. streamlit run app/app.py --server.port 8000 Our app is set up to load data and generate the β€˜All β€” cumulative cases’ plot by default seen below. Since our forecasting is live, it can take some time to generate plots after you select them from the dropdown. To reduce this loading time, we’ve added Streamlit cache to store results of the function, our plots. Our app has a dropdown to select which plot you would like to view. When you choose an option that is not the default, FB prophet runs the forecast on demand. The resultant Dataframe is then passed to Streamlit, which displays our data. What we cache with Streamlit doesn’t have to be data. We can cache anything, like our forecasts! Notice the alert in yellow β€œRunning make_forecast(...)” appears only the first time an option is selected. Then when we reselect β€œCumulative Recoveries,” there is no forecast; instead, our plot is pulled out of the cache. This caching allows for smooth swapping between plots once they are forecasted. To run our app on Heroku, we need to add a Procifle to our GitHub repository to serve our app on their platform. Here is our procfile. web: sh setup.sh && streamlit run app/app.py Notice that we are calling our setup.sh file to set our email and port on the Heroku machine. Then we tell streamlit to run our app. Just add this Procfile to your project root and you'll be able to run on Heroku. Now let’s go to Heroku’s website and deploy our app from GitHub using the GUI. To connect your repository, select GitHub, enter the name of the repository and hit search. Once your username and repository appear, click connect. Now select the desired branch and click deploy. Build logs will begin to populate a console on the page. Notice that Heroku looks for a requirements.txt file first then installs dependencies from Pipenv’s Pipfile.lock. If you don’t use Pipenv, you will need to have a requiremnts.txt for this build to occur. Once your environment has been built from the Pipfile.lock and the build is successful, you will see the below message. The app is successfully deployed! Click to view button to see the deployed app on Heroku. Now we can view our app live on Heroku and run forecasts on their platform. Check out our app here! st-covid-forecast.herokuapp.com We can enable automatic deployment to have changes to the Github master be displayed on Heroku as they are pushed. If you use this method, you’ll want to be sure that you always have a working master branch. To review we discussed Streamlit and Facebook Prophet as tools that allow us to make forecasting dashboards with minimal effort and no cost. Streamlit is opinionated, easy to use, and allows us to have our front and backend code in a single file. We used these tools to make a simple dashboard showing COVID data, what will you use them for? Thank you for reading! Please let us know what tool you use for dashboards and what you are looking to learn more about.
[ { "code": null, "e": 212, "s": 171, "text": "By: Edward Krueger and Douglas Franklin." }, { "code": null, "e": 386, "s": 212, "text": "Streamlit and Facebook Prophet give us the ability to create a clean forecasting dashboard with minimal effort and no cost. This makes for a solid proof of concept workflow." }, { "code": null, "e": 524, "s": 386, "text": "In this project, we create a dashboard using Streamlit and Prophet to showcase data and make forecasts and then deploy our app to Heroku." }, { "code": null, "e": 647, "s": 524, "text": "Here is a link to the GitHub repository with our code for the project. Note that we use Pipenv to manage our dependencies." }, { "code": null, "e": 658, "s": 647, "text": "github.com" }, { "code": null, "e": 1015, "s": 658, "text": "Streamlit is a free and open-source app framework that presents an easy way for data scientists and machine learning engineers to create great Python apps quickly. Streamlit’s opinioned nature makes building frontends easy. Lastly, Streamlit can make experimentation and production of data apps and machine learning analysis easier to do and to iterate on." }, { "code": null, "e": 1039, "s": 1015, "text": "Check it out on GitHub." }, { "code": null, "e": 1050, "s": 1039, "text": "github.com" }, { "code": null, "e": 1330, "s": 1050, "text": "Streamlit is excellent because it embraces Python scripting, treats widgets as variables, and caches data and computation for reuse. This allows us to have custom complex visualizations that only need to load once. Additionally, Streamlit can be used locally or run on the cloud." }, { "code": null, "e": 1396, "s": 1330, "text": "Before you get started, you’re going to need Python 3.6 or later." }, { "code": null, "e": 1534, "s": 1396, "text": "First, let’s install streamlit. If you have issues getting your machine set up, feel free to use our Pipfile from the project repository." }, { "code": null, "e": 1558, "s": 1534, "text": "$ pip install streamlit" }, { "code": null, "e": 1624, "s": 1558, "text": "Now run the hello world app to make sure everything it’s working:" }, { "code": null, "e": 1642, "s": 1624, "text": "$ streamlit hello" }, { "code": null, "e": 1910, "s": 1642, "text": "This command opens a web server on your computer where you can play around with some demos! The first time you run this command, you may be prompted for an email that is added to ~/.streamlit/config.toml . It is not necessary to add your email to use to the software." }, { "code": null, "e": 2123, "s": 1910, "text": "It’s worth noting that this email prompt will appear each time you run Streamlit without a complete config.toml file. To get around this, we use this bash script to input our email and the port we want to run on." }, { "code": null, "e": 2189, "s": 2123, "text": "Once we run this setup.sh script, we have our email and port set." }, { "code": null, "e": 2401, "s": 2189, "text": "Facebook Prophet or FB Prophet is, fittingly, a prediction tool. In lieu of predicting the end-times, we are going to forecast time series COVID data. FB Prophet uses pandas and takes in and outputs a Dataframe." }, { "code": null, "e": 2522, "s": 2401, "text": "The Dataframes passed to FB prophet must have a β€œds” and β€œy” column. We then feed a Dataframe containing only dates into" }, { "code": null, "e": 2576, "s": 2522, "text": "FB Prophet and the forecast fills the missing values." }, { "code": null, "e": 2756, "s": 2576, "text": "We had some issues getting this set up locally on a windows 10 machine and within a docker container. However, we had no complications at all when using GCP AI Platform notebooks." }, { "code": null, "e": 2817, "s": 2756, "text": "You will need to install pystanbefore installing fbprophet ." }, { "code": null, "e": 2836, "s": 2817, "text": "pip install pystan" }, { "code": null, "e": 2868, "s": 2836, "text": "Then you should be able to run:" }, { "code": null, "e": 2890, "s": 2868, "text": "pip install fbprophet" }, { "code": null, "e": 3093, "s": 2890, "text": "Note that you might get an error with FB Prophet that states it can’t be found. We ran into this error and the package was found. If you have issues with setup, this try a cloud VM or using our Pipfile!" }, { "code": null, "e": 3206, "s": 3093, "text": "Now that we have Streamlit and a basic understanding of what it does let’s get started with our forecasting app." }, { "code": null, "e": 3362, "s": 3206, "text": "Pandas works well with Streamlit and is already a dependency for FB Prophet, so we are using it in the load_data.py file to make our lives a little easier." }, { "code": null, "e": 3470, "s": 3362, "text": "All of our data is in the data.json file; we need to load it into Pandas and transform it into a Dataframe." }, { "code": null, "e": 3680, "s": 3470, "text": "The rest of our app code is relatively simple and presents us with the dropdown options and select functions. This allows our app to get data and generate plots when a user selects an option from the dropdown." }, { "code": null, "e": 3712, "s": 3680, "text": "Check out the app.py code here." }, { "code": null, "e": 3723, "s": 3712, "text": "github.com" }, { "code": null, "e": 3899, "s": 3723, "text": "Streamlit lets us write apps like they are Python scripts. This means that when a new selection is picked in our dropdown, the entire app file runs again to generate the plot." }, { "code": null, "e": 4010, "s": 3899, "text": "Let run our app and see the default view. Use the following line to run your streamlit app on local port 8000." }, { "code": null, "e": 4054, "s": 4010, "text": "streamlit run app/app.py --server.port 8000" }, { "code": null, "e": 4155, "s": 4054, "text": "Our app is set up to load data and generate the β€˜All β€” cumulative cases’ plot by default seen below." }, { "code": null, "e": 4369, "s": 4155, "text": "Since our forecasting is live, it can take some time to generate plots after you select them from the dropdown. To reduce this loading time, we’ve added Streamlit cache to store results of the function, our plots." }, { "code": null, "e": 4606, "s": 4369, "text": "Our app has a dropdown to select which plot you would like to view. When you choose an option that is not the default, FB prophet runs the forecast on demand. The resultant Dataframe is then passed to Streamlit, which displays our data." }, { "code": null, "e": 4925, "s": 4606, "text": "What we cache with Streamlit doesn’t have to be data. We can cache anything, like our forecasts! Notice the alert in yellow β€œRunning make_forecast(...)” appears only the first time an option is selected. Then when we reselect β€œCumulative Recoveries,” there is no forecast; instead, our plot is pulled out of the cache." }, { "code": null, "e": 5005, "s": 4925, "text": "This caching allows for smooth swapping between plots once they are forecasted." }, { "code": null, "e": 5140, "s": 5005, "text": "To run our app on Heroku, we need to add a Procifle to our GitHub repository to serve our app on their platform. Here is our procfile." }, { "code": null, "e": 5185, "s": 5140, "text": "web: sh setup.sh && streamlit run app/app.py" }, { "code": null, "e": 5399, "s": 5185, "text": "Notice that we are calling our setup.sh file to set our email and port on the Heroku machine. Then we tell streamlit to run our app. Just add this Procfile to your project root and you'll be able to run on Heroku." }, { "code": null, "e": 5478, "s": 5399, "text": "Now let’s go to Heroku’s website and deploy our app from GitHub using the GUI." }, { "code": null, "e": 5675, "s": 5478, "text": "To connect your repository, select GitHub, enter the name of the repository and hit search. Once your username and repository appear, click connect. Now select the desired branch and click deploy." }, { "code": null, "e": 5936, "s": 5675, "text": "Build logs will begin to populate a console on the page. Notice that Heroku looks for a requirements.txt file first then installs dependencies from Pipenv’s Pipfile.lock. If you don’t use Pipenv, you will need to have a requiremnts.txt for this build to occur." }, { "code": null, "e": 6056, "s": 5936, "text": "Once your environment has been built from the Pipfile.lock and the build is successful, you will see the below message." }, { "code": null, "e": 6222, "s": 6056, "text": "The app is successfully deployed! Click to view button to see the deployed app on Heroku. Now we can view our app live on Heroku and run forecasts on their platform." }, { "code": null, "e": 6246, "s": 6222, "text": "Check out our app here!" }, { "code": null, "e": 6278, "s": 6246, "text": "st-covid-forecast.herokuapp.com" }, { "code": null, "e": 6486, "s": 6278, "text": "We can enable automatic deployment to have changes to the Github master be displayed on Heroku as they are pushed. If you use this method, you’ll want to be sure that you always have a working master branch." }, { "code": null, "e": 6733, "s": 6486, "text": "To review we discussed Streamlit and Facebook Prophet as tools that allow us to make forecasting dashboards with minimal effort and no cost. Streamlit is opinionated, easy to use, and allows us to have our front and backend code in a single file." }, { "code": null, "e": 6828, "s": 6733, "text": "We used these tools to make a simple dashboard showing COVID data, what will you use them for?" } ]
CSS - Media Types
One of the most important features of style sheets is that they specify how a document is to be presented on different media: on the screen, on paper, with a speech synthesizer, with a braille device, etc. We have currently two ways to specify media dependencies for style sheets βˆ’ Specify the target medium from a style sheet with the @media or @import at-rules. Specify the target medium from a style sheet with the @media or @import at-rules. Specify the target medium within the document language. Specify the target medium within the document language. An @media rule specifies the target media types (separated by commas) of a set of rules. Given below is an example βˆ’ <style tyle = "text/css"> <!-- @media print { body { font-size: 10pt } } @media screen { body { font-size: 12pt } } @media screen, print { body { line-height: 1.2 } } --> </style> In HTML 4.0, the media attribute on the LINK element specifies the target media of an external style sheet βˆ’ Following is an example βˆ’ <style tyle = "text/css"> <!-- <!doctype html public "-//w3c//dtd html 4.0//en"> <html> <head> <title>link to a target medium</title> <link rel = "stylesheet" type = "text/css" media = "print, handheld" href = "foo.css"> </head> <body> <p>the body... </body> </html> --> </style> The names chosen for CSS media types reflect target devices for which the relevant properties make sense. They give a sense of what device the media type is meant to refer to. Given below is a list of various media types βˆ’ all Suitable for all devices. aural Intended for speech synthesizers. braille Intended for braille tactile feedback devices. embossed Intended for paged braille printers. handheld Intended for handheld devices (typically small screen, monochrome, limited bandwidth). print Intended for paged, opaque material and for documents viewed on screen in print preview mode. Please consult the section on paged media. projection Intended for projected presentations, for example projectors or print to transparencies. Please consult the section on paged media. screen Intended primarily for color computer screens. tty Intended for media using a fixed-pitch character grid, such as teletypes, terminals, or portable devices with limited display capabilities. tv Intended for television-type devices. NOTE βˆ’ Media type names are case-insensitive. 33 Lectures 2.5 hours Anadi Sharma 26 Lectures 2.5 hours Frahaan Hussain 44 Lectures 4.5 hours DigiFisk (Programming Is Fun) 21 Lectures 2.5 hours DigiFisk (Programming Is Fun) 51 Lectures 7.5 hours DigiFisk (Programming Is Fun) 52 Lectures 4 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2832, "s": 2626, "text": "One of the most important features of style sheets is that they specify how a document is to be presented on different media: on the screen, on paper, with a speech synthesizer, with a braille device, etc." }, { "code": null, "e": 2908, "s": 2832, "text": "We have currently two ways to specify media dependencies for style sheets βˆ’" }, { "code": null, "e": 2990, "s": 2908, "text": "Specify the target medium from a style sheet with the @media or @import at-rules." }, { "code": null, "e": 3072, "s": 2990, "text": "Specify the target medium from a style sheet with the @media or @import at-rules." }, { "code": null, "e": 3128, "s": 3072, "text": "Specify the target medium within the document language." }, { "code": null, "e": 3184, "s": 3128, "text": "Specify the target medium within the document language." }, { "code": null, "e": 3273, "s": 3184, "text": "An @media rule specifies the target media types (separated by commas) of a set of rules." }, { "code": null, "e": 3301, "s": 3273, "text": "Given below is an example βˆ’" }, { "code": null, "e": 3552, "s": 3301, "text": "<style tyle = \"text/css\">\n <!--\n @media print {\n body { font-size: 10pt }\n }\n\t\n @media screen {\n body { font-size: 12pt }\n }\n @media screen, print {\n body { line-height: 1.2 }\n }\n -->\n</style>" }, { "code": null, "e": 3661, "s": 3552, "text": "In HTML 4.0, the media attribute on the LINK element specifies the target media of an external style sheet βˆ’" }, { "code": null, "e": 3687, "s": 3661, "text": "Following is an example βˆ’" }, { "code": null, "e": 4080, "s": 3687, "text": "<style tyle = \"text/css\">\n <!--\n <!doctype html public \"-//w3c//dtd html 4.0//en\">\n <html>\n <head>\n <title>link to a target medium</title>\n <link rel = \"stylesheet\" type = \"text/css\" media = \"print, \n handheld\" href = \"foo.css\">\n </head>\n\n <body>\n <p>the body...\n </body>\n </html>\n -->\n</style>" }, { "code": null, "e": 4303, "s": 4080, "text": "The names chosen for CSS media types reflect target devices for which the relevant properties make sense. They give a sense of what device the media type is meant to refer to. Given below is a list of various media types βˆ’" }, { "code": null, "e": 4307, "s": 4303, "text": "all" }, { "code": null, "e": 4333, "s": 4307, "text": "Suitable for all devices." }, { "code": null, "e": 4339, "s": 4333, "text": "aural" }, { "code": null, "e": 4373, "s": 4339, "text": "Intended for speech synthesizers." }, { "code": null, "e": 4381, "s": 4373, "text": "braille" }, { "code": null, "e": 4428, "s": 4381, "text": "Intended for braille tactile feedback devices." }, { "code": null, "e": 4437, "s": 4428, "text": "embossed" }, { "code": null, "e": 4474, "s": 4437, "text": "Intended for paged braille printers." }, { "code": null, "e": 4483, "s": 4474, "text": "handheld" }, { "code": null, "e": 4570, "s": 4483, "text": "Intended for handheld devices (typically small screen, monochrome, limited bandwidth)." }, { "code": null, "e": 4576, "s": 4570, "text": "print" }, { "code": null, "e": 4713, "s": 4576, "text": "Intended for paged, opaque material and for documents viewed on screen in print preview mode. Please consult the section on paged media." }, { "code": null, "e": 4724, "s": 4713, "text": "projection" }, { "code": null, "e": 4856, "s": 4724, "text": "Intended for projected presentations, for example projectors or print to transparencies. Please consult the section on paged media." }, { "code": null, "e": 4863, "s": 4856, "text": "screen" }, { "code": null, "e": 4910, "s": 4863, "text": "Intended primarily for color computer screens." }, { "code": null, "e": 4914, "s": 4910, "text": "tty" }, { "code": null, "e": 5054, "s": 4914, "text": "Intended for media using a fixed-pitch character grid, such as teletypes, terminals, or portable devices with limited display capabilities." }, { "code": null, "e": 5057, "s": 5054, "text": "tv" }, { "code": null, "e": 5095, "s": 5057, "text": "Intended for television-type devices." }, { "code": null, "e": 5141, "s": 5095, "text": "NOTE βˆ’ Media type names are case-insensitive." }, { "code": null, "e": 5176, "s": 5141, "text": "\n 33 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5190, "s": 5176, "text": " Anadi Sharma" }, { "code": null, "e": 5225, "s": 5190, "text": "\n 26 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5242, "s": 5225, "text": " Frahaan Hussain" }, { "code": null, "e": 5277, "s": 5242, "text": "\n 44 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5308, "s": 5277, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5343, "s": 5308, "text": "\n 21 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5374, "s": 5343, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5409, "s": 5374, "text": "\n 51 Lectures \n 7.5 hours \n" }, { "code": null, "e": 5440, "s": 5409, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5473, "s": 5440, "text": "\n 52 Lectures \n 4 hours \n" }, { "code": null, "e": 5504, "s": 5473, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5511, "s": 5504, "text": " Print" }, { "code": null, "e": 5522, "s": 5511, "text": " Add Notes" } ]
CSS Styling Lists
In HTML, there are two main types of lists: unordered lists (<ul>) - the list items are marked with bullets ordered lists (<ol>) - the list items are marked with numbers or letters The CSS list properties allow you to: Set different list item markers for ordered lists Set different list item markers for unordered lists Set an image as the list item marker Add background colors to lists and list items The list-style-type property specifies the type of list item marker. The following example shows some of the available list item markers: Note: Some of the values are for unordered lists, and some for ordered lists. The list-style-image property specifies an image as the list item marker: The list-style-position property specifies the position of the list-item markers (bullet points). "list-style-position: outside;" means that the bullet points will be outside the list item. The start of each line of a list item will be aligned vertically. This is default: Coffee - A brewed drink prepared from roasted coffee beans... Tea Coca-cola "list-style-position: inside;" means that the bullet points will be inside the list item. As it is part of the list item, it will be part of the text and push the text at the start: Coffee - A brewed drink prepared from roasted coffee beans... Tea Coca-cola The list-style-type:none property can also be used to remove the markers/bullets. Note that the list also has default margin and padding. To remove this, add margin:0 and padding:0 to <ul> or <ol>: The list-style property is a shorthand property. It is used to set all the list properties in one declaration: When using the shorthand property, the order of the property values are: list-style-type (if a list-style-image is specified, the value of this property will be displayed if the image for some reason cannot be displayed) list-style-position (specifies whether the list-item markers should appear inside or outside the content flow) list-style-image (specifies an image as the list item marker) If one of the property values above are missing, the default value for the missing property will be inserted, if any. We can also style lists with colors, to make them look a little more interesting. Anything added to the <ol> or <ul> tag, affects the entire list, while properties added to the <li> tag will affect the individual list items: Result: Coffee Tea Coca Cola Coffee Tea Coca Cola Coffee Tea Coca Cola Customized list with a red left border This example demonstrates how to create a list with a red left border. Full-width bordered list This example demonstrates how to create a bordered list without bullets. All the different list-item markers for lists This example demonstrates all the different list-item markers in CSS. Set the list style for unordered lists to "square". <style> ul { : ; } </style> <body> <ul> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> </body> Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 174, "s": 130, "text": "In HTML, there are two main types of lists:" }, { "code": null, "e": 238, "s": 174, "text": "unordered lists (<ul>) - the list items are marked with bullets" }, { "code": null, "e": 311, "s": 238, "text": "ordered lists (<ol>) - the list items are marked with numbers or letters" }, { "code": null, "e": 349, "s": 311, "text": "The CSS list properties allow you to:" }, { "code": null, "e": 399, "s": 349, "text": "Set different list item markers for ordered lists" }, { "code": null, "e": 451, "s": 399, "text": "Set different list item markers for unordered lists" }, { "code": null, "e": 488, "s": 451, "text": "Set an image as the list item marker" }, { "code": null, "e": 534, "s": 488, "text": "Add background colors to lists and list items" }, { "code": null, "e": 604, "s": 534, "text": "The list-style-type property specifies the type of list item \nmarker." }, { "code": null, "e": 674, "s": 604, "text": "The following example shows some of the available list item markers: " }, { "code": null, "e": 752, "s": 674, "text": "Note: Some of the values are for unordered lists, and some for ordered lists." }, { "code": null, "e": 827, "s": 752, "text": "The list-style-image property specifies an image as the list \nitem marker:" }, { "code": null, "e": 926, "s": 827, "text": "The list-style-position property specifies the position of the list-item markers \n(bullet points)." }, { "code": null, "e": 1103, "s": 926, "text": "\"list-style-position: outside;\" means that the bullet points will be outside \nthe list item. The start of each line of a list item will be aligned vertically. \nThis is default:" }, { "code": null, "e": 1165, "s": 1103, "text": "Coffee -\nA brewed drink prepared from roasted coffee beans..." }, { "code": null, "e": 1169, "s": 1165, "text": "Tea" }, { "code": null, "e": 1179, "s": 1169, "text": "Coca-cola" }, { "code": null, "e": 1363, "s": 1179, "text": "\"list-style-position: inside;\" means that the bullet points will be inside \nthe list item. As it is part of the list item, it will be part of the text and \npush the text at the start:" }, { "code": null, "e": 1425, "s": 1363, "text": "Coffee -\nA brewed drink prepared from roasted coffee beans..." }, { "code": null, "e": 1429, "s": 1425, "text": "Tea" }, { "code": null, "e": 1439, "s": 1429, "text": "Coca-cola" }, { "code": null, "e": 1639, "s": 1439, "text": "The list-style-type:none property can also be \nused to remove the markers/bullets. Note that the list also has default margin \nand padding. To remove this, add margin:0 and padding:0 to <ul> or <ol>:" }, { "code": null, "e": 1751, "s": 1639, "text": "The list-style property is a shorthand property. It is used to set all the \nlist properties in one declaration:" }, { "code": null, "e": 1824, "s": 1751, "text": "When using the shorthand property, the order of the property values are:" }, { "code": null, "e": 1974, "s": 1824, "text": "list-style-type (if a list-style-image is specified, \nthe value of this property will be displayed if the image for some reason \ncannot be displayed)" }, { "code": null, "e": 2085, "s": 1974, "text": "list-style-position (specifies whether the list-item markers should appear inside or outside the content flow)" }, { "code": null, "e": 2148, "s": 2085, "text": "list-style-image (specifies an image as the list item \nmarker)" }, { "code": null, "e": 2267, "s": 2148, "text": "If one of the property values above are missing, the default value for the \nmissing property will be inserted, if any." }, { "code": null, "e": 2350, "s": 2267, "text": "We can also style lists with colors, to make them look a little more \ninteresting." }, { "code": null, "e": 2494, "s": 2350, "text": "Anything added to the <ol> or <ul> tag, affects the entire list, while \nproperties added to the <li> tag will affect the individual list items:" }, { "code": null, "e": 2502, "s": 2494, "text": "Result:" }, { "code": null, "e": 2525, "s": 2502, "text": "\nCoffee\nTea\nCoca Cola\n" }, { "code": null, "e": 2532, "s": 2525, "text": "Coffee" }, { "code": null, "e": 2536, "s": 2532, "text": "Tea" }, { "code": null, "e": 2546, "s": 2536, "text": "Coca Cola" }, { "code": null, "e": 2553, "s": 2546, "text": "Coffee" }, { "code": null, "e": 2557, "s": 2553, "text": "Tea" }, { "code": null, "e": 2567, "s": 2557, "text": "Coca Cola" }, { "code": null, "e": 2677, "s": 2567, "text": "Customized list with a red left border\nThis example demonstrates how to create a list with a red left border." }, { "code": null, "e": 2775, "s": 2677, "text": "Full-width bordered list\nThis example demonstrates how to create a bordered list without bullets." }, { "code": null, "e": 2891, "s": 2775, "text": "All the different list-item markers for lists\nThis example demonstrates all the different list-item markers in CSS." }, { "code": null, "e": 2943, "s": 2891, "text": "Set the list style for unordered lists to \"square\"." }, { "code": null, "e": 3055, "s": 2943, "text": "<style>\nul {\n : ;\n}\n</style>\n\n<body>\n<ul>\n <li>Coffee</li>\n <li>Tea</li>\n <li>Coca Cola</li>\n</ul>\n</body>\n" }, { "code": null, "e": 3074, "s": 3055, "text": "Start the Exercise" }, { "code": null, "e": 3107, "s": 3074, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 3149, "s": 3107, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 3256, "s": 3149, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 3275, "s": 3256, "text": "[email protected]" } ]
AI-Tunes: Creating New Songs with GPT-3 | Towards Data Science
I have been experimenting with various AI-based music generation systems for over a year now, and I hate to say it, but most of the music generated by AI sounds like junk. It’s either too complicated and rambling or too simple and repetitive. It almost never has a pleasing melody with a global structure to the composition. We have witnessed recent strides in AI-based content creation for other forms of media, like images and text. So it is confounding that the quality of AI-generated music seems so far behind. When I heard that OpenAI released an API for fine-tuning their GPT-3 text processing models [1], my first thought was, aha!, maybe I can use it to create music that doesn’t suck. It took a little work, but I managed to wrangle some training data from music in the public domain and used it to teach GPT-3 how to compose music. I will explain what I did fully in this article, but first, here is a sample that I cherry-picked from five generated songs. 1.1K plays1.1K OK, it’s not great, but at least to my ears, it sounds interesting and, dare I say, good? Up next is an overview of the system, which I dubbed AI-Tunes. Here is a high-level diagram for AI-Tunes. After a brief discussion of each component, I will explain the processing steps in greater detail in the sections below. I started by downloading the OpenEWLD [2] database of over 500 songs in the public domain. Each song has a melody with corresponding chords. The songs are in a format called MusicXML, which is in plain text but the format has a lot of overhead. So I used an open-source script called xml2abc[3] to convert the songs to ABC format [4], which is more streamlined and therefore more conducive for training a text-based Machine Learning (ML) system. I then used a library from MIT called music21 [5] to process the songs and transpose them to the key of C Major, making it easier for the machine to understand the music. The formatted songs were saved in a training file and uploaded to OpenAI’s fine-tuning service. I trained their GPT-3 Curie transformer model to generate a song after being prompted by a song title and band name. Although the Curie model generates the music, I am using its big brother, Davinci, to automatically generate a song title and band name. I use these two pieces of data to prompt the fine-tuned Curie model to generate five candidate songs. I use a package called music_geometry_eval [6] to analyze the tonal qualities of the five songs. The analysis is based on the music theory described in the book β€œA Geometry of Music” by Dmitri Tymoczko [7]. I then choose the song that has the statistically closest tonal quality to the songs in the training set. Finally, I show the songs as a visual piano-roll and play them. The sections below describe details of the components and processes used in AI-Tunes. Be sure to check out more generated songs in the Appendix below. One of the keys to getting good results from an ML system is having good training data. In researching music generating systems, I found that authors of papers often do not post their training datasets due to copyright restrictions. Although there are many sites that host user-generated MIDI files of popular songs, the copyrights to these songs are still owned by the authors/publishers. And using copyrighted material for training data is in a legal gray area if the results are to be used commercially. I found a dataset called OpenEWLD that can be used freely. It is a pared-down version of the Enhanced Wikifonia Leadsheet Dataset (EWLD) [8], a collection of over 5,000 songs in MusicXML format [9]. Note that a β€œleadsheet” is a simplified song score with just the melody and chords. The OpenEWLD is an extraction of 502 songs in the EWLD that are in the public domain and can be used for training ML systems. Fair notice: I did not check the provenance of all the songs in the OpenEWLD to make sure that they are actually in the public domain. But a quick perusal of the titles/composers shows a bunch of old-time tunes, like these: β€œAin’t Misbehavin’ ” by Andy Razaf, Fats Waller, and Harry Brooksβ€œMakin’ Whoopee!” by Gus Kahn and Walter Donaldsonβ€œMaple Leaf Rag” by Scott Joplinβ€œOh! Susanna” by Stephen Fosterβ€œWe’re in the Money” by Al Dubin and Harry Warren β€œAin’t Misbehavin’ ” by Andy Razaf, Fats Waller, and Harry Brooks β€œMakin’ Whoopee!” by Gus Kahn and Walter Donaldson β€œMaple Leaf Rag” by Scott Joplin β€œOh! Susanna” by Stephen Foster β€œWe’re in the Money” by Al Dubin and Harry Warren Here is an example of one of the songs in the OpenEWLD collection. You can see a β€œpiano roll” of the song, which is a graph with pitch values of the notes on the y-axis and time on the x-axis. And you can play the song on SoundCloud below. 693 plays693 As I mentioned above, songs in the OpenEWLD [8] are in MusicXML format, which works fine, but has a lot of extra formatting text. Although an ML system could learn all of the formatting commands and generate songs in this format, I found that it was better to reduce the musical notation to the bare minimum. The ABC format by Chris Walshaw [4] is a good match. For example, here is the first part of the song β€œWe’re in the Money” in MusicXML and ABC formats. You can see that the song is dramatically simplified when converted to the ABC format. The XML format requires 503 characters for the header and 443 for the first two notes. The ABC format specifies the same information using only 85 characters for the header and 8 characters for the first two notes. I use an open-source script called xml2abc by Wim Vree [3] to convert the songs from MusicXML to ABC format. Here is the command I use for the conversion. python xml2abc.py were-in-the-money.xml -u -d 4 This will read the file β€œwere-in-the-money.xml”, convert it, and save it as β€œwere-in-the-money.abc”. The -u option will β€œunroll” any repeated measures, and the -d 4 option will set the default note duration to be a quarter note. Using both of these options helps the machine learning process by standardizing the music scores. Here’s the entire β€œWe’re in the Money” song in ABC format. X:1T:We're In The MoneyC:Harry WarrenL:1/4M:2/2I:linebreak $K:CV:1 treble "C" z E G3/2 E/ |"Dm7" F"G7" G3 |"C" z E G3/2 E/ |"Dm7" F"G7" G3 "C" z e"C+" e3/2 c/ | %5 | "F" d c d"Ab7" c |"C" e c"Dm7" c"G7" d"C" c2 z2 |"C" z E G3/2 E/ |"Dm7" F"G7" G3 | %10"C" z E G3/2 E/ |"Dm7" F"G7" G3 |$"C" z e"C+" e3/2 c/"F" d c d"Ab7" c |"C" e c"Dm7" c"G7" d | %15"C" c2 z2 |"C" c2 z2 |$ z"Cmaj7" e d/c/B/A/ |"Cmaj7" B B z/ c A/"Cmaj7" B B2 c |"Cmaj7" B4 |$ %21"Cmaj7" z e d/c/B/A/ |"Cmaj7" B B z/ B B/ |"Bb" _B B"A7" A A"Ab7" _A A"G7" G z |$ %25 | "C" z E G3/2 E/ |"Dm7" F"G7" G3"C" z E G3/2 E/ |"Dm7" F"G7" G3 |$"C" z e"C+" e3/2 c/ | %30"F" d c d"Ab7" c |"C" e c2"G7" d |"C" c3 z | %33 I prepare the songs to be used as training data by performing these processing steps: Filter out songs that don’t use the 4/4 and 2/2 time signaturesTranspose songs to the key of C MajorStrip out lyrics and other unnecessary dataReplace newlines with a β€œ$” symbol Filter out songs that don’t use the 4/4 and 2/2 time signatures Transpose songs to the key of C Major Strip out lyrics and other unnecessary data Replace newlines with a β€œ$” symbol Unifying the time and key signatures makes it easier for the ML system to learn about the melody notes and timing. A majority of songs use either 4/4 or 2/2 time (381 of 502) so it is not worth the effort to get the system to understand other meters. And most of the songs are already in the key of C Major (303 of 502). I use a function in the music21 package [5] to transpose the songs to a unified key. I strip out the lyrics to help the system to focus on just the notes. I converted the newlines to β€œ$” in order to adhere to a quirk of the GPT-3 fine-tuning system. Otherwise, it converts the newlines to commas; this would create a problem for songs in ABC format as commas are already used to specify notes in different octaves. In order to fine-tune OpenAI’s GPT-3 models, the first step is to compile a text file that has pairs of prompts and completions in JSON format. For the prompt, I use the song title and the composer's name. The completion is the prepped song in ABC format. Here is what two of the prompt-completion pairs look like: {"prompt": "X: 1 $ T: We're In The Money $ C: Harry Warren $ <song>", "completion": " `C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z e`C+` e3/2 c/ | $ `F` d c d`G#7` c |`C` e c`Dm7` c`G7` d |`C` c2 z2 |`C` z E G3/2 E/ |`Dm7` F`G7` G3 | $ `C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z e`C+` e3/2 c/ |`F` d c d`G#7` c |`C` e c`Dm7` c`G7` d | $ `C` c2 z2 |`C` c2 z2 | z`Cmaj7` e d/c/B/A/ |`Cmaj7` B B z/ c A/ |`Cmaj7` B B2 c |`Cmaj7` B4 | $ `Cmaj7` z e d/c/B/A/ |`Cmaj7` B B z/ B B/ |`Bb` _B B`A7` A A |`G#7` ^G G`G7` =G z | $ `C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z e`C+` e3/2 c/ | $ `F` d c d`G#7` c |`C` e c2`G7` d |`C` c3 z | $ <end>"}{"prompt": "X: 1 $ T: They Didn't Believe Me $ C: Jerome Kern $ <song>", "completion": " z G A c |`Dm7` d2 d2- |`G7` d e d/>e/c/>d/ |`C` e4- |`Em7b5` e e`A7b9` (3e f g |`Dm7` d2 d2- | $ `G7` d d (3d e f |`C` G2 G2- |`Am7` G G A c |`Dm7` f A B c |`G7` d3/2 B/ c`G7/F` d | $ `Em7` g B c d |`Am` e2 e ^f |`Em` g e/>^f/ g2- |`B7` g ^f =e _e |`Em7``Bb9` e4- | $ `A7` e g`A7b9` f e |`Dm7` d2 d2- |`G7` d d/>e/ (3d/e/d/ c/>d/ |`C6` e2 e2- |`Am7` e c d e | $ `Dm` f2 f2 |`G7` f f e _e |`C6``Bb9` e4- |`A7` e e e/f/ g |`Dm` d2 d2- |`G7` d d d/e/ f | $ `C` G2`Dm7` G2- |`Em7` G G`A7` ^G A |`Dm7` f A B c |`G7` d2`G7b9` e2 |`C` c4- | c z z2 | $ <end>"} OpenAI provides a utility that checks the validity of the training file. Here is the command I use to check my file. openai tools fine_tunes.prepare_data -f songs.jsonl Here is the result. Analyzing...- Your file contains 374 prompt-completion pairs- More than a third of your `completion` column/key is uppercase. - All prompts end with suffix ` $ <song>`- All prompts start with prefix `X: 1 $ T: `- All completions end with suffix ` | $ <end>`Based on the analysis we will perform the following actions:- [Recommended] Lowercase all your data in column/key `completion` [Y/n]: n It only flags one problem, which really isn’t a problem. The prepare_data script noticed that a lot of the text in the completions is in uppercase. This is due to the fact that the root of the chords and many of the notes are specified with uppercase letters. This warning is probably meant for conversational text, not music, so I just ignored the warning. Once the training file is in good shape, it’s easy to fine-tune GPT-3. Here is the command: openai api fine_tunes.create -t songs.jsonl -m curie --n_epochs 5 I chose to use the largest of the available GPT-3 models for training, Curie. It’s not as big as Davinci, but it seems to work well. I also set the number of training epochs to 5, which indicates how many times to run through the dataset for training. Here is the result of the training. Created fine-tune: ft-Vk1UCsXpd65sXXayafTGAY0mStreaming events until fine-tuning is complete...(Ctrl-C will interrupt the stream, but not cancel the fine-tune)[2021-08-29 12:10:50] Fine-tune enqueued. Queue number: 0[2021-08-29 12:10:53] Fine-tune started[2021-08-29 12:12:55] Completed epoch 1/5[2021-08-29 12:13:41] Completed epoch 2/5[2021-08-29 12:14:27] Completed epoch 3/5[2021-08-29 12:15:13] Completed epoch 4/5[2021-08-29 12:15:59] Completed epoch 5/5[2021-08-29 12:17:09] Fine-tune succeededJob complete! Status: succeeded πŸŽ‰ As you can see, it only took about six minutes to run the training. The team at OpenAI gets extra credit for showing me a celebration emoji when the training is finished! Before we check out how well the model creates songs, I will show you how I create new song titles and band names as prompts, using GPT-3 Davinci. As you saw in the training data samples above, each line has a prompt with the song title and the composer name followed by the song in ABC format. In order to generate new songs, I create a new prompt with a new song and band name. Any text would do, but I think that it’s fun to see if the system can create a song when prompted with new information, like a song title and fake band name. Here’s an example prompt. "prompt": "X: 1 $ T: Expensive to Maintain $ C: Shaky Pies $ <song>" In order to make a lot of prompts like this, I put the GPT-3 Davinci system to work. No fine-tuning is necessary. The Davinci model works happily given a prompt like this. Note that I filled in fake band names and songs for the prompt. Create a new song title a new band name. Be creative!Band name: The ExecsSong title: Company Meeting###Band name: The One ChordsSong title: Moving Down to Burlington### And here are some sample results from GPT-3 Davinci. Band name: The WizardsSong title: I’ll Get There When I Get There###Band name: The UndergradsSong title: I'm Just a Kid###Band name: The FortunesSong title: What Do You Want from Me?### Looks like some fun songs! By the way, some of these generated song titles and/or band names might exist out in the real world, but if so, it’s OK. I am just using these to prompt the song-writing model. Now that we have some prompts, let’s see what the model can do. I generated five versions of the first song and chose the best one. OK, the melody is fairly simple and it sounds pretty good. Note the interesting structure which seems to be ABABCB. You can see and hear more generated songs in the Appendix below. For that last test, I got involved as a critic. I listened to all five generated versions of β€œI’ll Get There When I Get There” and chose the best one. Note that there were some clunkers in the batch. Some of them started off OK but veered into playing odd notes. And others simply repeated a phrase over and over again without much variation. Given that the system could crank out many versions of these tunes, I looked into using statistics to maybe help weed out the clunkers. I found that a lot of research has been done on the subject of measuring the tonal qualities of music. The book I mentioned above by Dmitri Tymoczko has the full title, β€œA Geometry of Music: Harmony and Counterpoint in the Extended Common Practice” [7]. In the book, Tymoczko discusses five features of music tonality. [These] five features are present in a wide range of [music] genres, Western and non-Western, past and present, and ... they jointly contribute to a sense of tonality: 1. Conjunct melodic motion. Melodies tend to move by short distances from note to note. 2. Acoustic consonance. Consonant harmonies are preferred to dissonant harmonies and tend to be used at points of musical stability. 3. Harmonic consistency. The harmonies in a passage of music, whatever they may be, tend to be structurally similar to one another. 4. Limited macroharmony. I use the term β€œmacroharmony” to refer to the total collection of notes heard over moderate spans of musical time. Tonal music tends to use relatively small macroharmonies, often involving five to eight notes. 5. Centricity. Over moderate spans of musical time, one note is heard as being more prominent than the others, appearing more frequently and serving as a goal of musical motion. - Dmitri Tymoczko in β€œA Geometry of Music” I found an open-source project on GitHub called music-geometry-eval [6] that has Python code to assess three of Tymoczko’s tonal features, conjunct melodic motion, limited macroharmony, and centricity. I ran all 374 songs in my training data through the code to find the average and standard deviation of the three metrics. Here are the results: Conjunct Melodic Motion (CMM) : 2.2715 Β± 0.4831Limited Macroharmony (LM) : 2.0305 Β± 0.5386Centricity (CENT): 0.3042 Β± 0.0891 And here are the stats from the five generated versions of β€œI’ll Get There When I Get There.” I also calculated a Normalized Distance to the Mean (NDM) value for each of the five songs, comparing the metrics from each generated song to the average metrics of the songs in the training dataset. Generating Song Version 0 CMM : 2.3385 LM : 3.5488 CENT: 0.5213 NDM : 8.1677Generating Song Version 1 CMM : 3.828 LM : 2.3396 CENT: 0.2677 NDM : 10.7161Generating Song Version 2 CMM : 3.124 LM : 1.5614 CENT: 0.2244 NDM : 3.8996 <-- Closest tonality to the training dataGenerating Song Version 3 CMM : 2.0206 LM : 3.4195 CENT: 0.4869 NDM : 7.0639Generating Song Version 4 CMM : 3.2644 LM : 1.4132 CENT: 0.2436 NDM : 5.5533 And sure enough, the song I chose to be β€œthe best” of the batch, Version 2, also happens to have the best NDM score. Note that this happens often, but it’s not always the case. After running this experiment about a dozen times, I find that sometimes the song with the second or third closest NDM score actually sounds the best. The AI-Tunes system works fairly well. Not every piece is good, but it often produces interesting music with recognizable themes and variations. If you know about music composition, you may notice that some of the pieces are in need of a little β€œclean up”. For example, sometimes the system does not strictly adhere to 4/4 time due to extra eighth notes inserted here and there. (Hint: Try tapping your foot to the beat when listening to the generated music.) The good news is that you can download the generated compositions as MIDI files and fix them up in notation software fairly easily. For example here is a cleaned-up version of the example song. As for the general quality of the compositions, there is definitely room for improvement. For example, if OpenAI makes fine-tuning available for their larger Davinci transformer, the resulting music would probably improve. Also, training the system on a larger dataset of music would definitely help. And it would probably update the style of music to be something from this Millenium πŸ˜„. Implementing Tymoczko’s other two tonal features, acoustic consonance and harmonic consistency, would help assess the generated results. It would be fairly easy to extend the AI-Tunes model to include features like musical phrase completion and chord conditioned generation. For phrase completion, the training set would need to contain song parts, with one or more measures from the original song in the prompt, and the response would contain one or more measures that pick up from that point in the song. When running the system to generate new parts, a set of preceding chords and melody would be passed in, and the system would complete the musical phrase. For chord conditioning, the prompt for training would contain just the chords of the original song in ABC format, and the expected response would be the original melody. When generating music, just the chords would be passed in, and the system would generate a melody that would match the chords. All source code for this project is available on GitHub. You can experiment with the code using this Google Colab. This Colab only works if you have an account with OpenAI. If you don’t have an account you can sign up here. I released the source code under the CC BY-SA license. I would like to thank Jennifer Lim and Oliver Strimpel for their help with this project. And I would like to thank Georgina Lewis at the MIT Libraries for helping me track down a copy of β€œA Geometry of Music.” [1] OpenAI, GPT Fine-tunes API (2021) [2] F. Simonetta, OpenEWLD (2017) [3] W. Vree, xml2abc (2012) [4] C. Walshaw, ABC Notation (1997) [5] MIT, music21 (2010) [6] S. G. Valencia, music-geometry-eval (2017) [7] D. Tymoczko, A Geometry of Music: Harmony and Counterpoint in the Extended Common Practice (2010), Oxford Studies in Music Theory [8] F. Simonetta, Enhanced Wikifonia Leadsheet Dataset, (2018) [9] M. Good, MusicMXL (2004) Here you can find some more examples of songs generated by AI-Tunes. To get unlimited access to all articles on Medium, become a member for $5/month. Non-members can only read three locked stories each month. Some rights reserved
[ { "code": null, "e": 496, "s": 171, "text": "I have been experimenting with various AI-based music generation systems for over a year now, and I hate to say it, but most of the music generated by AI sounds like junk. It’s either too complicated and rambling or too simple and repetitive. It almost never has a pleasing melody with a global structure to the composition." }, { "code": null, "e": 687, "s": 496, "text": "We have witnessed recent strides in AI-based content creation for other forms of media, like images and text. So it is confounding that the quality of AI-generated music seems so far behind." }, { "code": null, "e": 1139, "s": 687, "text": "When I heard that OpenAI released an API for fine-tuning their GPT-3 text processing models [1], my first thought was, aha!, maybe I can use it to create music that doesn’t suck. It took a little work, but I managed to wrangle some training data from music in the public domain and used it to teach GPT-3 how to compose music. I will explain what I did fully in this article, but first, here is a sample that I cherry-picked from five generated songs." }, { "code": null, "e": 1158, "s": 1139, "text": "\n\n1.1K plays1.1K\n\n" }, { "code": null, "e": 1248, "s": 1158, "text": "OK, it’s not great, but at least to my ears, it sounds interesting and, dare I say, good?" }, { "code": null, "e": 1311, "s": 1248, "text": "Up next is an overview of the system, which I dubbed AI-Tunes." }, { "code": null, "e": 1475, "s": 1311, "text": "Here is a high-level diagram for AI-Tunes. After a brief discussion of each component, I will explain the processing steps in greater detail in the sections below." }, { "code": null, "e": 1921, "s": 1475, "text": "I started by downloading the OpenEWLD [2] database of over 500 songs in the public domain. Each song has a melody with corresponding chords. The songs are in a format called MusicXML, which is in plain text but the format has a lot of overhead. So I used an open-source script called xml2abc[3] to convert the songs to ABC format [4], which is more streamlined and therefore more conducive for training a text-based Machine Learning (ML) system." }, { "code": null, "e": 2305, "s": 1921, "text": "I then used a library from MIT called music21 [5] to process the songs and transpose them to the key of C Major, making it easier for the machine to understand the music. The formatted songs were saved in a training file and uploaded to OpenAI’s fine-tuning service. I trained their GPT-3 Curie transformer model to generate a song after being prompted by a song title and band name." }, { "code": null, "e": 2544, "s": 2305, "text": "Although the Curie model generates the music, I am using its big brother, Davinci, to automatically generate a song title and band name. I use these two pieces of data to prompt the fine-tuned Curie model to generate five candidate songs." }, { "code": null, "e": 2921, "s": 2544, "text": "I use a package called music_geometry_eval [6] to analyze the tonal qualities of the five songs. The analysis is based on the music theory described in the book β€œA Geometry of Music” by Dmitri Tymoczko [7]. I then choose the song that has the statistically closest tonal quality to the songs in the training set. Finally, I show the songs as a visual piano-roll and play them." }, { "code": null, "e": 3072, "s": 2921, "text": "The sections below describe details of the components and processes used in AI-Tunes. Be sure to check out more generated songs in the Appendix below." }, { "code": null, "e": 3579, "s": 3072, "text": "One of the keys to getting good results from an ML system is having good training data. In researching music generating systems, I found that authors of papers often do not post their training datasets due to copyright restrictions. Although there are many sites that host user-generated MIDI files of popular songs, the copyrights to these songs are still owned by the authors/publishers. And using copyrighted material for training data is in a legal gray area if the results are to be used commercially." }, { "code": null, "e": 3988, "s": 3579, "text": "I found a dataset called OpenEWLD that can be used freely. It is a pared-down version of the Enhanced Wikifonia Leadsheet Dataset (EWLD) [8], a collection of over 5,000 songs in MusicXML format [9]. Note that a β€œleadsheet” is a simplified song score with just the melody and chords. The OpenEWLD is an extraction of 502 songs in the EWLD that are in the public domain and can be used for training ML systems." }, { "code": null, "e": 4212, "s": 3988, "text": "Fair notice: I did not check the provenance of all the songs in the OpenEWLD to make sure that they are actually in the public domain. But a quick perusal of the titles/composers shows a bunch of old-time tunes, like these:" }, { "code": null, "e": 4440, "s": 4212, "text": "β€œAin’t Misbehavin’ ” by Andy Razaf, Fats Waller, and Harry Brooksβ€œMakin’ Whoopee!” by Gus Kahn and Walter Donaldsonβ€œMaple Leaf Rag” by Scott Joplinβ€œOh! Susanna” by Stephen Fosterβ€œWe’re in the Money” by Al Dubin and Harry Warren" }, { "code": null, "e": 4506, "s": 4440, "text": "β€œAin’t Misbehavin’ ” by Andy Razaf, Fats Waller, and Harry Brooks" }, { "code": null, "e": 4557, "s": 4506, "text": "β€œMakin’ Whoopee!” by Gus Kahn and Walter Donaldson" }, { "code": null, "e": 4590, "s": 4557, "text": "β€œMaple Leaf Rag” by Scott Joplin" }, { "code": null, "e": 4622, "s": 4590, "text": "β€œOh! Susanna” by Stephen Foster" }, { "code": null, "e": 4672, "s": 4622, "text": "β€œWe’re in the Money” by Al Dubin and Harry Warren" }, { "code": null, "e": 4912, "s": 4672, "text": "Here is an example of one of the songs in the OpenEWLD collection. You can see a β€œpiano roll” of the song, which is a graph with pitch values of the notes on the y-axis and time on the x-axis. And you can play the song on SoundCloud below." }, { "code": null, "e": 4929, "s": 4912, "text": "\n\n693 plays693\n\n" }, { "code": null, "e": 5389, "s": 4929, "text": "As I mentioned above, songs in the OpenEWLD [8] are in MusicXML format, which works fine, but has a lot of extra formatting text. Although an ML system could learn all of the formatting commands and generate songs in this format, I found that it was better to reduce the musical notation to the bare minimum. The ABC format by Chris Walshaw [4] is a good match. For example, here is the first part of the song β€œWe’re in the Money” in MusicXML and ABC formats." }, { "code": null, "e": 5691, "s": 5389, "text": "You can see that the song is dramatically simplified when converted to the ABC format. The XML format requires 503 characters for the header and 443 for the first two notes. The ABC format specifies the same information using only 85 characters for the header and 8 characters for the first two notes." }, { "code": null, "e": 5846, "s": 5691, "text": "I use an open-source script called xml2abc by Wim Vree [3] to convert the songs from MusicXML to ABC format. Here is the command I use for the conversion." }, { "code": null, "e": 5894, "s": 5846, "text": "python xml2abc.py were-in-the-money.xml -u -d 4" }, { "code": null, "e": 6221, "s": 5894, "text": "This will read the file β€œwere-in-the-money.xml”, convert it, and save it as β€œwere-in-the-money.abc”. The -u option will β€œunroll” any repeated measures, and the -d 4 option will set the default note duration to be a quarter note. Using both of these options helps the machine learning process by standardizing the music scores." }, { "code": null, "e": 6280, "s": 6221, "text": "Here’s the entire β€œWe’re in the Money” song in ABC format." }, { "code": null, "e": 6953, "s": 6280, "text": "X:1T:We're In The MoneyC:Harry WarrenL:1/4M:2/2I:linebreak $K:CV:1 treble \"C\" z E G3/2 E/ |\"Dm7\" F\"G7\" G3 |\"C\" z E G3/2 E/ |\"Dm7\" F\"G7\" G3 \"C\" z e\"C+\" e3/2 c/ | %5 | \"F\" d c d\"Ab7\" c |\"C\" e c\"Dm7\" c\"G7\" d\"C\" c2 z2 |\"C\" z E G3/2 E/ |\"Dm7\" F\"G7\" G3 | %10\"C\" z E G3/2 E/ |\"Dm7\" F\"G7\" G3 |$\"C\" z e\"C+\" e3/2 c/\"F\" d c d\"Ab7\" c |\"C\" e c\"Dm7\" c\"G7\" d | %15\"C\" c2 z2 |\"C\" c2 z2 |$ z\"Cmaj7\" e d/c/B/A/ |\"Cmaj7\" B B z/ c A/\"Cmaj7\" B B2 c |\"Cmaj7\" B4 |$ %21\"Cmaj7\" z e d/c/B/A/ |\"Cmaj7\" B B z/ B B/ |\"Bb\" _B B\"A7\" A A\"Ab7\" _A A\"G7\" G z |$ %25 | \"C\" z E G3/2 E/ |\"Dm7\" F\"G7\" G3\"C\" z E G3/2 E/ |\"Dm7\" F\"G7\" G3 |$\"C\" z e\"C+\" e3/2 c/ | %30\"F\" d c d\"Ab7\" c |\"C\" e c2\"G7\" d |\"C\" c3 z | %33" }, { "code": null, "e": 7039, "s": 6953, "text": "I prepare the songs to be used as training data by performing these processing steps:" }, { "code": null, "e": 7217, "s": 7039, "text": "Filter out songs that don’t use the 4/4 and 2/2 time signaturesTranspose songs to the key of C MajorStrip out lyrics and other unnecessary dataReplace newlines with a β€œ$” symbol" }, { "code": null, "e": 7281, "s": 7217, "text": "Filter out songs that don’t use the 4/4 and 2/2 time signatures" }, { "code": null, "e": 7319, "s": 7281, "text": "Transpose songs to the key of C Major" }, { "code": null, "e": 7363, "s": 7319, "text": "Strip out lyrics and other unnecessary data" }, { "code": null, "e": 7398, "s": 7363, "text": "Replace newlines with a β€œ$” symbol" }, { "code": null, "e": 7804, "s": 7398, "text": "Unifying the time and key signatures makes it easier for the ML system to learn about the melody notes and timing. A majority of songs use either 4/4 or 2/2 time (381 of 502) so it is not worth the effort to get the system to understand other meters. And most of the songs are already in the key of C Major (303 of 502). I use a function in the music21 package [5] to transpose the songs to a unified key." }, { "code": null, "e": 8134, "s": 7804, "text": "I strip out the lyrics to help the system to focus on just the notes. I converted the newlines to β€œ$” in order to adhere to a quirk of the GPT-3 fine-tuning system. Otherwise, it converts the newlines to commas; this would create a problem for songs in ABC format as commas are already used to specify notes in different octaves." }, { "code": null, "e": 8390, "s": 8134, "text": "In order to fine-tune OpenAI’s GPT-3 models, the first step is to compile a text file that has pairs of prompts and completions in JSON format. For the prompt, I use the song title and the composer's name. The completion is the prepped song in ABC format." }, { "code": null, "e": 8449, "s": 8390, "text": "Here is what two of the prompt-completion pairs look like:" }, { "code": null, "e": 9777, "s": 8449, "text": "{\"prompt\": \"X: 1 $ T: We're In The Money $ C: Harry Warren $ <song>\", \"completion\": \" `C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z e`C+` e3/2 c/ | $ `F` d c d`G#7` c |`C` e c`Dm7` c`G7` d |`C` c2 z2 |`C` z E G3/2 E/ |`Dm7` F`G7` G3 | $ `C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z e`C+` e3/2 c/ |`F` d c d`G#7` c |`C` e c`Dm7` c`G7` d | $ `C` c2 z2 |`C` c2 z2 | z`Cmaj7` e d/c/B/A/ |`Cmaj7` B B z/ c A/ |`Cmaj7` B B2 c |`Cmaj7` B4 | $ `Cmaj7` z e d/c/B/A/ |`Cmaj7` B B z/ B B/ |`Bb` _B B`A7` A A |`G#7` ^G G`G7` =G z | $ `C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z E G3/2 E/ |`Dm7` F`G7` G3 |`C` z e`C+` e3/2 c/ | $ `F` d c d`G#7` c |`C` e c2`G7` d |`C` c3 z | $ <end>\"}{\"prompt\": \"X: 1 $ T: They Didn't Believe Me $ C: Jerome Kern $ <song>\", \"completion\": \" z G A c |`Dm7` d2 d2- |`G7` d e d/>e/c/>d/ |`C` e4- |`Em7b5` e e`A7b9` (3e f g |`Dm7` d2 d2- | $ `G7` d d (3d e f |`C` G2 G2- |`Am7` G G A c |`Dm7` f A B c |`G7` d3/2 B/ c`G7/F` d | $ `Em7` g B c d |`Am` e2 e ^f |`Em` g e/>^f/ g2- |`B7` g ^f =e _e |`Em7``Bb9` e4- | $ `A7` e g`A7b9` f e |`Dm7` d2 d2- |`G7` d d/>e/ (3d/e/d/ c/>d/ |`C6` e2 e2- |`Am7` e c d e | $ `Dm` f2 f2 |`G7` f f e _e |`C6``Bb9` e4- |`A7` e e e/f/ g |`Dm` d2 d2- |`G7` d d d/e/ f | $ `C` G2`Dm7` G2- |`Em7` G G`A7` ^G A |`Dm7` f A B c |`G7` d2`G7b9` e2 |`C` c4- | c z z2 | $ <end>\"}" }, { "code": null, "e": 9894, "s": 9777, "text": "OpenAI provides a utility that checks the validity of the training file. Here is the command I use to check my file." }, { "code": null, "e": 9946, "s": 9894, "text": "openai tools fine_tunes.prepare_data -f songs.jsonl" }, { "code": null, "e": 9966, "s": 9946, "text": "Here is the result." }, { "code": null, "e": 10359, "s": 9966, "text": "Analyzing...- Your file contains 374 prompt-completion pairs- More than a third of your `completion` column/key is uppercase. - All prompts end with suffix ` $ <song>`- All prompts start with prefix `X: 1 $ T: `- All completions end with suffix ` | $ <end>`Based on the analysis we will perform the following actions:- [Recommended] Lowercase all your data in column/key `completion` [Y/n]: n" }, { "code": null, "e": 10717, "s": 10359, "text": "It only flags one problem, which really isn’t a problem. The prepare_data script noticed that a lot of the text in the completions is in uppercase. This is due to the fact that the root of the chords and many of the notes are specified with uppercase letters. This warning is probably meant for conversational text, not music, so I just ignored the warning." }, { "code": null, "e": 10809, "s": 10717, "text": "Once the training file is in good shape, it’s easy to fine-tune GPT-3. Here is the command:" }, { "code": null, "e": 10875, "s": 10809, "text": "openai api fine_tunes.create -t songs.jsonl -m curie --n_epochs 5" }, { "code": null, "e": 11127, "s": 10875, "text": "I chose to use the largest of the available GPT-3 models for training, Curie. It’s not as big as Davinci, but it seems to work well. I also set the number of training epochs to 5, which indicates how many times to run through the dataset for training." }, { "code": null, "e": 11163, "s": 11127, "text": "Here is the result of the training." }, { "code": null, "e": 11698, "s": 11163, "text": "Created fine-tune: ft-Vk1UCsXpd65sXXayafTGAY0mStreaming events until fine-tuning is complete...(Ctrl-C will interrupt the stream, but not cancel the fine-tune)[2021-08-29 12:10:50] Fine-tune enqueued. Queue number: 0[2021-08-29 12:10:53] Fine-tune started[2021-08-29 12:12:55] Completed epoch 1/5[2021-08-29 12:13:41] Completed epoch 2/5[2021-08-29 12:14:27] Completed epoch 3/5[2021-08-29 12:15:13] Completed epoch 4/5[2021-08-29 12:15:59] Completed epoch 5/5[2021-08-29 12:17:09] Fine-tune succeededJob complete! Status: succeeded πŸŽ‰" }, { "code": null, "e": 11869, "s": 11698, "text": "As you can see, it only took about six minutes to run the training. The team at OpenAI gets extra credit for showing me a celebration emoji when the training is finished!" }, { "code": null, "e": 12016, "s": 11869, "text": "Before we check out how well the model creates songs, I will show you how I create new song titles and band names as prompts, using GPT-3 Davinci." }, { "code": null, "e": 12433, "s": 12016, "text": "As you saw in the training data samples above, each line has a prompt with the song title and the composer name followed by the song in ABC format. In order to generate new songs, I create a new prompt with a new song and band name. Any text would do, but I think that it’s fun to see if the system can create a song when prompted with new information, like a song title and fake band name. Here’s an example prompt." }, { "code": null, "e": 12502, "s": 12433, "text": "\"prompt\": \"X: 1 $ T: Expensive to Maintain $ C: Shaky Pies $ <song>\"" }, { "code": null, "e": 12738, "s": 12502, "text": "In order to make a lot of prompts like this, I put the GPT-3 Davinci system to work. No fine-tuning is necessary. The Davinci model works happily given a prompt like this. Note that I filled in fake band names and songs for the prompt." }, { "code": null, "e": 12907, "s": 12738, "text": "Create a new song title a new band name. Be creative!Band name: The ExecsSong title: Company Meeting###Band name: The One ChordsSong title: Moving Down to Burlington###" }, { "code": null, "e": 12960, "s": 12907, "text": "And here are some sample results from GPT-3 Davinci." }, { "code": null, "e": 13146, "s": 12960, "text": "Band name: The WizardsSong title: I’ll Get There When I Get There###Band name: The UndergradsSong title: I'm Just a Kid###Band name: The FortunesSong title: What Do You Want from Me?###" }, { "code": null, "e": 13350, "s": 13146, "text": "Looks like some fun songs! By the way, some of these generated song titles and/or band names might exist out in the real world, but if so, it’s OK. I am just using these to prompt the song-writing model." }, { "code": null, "e": 13482, "s": 13350, "text": "Now that we have some prompts, let’s see what the model can do. I generated five versions of the first song and chose the best one." }, { "code": null, "e": 13663, "s": 13482, "text": "OK, the melody is fairly simple and it sounds pretty good. Note the interesting structure which seems to be ABABCB. You can see and hear more generated songs in the Appendix below." }, { "code": null, "e": 14006, "s": 13663, "text": "For that last test, I got involved as a critic. I listened to all five generated versions of β€œI’ll Get There When I Get There” and chose the best one. Note that there were some clunkers in the batch. Some of them started off OK but veered into playing odd notes. And others simply repeated a phrase over and over again without much variation." }, { "code": null, "e": 14245, "s": 14006, "text": "Given that the system could crank out many versions of these tunes, I looked into using statistics to maybe help weed out the clunkers. I found that a lot of research has been done on the subject of measuring the tonal qualities of music." }, { "code": null, "e": 14461, "s": 14245, "text": "The book I mentioned above by Dmitri Tymoczko has the full title, β€œA Geometry of Music: Harmony and Counterpoint in the Extended Common Practice” [7]. In the book, Tymoczko discusses five features of music tonality." }, { "code": null, "e": 14629, "s": 14461, "text": "[These] five features are present in a wide range of [music] genres, Western and non-Western, past and present, and ... they jointly contribute to a sense of tonality:" }, { "code": null, "e": 14717, "s": 14629, "text": "1. Conjunct melodic motion. Melodies tend to move by short distances from note to note." }, { "code": null, "e": 14850, "s": 14717, "text": "2. Acoustic consonance. Consonant harmonies are preferred to dissonant harmonies and tend to be used at points of musical stability." }, { "code": null, "e": 14982, "s": 14850, "text": "3. Harmonic consistency. The harmonies in a passage of music, whatever they may be, tend to be structurally similar to one another." }, { "code": null, "e": 15217, "s": 14982, "text": "4. Limited macroharmony. I use the term β€œmacroharmony” to refer to the total collection of notes heard over moderate spans of musical time. Tonal music tends to use relatively small macroharmonies, often involving five to eight notes." }, { "code": null, "e": 15395, "s": 15217, "text": "5. Centricity. Over moderate spans of musical time, one note is heard as being more prominent than the others, appearing more frequently and serving as a goal of musical motion." }, { "code": null, "e": 15438, "s": 15395, "text": "- Dmitri Tymoczko in β€œA Geometry of Music”" }, { "code": null, "e": 15640, "s": 15438, "text": "I found an open-source project on GitHub called music-geometry-eval [6] that has Python code to assess three of Tymoczko’s tonal features, conjunct melodic motion, limited macroharmony, and centricity." }, { "code": null, "e": 15784, "s": 15640, "text": "I ran all 374 songs in my training data through the code to find the average and standard deviation of the three metrics. Here are the results:" }, { "code": null, "e": 15926, "s": 15784, "text": "Conjunct Melodic Motion (CMM) : 2.2715 Β± 0.4831Limited Macroharmony (LM) : 2.0305 Β± 0.5386Centricity (CENT): 0.3042 Β± 0.0891" }, { "code": null, "e": 16220, "s": 15926, "text": "And here are the stats from the five generated versions of β€œI’ll Get There When I Get There.” I also calculated a Normalized Distance to the Mean (NDM) value for each of the five songs, comparing the metrics from each generated song to the average metrics of the songs in the training dataset." }, { "code": null, "e": 16668, "s": 16220, "text": "Generating Song Version 0 CMM : 2.3385 LM : 3.5488 CENT: 0.5213 NDM : 8.1677Generating Song Version 1 CMM : 3.828 LM : 2.3396 CENT: 0.2677 NDM : 10.7161Generating Song Version 2 CMM : 3.124 LM : 1.5614 CENT: 0.2244 NDM : 3.8996 <-- Closest tonality to the training dataGenerating Song Version 3 CMM : 2.0206 LM : 3.4195 CENT: 0.4869 NDM : 7.0639Generating Song Version 4 CMM : 3.2644 LM : 1.4132 CENT: 0.2436 NDM : 5.5533" }, { "code": null, "e": 16996, "s": 16668, "text": "And sure enough, the song I chose to be β€œthe best” of the batch, Version 2, also happens to have the best NDM score. Note that this happens often, but it’s not always the case. After running this experiment about a dozen times, I find that sometimes the song with the second or third closest NDM score actually sounds the best." }, { "code": null, "e": 17141, "s": 16996, "text": "The AI-Tunes system works fairly well. Not every piece is good, but it often produces interesting music with recognizable themes and variations." }, { "code": null, "e": 17456, "s": 17141, "text": "If you know about music composition, you may notice that some of the pieces are in need of a little β€œclean up”. For example, sometimes the system does not strictly adhere to 4/4 time due to extra eighth notes inserted here and there. (Hint: Try tapping your foot to the beat when listening to the generated music.)" }, { "code": null, "e": 17650, "s": 17456, "text": "The good news is that you can download the generated compositions as MIDI files and fix them up in notation software fairly easily. For example here is a cleaned-up version of the example song." }, { "code": null, "e": 17873, "s": 17650, "text": "As for the general quality of the compositions, there is definitely room for improvement. For example, if OpenAI makes fine-tuning available for their larger Davinci transformer, the resulting music would probably improve." }, { "code": null, "e": 18038, "s": 17873, "text": "Also, training the system on a larger dataset of music would definitely help. And it would probably update the style of music to be something from this Millenium πŸ˜„." }, { "code": null, "e": 18175, "s": 18038, "text": "Implementing Tymoczko’s other two tonal features, acoustic consonance and harmonic consistency, would help assess the generated results." }, { "code": null, "e": 18313, "s": 18175, "text": "It would be fairly easy to extend the AI-Tunes model to include features like musical phrase completion and chord conditioned generation." }, { "code": null, "e": 18699, "s": 18313, "text": "For phrase completion, the training set would need to contain song parts, with one or more measures from the original song in the prompt, and the response would contain one or more measures that pick up from that point in the song. When running the system to generate new parts, a set of preceding chords and melody would be passed in, and the system would complete the musical phrase." }, { "code": null, "e": 18996, "s": 18699, "text": "For chord conditioning, the prompt for training would contain just the chords of the original song in ABC format, and the expected response would be the original melody. When generating music, just the chords would be passed in, and the system would generate a melody that would match the chords." }, { "code": null, "e": 19275, "s": 18996, "text": "All source code for this project is available on GitHub. You can experiment with the code using this Google Colab. This Colab only works if you have an account with OpenAI. If you don’t have an account you can sign up here. I released the source code under the CC BY-SA license." }, { "code": null, "e": 19485, "s": 19275, "text": "I would like to thank Jennifer Lim and Oliver Strimpel for their help with this project. And I would like to thank Georgina Lewis at the MIT Libraries for helping me track down a copy of β€œA Geometry of Music.”" }, { "code": null, "e": 19523, "s": 19485, "text": "[1] OpenAI, GPT Fine-tunes API (2021)" }, { "code": null, "e": 19557, "s": 19523, "text": "[2] F. Simonetta, OpenEWLD (2017)" }, { "code": null, "e": 19585, "s": 19557, "text": "[3] W. Vree, xml2abc (2012)" }, { "code": null, "e": 19621, "s": 19585, "text": "[4] C. Walshaw, ABC Notation (1997)" }, { "code": null, "e": 19645, "s": 19621, "text": "[5] MIT, music21 (2010)" }, { "code": null, "e": 19692, "s": 19645, "text": "[6] S. G. Valencia, music-geometry-eval (2017)" }, { "code": null, "e": 19826, "s": 19692, "text": "[7] D. Tymoczko, A Geometry of Music: Harmony and Counterpoint in the Extended Common Practice (2010), Oxford Studies in Music Theory" }, { "code": null, "e": 19889, "s": 19826, "text": "[8] F. Simonetta, Enhanced Wikifonia Leadsheet Dataset, (2018)" }, { "code": null, "e": 19918, "s": 19889, "text": "[9] M. Good, MusicMXL (2004)" }, { "code": null, "e": 19987, "s": 19918, "text": "Here you can find some more examples of songs generated by AI-Tunes." }, { "code": null, "e": 20127, "s": 19987, "text": "To get unlimited access to all articles on Medium, become a member for $5/month. Non-members can only read three locked stories each month." } ]
Hierarchical Clustering on Categorical Data in R | by Anastasia Reusova | Towards Data Science
This was my first attempt to perform customer clustering on real-life data, and it’s been a valuable experience. While articles and blog posts about clustering using numerical variables on the net are abundant, it took me some time to find solutions for categorical data, which is, indeed, less straightforward if you think of it. Methods for categorical data clustering are still being developed β€” I will try one or the other in a different post. On the other hand, I have come across opinions that clustering categorical data might not produce a sensible result β€” and partially, this is true (there’s an amazing discussion at CrossValidated). At a certain point, I thought β€œWhat am doing, why not just break it all down in cohorts.” But cohort analysis is not always sensible as well, especially in case you get more categorical variables with higher number of levels β€” you can easily skimming through 5–7 cohorts might be easy, but what if you have 22 variables with 5 levels each (say, it’s a customer survey with discrete scores of 1,2,3,4,5), and you need to see what are the distinctive groups of customers you have β€” you would have 22x5 cohorts. Nobody wants to do this. Clustering could appear to be useful. So this post is all about sharing what I wish I bumped into when I started with clustering. The clustering process itself contains 3 distinctive steps: Calculating dissimilarity matrix β€” is arguably the most important decision in clustering, and all your further steps are going to be based on the dissimilarity matrix you’ve made.Choosing the clustering methodAssessing clusters Calculating dissimilarity matrix β€” is arguably the most important decision in clustering, and all your further steps are going to be based on the dissimilarity matrix you’ve made. Choosing the clustering method Assessing clusters This post is going to be sort of beginner level, covering the basics and implementation in R. Dissimilarity MatrixArguably, this is the backbone of your clustering. Dissimilarity matrix is a mathematical expression of how different, or distant, the points in a data set are from each other, so you can later group the closest ones together or separate the furthest ones β€” which is a core idea of clustering. This is the step where data types differences are important as dissimilarity matrix is based on distances between individual data points. While it is quite easy to imagine distances between numerical data points (remember Eucledian distances, as an example?), categorical data (factors in R) does not seem as obvious. In order to calculate a dissimilarity matrix in this case, you would go for something called Gower distance. I won’t get into the math of it, but I am providing a links here and here. To do that I prefer to use daisy() with metric = c("gower") from the cluster package. #----- Dummy Data -----## the data will be sterile clean in order to not get distracted with other issues that might arise, but I will also write about some difficulties I had, outside the codelibrary(dplyr)# ensuring reproducibility for samplingset.seed(40)# generating random variable set# specifying ordered factors, strings will be converted to factors when using data.frame()# customer ids come first, we will generate 200 customer ids from 1 to 200id.s <- c(1:200) %>% factor()budget.s <- sample(c("small", "med", "large"), 200, replace = T) %>% factor(levels=c("small", "med", "large"), ordered = TRUE)origins.s <- sample(c("x", "y", "z"), 200, replace = T, prob = c(0.7, 0.15, 0.15))area.s <- sample(c("area1", "area2", "area3", "area4"), 200, replace = T, prob = c(0.3, 0.1, 0.5, 0.2))source.s <- sample(c("facebook", "email", "link", "app"), 200, replace = T, prob = c(0.1,0.2, 0.3, 0.4))## day of week - probabilities are mocking the demand curvedow.s <- sample(c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), 200, replace = T, prob = c(0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2)) %>% factor(levels=c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), ordered = TRUE)# dish dish.s <- sample(c("delicious", "the one you don't like", "pizza"), 200, replace = T) # by default, data.frame() will convert all the strings to factorssynthetic.customers <- data.frame(id.s, budget.s, origins.s, area.s, source.s, dow.s, dish.s)#----- Dissimilarity Matrix -----#library(cluster) # to perform different types of hierarchical clustering# package functions used: daisy(), diana(), clusplot()gower.dist <- daisy(synthetic.customers[ ,2:7], metric = c("gower"))# class(gower.dist) ## dissimilarity , dist Done with a dissimilarity matrix. That’s very fast on 200 observations, but can be very computationally expensive in case you have a large data set. In reality, it is quite likely that you will have to clean the dataset first, perform the necessary transformations from strings to factors and keep an eye on missing values. In my own case, the dataset contained rows of missing values, which nicely clustered together every time, leading me to assume that I found a treasure until I had a look at the values (meh!). Clustering Algorithms You could have heard that there is k-means and hierarchical clustering. In this post, I focus on the latter as it is a more exploratory type, and it can be approached differently: you could choose to follow either agglomerative (bottom-up) or divisive (top-down) way of clustering. Agglomerative clustering will start with n clusters, where n is the number of observations, assuming that each of them is its own separate cluster. Then the algorithm will try to find most similar data points and group them, so they start forming clusters. In contrast, divisive clustering will go the other way around β€” assuming all your n data points are one big cluster and dividing most dissimilar ones into separate groups. If you are thinking which one of them to use, it is always worth trying all the options, but in general, agglomerative clustering is better in discovering small clusters, and is used by most software; divisive clustering β€” in discovering larger clusters. I personally like having a look at dendrograms β€” graphical representation of clustering first to decide which method I will stick to. As you will see below, some of dendrograms will be pretty balanced , while others will look like a mess. # The main input for the code below is dissimilarity (distance matrix)# After dissimilarity matrix was calculated, the further steps will be the same for all data types# I prefer to look at the dendrogram and fine the most appealing one first - in this case, I was looking for a more balanced one - to further continue with assessment#------------ DIVISIVE CLUSTERING ------------#divisive.clust <- diana(as.matrix(gower.dist), diss = TRUE, keep.diss = TRUE)plot(divisive.clust, main = "Divisive") #------------ AGGLOMERATIVE CLUSTERING ------------## I am looking for the most balanced approach# Complete linkages is the approach that best fits this demand - I will leave only this one here, don't want to get it cluttered# completeaggl.clust.c <- hclust(gower.dist, method = "complete")plot(aggl.clust.c, main = "Agglomerative, complete linkages") Assessing clusters Here, you will decide between different clustering algorithms and a different number of clusters. As it often happens with assessment, there is more than one way possible, complemented by your own judgement. It’s bold and in italics because your own judgement is important β€” the number of clusters should make practical sense and they way data is divided into groups should make sense too. Working with categorical variables, you might end up with non-sense clusters because the combination of their values is limited β€” they are discrete, so is the number of their combinations. Possibly, you don’t want to have a very small number of clusters either β€” they are likely to be too general. In the end, it all comes to your goal and what you do your analysis for. Conceptually, when clusters are created, you are interested in distinctive groups of data points, such that the distance between them within clusters (or compactness) is minimal while the distance between groups (separation) is as large as possible. This is intuitively easy to understand: distance between points is a measure of their dissimilarity derived from dissimilarity matrix. Hence, the assessment of clustering is built around evaluation of compactness and separation. I will go for 2 approaches here and show that one of them might produce nonsense results: Elbow method: start with it when the compactness of clusters, or similarities within groups are most important for your analysis. Silhouette method: as a measure of data consistency, the silhouette plot displays a measure of how close each point in one cluster is to points in the neighboring clusters. In practice, they are very likely to provide different results that might be confusing at a certain pointβ€” different number of clusters will correspond to the most compact / most distinctively separated clusters, so judgement and understanding what your data is actually about will be a significant part of making the final decision. There are also a bunch of measurements that you can analyze for your own case. I am adding them to the code itself. # Cluster stats comes out as list while it is more convenient to look at it as a table# This code below will produce a dataframe with observations in columns and variables in row# Not quite tidy data, which will require a tweak for plotting, but I prefer this view as an output here as I find it more comprehensive library(fpc)cstats.table <- function(dist, tree, k) {clust.assess <- c("cluster.number","n","within.cluster.ss","average.within","average.between", "wb.ratio","dunn2","avg.silwidth")clust.size <- c("cluster.size")stats.names <- c()row.clust <- c()output.stats <- matrix(ncol = k, nrow = length(clust.assess))cluster.sizes <- matrix(ncol = k, nrow = k)for(i in c(1:k)){ row.clust[i] <- paste("Cluster-", i, " size")}for(i in c(2:k)){ stats.names[i] <- paste("Test", i-1) for(j in seq_along(clust.assess)){ output.stats[j, i] <- unlist(cluster.stats(d = dist, clustering = cutree(tree, k = i))[clust.assess])[j] } for(d in 1:k) { cluster.sizes[d, i] <- unlist(cluster.stats(d = dist, clustering = cutree(tree, k = i))[clust.size])[d] dim(cluster.sizes[d, i]) <- c(length(cluster.sizes[i]), 1) cluster.sizes[d, i] }}output.stats.df <- data.frame(output.stats)cluster.sizes <- data.frame(cluster.sizes)cluster.sizes[is.na(cluster.sizes)] <- 0rows.all <- c(clust.assess, row.clust)# rownames(output.stats.df) <- clust.assessoutput <- rbind(output.stats.df, cluster.sizes)[ ,-1]colnames(output) <- stats.names[2:k]rownames(output) <- rows.allis.num <- sapply(output, is.numeric)output[is.num] <- lapply(output[is.num], round, 2)output}# I am capping the maximum amout of clusters by 7# I want to choose a reasonable number, based on which I will be able to see basic differences between customer groups as a resultstats.df.divisive <- cstats.table(gower.dist, divisive.clust, 7)stats.df.divisive Look, average.within, which is an average distance among observations within clusters, is shrinking, so does within cluster SS. Average silhouette width is a bit less straightforward, but the reverse relationship is nevertheless there. See how disproportional the size of clusters is. I wouldn’t rush into working with incomparable number of observations within clusters. One of the reasons, the dataset can be imbalanced, and some group of observations will outweigh all the rest in the analysis β€” this is not good and is likely to lead to biases. stats.df.aggl <-cstats.table(gower.dist, aggl.clust.c, 7) #complete linkages looks like the most balanced approachstats.df.aggl Notice how more balanced agglomerative complete linkages hierarchical clustering is compared on the number of observations per group. # --------- Choosing the number of clusters ---------## Using "Elbow" and "Silhouette" methods to identify the best number of clusters# to better picture the trend, I will go for more than 7 clusters.library(ggplot2)# Elbow# Divisive clusteringggplot(data = data.frame(t(cstats.table(gower.dist, divisive.clust, 15))), aes(x=cluster.number, y=within.cluster.ss)) + geom_point()+ geom_line()+ ggtitle("Divisive clustering") + labs(x = "Num.of clusters", y = "Within clusters sum of squares (SS)") + theme(plot.title = element_text(hjust = 0.5)) So, we’ve produced the β€œelbow” graph. It shows how the within sum of squares β€” as a measure of closeness of observations : the lower it is the closer the observations within the clusters are β€” changes for the different number of clusters. Ideally, we should see a distinctive β€œbend” in the elbow where splitting clusters further gives only minor decrease in the SS. In the case of a graph below, I would go for something around 7. Although in this case, one of a clusters will consist of only 2 observations, let’s see what happens with agglomerative clustering. # Agglomerative clustering,provides a more ambiguous pictureggplot(data = data.frame(t(cstats.table(gower.dist, aggl.clust.c, 15))), aes(x=cluster.number, y=within.cluster.ss)) + geom_point()+ geom_line()+ ggtitle("Agglomerative clustering") + labs(x = "Num.of clusters", y = "Within clusters sum of squares (SS)") + theme(plot.title = element_text(hjust = 0.5)) Agglomerative β€œelbow” looks similar to that of divisive, except that agglomerative one looks smoother β€” with β€œbends” being less abrupt. Similarly to divisive clustering, I would go for 7 clusters, but choosing between the two methods, I like the size of the clusters produced by the agglomerative method more β€” I want something comparable in size. # Silhouetteggplot(data = data.frame(t(cstats.table(gower.dist, divisive.clust, 15))), aes(x=cluster.number, y=avg.silwidth)) + geom_point()+ geom_line()+ ggtitle("Divisive clustering") + labs(x = "Num.of clusters", y = "Average silhouette width") + theme(plot.title = element_text(hjust = 0.5)) When it comes to silhouette assessment, the rule is you should choose the number that maximizes the silhouette coefficient because you want clusters that are distinctive (far) enough to be considered separate. The silhouette coefficient ranges between -1 and 1, with 1 indicating good consistency within clusters, -1 β€” not so good. From the plot above, you would not go for 5 clusters β€” you would rather prefer 9. As a comparison, for the β€œeasy” case, the silhouette plot is likely to look like the graph below. We are not quite, but almost there. ggplot(data = data.frame(t(cstats.table(gower.dist, aggl.clust.c, 15))), aes(x=cluster.number, y=avg.silwidth)) + geom_point()+ geom_line()+ ggtitle("Agglomerative clustering") + labs(x = "Num.of clusters", y = "Average silhouette width") + theme(plot.title = element_text(hjust = 0.5)) What the silhouette width graph above is saying is β€œthe more you break the dataset, the more distinctive the clusters become”. Ultimately, you will end up with individual data points β€” and you don’t want that, and if you try a larger k for the number of clusters β€” you will see it. E.g., at k=30, I got the following graph: So-so: the more you split, the better it gets, but we can’t be splitting till individual data points (remember that we have 30 clusters here in the graph above, and only 200 data points). Summing it all up, agglomerative clustering in this case looks way more balanced to me β€” the cluster sizes are more or less comparable (look at that cluster with just 2 observations in the divisive section!), and I would go for 7 clusters obtained by this method. Let’s see how they look and check what’s inside. The dataset consists of 6 variables which need to be visualized in 2D or 3D, so it’s time for a challenge! The nature of categorical data poses some limitations too, so using some pre-defined solutions might get tricky. What I want to a) see how observations are clustered, b) know is how observations are distributed across categories, thus I created a) a colored dendrogram, b) a heatmap of observations count per variable within each cluster. library("ggplot2")library("reshape2")library("purrr")library("dplyr")# let's start with a dendrogramlibrary("dendextend")dendro <- as.dendrogram(aggl.clust.c)dendro.col <- dendro %>% set("branches_k_color", k = 7, value = c("darkslategray", "darkslategray4", "darkslategray3", "gold3", "darkcyan", "cyan3", "gold3")) %>% set("branches_lwd", 0.6) %>% set("labels_colors", value = c("darkslategray")) %>% set("labels_cex", 0.5)ggd1 <- as.ggdend(dendro.col)ggplot(ggd1, theme = theme_minimal()) + labs(x = "Num. observations", y = "Height", title = "Dendrogram, k = 7") # Radial plot looks less cluttered (and cooler)ggplot(ggd1, labels = T) + scale_y_reverse(expand = c(0.2, 0)) + coord_polar(theta="x") # Time for the heatmap# the 1st step here is to have 1 variable per row# factors have to be converted to characters in order not to be droppedclust.num <- cutree(aggl.clust.c, k = 7)synthetic.customers.cl <- cbind(synthetic.customers, clust.num)cust.long <- melt(data.frame(lapply(synthetic.customers.cl, as.character), stringsAsFactors=FALSE), id = c("id.s", "clust.num"), factorsAsStrings=T)cust.long.q <- cust.long %>% group_by(clust.num, variable, value) %>% mutate(count = n_distinct(id.s)) %>% distinct(clust.num, variable, value, count)# heatmap.c will be suitable in case you want to go for absolute counts - but it doesn't tell much to my tasteheatmap.c <- ggplot(cust.long.q, aes(x = clust.num, y = factor(value, levels = c("x","y","z", "mon", "tue", "wed", "thu", "fri","sat","sun", "delicious", "the one you don't like", "pizza", "facebook", "email", "link", "app", "area1", "area2", "area3", "area4", "small", "med", "large"), ordered = T))) + geom_tile(aes(fill = count))+ scale_fill_gradient2(low = "darkslategray1", mid = "yellow", high = "turquoise4")# calculating the percent of each factor level in the absolute count of cluster memberscust.long.p <- cust.long.q %>% group_by(clust.num, variable) %>% mutate(perc = count / sum(count)) %>% arrange(clust.num)heatmap.p <- ggplot(cust.long.p, aes(x = clust.num, y = factor(value, levels = c("x","y","z", "mon", "tue", "wed", "thu", "fri","sat", "sun", "delicious", "the one you don't like", "pizza", "facebook", "email", "link", "app", "area1", "area2", "area3", "area4", "small", "med", "large"), ordered = T))) + geom_tile(aes(fill = perc), alpha = 0.85)+ labs(title = "Distribution of characteristics across clusters", x = "Cluster number", y = NULL) + geom_hline(yintercept = 3.5) + geom_hline(yintercept = 10.5) + geom_hline(yintercept = 13.5) + geom_hline(yintercept = 17.5) + geom_hline(yintercept = 21.5) + scale_fill_gradient2(low = "darkslategray1", mid = "yellow", high = "turquoise4")heatmap.p Having a heatmap, you see the how many observations fall into each factor level within initial factors (variables we’ve started with). The deeper blue corresponds to a higher relative number of observations within a cluster. In this one, you can also see that day of the week / basket size have almost the same amount of customers in each binβ€” it might mean those are not definitive for the analysis and might be omitted. Closing noteIn this post, we’ve gone through dissimilarity matrix calculations, trying out agglomerative and divisive hierarchical clustering methods and had a look at cluster assessment with the β€œelbow” and β€œsilhouette” methods. In this post, we’ve gone through dissimilarity matrix calculations, trying out agglomerative and divisive hierarchical clustering methods and had a look at cluster assessment. Divisive and agglomerative hierarchical clustering are a good place to start exploring, but don’t stop there if your goal is to be a cluster master β€” there are much more methods and techniques popping up out there. In comparison with numerical data clustering, the main difference is hidden in the dissimilarity matrix calculation. From the point of assessment, not all the standard clustering assessment methods will produce reliable and sensible results β€” the silhouette method will likely to be off. Lastly, it’s been a while since I did this exercise. By now, I see some drawbacks behind my approach, and I welcome any feedback. One general pitfall of my analysis lies beyond clustering itself β€” my dataset was imbalanced in many ways, which remained unaddressed. I could see the effect it had on clustering: having 70% of customers belonging to one factor level (nationality in this case), this group was dominating most of the resulting clusters, making it hard to figure out differences within other factor levels. Balancing the dataset and comparing cluster results is what I’m going to try next, and will write a separate post to cover that. Finally, if you’re up for cloning, here’s the github link: https://github.com/khunreus/cluster-categorical And hope you enjoyed it! Here are the sources that I found useful: Hierarchical clustering tutorial (data preparation, clustering, visualization), overall, this blog might be useful for someone interested in business analytics with R: http://uc-r.github.io/hc_clustering and https://uc-r.github.io/kmeans_clustering Cluster validation: http://www.sthda.com/english/articles/29-cluster-validation-essentials/97-cluster-validation-statistics-must-know-methods/ An example of document categorization (hierarchical and k-means): https://eight2late.wordpress.com/2015/07/22/a-gentle-introduction-to-cluster-analysis-using-r/ denextend package is rather interesting, allows to compare cluster structure between different methods: https://cran.r-project.org/web/packages/dendextend/vignettes/introduction.html#the-set-function There are not only dendrograms, but also clustergrams: https://www.r-statistics.com/2010/06/clustergram-visualization-and-diagnostics-for-cluster-analysis-r-code/ Combining clustering heatmap and a dendrogram: https://jcoliver.github.io/learn-r/008-ggplot-dendrograms-and-heatmaps.html I personally would be interested in trying out the method introduced in https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5025633/, their GitHub repository: https://github.com/khunreus/EnsCat
[ { "code": null, "e": 619, "s": 171, "text": "This was my first attempt to perform customer clustering on real-life data, and it’s been a valuable experience. While articles and blog posts about clustering using numerical variables on the net are abundant, it took me some time to find solutions for categorical data, which is, indeed, less straightforward if you think of it. Methods for categorical data clustering are still being developed β€” I will try one or the other in a different post." }, { "code": null, "e": 1480, "s": 619, "text": "On the other hand, I have come across opinions that clustering categorical data might not produce a sensible result β€” and partially, this is true (there’s an amazing discussion at CrossValidated). At a certain point, I thought β€œWhat am doing, why not just break it all down in cohorts.” But cohort analysis is not always sensible as well, especially in case you get more categorical variables with higher number of levels β€” you can easily skimming through 5–7 cohorts might be easy, but what if you have 22 variables with 5 levels each (say, it’s a customer survey with discrete scores of 1,2,3,4,5), and you need to see what are the distinctive groups of customers you have β€” you would have 22x5 cohorts. Nobody wants to do this. Clustering could appear to be useful. So this post is all about sharing what I wish I bumped into when I started with clustering." }, { "code": null, "e": 1540, "s": 1480, "text": "The clustering process itself contains 3 distinctive steps:" }, { "code": null, "e": 1768, "s": 1540, "text": "Calculating dissimilarity matrix β€” is arguably the most important decision in clustering, and all your further steps are going to be based on the dissimilarity matrix you’ve made.Choosing the clustering methodAssessing clusters" }, { "code": null, "e": 1948, "s": 1768, "text": "Calculating dissimilarity matrix β€” is arguably the most important decision in clustering, and all your further steps are going to be based on the dissimilarity matrix you’ve made." }, { "code": null, "e": 1979, "s": 1948, "text": "Choosing the clustering method" }, { "code": null, "e": 1998, "s": 1979, "text": "Assessing clusters" }, { "code": null, "e": 2092, "s": 1998, "text": "This post is going to be sort of beginner level, covering the basics and implementation in R." }, { "code": null, "e": 2406, "s": 2092, "text": "Dissimilarity MatrixArguably, this is the backbone of your clustering. Dissimilarity matrix is a mathematical expression of how different, or distant, the points in a data set are from each other, so you can later group the closest ones together or separate the furthest ones β€” which is a core idea of clustering." }, { "code": null, "e": 2724, "s": 2406, "text": "This is the step where data types differences are important as dissimilarity matrix is based on distances between individual data points. While it is quite easy to imagine distances between numerical data points (remember Eucledian distances, as an example?), categorical data (factors in R) does not seem as obvious." }, { "code": null, "e": 2994, "s": 2724, "text": "In order to calculate a dissimilarity matrix in this case, you would go for something called Gower distance. I won’t get into the math of it, but I am providing a links here and here. To do that I prefer to use daisy() with metric = c(\"gower\") from the cluster package." }, { "code": null, "e": 4813, "s": 2994, "text": "#----- Dummy Data -----## the data will be sterile clean in order to not get distracted with other issues that might arise, but I will also write about some difficulties I had, outside the codelibrary(dplyr)# ensuring reproducibility for samplingset.seed(40)# generating random variable set# specifying ordered factors, strings will be converted to factors when using data.frame()# customer ids come first, we will generate 200 customer ids from 1 to 200id.s <- c(1:200) %>% factor()budget.s <- sample(c(\"small\", \"med\", \"large\"), 200, replace = T) %>% factor(levels=c(\"small\", \"med\", \"large\"), ordered = TRUE)origins.s <- sample(c(\"x\", \"y\", \"z\"), 200, replace = T, prob = c(0.7, 0.15, 0.15))area.s <- sample(c(\"area1\", \"area2\", \"area3\", \"area4\"), 200, replace = T, prob = c(0.3, 0.1, 0.5, 0.2))source.s <- sample(c(\"facebook\", \"email\", \"link\", \"app\"), 200, replace = T, prob = c(0.1,0.2, 0.3, 0.4))## day of week - probabilities are mocking the demand curvedow.s <- sample(c(\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"), 200, replace = T, prob = c(0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2)) %>% factor(levels=c(\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"), ordered = TRUE)# dish dish.s <- sample(c(\"delicious\", \"the one you don't like\", \"pizza\"), 200, replace = T) # by default, data.frame() will convert all the strings to factorssynthetic.customers <- data.frame(id.s, budget.s, origins.s, area.s, source.s, dow.s, dish.s)#----- Dissimilarity Matrix -----#library(cluster) # to perform different types of hierarchical clustering# package functions used: daisy(), diana(), clusplot()gower.dist <- daisy(synthetic.customers[ ,2:7], metric = c(\"gower\"))# class(gower.dist) ## dissimilarity , dist" }, { "code": null, "e": 4962, "s": 4813, "text": "Done with a dissimilarity matrix. That’s very fast on 200 observations, but can be very computationally expensive in case you have a large data set." }, { "code": null, "e": 5329, "s": 4962, "text": "In reality, it is quite likely that you will have to clean the dataset first, perform the necessary transformations from strings to factors and keep an eye on missing values. In my own case, the dataset contained rows of missing values, which nicely clustered together every time, leading me to assume that I found a treasure until I had a look at the values (meh!)." }, { "code": null, "e": 5633, "s": 5329, "text": "Clustering Algorithms You could have heard that there is k-means and hierarchical clustering. In this post, I focus on the latter as it is a more exploratory type, and it can be approached differently: you could choose to follow either agglomerative (bottom-up) or divisive (top-down) way of clustering." }, { "code": null, "e": 5890, "s": 5633, "text": "Agglomerative clustering will start with n clusters, where n is the number of observations, assuming that each of them is its own separate cluster. Then the algorithm will try to find most similar data points and group them, so they start forming clusters." }, { "code": null, "e": 6062, "s": 5890, "text": "In contrast, divisive clustering will go the other way around β€” assuming all your n data points are one big cluster and dividing most dissimilar ones into separate groups." }, { "code": null, "e": 6317, "s": 6062, "text": "If you are thinking which one of them to use, it is always worth trying all the options, but in general, agglomerative clustering is better in discovering small clusters, and is used by most software; divisive clustering β€” in discovering larger clusters." }, { "code": null, "e": 6556, "s": 6317, "text": "I personally like having a look at dendrograms β€” graphical representation of clustering first to decide which method I will stick to. As you will see below, some of dendrograms will be pretty balanced , while others will look like a mess." }, { "code": null, "e": 7072, "s": 6556, "text": "# The main input for the code below is dissimilarity (distance matrix)# After dissimilarity matrix was calculated, the further steps will be the same for all data types# I prefer to look at the dendrogram and fine the most appealing one first - in this case, I was looking for a more balanced one - to further continue with assessment#------------ DIVISIVE CLUSTERING ------------#divisive.clust <- diana(as.matrix(gower.dist), diss = TRUE, keep.diss = TRUE)plot(divisive.clust, main = \"Divisive\")" }, { "code": null, "e": 7428, "s": 7072, "text": "#------------ AGGLOMERATIVE CLUSTERING ------------## I am looking for the most balanced approach# Complete linkages is the approach that best fits this demand - I will leave only this one here, don't want to get it cluttered# completeaggl.clust.c <- hclust(gower.dist, method = \"complete\")plot(aggl.clust.c, main = \"Agglomerative, complete linkages\")" }, { "code": null, "e": 8208, "s": 7428, "text": "Assessing clusters Here, you will decide between different clustering algorithms and a different number of clusters. As it often happens with assessment, there is more than one way possible, complemented by your own judgement. It’s bold and in italics because your own judgement is important β€” the number of clusters should make practical sense and they way data is divided into groups should make sense too. Working with categorical variables, you might end up with non-sense clusters because the combination of their values is limited β€” they are discrete, so is the number of their combinations. Possibly, you don’t want to have a very small number of clusters either β€” they are likely to be too general. In the end, it all comes to your goal and what you do your analysis for." }, { "code": null, "e": 8687, "s": 8208, "text": "Conceptually, when clusters are created, you are interested in distinctive groups of data points, such that the distance between them within clusters (or compactness) is minimal while the distance between groups (separation) is as large as possible. This is intuitively easy to understand: distance between points is a measure of their dissimilarity derived from dissimilarity matrix. Hence, the assessment of clustering is built around evaluation of compactness and separation." }, { "code": null, "e": 8777, "s": 8687, "text": "I will go for 2 approaches here and show that one of them might produce nonsense results:" }, { "code": null, "e": 8907, "s": 8777, "text": "Elbow method: start with it when the compactness of clusters, or similarities within groups are most important for your analysis." }, { "code": null, "e": 9080, "s": 8907, "text": "Silhouette method: as a measure of data consistency, the silhouette plot displays a measure of how close each point in one cluster is to points in the neighboring clusters." }, { "code": null, "e": 9414, "s": 9080, "text": "In practice, they are very likely to provide different results that might be confusing at a certain pointβ€” different number of clusters will correspond to the most compact / most distinctively separated clusters, so judgement and understanding what your data is actually about will be a significant part of making the final decision." }, { "code": null, "e": 9530, "s": 9414, "text": "There are also a bunch of measurements that you can analyze for your own case. I am adding them to the code itself." }, { "code": null, "e": 11382, "s": 9530, "text": "# Cluster stats comes out as list while it is more convenient to look at it as a table# This code below will produce a dataframe with observations in columns and variables in row# Not quite tidy data, which will require a tweak for plotting, but I prefer this view as an output here as I find it more comprehensive library(fpc)cstats.table <- function(dist, tree, k) {clust.assess <- c(\"cluster.number\",\"n\",\"within.cluster.ss\",\"average.within\",\"average.between\", \"wb.ratio\",\"dunn2\",\"avg.silwidth\")clust.size <- c(\"cluster.size\")stats.names <- c()row.clust <- c()output.stats <- matrix(ncol = k, nrow = length(clust.assess))cluster.sizes <- matrix(ncol = k, nrow = k)for(i in c(1:k)){ row.clust[i] <- paste(\"Cluster-\", i, \" size\")}for(i in c(2:k)){ stats.names[i] <- paste(\"Test\", i-1) for(j in seq_along(clust.assess)){ output.stats[j, i] <- unlist(cluster.stats(d = dist, clustering = cutree(tree, k = i))[clust.assess])[j] } for(d in 1:k) { cluster.sizes[d, i] <- unlist(cluster.stats(d = dist, clustering = cutree(tree, k = i))[clust.size])[d] dim(cluster.sizes[d, i]) <- c(length(cluster.sizes[i]), 1) cluster.sizes[d, i] }}output.stats.df <- data.frame(output.stats)cluster.sizes <- data.frame(cluster.sizes)cluster.sizes[is.na(cluster.sizes)] <- 0rows.all <- c(clust.assess, row.clust)# rownames(output.stats.df) <- clust.assessoutput <- rbind(output.stats.df, cluster.sizes)[ ,-1]colnames(output) <- stats.names[2:k]rownames(output) <- rows.allis.num <- sapply(output, is.numeric)output[is.num] <- lapply(output[is.num], round, 2)output}# I am capping the maximum amout of clusters by 7# I want to choose a reasonable number, based on which I will be able to see basic differences between customer groups as a resultstats.df.divisive <- cstats.table(gower.dist, divisive.clust, 7)stats.df.divisive" }, { "code": null, "e": 11618, "s": 11382, "text": "Look, average.within, which is an average distance among observations within clusters, is shrinking, so does within cluster SS. Average silhouette width is a bit less straightforward, but the reverse relationship is nevertheless there." }, { "code": null, "e": 11931, "s": 11618, "text": "See how disproportional the size of clusters is. I wouldn’t rush into working with incomparable number of observations within clusters. One of the reasons, the dataset can be imbalanced, and some group of observations will outweigh all the rest in the analysis β€” this is not good and is likely to lead to biases." }, { "code": null, "e": 12059, "s": 11931, "text": "stats.df.aggl <-cstats.table(gower.dist, aggl.clust.c, 7) #complete linkages looks like the most balanced approachstats.df.aggl" }, { "code": null, "e": 12193, "s": 12059, "text": "Notice how more balanced agglomerative complete linkages hierarchical clustering is compared on the number of observations per group." }, { "code": null, "e": 12745, "s": 12193, "text": "# --------- Choosing the number of clusters ---------## Using \"Elbow\" and \"Silhouette\" methods to identify the best number of clusters# to better picture the trend, I will go for more than 7 clusters.library(ggplot2)# Elbow# Divisive clusteringggplot(data = data.frame(t(cstats.table(gower.dist, divisive.clust, 15))), aes(x=cluster.number, y=within.cluster.ss)) + geom_point()+ geom_line()+ ggtitle(\"Divisive clustering\") + labs(x = \"Num.of clusters\", y = \"Within clusters sum of squares (SS)\") + theme(plot.title = element_text(hjust = 0.5))" }, { "code": null, "e": 13308, "s": 12745, "text": "So, we’ve produced the β€œelbow” graph. It shows how the within sum of squares β€” as a measure of closeness of observations : the lower it is the closer the observations within the clusters are β€” changes for the different number of clusters. Ideally, we should see a distinctive β€œbend” in the elbow where splitting clusters further gives only minor decrease in the SS. In the case of a graph below, I would go for something around 7. Although in this case, one of a clusters will consist of only 2 observations, let’s see what happens with agglomerative clustering." }, { "code": null, "e": 13679, "s": 13308, "text": "# Agglomerative clustering,provides a more ambiguous pictureggplot(data = data.frame(t(cstats.table(gower.dist, aggl.clust.c, 15))), aes(x=cluster.number, y=within.cluster.ss)) + geom_point()+ geom_line()+ ggtitle(\"Agglomerative clustering\") + labs(x = \"Num.of clusters\", y = \"Within clusters sum of squares (SS)\") + theme(plot.title = element_text(hjust = 0.5))" }, { "code": null, "e": 14027, "s": 13679, "text": "Agglomerative β€œelbow” looks similar to that of divisive, except that agglomerative one looks smoother β€” with β€œbends” being less abrupt. Similarly to divisive clustering, I would go for 7 clusters, but choosing between the two methods, I like the size of the clusters produced by the agglomerative method more β€” I want something comparable in size." }, { "code": null, "e": 14331, "s": 14027, "text": "# Silhouetteggplot(data = data.frame(t(cstats.table(gower.dist, divisive.clust, 15))), aes(x=cluster.number, y=avg.silwidth)) + geom_point()+ geom_line()+ ggtitle(\"Divisive clustering\") + labs(x = \"Num.of clusters\", y = \"Average silhouette width\") + theme(plot.title = element_text(hjust = 0.5))" }, { "code": null, "e": 14541, "s": 14331, "text": "When it comes to silhouette assessment, the rule is you should choose the number that maximizes the silhouette coefficient because you want clusters that are distinctive (far) enough to be considered separate." }, { "code": null, "e": 14663, "s": 14541, "text": "The silhouette coefficient ranges between -1 and 1, with 1 indicating good consistency within clusters, -1 β€” not so good." }, { "code": null, "e": 14745, "s": 14663, "text": "From the plot above, you would not go for 5 clusters β€” you would rather prefer 9." }, { "code": null, "e": 14879, "s": 14745, "text": "As a comparison, for the β€œeasy” case, the silhouette plot is likely to look like the graph below. We are not quite, but almost there." }, { "code": null, "e": 15174, "s": 14879, "text": "ggplot(data = data.frame(t(cstats.table(gower.dist, aggl.clust.c, 15))), aes(x=cluster.number, y=avg.silwidth)) + geom_point()+ geom_line()+ ggtitle(\"Agglomerative clustering\") + labs(x = \"Num.of clusters\", y = \"Average silhouette width\") + theme(plot.title = element_text(hjust = 0.5))" }, { "code": null, "e": 15498, "s": 15174, "text": "What the silhouette width graph above is saying is β€œthe more you break the dataset, the more distinctive the clusters become”. Ultimately, you will end up with individual data points β€” and you don’t want that, and if you try a larger k for the number of clusters β€” you will see it. E.g., at k=30, I got the following graph:" }, { "code": null, "e": 15686, "s": 15498, "text": "So-so: the more you split, the better it gets, but we can’t be splitting till individual data points (remember that we have 30 clusters here in the graph above, and only 200 data points)." }, { "code": null, "e": 15999, "s": 15686, "text": "Summing it all up, agglomerative clustering in this case looks way more balanced to me β€” the cluster sizes are more or less comparable (look at that cluster with just 2 observations in the divisive section!), and I would go for 7 clusters obtained by this method. Let’s see how they look and check what’s inside." }, { "code": null, "e": 16445, "s": 15999, "text": "The dataset consists of 6 variables which need to be visualized in 2D or 3D, so it’s time for a challenge! The nature of categorical data poses some limitations too, so using some pre-defined solutions might get tricky. What I want to a) see how observations are clustered, b) know is how observations are distributed across categories, thus I created a) a colored dendrogram, b) a heatmap of observations count per variable within each cluster." }, { "code": null, "e": 17026, "s": 16445, "text": "library(\"ggplot2\")library(\"reshape2\")library(\"purrr\")library(\"dplyr\")# let's start with a dendrogramlibrary(\"dendextend\")dendro <- as.dendrogram(aggl.clust.c)dendro.col <- dendro %>% set(\"branches_k_color\", k = 7, value = c(\"darkslategray\", \"darkslategray4\", \"darkslategray3\", \"gold3\", \"darkcyan\", \"cyan3\", \"gold3\")) %>% set(\"branches_lwd\", 0.6) %>% set(\"labels_colors\", value = c(\"darkslategray\")) %>% set(\"labels_cex\", 0.5)ggd1 <- as.ggdend(dendro.col)ggplot(ggd1, theme = theme_minimal()) + labs(x = \"Num. observations\", y = \"Height\", title = \"Dendrogram, k = 7\")" }, { "code": null, "e": 17164, "s": 17026, "text": "# Radial plot looks less cluttered (and cooler)ggplot(ggd1, labels = T) + scale_y_reverse(expand = c(0.2, 0)) + coord_polar(theta=\"x\")" }, { "code": null, "e": 19687, "s": 17164, "text": "# Time for the heatmap# the 1st step here is to have 1 variable per row# factors have to be converted to characters in order not to be droppedclust.num <- cutree(aggl.clust.c, k = 7)synthetic.customers.cl <- cbind(synthetic.customers, clust.num)cust.long <- melt(data.frame(lapply(synthetic.customers.cl, as.character), stringsAsFactors=FALSE), id = c(\"id.s\", \"clust.num\"), factorsAsStrings=T)cust.long.q <- cust.long %>% group_by(clust.num, variable, value) %>% mutate(count = n_distinct(id.s)) %>% distinct(clust.num, variable, value, count)# heatmap.c will be suitable in case you want to go for absolute counts - but it doesn't tell much to my tasteheatmap.c <- ggplot(cust.long.q, aes(x = clust.num, y = factor(value, levels = c(\"x\",\"y\",\"z\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\",\"sat\",\"sun\", \"delicious\", \"the one you don't like\", \"pizza\", \"facebook\", \"email\", \"link\", \"app\", \"area1\", \"area2\", \"area3\", \"area4\", \"small\", \"med\", \"large\"), ordered = T))) + geom_tile(aes(fill = count))+ scale_fill_gradient2(low = \"darkslategray1\", mid = \"yellow\", high = \"turquoise4\")# calculating the percent of each factor level in the absolute count of cluster memberscust.long.p <- cust.long.q %>% group_by(clust.num, variable) %>% mutate(perc = count / sum(count)) %>% arrange(clust.num)heatmap.p <- ggplot(cust.long.p, aes(x = clust.num, y = factor(value, levels = c(\"x\",\"y\",\"z\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\",\"sat\", \"sun\", \"delicious\", \"the one you don't like\", \"pizza\", \"facebook\", \"email\", \"link\", \"app\", \"area1\", \"area2\", \"area3\", \"area4\", \"small\", \"med\", \"large\"), ordered = T))) + geom_tile(aes(fill = perc), alpha = 0.85)+ labs(title = \"Distribution of characteristics across clusters\", x = \"Cluster number\", y = NULL) + geom_hline(yintercept = 3.5) + geom_hline(yintercept = 10.5) + geom_hline(yintercept = 13.5) + geom_hline(yintercept = 17.5) + geom_hline(yintercept = 21.5) + scale_fill_gradient2(low = \"darkslategray1\", mid = \"yellow\", high = \"turquoise4\")heatmap.p" }, { "code": null, "e": 20109, "s": 19687, "text": "Having a heatmap, you see the how many observations fall into each factor level within initial factors (variables we’ve started with). The deeper blue corresponds to a higher relative number of observations within a cluster. In this one, you can also see that day of the week / basket size have almost the same amount of customers in each binβ€” it might mean those are not definitive for the analysis and might be omitted." }, { "code": null, "e": 20339, "s": 20109, "text": "Closing noteIn this post, we’ve gone through dissimilarity matrix calculations, trying out agglomerative and divisive hierarchical clustering methods and had a look at cluster assessment with the β€œelbow” and β€œsilhouette” methods." }, { "code": null, "e": 20515, "s": 20339, "text": "In this post, we’ve gone through dissimilarity matrix calculations, trying out agglomerative and divisive hierarchical clustering methods and had a look at cluster assessment." }, { "code": null, "e": 21018, "s": 20515, "text": "Divisive and agglomerative hierarchical clustering are a good place to start exploring, but don’t stop there if your goal is to be a cluster master β€” there are much more methods and techniques popping up out there. In comparison with numerical data clustering, the main difference is hidden in the dissimilarity matrix calculation. From the point of assessment, not all the standard clustering assessment methods will produce reliable and sensible results β€” the silhouette method will likely to be off." }, { "code": null, "e": 21666, "s": 21018, "text": "Lastly, it’s been a while since I did this exercise. By now, I see some drawbacks behind my approach, and I welcome any feedback. One general pitfall of my analysis lies beyond clustering itself β€” my dataset was imbalanced in many ways, which remained unaddressed. I could see the effect it had on clustering: having 70% of customers belonging to one factor level (nationality in this case), this group was dominating most of the resulting clusters, making it hard to figure out differences within other factor levels. Balancing the dataset and comparing cluster results is what I’m going to try next, and will write a separate post to cover that." }, { "code": null, "e": 21773, "s": 21666, "text": "Finally, if you’re up for cloning, here’s the github link: https://github.com/khunreus/cluster-categorical" }, { "code": null, "e": 21798, "s": 21773, "text": "And hope you enjoyed it!" }, { "code": null, "e": 21840, "s": 21798, "text": "Here are the sources that I found useful:" }, { "code": null, "e": 22089, "s": 21840, "text": "Hierarchical clustering tutorial (data preparation, clustering, visualization), overall, this blog might be useful for someone interested in business analytics with R: http://uc-r.github.io/hc_clustering and https://uc-r.github.io/kmeans_clustering" }, { "code": null, "e": 22232, "s": 22089, "text": "Cluster validation: http://www.sthda.com/english/articles/29-cluster-validation-essentials/97-cluster-validation-statistics-must-know-methods/" }, { "code": null, "e": 22393, "s": 22232, "text": "An example of document categorization (hierarchical and k-means): https://eight2late.wordpress.com/2015/07/22/a-gentle-introduction-to-cluster-analysis-using-r/" }, { "code": null, "e": 22593, "s": 22393, "text": "denextend package is rather interesting, allows to compare cluster structure between different methods: https://cran.r-project.org/web/packages/dendextend/vignettes/introduction.html#the-set-function" }, { "code": null, "e": 22756, "s": 22593, "text": "There are not only dendrograms, but also clustergrams: https://www.r-statistics.com/2010/06/clustergram-visualization-and-diagnostics-for-cluster-analysis-r-code/" }, { "code": null, "e": 22879, "s": 22756, "text": "Combining clustering heatmap and a dendrogram: https://jcoliver.github.io/learn-r/008-ggplot-dendrograms-and-heatmaps.html" } ]
Lex program to count the frequency of the given word in a file - GeeksforGeeks
10 Oct, 2021 Problem: Given a text file as input, the task is to count frequency of a given word in the file. Explanation: Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Approach: As we know, yytext holds the value of current matched token, we can compare it with the word whose frequency is to be counted. if the value of yytext and the given word are same, increment the count variable.Input File: input.txt Below is the implementation of above approach: C /* LEX code to count the frequency of the given word in a file */ /* Definition section *//* variable word indicates the word whose frequency is to be count *//* variable count is used to store the frequency of the given word */ %{#include<stdio.h>#include<string.h> char word [] = "geeks";int count = 0; %} /* Rule Section *//* Rule 1 compares the matched token with the word to count and increments the count variable on successful match *//* Rule 2 matches everything other than string (consists of alphabets only ) and do nothing */ %%[a-zA-Z]+ { if(strcmp(yytext, word)==0) count++; }. ; %% int yywrap(){ return 1;} /* code section */int main(){ extern FILE *yyin, *yyout; /* open the input file in read mode */ yyin=fopen("input.txt", "r"); yylex(); printf("%d", count); } Output: ruhelaa48 Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Code Optimization in Compiler Design Intermediate Code Generation in Compiler Design Difference between Top down parsing and Bottom up parsing Loop Optimization in Compiler Design Difference between Compiler and Interpreter Symbol Table in Compiler Input Buffering in Compiler Design Ambiguous Grammar Introduction of Compiler Design Types of Parsers in Compiler Design
[ { "code": null, "e": 24630, "s": 24602, "text": "\n10 Oct, 2021" }, { "code": null, "e": 25222, "s": 24630, "text": "Problem: Given a text file as input, the task is to count frequency of a given word in the file. Explanation: Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Approach: As we know, yytext holds the value of current matched token, we can compare it with the word whose frequency is to be counted. if the value of yytext and the given word are same, increment the count variable.Input File: input.txt " }, { "code": null, "e": 25269, "s": 25222, "text": "Below is the implementation of above approach:" }, { "code": null, "e": 25271, "s": 25269, "text": "C" }, { "code": "/* LEX code to count the frequency of the given word in a file */ /* Definition section *//* variable word indicates the word whose frequency is to be count *//* variable count is used to store the frequency of the given word */ %{#include<stdio.h>#include<string.h> char word [] = \"geeks\";int count = 0; %} /* Rule Section *//* Rule 1 compares the matched token with the word to count and increments the count variable on successful match *//* Rule 2 matches everything other than string (consists of alphabets only ) and do nothing */ %%[a-zA-Z]+ { if(strcmp(yytext, word)==0) count++; }. ; %% int yywrap(){ return 1;} /* code section */int main(){ extern FILE *yyin, *yyout; /* open the input file in read mode */ yyin=fopen(\"input.txt\", \"r\"); yylex(); printf(\"%d\", count); }", "e": 26165, "s": 25271, "text": null }, { "code": null, "e": 26173, "s": 26165, "text": "Output:" }, { "code": null, "e": 26183, "s": 26173, "text": "ruhelaa48" }, { "code": null, "e": 26195, "s": 26183, "text": "Lex program" }, { "code": null, "e": 26211, "s": 26195, "text": "Compiler Design" }, { "code": null, "e": 26309, "s": 26211, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26318, "s": 26309, "text": "Comments" }, { "code": null, "e": 26331, "s": 26318, "text": "Old Comments" }, { "code": null, "e": 26368, "s": 26331, "text": "Code Optimization in Compiler Design" }, { "code": null, "e": 26416, "s": 26368, "text": "Intermediate Code Generation in Compiler Design" }, { "code": null, "e": 26474, "s": 26416, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 26511, "s": 26474, "text": "Loop Optimization in Compiler Design" }, { "code": null, "e": 26555, "s": 26511, "text": "Difference between Compiler and Interpreter" }, { "code": null, "e": 26580, "s": 26555, "text": "Symbol Table in Compiler" }, { "code": null, "e": 26615, "s": 26580, "text": "Input Buffering in Compiler Design" }, { "code": null, "e": 26633, "s": 26615, "text": "Ambiguous Grammar" }, { "code": null, "e": 26665, "s": 26633, "text": "Introduction of Compiler Design" } ]
Association, Composition and Aggregation in Java
Association refers to the relationship between multiple objects. It refers to how objects are related to each other and how they are using each other's functionality. Composition and aggregation are two types of association. The composition is the strong type of association. An association is said to composition if an Object owns another object and another object cannot exist without the owner object. Consider the case of Human having a heart. Here Human object contains the heart and heart cannot exist without Human. Aggregation is a weak association. An association is said to be aggregation if both Objects can exist independently. For example, a Team object and a Player object. The team contains multiple players but a player can exist without a team. //Car must have Engine public class Car { //engine is a mandatory part of the car private final Engine engine; public Car () { engine = new Engine(); } } //Engine Object class Engine {} //Team public class Team { //players can be 0 or more private List players; public Car () { players = new ArrayList(); } } //Player Object class Player {}
[ { "code": null, "e": 1287, "s": 1062, "text": "Association refers to the relationship between multiple objects. It refers to how objects are related to each other and how they are using each other's functionality. Composition and aggregation are two types of association." }, { "code": null, "e": 1585, "s": 1287, "text": "The composition is the strong type of association. An association is said to composition if an Object owns another object and another object cannot exist without the owner object. Consider the case of Human having a heart. Here Human object contains the heart and heart cannot exist without Human." }, { "code": null, "e": 1824, "s": 1585, "text": "Aggregation is a weak association. An association is said to be aggregation if both Objects can exist independently. For example, a Team object and a Player object. The team contains multiple players but a player can exist without a team." }, { "code": null, "e": 2030, "s": 1824, "text": "//Car must have Engine\npublic class Car {\n //engine is a mandatory part of the car\n private final Engine engine;\n\n public Car () {\n engine = new Engine();\n }\n}\n\n//Engine Object\nclass Engine {}" }, { "code": null, "e": 2210, "s": 2030, "text": "//Team\npublic class Team { \n //players can be 0 or more\n private List players;\n\n public Car () {\n players = new ArrayList();\n }\n}\n//Player Object\nclass Player {}" } ]
Mathematics | Generalized PnC Set 1
15 Dec, 2021 Prerequisite – PnC and Binomial Coefficients So far every problem discussed in previous articles has had sets of distinct elements, but sometimes problems may involve repeated use of elements. This article covers such problems, where elements of the set are indistinguishable (or identical or not distinct). Permutations with repetition –Counting permutations when repetition of elements can be easily done using the product rule. Example, number of strings of length is , since for every character there are 26 possibilities. The number of -permutations of a set of objects with repetition is . Combinations with repetition –Counting the number of combinations with repetition is a bit more complicated than counting permutations. Consider a set of types of objects and we need to find out in how many ways can elements be chosen. To solve the above problem we will first take a look at a similar problem that is arranging bars(|) and stars(*). Suppose there are 5 bars and 3 stars. One possible arrangement is – ||*||**| They can be arranged in ways. Our original problem is similar to the above problem. The bars represent divisions between the types of elements such that each type is separated by a bar and the number of stars is . If a star is before the nth bar, then that means an item of nth type is selected, except for the last type where the star can be after a bar. For example, the arrangement mentioned above, ||*||**|, represents a selection of 1 element of 3rd type and 2 elements of 5th type. In this way our original problem can be thought of as arranging stars (elements) and bars(divisions). The above result can be generalized as- There are -combinations from a set with elements when repetition is allowed. Example 1 – In how many ways can 4 drinks can be chosen out of 6 possible types of drinks? There is no restriction on the number of drinks of a type that can be chosen and drinks of the same type are indistinguishable. Solution – The above scenario is a direct application of finding combinations with repetition. So the number of 4-combinations is – . Example 2 – How many solutions does the equation have, where are non-negative integers? Solution – can have values ranging from 0 to 11. This situation is analogous to finding 11-combinations of 3 types of objects. So number of solutions is – Example 3 – Consider the same question as Example 2 but with the additional constraint that . Solution – Since the minimum value of is 1, the effective equation becomes . So the number of solutions is- Example 4 – Consider the same question as Example 2 but with the additional constraint that . Solution – Since the constraint is not a lower limit but an upper limit, it cannot be solved in the same way as in Example 3. There is another way of solving such problems. For each type of object we assign a polynomial of the form – , where β€˜ll’ and β€˜ul’ are the lower and upper limits for that type of object. Then all such polynomials are multiplied and the coefficient of is the number of -combinations. In our case, there is a constraint only on . Its polynomial therefore is- Polynomial for and is- Since multiplying polynomials can be tedious, we use a trick which uses the binomial theorem. The above polynomial can be extended to be an infinite series since the higher order terms won’t make any difference as we are only looking for the coefficient of . So the polynomial for and is- The above polynomial is also the expansion for . On multiplying the polynomials we get- can be expanded through binomial theorem for negative exponents. We won’t need to expand the complete polynomial, as we just need the terms and , because they will be multiplied by 1 and to get terms of . . For [Tex]k=10 [/Tex], we get- For [Tex]k=11 [/Tex], we get- On multiplying the above obtained terms with and 1 we get terms of . On adding them up we get-. Therefore there are 23 solutions to the given equation. Example 5 – Consider the same question as in Example-2 but with an inequality i.e. . Solution – We could solve this problem in 2 ways. One way is to add up all -combinations for values of starting from 0 upto 11 i.e. for . We get the following values- For = 0, ways = C(3-1+0,2) = C(2,2) = 1 For = 1, ways = C(3-1+1,2) = C(3,2) = 3 For = 2, ways = C(3-1+2,2) = C(4,2) = 6 For = 3, ways = C(3-1+3,2) = C(5,2) = 10 For = 4, ways = C(3-1+4,2) = C(6,2) = 15 For = 5, ways = C(3-1+5,2) = C(7,2) = 21 For = 6, ways = C(3-1+6,2) = C(8,2) = 28 For = 7, ways = C(3-1+7,2) = C(9,2) = 36 For = 8, ways = C(3-1+8,2) = C(10,2) = 45 For = 9, ways = C(3-1+9,2) = C(11,2) = 55 For = 10, ways = C(3-1+10,2) = C(12,2) = 66 For = 11, ways = C(3-1+11,2) = C(13,2) = 78 Total number of solutions = 364 The above problem is the same as finding the number of solutions for the equation- The extra variable can be thought of as the difference of 11 and . When is 0, is 11. So takes values accordingly. And the number of solutions of this equation is – C(4-1+11,4-1) = C(14,3) = 364. References –Permutations and Combinations Discrete Mathematics and its Applications, by Kenneth H Rosen This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ManasChhabra2 binomial coefficient Discrete Mathematics Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inequalities in LaTeX Difference between Propositional Logic and Predicate Logic Arrow Symbols in LaTeX Set Notations in LaTeX Activation Functions Mutual exclusion in distributed system Three address code in Compiler S - attributed and L - attributed SDTs in Syntax directed translation Types of Operating Systems Code Optimization in Compiler Design
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Dec, 2021" }, { "code": null, "e": 100, "s": 54, "text": "Prerequisite – PnC and Binomial Coefficients " }, { "code": null, "e": 364, "s": 100, "text": "So far every problem discussed in previous articles has had sets of distinct elements, but sometimes problems may involve repeated use of elements. This article covers such problems, where elements of the set are indistinguishable (or identical or not distinct). " }, { "code": null, "e": 584, "s": 364, "text": "Permutations with repetition –Counting permutations when repetition of elements can be easily done using the product rule. Example, number of strings of length is , since for every character there are 26 possibilities. " }, { "code": null, "e": 656, "s": 584, "text": "The number of -permutations of a set of objects \n\nwith repetition is ." }, { "code": null, "e": 1076, "s": 656, "text": "Combinations with repetition –Counting the number of combinations with repetition is a bit more complicated than counting permutations. Consider a set of types of objects and we need to find out in how many ways can elements be chosen. To solve the above problem we will first take a look at a similar problem that is arranging bars(|) and stars(*). Suppose there are 5 bars and 3 stars. One possible arrangement is – " }, { "code": null, "e": 1085, "s": 1076, "text": "||*||**|" }, { "code": null, "e": 1717, "s": 1085, "text": "They can be arranged in ways. Our original problem is similar to the above problem. The bars represent divisions between the types of elements such that each type is separated by a bar and the number of stars is . If a star is before the nth bar, then that means an item of nth type is selected, except for the last type where the star can be after a bar. For example, the arrangement mentioned above, ||*||**|, represents a selection of 1 element of 3rd type and 2 elements of 5th type. In this way our original problem can be thought of as arranging stars (elements) and bars(divisions). The above result can be generalized as- " }, { "code": null, "e": 1799, "s": 1717, "text": "There are \n\n-combinations from a set with \n\nelements when repetition is allowed." }, { "code": null, "e": 2020, "s": 1799, "text": "Example 1 – In how many ways can 4 drinks can be chosen out of 6 possible types of drinks? There is no restriction on the number of drinks of a type that can be chosen and drinks of the same type are indistinguishable. " }, { "code": null, "e": 2156, "s": 2020, "text": "Solution – The above scenario is a direct application of finding combinations with repetition. So the number of 4-combinations is – . " }, { "code": null, "e": 2246, "s": 2156, "text": "Example 2 – How many solutions does the equation have, where are non-negative integers? " }, { "code": null, "e": 2402, "s": 2246, "text": "Solution – can have values ranging from 0 to 11. This situation is analogous to finding 11-combinations of 3 types of objects. So number of solutions is – " }, { "code": null, "e": 2500, "s": 2404, "text": "Example 3 – Consider the same question as Example 2 but with the additional constraint that . " }, { "code": null, "e": 2610, "s": 2500, "text": "Solution – Since the minimum value of is 1, the effective equation becomes . So the number of solutions is- " }, { "code": null, "e": 2706, "s": 2610, "text": "Example 4 – Consider the same question as Example 2 but with the additional constraint that . " }, { "code": null, "e": 4011, "s": 2706, "text": "Solution – Since the constraint is not a lower limit but an upper limit, it cannot be solved in the same way as in Example 3. There is another way of solving such problems. For each type of object we assign a polynomial of the form – , where β€˜ll’ and β€˜ul’ are the lower and upper limits for that type of object. Then all such polynomials are multiplied and the coefficient of is the number of -combinations. In our case, there is a constraint only on . Its polynomial therefore is- Polynomial for and is- Since multiplying polynomials can be tedious, we use a trick which uses the binomial theorem. The above polynomial can be extended to be an infinite series since the higher order terms won’t make any difference as we are only looking for the coefficient of . So the polynomial for and is- The above polynomial is also the expansion for . On multiplying the polynomials we get- can be expanded through binomial theorem for negative exponents. We won’t need to expand the complete polynomial, as we just need the terms and , because they will be multiplied by 1 and to get terms of . . For [Tex]k=10 [/Tex], we get- For [Tex]k=11 [/Tex], we get- On multiplying the above obtained terms with and 1 we get terms of . On adding them up we get-. Therefore there are 23 solutions to the given equation. " }, { "code": null, "e": 4098, "s": 4011, "text": "Example 5 – Consider the same question as in Example-2 but with an inequality i.e. . " }, { "code": null, "e": 5074, "s": 4098, "text": "Solution – We could solve this problem in 2 ways. One way is to add up all -combinations for values of starting from 0 upto 11 i.e. for . We get the following values- For = 0, ways = C(3-1+0,2) = C(2,2) = 1 For = 1, ways = C(3-1+1,2) = C(3,2) = 3 For = 2, ways = C(3-1+2,2) = C(4,2) = 6 For = 3, ways = C(3-1+3,2) = C(5,2) = 10 For = 4, ways = C(3-1+4,2) = C(6,2) = 15 For = 5, ways = C(3-1+5,2) = C(7,2) = 21 For = 6, ways = C(3-1+6,2) = C(8,2) = 28 For = 7, ways = C(3-1+7,2) = C(9,2) = 36 For = 8, ways = C(3-1+8,2) = C(10,2) = 45 For = 9, ways = C(3-1+9,2) = C(11,2) = 55 For = 10, ways = C(3-1+10,2) = C(12,2) = 66 For = 11, ways = C(3-1+11,2) = C(13,2) = 78 Total number of solutions = 364 The above problem is the same as finding the number of solutions for the equation- The extra variable can be thought of as the difference of 11 and . When is 0, is 11. So takes values accordingly. And the number of solutions of this equation is – C(4-1+11,4-1) = C(14,3) = 364. " }, { "code": null, "e": 5601, "s": 5074, "text": "References –Permutations and Combinations Discrete Mathematics and its Applications, by Kenneth H Rosen This article is contributed by Chirag Manwani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5615, "s": 5601, "text": "ManasChhabra2" }, { "code": null, "e": 5636, "s": 5615, "text": "binomial coefficient" }, { "code": null, "e": 5657, "s": 5636, "text": "Discrete Mathematics" }, { "code": null, "e": 5681, "s": 5657, "text": "Engineering Mathematics" }, { "code": null, "e": 5689, "s": 5681, "text": "GATE CS" }, { "code": null, "e": 5787, "s": 5689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5809, "s": 5787, "text": "Inequalities in LaTeX" }, { "code": null, "e": 5868, "s": 5809, "text": "Difference between Propositional Logic and Predicate Logic" }, { "code": null, "e": 5891, "s": 5868, "text": "Arrow Symbols in LaTeX" }, { "code": null, "e": 5914, "s": 5891, "text": "Set Notations in LaTeX" }, { "code": null, "e": 5935, "s": 5914, "text": "Activation Functions" }, { "code": null, "e": 5974, "s": 5935, "text": "Mutual exclusion in distributed system" }, { "code": null, "e": 6005, "s": 5974, "text": "Three address code in Compiler" }, { "code": null, "e": 6075, "s": 6005, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 6102, "s": 6075, "text": "Types of Operating Systems" } ]
numpy.diff() in Python
22 Jul, 2021 numpy.diff(arr[, n[, axis]]) function is used when we calculate the n-th order discrete difference along the given axis. The first order difference is given by out[i] = arr[i+1] – arr[i] along the given axis. If we have to calculate higher differences, we are using diff recursively. Syntax: numpy.diff()Parameters: arr : [array_like] Input array. n : [int, optional] The number of times values are differenced. axis : [int, optional] The axis along which the difference is taken, default is the last axis.Returns : [ndarray]The n-th discrete difference. The output is the same as a except along axis where the dimension is smaller by n. Code #1 : Python3 # Python program explaining# numpy.diff() method # importing numpyimport numpy as geek # input arrayarr = geek.array([1, 3, 4, 7, 9]) print("Input array : ", arr)print("First order difference : ", geek.diff(arr))print("Second order difference : ", geek.diff(arr, n = 2))print("Third order difference : ", geek.diff(arr, n = 3)) Input array : [1 3 4 7 9] First order difference : [2 1 3 2] Second order difference : [-1 2 -1] Third order difference : [ 3 -3] Code #2 : Python3 # Python program explaining# numpy.diff() method # importing numpyimport numpy as geek # input arrayarr = geek.array([[1, 2, 3, 5], [4, 6, 7, 9]]) print("Input array : ", arr)print("Difference when axis is 0 : ", geek.diff(arr, axis = 0))print("Difference when axis is 1 : ", geek.diff(arr, axis = 1)) Input array : [[1 2 3 5] [4 6 7 9]] Difference with axis 0 : [[3 4 4 4]] Difference with axis 1 : [[1 1 2] [2 1 2]] sumitgumber28 Python-numpy Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2021" }, { "code": null, "e": 312, "s": 28, "text": "numpy.diff(arr[, n[, axis]]) function is used when we calculate the n-th order discrete difference along the given axis. The first order difference is given by out[i] = arr[i+1] – arr[i] along the given axis. If we have to calculate higher differences, we are using diff recursively." }, { "code": null, "e": 668, "s": 312, "text": "Syntax: numpy.diff()Parameters: arr : [array_like] Input array. n : [int, optional] The number of times values are differenced. axis : [int, optional] The axis along which the difference is taken, default is the last axis.Returns : [ndarray]The n-th discrete difference. The output is the same as a except along axis where the dimension is smaller by n. " }, { "code": null, "e": 680, "s": 668, "text": "Code #1 : " }, { "code": null, "e": 688, "s": 680, "text": "Python3" }, { "code": "# Python program explaining# numpy.diff() method # importing numpyimport numpy as geek # input arrayarr = geek.array([1, 3, 4, 7, 9]) print(\"Input array : \", arr)print(\"First order difference : \", geek.diff(arr))print(\"Second order difference : \", geek.diff(arr, n = 2))print(\"Third order difference : \", geek.diff(arr, n = 3))", "e": 1023, "s": 688, "text": null }, { "code": null, "e": 1161, "s": 1023, "text": "Input array : [1 3 4 7 9]\nFirst order difference : [2 1 3 2]\nSecond order difference : [-1 2 -1]\nThird order difference : [ 3 -3]" }, { "code": null, "e": 1176, "s": 1163, "text": " Code #2 : " }, { "code": null, "e": 1184, "s": 1176, "text": "Python3" }, { "code": "# Python program explaining# numpy.diff() method # importing numpyimport numpy as geek # input arrayarr = geek.array([[1, 2, 3, 5], [4, 6, 7, 9]]) print(\"Input array : \", arr)print(\"Difference when axis is 0 : \", geek.diff(arr, axis = 0))print(\"Difference when axis is 1 : \", geek.diff(arr, axis = 1))", "e": 1491, "s": 1184, "text": null }, { "code": null, "e": 1613, "s": 1491, "text": "Input array : [[1 2 3 5]\n [4 6 7 9]]\nDifference with axis 0 : [[3 4 4 4]]\nDifference with axis 1 : [[1 1 2]\n [2 1 2]]" }, { "code": null, "e": 1629, "s": 1615, "text": "sumitgumber28" }, { "code": null, "e": 1642, "s": 1629, "text": "Python-numpy" }, { "code": null, "e": 1658, "s": 1642, "text": "Python Programs" } ]
Java - Logical Operators Example
The following simple example program demonstrates the logical operators. Copy and paste the following Java program in Test.java file and compile and run this program βˆ’ public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println("a && b = " + (a&&b)); System.out.println("a || b = " + (a||b) ); System.out.println("!(a && b) = " + !(a && b)); } } This will produce the following result βˆ’ a && b = false a || b = true !(a && b) = true
[ { "code": null, "e": 2679, "s": 2511, "text": "The following simple example program demonstrates the logical operators. Copy and paste the following Java program in Test.java file and compile and run this program βˆ’" }, { "code": null, "e": 2952, "s": 2679, "text": "public class Test {\n\n public static void main(String args[]) {\n boolean a = true;\n boolean b = false;\n\n System.out.println(\"a && b = \" + (a&&b));\n System.out.println(\"a || b = \" + (a||b) );\n System.out.println(\"!(a && b) = \" + !(a && b));\n }\n}" }, { "code": null, "e": 2993, "s": 2952, "text": "This will produce the following result βˆ’" } ]
Getting the Determinant of the Matrix in R Programming – det() Function
03 Jun, 2020 det() function in R Language is used to calculate the determinant of the specified matrix. Syntax: det(x, ...) Parameters:x: matrix Example 1: # R program to illustrate# det function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(c(3, 2, 6, -1, 7, 3, 2, 6, -1), 3, 3) # Getting the matrix representationx # Calling the det() functiondet(x) Output: [, 1] [, 2] [, 3] [1, ] 3 -1 2 [2, ] 2 7 6 [3, ] 6 3 -1 [1] -185 Example 2: # R program to illustrate# det function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(c(3, 2, 6, -1, 7, 3, 2, 6, -1), 3, 3) # Getting the matrix representationx # Getting the transpose of the matrix xy <- t(x)y # Calling the det() functiondet(y) Output: [, 1] [, 2] [, 3] [1, ] 3 -1 2 [2, ] 2 7 6 [3, ] 6 3 -1 [, 1] [, 2] [, 3] [1, ] 3 2 6 [2, ] -1 7 3 [3, ] 2 6 -1 [1] -185 R Matrix-Function R Language 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 Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2020" }, { "code": null, "e": 119, "s": 28, "text": "det() function in R Language is used to calculate the determinant of the specified matrix." }, { "code": null, "e": 139, "s": 119, "text": "Syntax: det(x, ...)" }, { "code": null, "e": 160, "s": 139, "text": "Parameters:x: matrix" }, { "code": null, "e": 171, "s": 160, "text": "Example 1:" }, { "code": "# R program to illustrate# det function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(c(3, 2, 6, -1, 7, 3, 2, 6, -1), 3, 3) # Getting the matrix representationx # Calling the det() functiondet(x)", "e": 386, "s": 171, "text": null }, { "code": null, "e": 394, "s": 386, "text": "Output:" }, { "code": null, "e": 491, "s": 394, "text": " [, 1] [, 2] [, 3]\n[1, ] 3 -1 2\n[2, ] 2 7 6\n[3, ] 6 3 -1\n\n[1] -185\n" }, { "code": null, "e": 502, "s": 491, "text": "Example 2:" }, { "code": "# R program to illustrate# det function # Initializing a matrix with# 3 rows and 3 columnsx <- matrix(c(3, 2, 6, -1, 7, 3, 2, 6, -1), 3, 3) # Getting the matrix representationx # Getting the transpose of the matrix xy <- t(x)y # Calling the det() functiondet(y)", "e": 768, "s": 502, "text": null }, { "code": null, "e": 776, "s": 768, "text": "Output:" }, { "code": null, "e": 960, "s": 776, "text": " [, 1] [, 2] [, 3]\n[1, ] 3 -1 2\n[2, ] 2 7 6\n[3, ] 6 3 -1\n\n [, 1] [, 2] [, 3]\n[1, ] 3 2 6\n[2, ] -1 7 3\n[3, ] 2 6 -1\n\n[1] -185\n" }, { "code": null, "e": 978, "s": 960, "text": "R Matrix-Function" }, { "code": null, "e": 989, "s": 978, "text": "R Language" }, { "code": null, "e": 1087, "s": 989, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1139, "s": 1087, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1191, "s": 1139, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1249, "s": 1191, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1281, "s": 1249, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1316, "s": 1281, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1360, "s": 1316, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1398, "s": 1360, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1447, "s": 1398, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 1464, "s": 1447, "text": "R - if statement" } ]
How to align header with wrapper in Bootstrap ?
30 Jun, 2020 An HTML wrapper permits you to center header, content, and footer inside a webpage. Headers could be very fancy. Using CSS or bootstrap in a creative way can give you with a sidebar, or two-column look to your active website pages. Syntax: <div class="wrapper"> content... </div> Example: HTML <!DOCTYPE html><html lang="en"> <head> <title> How to align header with wrapper in Bootstrap? </title> <style type="text/css"> .wrapper { width: 500px; margin: 0 auto; } </style></head> <body> <div class="wrapper"> <h1 style="color: green"> GeeksforGeeks </h1> Piece of text inside a 500px width div centered on the page </div></body> </html> Output: How this works: Create a wrapper and assign it a certain width. Apply an automatic horizontal margin to it by using margin: auto or margin-left: auto or margin-right: auto property. Make sure your content will be centered. There are three methods to align header with wrapper that are discussed below: Method 1: Align header with the wrapper in CSS. HTML <!DOCTYPE html><html lang="en"> <head> <title> Bootstrap 4 Align Header with Wrapper </title> <style type="text/css"> /* Fit the body to the edges of the screen */ body { margin: 0; padding: 0; } nav { width: 100%; background: lightgreen; font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: black !important; font-family: tahoma; padding: 0; margin: 0; } /* The centered wrapper, all other content divs will go interior and this will never surpass the width of 960px. */ .wrapper { width: 960px; max-width: 100%; margin: 0 auto; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; } li { float: right; } li a { display: block; color: black; text-align: center; padding: 14px 16px; text-decoration: none; } </style></head> <body> <header> <nav> <div class="wrapper"> <ul> <li><a href="#contact"> Contact </a></li> <li><a href="#about"> About </a></li> <li><a class="active" href="#home">Home </a></li> </ul> </div> </nav> </header> <center> <h1 style="color: green"> GeeksforGeeks </h1> </center></body> </html> Method 2: Align header with wrapper in Bootstrap 4. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title> Bootstrap 4 Align Header with Wrapper </title> <style type="text/css"> html, body { height: 100%; margin: 0; } .wrapper { min-height: 100%; width: 300px; margin: 0 auto; margin-bottom: -50px; } .push { height: 50px; } .navbar a { font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: black !important; } </style></head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light border-top border-bottom border-dark"> <div class="wrapper"> <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="navbarSupportedContent" style=""> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only"> (current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contact </a> </li> </ul> </div> <div class="push"></div> </div> </nav> </header> <center> <h1 style="color: green"> GeeksforGeeks </h1> </center></body> </html> Note: A β€œwrapper” encapsulates all other visual components on the page. The most straightforward way is to have a β€œwrapper” div part with a width along with left and right auto-edges. Negative edges can also be used for horizontal and vertical centering. But it comes with its own drawbacks like, if the window browser will be resized, the content cannot be seen any longer. Method 3: Align header with flexbox in Bootstrap 4. In the following example, CSS β€œFlexbox” within the nav is used to center the content. HTML <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"> </script> <title> Bootstrap 4 Align header with wrapper </title> <style type="text/css"> .navbar { display: flex; justify-content: space-between; } .navbar-collapse { flex-grow: 0; } .navbar-expand-lg .navbar-collapse { justify-content: flex-end; } .flex-mobile-nav { display: flex; justify-content: space-between; width: 100%; } .nav-container-nav { max-width: 1024px; margin: 0 auto; width: 100%; display: flex; } .navbar a { font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: black !important; } </style></head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light border-top border-bottom border-dark"> <div class="nav-container-nav"> <div class="flex-mobile-nav"> <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> </div> <div class="navbar-collapse collapse" id="navbarSupportedContent" style=""> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#"> Home <span class="sr-only"> (current) </span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> About </a> </li> <li class="nav-item"> <a class="nav-link" href="#"> Contact </a> </li> </ul> </div> </div> </nav> </header> <center> <h1 style="color: green"><br> GeeksforGeeks </h1> </center></body> </html> Difference between wrapper and container: In programming languages, the word container is used for structures that can contain more than one part. A wrapper is something that wraps around a single object to give a better flexible interface. Bootstrap-Misc CSS-Misc HTML-Misc Picked Bootstrap CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to Use Bootstrap with React? How to set vertical alignment in Bootstrap ? Tailwind CSS vs Bootstrap How to toggle password visibility in forms using Bootstrap-icons ? How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 260, "s": 28, "text": "An HTML wrapper permits you to center header, content, and footer inside a webpage. Headers could be very fancy. Using CSS or bootstrap in a creative way can give you with a sidebar, or two-column look to your active website pages." }, { "code": null, "e": 268, "s": 260, "text": "Syntax:" }, { "code": null, "e": 312, "s": 268, "text": "<div class=\"wrapper\">\n content...\n</div>" }, { "code": null, "e": 321, "s": 312, "text": "Example:" }, { "code": null, "e": 326, "s": 321, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to align header with wrapper in Bootstrap? </title> <style type=\"text/css\"> .wrapper { width: 500px; margin: 0 auto; } </style></head> <body> <div class=\"wrapper\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> Piece of text inside a 500px width div centered on the page </div></body> </html>", "e": 783, "s": 326, "text": null }, { "code": null, "e": 791, "s": 783, "text": "Output:" }, { "code": null, "e": 1014, "s": 791, "text": "How this works: Create a wrapper and assign it a certain width. Apply an automatic horizontal margin to it by using margin: auto or margin-left: auto or margin-right: auto property. Make sure your content will be centered." }, { "code": null, "e": 1093, "s": 1014, "text": "There are three methods to align header with wrapper that are discussed below:" }, { "code": null, "e": 1141, "s": 1093, "text": "Method 1: Align header with the wrapper in CSS." }, { "code": null, "e": 1146, "s": 1141, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> Bootstrap 4 Align Header with Wrapper </title> <style type=\"text/css\"> /* Fit the body to the edges of the screen */ body { margin: 0; padding: 0; } nav { width: 100%; background: lightgreen; font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: black !important; font-family: tahoma; padding: 0; margin: 0; } /* The centered wrapper, all other content divs will go interior and this will never surpass the width of 960px. */ .wrapper { width: 960px; max-width: 100%; margin: 0 auto; } ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; } li { float: right; } li a { display: block; color: black; text-align: center; padding: 14px 16px; text-decoration: none; } </style></head> <body> <header> <nav> <div class=\"wrapper\"> <ul> <li><a href=\"#contact\"> Contact </a></li> <li><a href=\"#about\"> About </a></li> <li><a class=\"active\" href=\"#home\">Home </a></li> </ul> </div> </nav> </header> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> </center></body> </html>", "e": 2950, "s": 1146, "text": null }, { "code": null, "e": 3002, "s": 2950, "text": "Method 2: Align header with wrapper in Bootstrap 4." }, { "code": null, "e": 3007, "s": 3002, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title> Bootstrap 4 Align Header with Wrapper </title> <style type=\"text/css\"> html, body { height: 100%; margin: 0; } .wrapper { min-height: 100%; width: 300px; margin: 0 auto; margin-bottom: -50px; } .push { height: 50px; } .navbar a { font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: black !important; } </style></head> <body> <header> <nav class=\"navbar navbar-expand-lg navbar-light bg-light border-top border-bottom border-dark\"> <div class=\"wrapper\"> <button class=\"navbar-toggler collapsed\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> <div class=\"navbar-collapse collapse\" id=\"navbarSupportedContent\" style=\"\"> <ul class=\"navbar-nav\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home <span class=\"sr-only\"> (current) </span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contact </a> </li> </ul> </div> <div class=\"push\"></div> </div> </nav> </header> <center> <h1 style=\"color: green\"> GeeksforGeeks </h1> </center></body> </html>", "e": 5917, "s": 3007, "text": null }, { "code": null, "e": 6292, "s": 5917, "text": "Note: A β€œwrapper” encapsulates all other visual components on the page. The most straightforward way is to have a β€œwrapper” div part with a width along with left and right auto-edges. Negative edges can also be used for horizontal and vertical centering. But it comes with its own drawbacks like, if the window browser will be resized, the content cannot be seen any longer." }, { "code": null, "e": 6430, "s": 6292, "text": "Method 3: Align header with flexbox in Bootstrap 4. In the following example, CSS β€œFlexbox” within the nav is used to center the content." }, { "code": null, "e": 6435, "s": 6430, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- Required meta tags --> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1, shrink-to-fit=no\"> <!-- Bootstrap CSS --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js\" integrity=\"sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js\" integrity=\"sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI\" crossorigin=\"anonymous\"> </script> <title> Bootstrap 4 Align header with wrapper </title> <style type=\"text/css\"> .navbar { display: flex; justify-content: space-between; } .navbar-collapse { flex-grow: 0; } .navbar-expand-lg .navbar-collapse { justify-content: flex-end; } .flex-mobile-nav { display: flex; justify-content: space-between; width: 100%; } .nav-container-nav { max-width: 1024px; margin: 0 auto; width: 100%; display: flex; } .navbar a { font-size: 1.1rem !important; font-weight: bold; text-transform: uppercase !important; color: black !important; } </style></head> <body> <header> <nav class=\"navbar navbar-expand-lg navbar-light bg-light border-top border-bottom border-dark\"> <div class=\"nav-container-nav\"> <div class=\"flex-mobile-nav\"> <button class=\"navbar-toggler collapsed\" type=\"button\" data-toggle=\"collapse\" data-target=\"#navbarSupportedContent\" aria-controls=\"navbarSupportedContent\" aria-expanded=\"false\" aria-label=\"Toggle navigation\"> <span class=\"navbar-toggler-icon\"></span> </button> </div> <div class=\"navbar-collapse collapse\" id=\"navbarSupportedContent\" style=\"\"> <ul class=\"navbar-nav\"> <li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\"> Home <span class=\"sr-only\"> (current) </span> </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> About </a> </li> <li class=\"nav-item\"> <a class=\"nav-link\" href=\"#\"> Contact </a> </li> </ul> </div> </div> </nav> </header> <center> <h1 style=\"color: green\"><br> GeeksforGeeks </h1> </center></body> </html>", "e": 9654, "s": 6435, "text": null }, { "code": null, "e": 9895, "s": 9654, "text": "Difference between wrapper and container: In programming languages, the word container is used for structures that can contain more than one part. A wrapper is something that wraps around a single object to give a better flexible interface." }, { "code": null, "e": 9910, "s": 9895, "text": "Bootstrap-Misc" }, { "code": null, "e": 9919, "s": 9910, "text": "CSS-Misc" }, { "code": null, "e": 9929, "s": 9919, "text": "HTML-Misc" }, { "code": null, "e": 9936, "s": 9929, "text": "Picked" }, { "code": null, "e": 9946, "s": 9936, "text": "Bootstrap" }, { "code": null, "e": 9950, "s": 9946, "text": "CSS" }, { "code": null, "e": 9955, "s": 9950, "text": "HTML" }, { "code": null, "e": 9972, "s": 9955, "text": "Web Technologies" }, { "code": null, "e": 9999, "s": 9972, "text": "Web technologies Questions" }, { "code": null, "e": 10004, "s": 9999, "text": "HTML" }, { "code": null, "e": 10102, "s": 10004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10143, "s": 10102, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 10176, "s": 10143, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 10221, "s": 10176, "text": "How to set vertical alignment in Bootstrap ?" }, { "code": null, "e": 10247, "s": 10221, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 10314, "s": 10247, "text": "How to toggle password visibility in forms using Bootstrap-icons ?" }, { "code": null, "e": 10362, "s": 10314, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 10424, "s": 10362, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 10474, "s": 10424, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 10532, "s": 10474, "text": "How to create footer to stay at the bottom of a Web page?" } ]
Remove elements from a List that satisfy given predicate in Java
01 Nov, 2020 Below are the methods to efficiently remove elements from a List satisfying a Predicate condition: p ==> Predicate, specifying the condition l ==> List, from which element to be removed Below program demonstrates the removal of null elements from the list, using the Predicate Java // Java Program to remove nulls// from a List using iterator and Predicateimport java.util.function.Predicate;import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> l, Predicate<T> p) { // Create an iterator from the l Iterator<T> itr = l.iterator(); // Find and remove all null while (itr.hasNext()) { // Fetching the next element T t = itr.next(); // Checking for Predicate condition if (!p.test(t)) { // If the condition matches, // remove that element itr.remove(); } } // Return the null return l; } public static void main(String[] args) { // Create the l with null values List<String> l = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("List with null values: " + l); // Creating a Predicate condition checking for null Predicate<String> isNull = item -> Objects.nonNull(item); // Removing nulls using iterator and Predicate l = removeNullUsingIterator(l, isNull); // Print the list System.out.println("List with null values removed: " + l); }} List with null values: [Geeks, null, forGeeks, null, A computer portal] List with null values removed: [Geeks, forGeeks, A computer portal] In this method, a collection containing elements to be removed is used to remove those elements from the original l. It requires creating a collection with the required elements using a Predicate condition. After doing this, the original l is searched for this collection and all instances of it are removed. Java // Java Program to remove 10// from a List using List.removeAll() and Predicateimport java.util.function.Predicate;import java.util.*; class GFG { // Generic function to remove elements using Predicate public static <T> List<T> removeElements(List<T> l, Predicate<T> p) { // Create collection using Predicate Collection<T> collection = new ArrayList<>(); for (T t : l) { if (p.test(t)) { collection.add(t); } } // Print the list System.out.println("Collection to be removed: " + collection); // Removing 10 using List.removeAll() // passing a collection l.removeAll(collection); // Return the list return l; } public static void main(String[] args) { // Create a list with null values List<String> l = new ArrayList<>( Arrays.asList("1", "10", "15", "10", "12", "5", "10", "20")); // Print the list System.out.println("Original List: " + l); // Creating a Predicate condition checking for 10 Predicate<String> is10 = i -> (i == "10"); // Removing using Predicate l = removeElements(l, is10); // Print the list System.out.println("Updated List: " + l); }} Original List: [1, 10, 15, 10, 12, 5, 10, 20] Collection to be removed: [10, 10, 10] Updated List: [1, 15, 12, 5, 20] Stream.filter() method can be used in Java 8 that returns a stream consisting of the elements that match the given predicate condition. Java // Java Program to remove nulls// from a List using Java 8import java.util.function.Predicate;import java.util.stream.Collectors;import java.util.*; class GFG { // Generic function to remove elements using Predicate public static <T> List<T> removeElements(List<T> l, Predicate<T> p) { // Removing nulls using Java Stream // using Predicate condition in lambda expression l = l.stream() .filter(p) .collect(Collectors.toList()); // Return the list return l; } public static void main(String[] args) { // Create a list with null values List<String> l = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("List with null values: " + l); // Creating a Predicate condition checking for null Predicate<String> isNull = i -> (i != null); // Removing using Predicate l = removeElements(l, isNull); // Print the list System.out.println("List with null values removed: " + l); }} List with null values: [Geeks, null, forGeeks, null, A computer portal] List with null values removed: [Geeks, forGeeks, A computer portal] As the name suggests, it is a direct method to remove all elements that satisfy the given predicate. Java // Java Program to remove nulls// from a List using Java 8import java.util.function.Predicate;import java.util.*; class GFG { // Generic function to remove elements using Predicate public static <T> List<T> removeElements(List<T> l, Predicate<T> p) { // Removing nulls using Java Stream // using Predicate condition in removeIf() l.removeIf(x -> p.test(x)); // Return the list return l; } public static void main(String[] args) { // Create a list with null values List<String> l = new ArrayList<>( Arrays.asList("Geeks", null, "forGeeks", null, "A computer portal")); // Print the list System.out.println("List with null values: " + l); // Creating a Predicate condition checking for null Predicate<String> isNull = i -> (i == null); // Removing using Predicate l = removeElements(l, isNull); // Print the list System.out.println("List with null values removed: " + l); }} List with null values: [Geeks, null, forGeeks, null, A computer portal] List with null values removed: [Geeks, forGeeks, A computer portal] amaannassar123 Java - util package Java-ArrayList Java-Collections java-lambda java-list Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2020" }, { "code": null, "e": 128, "s": 28, "text": "Below are the methods to efficiently remove elements from a List satisfying a Predicate condition: " }, { "code": null, "e": 218, "s": 128, "text": "p ==> Predicate, specifying the condition\nl ==> List, from which element to be removed\n" }, { "code": null, "e": 313, "s": 220, "text": "Below program demonstrates the removal of null elements from the list, using the Predicate " }, { "code": null, "e": 318, "s": 313, "text": "Java" }, { "code": "// Java Program to remove nulls// from a List using iterator and Predicateimport java.util.function.Predicate;import java.util.*; class GFG { // Generic function to remove Null Using Iterator public static <T> List<T> removeNullUsingIterator(List<T> l, Predicate<T> p) { // Create an iterator from the l Iterator<T> itr = l.iterator(); // Find and remove all null while (itr.hasNext()) { // Fetching the next element T t = itr.next(); // Checking for Predicate condition if (!p.test(t)) { // If the condition matches, // remove that element itr.remove(); } } // Return the null return l; } public static void main(String[] args) { // Create the l with null values List<String> l = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"List with null values: \" + l); // Creating a Predicate condition checking for null Predicate<String> isNull = item -> Objects.nonNull(item); // Removing nulls using iterator and Predicate l = removeNullUsingIterator(l, isNull); // Print the list System.out.println(\"List with null values removed: \" + l); }}", "e": 1814, "s": 318, "text": null }, { "code": null, "e": 1955, "s": 1814, "text": "List with null values: [Geeks, null, forGeeks, null, A computer portal]\nList with null values removed: [Geeks, forGeeks, A computer portal]\n" }, { "code": null, "e": 2265, "s": 1955, "text": "In this method, a collection containing elements to be removed is used to remove those elements from the original l. It requires creating a collection with the required elements using a Predicate condition. After doing this, the original l is searched for this collection and all instances of it are removed. " }, { "code": null, "e": 2270, "s": 2265, "text": "Java" }, { "code": "// Java Program to remove 10// from a List using List.removeAll() and Predicateimport java.util.function.Predicate;import java.util.*; class GFG { // Generic function to remove elements using Predicate public static <T> List<T> removeElements(List<T> l, Predicate<T> p) { // Create collection using Predicate Collection<T> collection = new ArrayList<>(); for (T t : l) { if (p.test(t)) { collection.add(t); } } // Print the list System.out.println(\"Collection to be removed: \" + collection); // Removing 10 using List.removeAll() // passing a collection l.removeAll(collection); // Return the list return l; } public static void main(String[] args) { // Create a list with null values List<String> l = new ArrayList<>( Arrays.asList(\"1\", \"10\", \"15\", \"10\", \"12\", \"5\", \"10\", \"20\")); // Print the list System.out.println(\"Original List: \" + l); // Creating a Predicate condition checking for 10 Predicate<String> is10 = i -> (i == \"10\"); // Removing using Predicate l = removeElements(l, is10); // Print the list System.out.println(\"Updated List: \" + l); }}", "e": 3556, "s": 2270, "text": null }, { "code": null, "e": 3675, "s": 3556, "text": "Original List: [1, 10, 15, 10, 12, 5, 10, 20]\nCollection to be removed: [10, 10, 10]\nUpdated List: [1, 15, 12, 5, 20]\n" }, { "code": null, "e": 3814, "s": 3677, "text": "Stream.filter() method can be used in Java 8 that returns a stream consisting of the elements that match the given predicate condition. " }, { "code": null, "e": 3819, "s": 3814, "text": "Java" }, { "code": "// Java Program to remove nulls// from a List using Java 8import java.util.function.Predicate;import java.util.stream.Collectors;import java.util.*; class GFG { // Generic function to remove elements using Predicate public static <T> List<T> removeElements(List<T> l, Predicate<T> p) { // Removing nulls using Java Stream // using Predicate condition in lambda expression l = l.stream() .filter(p) .collect(Collectors.toList()); // Return the list return l; } public static void main(String[] args) { // Create a list with null values List<String> l = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"List with null values: \" + l); // Creating a Predicate condition checking for null Predicate<String> isNull = i -> (i != null); // Removing using Predicate l = removeElements(l, isNull); // Print the list System.out.println(\"List with null values removed: \" + l); }}", "e": 5048, "s": 3819, "text": null }, { "code": null, "e": 5189, "s": 5048, "text": "List with null values: [Geeks, null, forGeeks, null, A computer portal]\nList with null values removed: [Geeks, forGeeks, A computer portal]\n" }, { "code": null, "e": 5291, "s": 5189, "text": "As the name suggests, it is a direct method to remove all elements that satisfy the given predicate. " }, { "code": null, "e": 5296, "s": 5291, "text": "Java" }, { "code": "// Java Program to remove nulls// from a List using Java 8import java.util.function.Predicate;import java.util.*; class GFG { // Generic function to remove elements using Predicate public static <T> List<T> removeElements(List<T> l, Predicate<T> p) { // Removing nulls using Java Stream // using Predicate condition in removeIf() l.removeIf(x -> p.test(x)); // Return the list return l; } public static void main(String[] args) { // Create a list with null values List<String> l = new ArrayList<>( Arrays.asList(\"Geeks\", null, \"forGeeks\", null, \"A computer portal\")); // Print the list System.out.println(\"List with null values: \" + l); // Creating a Predicate condition checking for null Predicate<String> isNull = i -> (i == null); // Removing using Predicate l = removeElements(l, isNull); // Print the list System.out.println(\"List with null values removed: \" + l); }}", "e": 6418, "s": 5296, "text": null }, { "code": null, "e": 6559, "s": 6418, "text": "List with null values: [Geeks, null, forGeeks, null, A computer portal]\nList with null values removed: [Geeks, forGeeks, A computer portal]\n" }, { "code": null, "e": 6574, "s": 6559, "text": "amaannassar123" }, { "code": null, "e": 6594, "s": 6574, "text": "Java - util package" }, { "code": null, "e": 6609, "s": 6594, "text": "Java-ArrayList" }, { "code": null, "e": 6626, "s": 6609, "text": "Java-Collections" }, { "code": null, "e": 6638, "s": 6626, "text": "java-lambda" }, { "code": null, "e": 6648, "s": 6638, "text": "java-list" }, { "code": null, "e": 6667, "s": 6648, "text": "Java-List-Programs" }, { "code": null, "e": 6672, "s": 6667, "text": "Java" }, { "code": null, "e": 6677, "s": 6672, "text": "Java" }, { "code": null, "e": 6694, "s": 6677, "text": "Java-Collections" } ]
Difference between Ambiguous and Unambiguous Grammar
15 Jul, 2020 Prerequisite – Context Free Grammars1. Ambiguous Grammar :A context-free grammar is called ambiguous grammar if there exists more than one derivation tree or parse tree. Example – S -> S + S / S * S / S / a 2. Unambiguous Grammar :A context-free grammar is called unambiguous grammar if there exists one and only one derivation tree or parse tree. Example – X -> AB A -> Aa / a B -> b Difference between Ambiguous and Unambiguous Grammar : Difference Between GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jul, 2020" }, { "code": null, "e": 223, "s": 53, "text": "Prerequisite – Context Free Grammars1. Ambiguous Grammar :A context-free grammar is called ambiguous grammar if there exists more than one derivation tree or parse tree." }, { "code": null, "e": 233, "s": 223, "text": "Example –" }, { "code": null, "e": 261, "s": 233, "text": "S -> S + S / S * S / S / a " }, { "code": null, "e": 402, "s": 261, "text": "2. Unambiguous Grammar :A context-free grammar is called unambiguous grammar if there exists one and only one derivation tree or parse tree." }, { "code": null, "e": 412, "s": 402, "text": "Example –" }, { "code": null, "e": 440, "s": 412, "text": "X -> AB\nA -> Aa / a\nB -> b " }, { "code": null, "e": 495, "s": 440, "text": "Difference between Ambiguous and Unambiguous Grammar :" }, { "code": null, "e": 514, "s": 495, "text": "Difference Between" }, { "code": null, "e": 522, "s": 514, "text": "GATE CS" }, { "code": null, "e": 555, "s": 522, "text": "Theory of Computation & Automata" } ]
Java Program to Implement Zhu–Takaoka String Matching Algorithm
12 Sep, 2021 Zhu-Takaoka String Matching Algorithm is a Variant of Boyer Moore Algorithm for Pattern Matching in a String. There is a slight change in the concept of Bad Maps in this algorithm. The concept of Good Suffixes remains as same as that of Boyer Moore’s but instead of using a single character for Bad Shifts, now in this algorithm, we will be performing two shifts. Hence, this algorithm provides a little speed over the Boyer’s one. Both Good suffixes and Two character Bad shifts can be used together in the code to give an extra edge in the performance of the Algorithm. We are discussing the idea of how to change the calculation of Bad Character Shifts for this algorithm and the idea of Good suffixes can be derived from Boyer’s algorithm. Working of Algorithms: At first, this algorithm starts the same as that of Boyer’s one starts i.e. comparing the pattern to the string from Right to Left. Hence, each character of the pattern is compared to that of string from Right to Left. So the starting index of the comparison should be the length of the pattern. String : ABCDEFGH Pattern: BCD So the comparison should begin at the index of β€˜C’ in string i.e. 2 (0-based indexing is used). So comparison starts at index = Length of Pattern – 1. If a match is found then the index is decremented till the matches are found. Once the match is not found then it’s time to make shifts for Bad Characters. String : ABCDEFGH Pattern: BCC a) At index 2 String has Char β€˜C’ and since Pattern[2]==’C’ so character match is found. So we are now going to check for previous indexes i.e. 1, 0. So at string[1] (which is equal to β€˜B”), Pattern[1]!=’B’ So the match is not found and is the time to shift the characters. Computing table for Bad Character Shifts (named ZTBC Table): This stage is a preprocessing stage i.e. should be done before starting the comparisons. Bad Character tables is a Hash Map which has all alphabets of Pattern as the keys and the value represents the number of shift the pattern should be given so that either: The mismatch becomes a match. The pattern passed that mismatched character of the string. So in Zhu-Takaoka Algorithm, we are maintaining a 2-D array that can give the number of shifts based on the first two characters of the string from where the comparison had started. Hence, increasing the number of shifts and decreasing the number of comparisons which results in more increased performance. Procedure: Logic building. The idea for computing the table is as depicted below: The table is made using a 2D Array where all the columns and rows are named by the character of the Patterns. The table is initialized with the length of the pattern since if the pair of char is not found in the pattern then the only way is to pass the whole pattern through pass the mismatched character. If pattern is = "ABCD" The ZTBC = A B C D E... A 4 4 4 4 4 B 4 4 4 4 4 C 4 4 4 4 4 D 4 4 4 4 4 E..... Now if out of the two char if the second one is the starting character of the pattern then shifting the whole pattern is not the right idea we should make a match of the second char with the first one of the pattern. So we should shift the pattern by Len-1. so For all i in size of array ZTBC[i][pattern[0]] = len-1. so ZTBC now looks like : ZTBC = A B C D E.... A 3 4 4 4 4 B 3 4 4 4 4 C 3 4 4 4 4 D 3 4 4 4 4 E..... Now if both characters are found consecutively in the pattern then we should shift the pattern only that much so that the pair of chars in string and pattern matches so. for all i in array.size ZTBC[pattern[i-1]][pattern[i]] = len-i-1 ; //This is the amount of shifts if two matching pair is found. So finally ZTBC looks like ZTBC = A B C D E ...... A 3 2 4 4 4 B 3 4 1 4 4 C 3 4 4 4 4 D 3 4 4 4 4 E....... Illustration: Hence, suppose a string and pattern is given as below: String S = "ABCABCDE" Pattern P = "ABCD" It is descriptively shown with the help of visual arts below as follows: So considering 0-Based indexing, we will begin at index 3 so s[3]!=P[3] // p[3]=='D' and S[3]=='A' Hence, a mismatch occurs, and we will shift the array by ZTBC[C][A] since last two consecutive char is CA in string. So now we will shift the pattern by 3 Since ZTBC[C][A] == 3, and now we are at index 6 ( 3+3 ) And now we should again start a comparison of the string and pattern as in step 1, and then we would found a match of pattern in the string so print it. We found one occurrence. Now since continuing further, we should now shift by the last two char i.e. CD in String since they are only at the previous index. Hence, we should shift our pattern by 1 and continue the same process. Also, we can include the idea of Good Suffixes in this program to find the max number of shifts necessary and hence make our code’s performance better. The idea of Good Suffixes is the same as that in Boyer’s one. Hence, presenting a general formula for the above shifting idea we get If a mismatch occurs at Char of String. Say Say S[i+m-k]!=P[m-k] //m is the size of pattern and j is the index of the start of matching . Then the number of the shift should be given as: ZTBC[S[i+m-2]][S[i+m-1]] // two consecutive char at the index where comparisons starts. Example: Java // Java Program to Implement Zhu–Takaoka String Matching// Algorithm // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Main classpublic class GFG { // Declaring custom strings as inputs and patterns public static String string = "ABCABCDEABCDEA"; public static String pattern = "ABCD"; // And their lengths public static int stringlen = 14; public static int patternlen = 4; // Preprocessing and calculating the ZTBC for above // pattern by creating an integer array // As alphabets are 26 so // square matrix of 26 * 26 public static int[][] ZTBC = new int[26][26]; // Method // To calculate ZTBC to // print the indepattern at which the patternlenatches // occurs public static void ZTBCCalculation() { // Declaring variables within this scope int i, j; // Iterating over to compute // using nested for loops for (i = 0; i < 26; ++i) for (j = 0; j < 26; ++j) ZTBC[i][j] = patternlen; for (i = 0; i < 26; ++i) ZTBC[i][pattern.charAt(0) - 'A'] = patternlen - 1; for (i = 1; i < patternlen - 1; ++i) ZTBC[pattern.charAt(i - 1) - 'A'] [pattern.charAt(i) - 'A'] = patternlen - 1 - i; } // Main driver method public static void main(String args[]) { // Declare variables in main() body int i, j; // Calling the above created Method 1 ZTBCCalculation(); // Lastly, searching pattern and printing the // indepattern j = 0; // Till condition holds true while (j <= stringlen - patternlen) { i = patternlen - 1; while (i >= 0 && pattern.charAt(i) == string.charAt(i + j)) --i; if (i < 0) { // Pattern detected System.out.println("Pattern Found at " + (j + 1)); j += patternlen; } // Not detected else j += ZTBC[string.charAt(j + patternlen - 2) - 'A'] [string.charAt(j + patternlen - 1) - 'A']; } }} Pattern Found at 4 Pattern Found at 9 Note: Runtime complexity is found to be O(stringlen*patternlen) For searching one and O(patterlen + (26*26)). Space Complexity is found to be O(26Γ—26) which is constant nearly for large test cases. surindertarika1234 sweetyty Java-String-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n12 Sep, 2021" }, { "code": null, "e": 416, "s": 52, "text": "Zhu-Takaoka String Matching Algorithm is a Variant of Boyer Moore Algorithm for Pattern Matching in a String. There is a slight change in the concept of Bad Maps in this algorithm. The concept of Good Suffixes remains as same as that of Boyer Moore’s but instead of using a single character for Bad Shifts, now in this algorithm, we will be performing two shifts." }, { "code": null, "e": 796, "s": 416, "text": "Hence, this algorithm provides a little speed over the Boyer’s one. Both Good suffixes and Two character Bad shifts can be used together in the code to give an extra edge in the performance of the Algorithm. We are discussing the idea of how to change the calculation of Bad Character Shifts for this algorithm and the idea of Good suffixes can be derived from Boyer’s algorithm." }, { "code": null, "e": 819, "s": 796, "text": "Working of Algorithms:" }, { "code": null, "e": 1115, "s": 819, "text": "At first, this algorithm starts the same as that of Boyer’s one starts i.e. comparing the pattern to the string from Right to Left. Hence, each character of the pattern is compared to that of string from Right to Left. So the starting index of the comparison should be the length of the pattern." }, { "code": null, "e": 1154, "s": 1115, "text": "String : ABCDEFGH\n\nPattern: BCD" }, { "code": null, "e": 1461, "s": 1154, "text": "So the comparison should begin at the index of β€˜C’ in string i.e. 2 (0-based indexing is used). So comparison starts at index = Length of Pattern – 1. If a match is found then the index is decremented till the matches are found. Once the match is not found then it’s time to make shifts for Bad Characters." }, { "code": null, "e": 1500, "s": 1461, "text": "String : ABCDEFGH\n\nPattern: BCC" }, { "code": null, "e": 1774, "s": 1500, "text": "a) At index 2 String has Char β€˜C’ and since Pattern[2]==’C’ so character match is found. So we are now going to check for previous indexes i.e. 1, 0. So at string[1] (which is equal to β€˜B”), Pattern[1]!=’B’ So the match is not found and is the time to shift the characters." }, { "code": null, "e": 2095, "s": 1774, "text": "Computing table for Bad Character Shifts (named ZTBC Table): This stage is a preprocessing stage i.e. should be done before starting the comparisons. Bad Character tables is a Hash Map which has all alphabets of Pattern as the keys and the value represents the number of shift the pattern should be given so that either:" }, { "code": null, "e": 2125, "s": 2095, "text": "The mismatch becomes a match." }, { "code": null, "e": 2185, "s": 2125, "text": "The pattern passed that mismatched character of the string." }, { "code": null, "e": 2492, "s": 2185, "text": "So in Zhu-Takaoka Algorithm, we are maintaining a 2-D array that can give the number of shifts based on the first two characters of the string from where the comparison had started. Hence, increasing the number of shifts and decreasing the number of comparisons which results in more increased performance." }, { "code": null, "e": 2575, "s": 2492, "text": "Procedure: Logic building. The idea for computing the table is as depicted below: " }, { "code": null, "e": 2881, "s": 2575, "text": "The table is made using a 2D Array where all the columns and rows are named by the character of the Patterns. The table is initialized with the length of the pattern since if the pair of char is not found in the pattern then the only way is to pass the whole pattern through pass the mismatched character." }, { "code": null, "e": 3101, "s": 2881, "text": "If pattern is = \"ABCD\"\n\nThe ZTBC = A B C D E...\n\n A 4 4 4 4 4 \n\n B 4 4 4 4 4\n\n C 4 4 4 4 4\n\n D 4 4 4 4 4\n\n E....." }, { "code": null, "e": 3359, "s": 3101, "text": "Now if out of the two char if the second one is the starting character of the pattern then shifting the whole pattern is not the right idea we should make a match of the second char with the first one of the pattern. So we should shift the pattern by Len-1." }, { "code": null, "e": 3644, "s": 3359, "text": "so For all i in size of array \n\nZTBC[i][pattern[0]] = len-1.\n\nso ZTBC now looks like :\n\nZTBC = A B C D E....\n\n A 3 4 4 4 4\n\n B 3 4 4 4 4\n\n C 3 4 4 4 4\n\n D 3 4 4 4 4\n\n E....." }, { "code": null, "e": 3814, "s": 3644, "text": "Now if both characters are found consecutively in the pattern then we should shift the pattern only that much so that the pair of chars in string and pattern matches so." }, { "code": null, "e": 4175, "s": 3814, "text": "for all i in array.size\n\nZTBC[pattern[i-1]][pattern[i]] = len-i-1 ; //This is the amount of shifts if two matching pair is found.\n\nSo finally ZTBC looks like\n\nZTBC = A B C D E ......\n\n A 3 2 4 4 4\n\n B 3 4 1 4 4\n\n C 3 4 4 4 4\n\n D 3 4 4 4 4\n\n E......." }, { "code": null, "e": 4190, "s": 4175, "text": "Illustration: " }, { "code": null, "e": 4245, "s": 4190, "text": "Hence, suppose a string and pattern is given as below:" }, { "code": null, "e": 4287, "s": 4245, "text": "String S = \"ABCABCDE\"\nPattern P = \"ABCD\"" }, { "code": null, "e": 4360, "s": 4287, "text": "It is descriptively shown with the help of visual arts below as follows:" }, { "code": null, "e": 4418, "s": 4360, "text": "So considering 0-Based indexing, we will begin at index 3" }, { "code": null, "e": 4460, "s": 4418, "text": "so s[3]!=P[3] // p[3]=='D' and S[3]=='A'" }, { "code": null, "e": 4518, "s": 4460, "text": "Hence, a mismatch occurs, and we will shift the array by " }, { "code": null, "e": 4579, "s": 4518, "text": "ZTBC[C][A] since last two consecutive char is CA in string. " }, { "code": null, "e": 4618, "s": 4579, "text": "So now we will shift the pattern by 3 " }, { "code": null, "e": 4675, "s": 4618, "text": "Since ZTBC[C][A] == 3, and now we are at index 6 ( 3+3 )" }, { "code": null, "e": 5385, "s": 4675, "text": "And now we should again start a comparison of the string and pattern as in step 1, and then we would found a match of pattern in the string so print it. We found one occurrence. Now since continuing further, we should now shift by the last two char i.e. CD in String since they are only at the previous index. Hence, we should shift our pattern by 1 and continue the same process. Also, we can include the idea of Good Suffixes in this program to find the max number of shifts necessary and hence make our code’s performance better. The idea of Good Suffixes is the same as that in Boyer’s one. Hence, presenting a general formula for the above shifting idea we get If a mismatch occurs at Char of String. Say" }, { "code": null, "e": 5479, "s": 5385, "text": "Say S[i+m-k]!=P[m-k] //m is the size of pattern and j is the index of the start of matching ." }, { "code": null, "e": 5528, "s": 5479, "text": "Then the number of the shift should be given as:" }, { "code": null, "e": 5616, "s": 5528, "text": "ZTBC[S[i+m-2]][S[i+m-1]] // two consecutive char at the index where comparisons starts." }, { "code": null, "e": 5625, "s": 5616, "text": "Example:" }, { "code": null, "e": 5630, "s": 5625, "text": "Java" }, { "code": "// Java Program to Implement Zhu–Takaoka String Matching// Algorithm // Importing required classesimport java.io.*;import java.lang.*;import java.util.*; // Main classpublic class GFG { // Declaring custom strings as inputs and patterns public static String string = \"ABCABCDEABCDEA\"; public static String pattern = \"ABCD\"; // And their lengths public static int stringlen = 14; public static int patternlen = 4; // Preprocessing and calculating the ZTBC for above // pattern by creating an integer array // As alphabets are 26 so // square matrix of 26 * 26 public static int[][] ZTBC = new int[26][26]; // Method // To calculate ZTBC to // print the indepattern at which the patternlenatches // occurs public static void ZTBCCalculation() { // Declaring variables within this scope int i, j; // Iterating over to compute // using nested for loops for (i = 0; i < 26; ++i) for (j = 0; j < 26; ++j) ZTBC[i][j] = patternlen; for (i = 0; i < 26; ++i) ZTBC[i][pattern.charAt(0) - 'A'] = patternlen - 1; for (i = 1; i < patternlen - 1; ++i) ZTBC[pattern.charAt(i - 1) - 'A'] [pattern.charAt(i) - 'A'] = patternlen - 1 - i; } // Main driver method public static void main(String args[]) { // Declare variables in main() body int i, j; // Calling the above created Method 1 ZTBCCalculation(); // Lastly, searching pattern and printing the // indepattern j = 0; // Till condition holds true while (j <= stringlen - patternlen) { i = patternlen - 1; while (i >= 0 && pattern.charAt(i) == string.charAt(i + j)) --i; if (i < 0) { // Pattern detected System.out.println(\"Pattern Found at \" + (j + 1)); j += patternlen; } // Not detected else j += ZTBC[string.charAt(j + patternlen - 2) - 'A'] [string.charAt(j + patternlen - 1) - 'A']; } }}", "e": 7946, "s": 5630, "text": null }, { "code": null, "e": 7987, "s": 7949, "text": "Pattern Found at 4\nPattern Found at 9" }, { "code": null, "e": 7993, "s": 7987, "text": "Note:" }, { "code": null, "e": 8097, "s": 7993, "text": "Runtime complexity is found to be O(stringlen*patternlen) For searching one and O(patterlen + (26*26))." }, { "code": null, "e": 8185, "s": 8097, "text": "Space Complexity is found to be O(26Γ—26) which is constant nearly for large test cases." }, { "code": null, "e": 8206, "s": 8187, "text": "surindertarika1234" }, { "code": null, "e": 8215, "s": 8206, "text": "sweetyty" }, { "code": null, "e": 8236, "s": 8215, "text": "Java-String-Programs" }, { "code": null, "e": 8243, "s": 8236, "text": "Picked" }, { "code": null, "e": 8248, "s": 8243, "text": "Java" }, { "code": null, "e": 8262, "s": 8248, "text": "Java Programs" }, { "code": null, "e": 8267, "s": 8262, "text": "Java" }, { "code": null, "e": 8365, "s": 8267, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8380, "s": 8365, "text": "Stream In Java" }, { "code": null, "e": 8401, "s": 8380, "text": "Introduction to Java" }, { "code": null, "e": 8422, "s": 8401, "text": "Constructors in Java" }, { "code": null, "e": 8441, "s": 8422, "text": "Exceptions in Java" }, { "code": null, "e": 8458, "s": 8441, "text": "Generics in Java" }, { "code": null, "e": 8484, "s": 8458, "text": "Java Programming Examples" }, { "code": null, "e": 8518, "s": 8484, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 8565, "s": 8518, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 8603, "s": 8565, "text": "Factory method design pattern in Java" } ]
Python Pandas - How to delete a row from a DataFrame
To delete a row from a DataFrame, use the drop() method and set the index label as the parameter. At first, let us create a DataFrame. We have index label as w, x, y, and z: dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'], columns=['a', 'b']) Now, let us use the index label and delete a row. Here, we will delete a row with index label β€˜w’ dataFrame = dataFrame.drop('w') Following is the code import pandas as pd # Create DataFrame dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b']) # DataFrame print"DataFrame...\n",dataFrame # deleting a row dataFrame = dataFrame.drop('w') print"DataFrame after deleting a row...\n",dataFrame This will produce the following output DataFrame... a b w 10 15 x 20 25 y 30 35 z 40 45 DataFrame after deleting a row... a b x 20 25 y 30 35 z 40 45
[ { "code": null, "e": 1285, "s": 1187, "text": "To delete a row from a DataFrame, use the drop() method and set the index label as the parameter." }, { "code": null, "e": 1361, "s": 1285, "text": "At first, let us create a DataFrame. We have index label as w, x, y, and z:" }, { "code": null, "e": 1475, "s": 1361, "text": "dataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],\ncolumns=['a', 'b'])" }, { "code": null, "e": 1573, "s": 1475, "text": "Now, let us use the index label and delete a row. Here, we will delete a row with index label β€˜w’" }, { "code": null, "e": 1606, "s": 1573, "text": "dataFrame = dataFrame.drop('w')\n" }, { "code": null, "e": 1628, "s": 1606, "text": "Following is the code" }, { "code": null, "e": 1929, "s": 1628, "text": "import pandas as pd\n\n# Create DataFrame\ndataFrame = pd.DataFrame([[10, 15], [20, 25], [30, 35], [40, 45]],index=['w', 'x', 'y', 'z'],columns=['a', 'b'])\n\n# DataFrame\nprint\"DataFrame...\\n\",dataFrame\n\n# deleting a row\ndataFrame = dataFrame.drop('w')\nprint\"DataFrame after deleting a row...\\n\",dataFrame" }, { "code": null, "e": 1968, "s": 1929, "text": "This will produce the following output" }, { "code": null, "e": 2103, "s": 1968, "text": "DataFrame...\n a b\nw 10 15\nx 20 25\ny 30 35\nz 40 45\nDataFrame after deleting a row...\n a b\nx 20 25\ny 30 35\nz 40 45" } ]
Delete a node in a Doubly Linked List
24 Jun, 2022 Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List Approach: The deletion of a node in a doubly-linked list can be divided into three main categories: After the deletion of the head node. After the deletion of the middle node. After the deletion of the last node. All three mentioned cases can be handled in two steps if the pointer of the node to be deleted and the head pointer is known. If the node to be deleted is the head node then make the next node as head.If a node is deleted, connect the next and previous node of the deleted node. If the node to be deleted is the head node then make the next node as head. If a node is deleted, connect the next and previous node of the deleted node. Algorithm Let the node to be deleted be del. If node to be deleted is head node, then change the head pointer to next current head. if headnode == del then headnode = del.nextNode Set prev of next to del, if next to del exists. if del.nextNode != none del.nextNode.previousNode = del.previousNode Set next of previous to del, if previous to del exists. if del.previousNode != none del.previousNode.nextNode = del.next C++ C Java Python3 C# Javascript // C++ program to delete a node from// Doubly Linked List#include <bits/stdc++.h>using namespace std; /* a node of the doubly linked list */class Node { public: int data; Node* next; Node* prev; }; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(Node** head_ref, Node* del) { /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del); return; } /* UTILITY FUNCTIONS *//* Function to insert a node at thebeginning of the Doubly Linked List */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(Node* node) { while (node != NULL) { cout << node->data << " "; node = node->next; } } /* Driver code*/int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create the doubly linked list 10<->8<->4<->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << "Original Linked list "; printList(head); /* delete nodes from the doubly linked list */ deleteNode(&head, head); /*delete first node*/ deleteNode(&head, head->next); /*delete middle node*/ deleteNode(&head, head->next); /*delete last node*/ /* Modified linked list will be NULL<-8->NULL */ cout << "\nModified Linked list "; printList(head); return 0;} // This code is contributed by rathbhupendra #include <stdio.h>#include <stdlib.h> /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del); return;} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(struct Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Let us create the doubly linked list 10<->8<->4<->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); printf("\n Original Linked list "); printList(head); /* delete nodes from the doubly linked list */ deleteNode(&head, head); /*delete first node*/ deleteNode(&head, head->next); /*delete middle node*/ deleteNode(&head, head->next); /*delete last node*/ /* Modified linked list will be NULL<-8->NULL */ printf("\n Modified Linked list "); printList(head); getchar();} // Java program to delete a node from// Doubly Linked List // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default initialized // as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { // 1. allocate node // 2. put in the data Node new_Node = new Node(new_data); // 3. Make next of new node as head // and previous as NULL new_Node.next = head; new_Node.prev = null; // 4. change prev of head node to new node if (head != null) head.prev = new_Node; // 5. move the head to point to the new node head = new_Node; } // This function prints contents of linked list // starting from the given node public void printlist(Node node) { Node last = null; while (node != null) { System.out.print(node.data + " "); last = node; node = node.next; } System.out.println(); } // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> data of node to be deleted. void deleteNode(Node del) { // Base case if (head == null || del == null) { return; } // If node to be deleted is head node if (head == del) { head = del.next; } // Change next only if node to be deleted // is NOT the last node if (del.next != null) { del.next.prev = del.prev; } // Change prev only if node to be deleted // is NOT the first node if (del.prev != null) { del.prev.next = del.next; } // Finally, free the memory occupied by del return; } // Driver Code public static void main(String[] args) { // Start with the empty list DLL dll = new DLL(); // Insert 2. So linked list becomes 2->NULL dll.push(2); // Insert 4. So linked list becomes 4->2->NULL dll.push(4); // Insert 8. So linked list becomes 8->4->2->NULL dll.push(8); // Insert 10. So linked list becomes 10->8->4->2->NULL dll.push(10); System.out.print("Created DLL is: "); dll.printlist(dll.head); // Deleting first node dll.deleteNode(dll.head); // List after deleting first node // 8->4->2 System.out.print("\nList after deleting first node: "); dll.printlist(dll.head); // Deleting middle node from 8->4->2 dll.deleteNode(dll.head.next); System.out.print("\nList after Deleting middle node: "); dll.printlist(dll.head); }} # Program to delete a node in a doubly-linked list # for Garbage collectionimport gc # A node of the doubly linked listclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Function to delete a node in a Doubly Linked List. # head_ref --> pointer to head node pointer. # dele --> pointer to node to be deleted def deleteNode(self, dele): # Base Case if self.head is None or dele is None: return # If node to be deleted is head node if self.head == dele: self.head = dele.next # Change next only if node to be deleted is NOT # the last node if dele.next is not None: dele.next.prev = dele.prev # Change prev only if node to be deleted is NOT # the first node if dele.prev is not None: dele.prev.next = dele.next # Finally, free the memory occupied by dele # Call python garbage collector gc.collect() # Given a reference to the head of a list and an # integer, inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = Node(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node def printList(self, node): while(node is not None): print(node.data,end=' ') node = node.next # Driver program to test the above functions # Start with empty listdll = DoublyLinkedList() # Let us create the doubly linked list 10<->8<->4<->2dll.push(2);dll.push(4);dll.push(8);dll.push(10); print ("\n Original Linked List",end=' ')dll.printList(dll.head) # delete nodes from doubly linked listdll.deleteNode(dll.head)dll.deleteNode(dll.head.next)dll.deleteNode(dll.head.next)# Modified linked list will be NULL<-8->NULLprint("\n Modified Linked List",end=' ')dll.printList(dll.head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to delete a node from// Doubly Linked Listusing System; // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ public class Node { public int data; public Node prev; public Node next; // Constructor to create a new node // next and prev is by default // initialized as null public Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { // 1. allocate node // 2. put in the data Node new_Node = new Node(new_data); // 3. Make next of new node as head // and previous as NULL new_Node.next = head; new_Node.prev = null; // 4. change prev of head node to new node if (head != null) head.prev = new_Node; // 5. move the head to point to the new node head = new_Node; } // This function prints contents of linked list // starting from the given node public void printlist(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } Console.WriteLine(); } // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> data of node to be deleted. void deleteNode(Node del) { // Base case if (head == null || del == null) { return; } // If node to be deleted is head node if (head == del) { head = del.next; } // Change next only if node to be deleted // is NOT the last node if (del.next != null) { del.next.prev = del.prev; } // Change prev only if node to be deleted // is NOT the first node if (del.prev != null) { del.prev.next = del.next; } // Finally, free the memory occupied by del return; } // Driver Code public static void Main() { // Start with the empty list DLL dll = new DLL(); // Insert 2. So linked list becomes 2->NULL dll.push(2); // Insert 4. So linked list becomes 4->2->NULL dll.push(4); // Insert 8. So linked list becomes 8->4->2->NULL dll.push(8); // Insert 10. So linked list becomes 10->8->4->2->NULL dll.push(10); Console.Write("Created DLL is: "); dll.printlist(dll.head); // Deleting first node dll.deleteNode(dll.head); // List after deleting first node // 8->4->2 Console.Write("\nList after deleting first node: "); dll.printlist(dll.head); // Deleting middle node from 8->4->2 dll.deleteNode(dll.head.next); Console.Write("\nList after Deleting middle node: "); dll.printlist(dll.head); }}// This code is contributed by PrinciRaj1992 <script> // Javascript program to delete a node from// Doubly Linked List // Class for Doubly Linked Listvar head; // head of list /* Doubly Linked list Node */ class Node { // Constructor to create a new node // next and prev is by default initialized // as null constructor(val) { this.data = val; this.prev = null; this.next = null; } } // Adding a node at the front of the list function push(new_data) { // 1. allocate node // 2. put in the data new_Node = new Node(new_data); // 3. Make next of new node as head // and previous as NULL new_Node.next = head; new_Node.prev = null; // 4. change prev of head node to new node if (head != null) head.prev = new_Node; // 5. move the head to point to the new node head = new_Node; } // This function prints contents of linked list // starting from the given node function printlist( node) { last = null; while (node != null) { document.write(node.data + " "); last = node; node = node.next; } document.write("<br/>"); } // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> data of node to be deleted. function deleteNode( del) { // Base case if (head == null || del == null) { return; } // If node to be deleted is head node if (head == del) { head = del.next; } // Change next only if node to be deleted // is NOT the last node if (del.next != null) { del.next.prev = del.prev; } // Change prev only if node to be deleted // is NOT the first node if (del.prev != null) { del.prev.next = del.next; } // Finally, free the memory occupied by del return; } // Driver Code // Start with the empty list // Insert 2. So linked list becomes 2->NULL push(2); // Insert 4. So linked list becomes 4->2->NULL push(4); // Insert 8. So linked list becomes 8->4->2->NULL push(8); // Insert 10. So linked list becomes 10->8->4->2->NULL push(10); document.write("Created DLL is: "); printlist(head); // Deleting first node deleteNode(head); deleteNode(head.next); deleteNode(head.next); document.write("Modified Linked list: "); printlist(head); // This code is contributed by todaysgaurav </script> Original Linked list 10 8 4 2 Modified Linked list 8 Complexity Analysis: Time Complexity: O(1). Since traversal of the linked list is not required so the time complexity is constant. Space Complexity: O(1). As no extra space is required, so the space complexity is constant. Please write comments if you find any of the above codes/algorithms incorrect, or find better ways to solve the same problem. RiskCatalyst princiraj1992 rathbhupendra Akanksha_Rai nidhi_biet andrew1234 shivrajsingh5 shivampuri todaysgaurav simranarora5sos amartyaghoshgfg sweatwork hardikkoriintern Amazon doubly linked list Linked List Amazon Linked List 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": 118, "s": 52, "text": "Pre-requisite: Doubly Link List Set 1| Introduction and Insertion" }, { "code": null, "e": 212, "s": 118, "text": "Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List " }, { "code": null, "e": 313, "s": 212, "text": "Approach: The deletion of a node in a doubly-linked list can be divided into three main categories: " }, { "code": null, "e": 351, "s": 313, "text": "After the deletion of the head node. " }, { "code": null, "e": 391, "s": 351, "text": "After the deletion of the middle node. " }, { "code": null, "e": 428, "s": 391, "text": "After the deletion of the last node." }, { "code": null, "e": 555, "s": 428, "text": "All three mentioned cases can be handled in two steps if the pointer of the node to be deleted and the head pointer is known. " }, { "code": null, "e": 708, "s": 555, "text": "If the node to be deleted is the head node then make the next node as head.If a node is deleted, connect the next and previous node of the deleted node." }, { "code": null, "e": 784, "s": 708, "text": "If the node to be deleted is the head node then make the next node as head." }, { "code": null, "e": 862, "s": 784, "text": "If a node is deleted, connect the next and previous node of the deleted node." }, { "code": null, "e": 873, "s": 862, "text": "Algorithm " }, { "code": null, "e": 908, "s": 873, "text": "Let the node to be deleted be del." }, { "code": null, "e": 995, "s": 908, "text": "If node to be deleted is head node, then change the head pointer to next current head." }, { "code": null, "e": 1050, "s": 995, "text": "if headnode == del then\n headnode = del.nextNode" }, { "code": null, "e": 1098, "s": 1050, "text": "Set prev of next to del, if next to del exists." }, { "code": null, "e": 1175, "s": 1098, "text": "if del.nextNode != none \n del.nextNode.previousNode = del.previousNode " }, { "code": null, "e": 1231, "s": 1175, "text": "Set next of previous to del, if previous to del exists." }, { "code": null, "e": 1303, "s": 1231, "text": "if del.previousNode != none \n del.previousNode.nextNode = del.next" }, { "code": null, "e": 1307, "s": 1303, "text": "C++" }, { "code": null, "e": 1309, "s": 1307, "text": "C" }, { "code": null, "e": 1314, "s": 1309, "text": "Java" }, { "code": null, "e": 1322, "s": 1314, "text": "Python3" }, { "code": null, "e": 1325, "s": 1322, "text": "C#" }, { "code": null, "e": 1336, "s": 1325, "text": "Javascript" }, { "code": "// C++ program to delete a node from// Doubly Linked List#include <bits/stdc++.h>using namespace std; /* a node of the doubly linked list */class Node { public: int data; Node* next; Node* prev; }; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(Node** head_ref, Node* del) { /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del); return; } /* UTILITY FUNCTIONS *//* Function to insert a node at thebeginning of the Doubly Linked List */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(Node* node) { while (node != NULL) { cout << node->data << \" \"; node = node->next; } } /* Driver code*/int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create the doubly linked list 10<->8<->4<->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << \"Original Linked list \"; printList(head); /* delete nodes from the doubly linked list */ deleteNode(&head, head); /*delete first node*/ deleteNode(&head, head->next); /*delete middle node*/ deleteNode(&head, head->next); /*delete last node*/ /* Modified linked list will be NULL<-8->NULL */ cout << \"\\nModified Linked list \"; printList(head); return 0;} // This code is contributed by rathbhupendra", "e": 3839, "s": 1336, "text": null }, { "code": "#include <stdio.h>#include <stdlib.h> /* a node of the doubly linked list */struct Node { int data; struct Node* next; struct Node* prev;}; /* Function to delete a node in a Doubly Linked List. head_ref --> pointer to head node pointer. del --> pointer to node to be deleted. */void deleteNode(struct Node** head_ref, struct Node* del){ /* base case */ if (*head_ref == NULL || del == NULL) return; /* If node to be deleted is head node */ if (*head_ref == del) *head_ref = del->next; /* Change next only if node to be deleted is NOT the last node */ if (del->next != NULL) del->next->prev = del->prev; /* Change prev only if node to be deleted is NOT the first node */ if (del->prev != NULL) del->prev->next = del->next; /* Finally, free the memory occupied by del*/ free(del); return;} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if ((*head_ref) != NULL) (*head_ref)->prev = new_node; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(struct Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Let us create the doubly linked list 10<->8<->4<->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); printf(\"\\n Original Linked list \"); printList(head); /* delete nodes from the doubly linked list */ deleteNode(&head, head); /*delete first node*/ deleteNode(&head, head->next); /*delete middle node*/ deleteNode(&head, head->next); /*delete last node*/ /* Modified linked list will be NULL<-8->NULL */ printf(\"\\n Modified Linked list \"); printList(head); getchar();}", "e": 6292, "s": 3839, "text": null }, { "code": "// Java program to delete a node from// Doubly Linked List // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ class Node { int data; Node prev; Node next; // Constructor to create a new node // next and prev is by default initialized // as null Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { // 1. allocate node // 2. put in the data Node new_Node = new Node(new_data); // 3. Make next of new node as head // and previous as NULL new_Node.next = head; new_Node.prev = null; // 4. change prev of head node to new node if (head != null) head.prev = new_Node; // 5. move the head to point to the new node head = new_Node; } // This function prints contents of linked list // starting from the given node public void printlist(Node node) { Node last = null; while (node != null) { System.out.print(node.data + \" \"); last = node; node = node.next; } System.out.println(); } // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> data of node to be deleted. void deleteNode(Node del) { // Base case if (head == null || del == null) { return; } // If node to be deleted is head node if (head == del) { head = del.next; } // Change next only if node to be deleted // is NOT the last node if (del.next != null) { del.next.prev = del.prev; } // Change prev only if node to be deleted // is NOT the first node if (del.prev != null) { del.prev.next = del.next; } // Finally, free the memory occupied by del return; } // Driver Code public static void main(String[] args) { // Start with the empty list DLL dll = new DLL(); // Insert 2. So linked list becomes 2->NULL dll.push(2); // Insert 4. So linked list becomes 4->2->NULL dll.push(4); // Insert 8. So linked list becomes 8->4->2->NULL dll.push(8); // Insert 10. So linked list becomes 10->8->4->2->NULL dll.push(10); System.out.print(\"Created DLL is: \"); dll.printlist(dll.head); // Deleting first node dll.deleteNode(dll.head); // List after deleting first node // 8->4->2 System.out.print(\"\\nList after deleting first node: \"); dll.printlist(dll.head); // Deleting middle node from 8->4->2 dll.deleteNode(dll.head.next); System.out.print(\"\\nList after Deleting middle node: \"); dll.printlist(dll.head); }}", "e": 9238, "s": 6292, "text": null }, { "code": "# Program to delete a node in a doubly-linked list # for Garbage collectionimport gc # A node of the doubly linked listclass Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Function to delete a node in a Doubly Linked List. # head_ref --> pointer to head node pointer. # dele --> pointer to node to be deleted def deleteNode(self, dele): # Base Case if self.head is None or dele is None: return # If node to be deleted is head node if self.head == dele: self.head = dele.next # Change next only if node to be deleted is NOT # the last node if dele.next is not None: dele.next.prev = dele.prev # Change prev only if node to be deleted is NOT # the first node if dele.prev is not None: dele.prev.next = dele.next # Finally, free the memory occupied by dele # Call python garbage collector gc.collect() # Given a reference to the head of a list and an # integer, inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = Node(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node def printList(self, node): while(node is not None): print(node.data,end=' ') node = node.next # Driver program to test the above functions # Start with empty listdll = DoublyLinkedList() # Let us create the doubly linked list 10<->8<->4<->2dll.push(2);dll.push(4);dll.push(8);dll.push(10); print (\"\\n Original Linked List\",end=' ')dll.printList(dll.head) # delete nodes from doubly linked listdll.deleteNode(dll.head)dll.deleteNode(dll.head.next)dll.deleteNode(dll.head.next)# Modified linked list will be NULL<-8->NULLprint(\"\\n Modified Linked List\",end=' ')dll.printList(dll.head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 11694, "s": 9238, "text": null }, { "code": "// C# program to delete a node from// Doubly Linked Listusing System; // Class for Doubly Linked Listpublic class DLL { Node head; // head of list /* Doubly Linked list Node*/ public class Node { public int data; public Node prev; public Node next; // Constructor to create a new node // next and prev is by default // initialized as null public Node(int d) { data = d; } } // Adding a node at the front of the list public void push(int new_data) { // 1. allocate node // 2. put in the data Node new_Node = new Node(new_data); // 3. Make next of new node as head // and previous as NULL new_Node.next = head; new_Node.prev = null; // 4. change prev of head node to new node if (head != null) head.prev = new_Node; // 5. move the head to point to the new node head = new_Node; } // This function prints contents of linked list // starting from the given node public void printlist(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } Console.WriteLine(); } // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> data of node to be deleted. void deleteNode(Node del) { // Base case if (head == null || del == null) { return; } // If node to be deleted is head node if (head == del) { head = del.next; } // Change next only if node to be deleted // is NOT the last node if (del.next != null) { del.next.prev = del.prev; } // Change prev only if node to be deleted // is NOT the first node if (del.prev != null) { del.prev.next = del.next; } // Finally, free the memory occupied by del return; } // Driver Code public static void Main() { // Start with the empty list DLL dll = new DLL(); // Insert 2. So linked list becomes 2->NULL dll.push(2); // Insert 4. So linked list becomes 4->2->NULL dll.push(4); // Insert 8. So linked list becomes 8->4->2->NULL dll.push(8); // Insert 10. So linked list becomes 10->8->4->2->NULL dll.push(10); Console.Write(\"Created DLL is: \"); dll.printlist(dll.head); // Deleting first node dll.deleteNode(dll.head); // List after deleting first node // 8->4->2 Console.Write(\"\\nList after deleting first node: \"); dll.printlist(dll.head); // Deleting middle node from 8->4->2 dll.deleteNode(dll.head.next); Console.Write(\"\\nList after Deleting middle node: \"); dll.printlist(dll.head); }}// This code is contributed by PrinciRaj1992", "e": 14699, "s": 11694, "text": null }, { "code": "<script> // Javascript program to delete a node from// Doubly Linked List // Class for Doubly Linked Listvar head; // head of list /* Doubly Linked list Node */ class Node { // Constructor to create a new node // next and prev is by default initialized // as null constructor(val) { this.data = val; this.prev = null; this.next = null; } } // Adding a node at the front of the list function push(new_data) { // 1. allocate node // 2. put in the data new_Node = new Node(new_data); // 3. Make next of new node as head // and previous as NULL new_Node.next = head; new_Node.prev = null; // 4. change prev of head node to new node if (head != null) head.prev = new_Node; // 5. move the head to point to the new node head = new_Node; } // This function prints contents of linked list // starting from the given node function printlist( node) { last = null; while (node != null) { document.write(node.data + \" \"); last = node; node = node.next; } document.write(\"<br/>\"); } // Function to delete a node in a Doubly Linked List. // head_ref --> pointer to head node pointer. // del --> data of node to be deleted. function deleteNode( del) { // Base case if (head == null || del == null) { return; } // If node to be deleted is head node if (head == del) { head = del.next; } // Change next only if node to be deleted // is NOT the last node if (del.next != null) { del.next.prev = del.prev; } // Change prev only if node to be deleted // is NOT the first node if (del.prev != null) { del.prev.next = del.next; } // Finally, free the memory occupied by del return; } // Driver Code // Start with the empty list // Insert 2. So linked list becomes 2->NULL push(2); // Insert 4. So linked list becomes 4->2->NULL push(4); // Insert 8. So linked list becomes 8->4->2->NULL push(8); // Insert 10. So linked list becomes 10->8->4->2->NULL push(10); document.write(\"Created DLL is: \"); printlist(head); // Deleting first node deleteNode(head); deleteNode(head.next); deleteNode(head.next); document.write(\"Modified Linked list: \"); printlist(head); // This code is contributed by todaysgaurav </script>", "e": 17390, "s": 14699, "text": null }, { "code": null, "e": 17444, "s": 17390, "text": "Original Linked list 10 8 4 2 \nModified Linked list 8" }, { "code": null, "e": 17468, "s": 17446, "text": "Complexity Analysis: " }, { "code": null, "e": 17578, "s": 17468, "text": "Time Complexity: O(1). Since traversal of the linked list is not required so the time complexity is constant." }, { "code": null, "e": 17670, "s": 17578, "text": "Space Complexity: O(1). As no extra space is required, so the space complexity is constant." }, { "code": null, "e": 17796, "s": 17670, "text": "Please write comments if you find any of the above codes/algorithms incorrect, or find better ways to solve the same problem." }, { "code": null, "e": 17809, "s": 17796, "text": "RiskCatalyst" }, { "code": null, "e": 17823, "s": 17809, "text": "princiraj1992" }, { "code": null, "e": 17837, "s": 17823, "text": "rathbhupendra" }, { "code": null, "e": 17850, "s": 17837, "text": "Akanksha_Rai" }, { "code": null, "e": 17861, "s": 17850, "text": "nidhi_biet" }, { "code": null, "e": 17872, "s": 17861, "text": "andrew1234" }, { "code": null, "e": 17886, "s": 17872, "text": "shivrajsingh5" }, { "code": null, "e": 17897, "s": 17886, "text": "shivampuri" }, { "code": null, "e": 17910, "s": 17897, "text": "todaysgaurav" }, { "code": null, "e": 17926, "s": 17910, "text": "simranarora5sos" }, { "code": null, "e": 17942, "s": 17926, "text": "amartyaghoshgfg" }, { "code": null, "e": 17952, "s": 17942, "text": "sweatwork" }, { "code": null, "e": 17969, "s": 17952, "text": "hardikkoriintern" }, { "code": null, "e": 17976, "s": 17969, "text": "Amazon" }, { "code": null, "e": 17995, "s": 17976, "text": "doubly linked list" }, { "code": null, "e": 18007, "s": 17995, "text": "Linked List" }, { "code": null, "e": 18014, "s": 18007, "text": "Amazon" }, { "code": null, "e": 18026, "s": 18014, "text": "Linked List" } ]
Printing Output of an R Program
22 Mar, 2022 In R there are various methods to print the output. Most common method to print output in R program, there is a function called print() is used. Also if the program of R is written over the console line by line then the output is printed normally, no need to use any function for print that output. To do this just select the output variable and press run button. Example: R # select 'x' and then press 'run' button# it will print 'GeeksforGeeks' on the consolex <- "GeeksforGeeks"x Output: [1] "GeeksforGeeks" Using print() function to print output is the most common method in R. Implementation of this method is very simple. Syntax: print(β€œany string”) or, print(variable) Example: R # R program to illustrate# printing output of an R program # print stringprint("GFG") # print variable# it will print 'GeeksforGeeks' on the consolex <- "GeeksforGeeks"print(x) Output: [1] "GFG" [1] "GeeksforGeeks" R provides a method paste() to print output with string and variable together. This method defined inside the print() function. paste() converts its arguments to character strings. One can also use paste0() method. Note: The difference between paste() and paste0() is that the argument sep by default is ” β€œ(paste) and β€œβ€(paste0). Syntax: print(paste(β€œany string”, variable)) or, print(paste0(variable, β€œany string”)) Example: R # R program to illustrate# printing output of an R program x <- "GeeksforGeeks" # using paste inside print()print(paste(x, "is best (paste inside print())")) # using paste0 inside print()print(paste0(x, "is best (paste0 inside print())")) Output: [1] "GeeksforGeeks is best (paste inside print())" [1] "GeeksforGeeksis best (paste0 inside print())" sprintf() is basically a C library function. This function is use to print string as C language. This is working as a wrapper function to print values and strings together like C language. This function returns a character vector containing a formatted combination of string and variable to be printed. Syntax: sprintf(β€œany string %d”, variable) or, sprintf(β€œany string %s”, variable) or, sprintf(β€œany string %f”, variable)) etc. Example: R # R program to illustrate# printing output of an R program x = "GeeksforGeeks" # stringx1 = 255 # integerx2 = 23.14 # float # string printsprintf("%s is best", x) # integer printsprintf("%d is integer", x1) # float printsprintf("%f is float", x2) Output: > sprintf("%s is best", x) [1] "GeeksforGeeks is best" > sprintf("%d is integer", x1) [1] "255 is integer" > sprintf("%f is float", x2) [1] "23.140000 is float" Another way to print output in R is using of cat() function. It’s same as print() function. cat() converts its arguments to character strings. This is useful for printing output in user defined functions. Syntax: cat(β€œany string”) or, cat(β€œany string”, variable) Example: R # R program to illustrate# printing output of an R program # print string with variable# "\n" for new linex = "GeeksforGeeks"cat(x, "is best\n") # print normal stringcat("This is R language") Output: GeeksforGeeks is best This is R language Another way to print something in R by using message() function. This is not used for print output but its use for showing simple diagnostic messages which are no warnings or errors in the program. But it can be used for normal uses for printing output. Syntax: message(β€œany string”) or, message(β€œany string”, variable) Example: R # R program to illustrate# printing output of an R program x = "GeeksforGeeks"# print string with variablemessage(x, "is best") # print normal stringmessage("This is R language") Output: GeeksforGeeks is best This is R language To print or write a file with a value of a variable there is a function called write(). This function is used a option called table to write a file. Syntax: write.table(variable, file = β€œfile1.txt”) or, write.table(β€œany string”, file = β€œfile1.txt”) Example: R # R program to illustrate# printing output of an R program x = "GeeksforGeeks"# write variablewrite.table(x, file = "my_data1.txt") # write normal stringwrite.table("GFG is best", file = "my_data2.txt") Output: simmytarika5 Picked R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Mar, 2022" }, { "code": null, "e": 402, "s": 28, "text": "In R there are various methods to print the output. Most common method to print output in R program, there is a function called print() is used. Also if the program of R is written over the console line by line then the output is printed normally, no need to use any function for print that output. To do this just select the output variable and press run button. Example: " }, { "code": null, "e": 404, "s": 402, "text": "R" }, { "code": "# select 'x' and then press 'run' button# it will print 'GeeksforGeeks' on the consolex <- \"GeeksforGeeks\"x", "e": 512, "s": 404, "text": null }, { "code": null, "e": 520, "s": 512, "text": "Output:" }, { "code": null, "e": 540, "s": 520, "text": "[1] \"GeeksforGeeks\"" }, { "code": null, "e": 657, "s": 540, "text": "Using print() function to print output is the most common method in R. Implementation of this method is very simple." }, { "code": null, "e": 705, "s": 657, "text": "Syntax: print(β€œany string”) or, print(variable)" }, { "code": null, "e": 715, "s": 705, "text": "Example: " }, { "code": null, "e": 717, "s": 715, "text": "R" }, { "code": "# R program to illustrate# printing output of an R program # print stringprint(\"GFG\") # print variable# it will print 'GeeksforGeeks' on the consolex <- \"GeeksforGeeks\"print(x)", "e": 894, "s": 717, "text": null }, { "code": null, "e": 902, "s": 894, "text": "Output:" }, { "code": null, "e": 932, "s": 902, "text": "[1] \"GFG\"\n[1] \"GeeksforGeeks\"" }, { "code": null, "e": 1147, "s": 932, "text": "R provides a method paste() to print output with string and variable together. This method defined inside the print() function. paste() converts its arguments to character strings. One can also use paste0() method." }, { "code": null, "e": 1263, "s": 1147, "text": "Note: The difference between paste() and paste0() is that the argument sep by default is ” β€œ(paste) and β€œβ€(paste0)." }, { "code": null, "e": 1350, "s": 1263, "text": "Syntax: print(paste(β€œany string”, variable)) or, print(paste0(variable, β€œany string”))" }, { "code": null, "e": 1360, "s": 1350, "text": "Example: " }, { "code": null, "e": 1362, "s": 1360, "text": "R" }, { "code": "# R program to illustrate# printing output of an R program x <- \"GeeksforGeeks\" # using paste inside print()print(paste(x, \"is best (paste inside print())\")) # using paste0 inside print()print(paste0(x, \"is best (paste0 inside print())\"))", "e": 1601, "s": 1362, "text": null }, { "code": null, "e": 1609, "s": 1601, "text": "Output:" }, { "code": null, "e": 1711, "s": 1609, "text": "[1] \"GeeksforGeeks is best (paste inside print())\"\n[1] \"GeeksforGeeksis best (paste0 inside print())\"" }, { "code": null, "e": 2014, "s": 1711, "text": "sprintf() is basically a C library function. This function is use to print string as C language. This is working as a wrapper function to print values and strings together like C language. This function returns a character vector containing a formatted combination of string and variable to be printed." }, { "code": null, "e": 2141, "s": 2014, "text": "Syntax: sprintf(β€œany string %d”, variable) or, sprintf(β€œany string %s”, variable) or, sprintf(β€œany string %f”, variable)) etc." }, { "code": null, "e": 2151, "s": 2141, "text": "Example: " }, { "code": null, "e": 2153, "s": 2151, "text": "R" }, { "code": "# R program to illustrate# printing output of an R program x = \"GeeksforGeeks\" # stringx1 = 255 # integerx2 = 23.14 # float # string printsprintf(\"%s is best\", x) # integer printsprintf(\"%d is integer\", x1) # float printsprintf(\"%f is float\", x2)", "e": 2420, "s": 2153, "text": null }, { "code": null, "e": 2428, "s": 2420, "text": "Output:" }, { "code": null, "e": 2589, "s": 2428, "text": "> sprintf(\"%s is best\", x)\n[1] \"GeeksforGeeks is best\"\n> sprintf(\"%d is integer\", x1)\n[1] \"255 is integer\"\n> sprintf(\"%f is float\", x2)\n[1] \"23.140000 is float\"" }, { "code": null, "e": 2794, "s": 2589, "text": "Another way to print output in R is using of cat() function. It’s same as print() function. cat() converts its arguments to character strings. This is useful for printing output in user defined functions." }, { "code": null, "e": 2852, "s": 2794, "text": "Syntax: cat(β€œany string”) or, cat(β€œany string”, variable)" }, { "code": null, "e": 2862, "s": 2852, "text": "Example: " }, { "code": null, "e": 2864, "s": 2862, "text": "R" }, { "code": "# R program to illustrate# printing output of an R program # print string with variable# \"\\n\" for new linex = \"GeeksforGeeks\"cat(x, \"is best\\n\") # print normal stringcat(\"This is R language\")", "e": 3056, "s": 2864, "text": null }, { "code": null, "e": 3064, "s": 3056, "text": "Output:" }, { "code": null, "e": 3105, "s": 3064, "text": "GeeksforGeeks is best\nThis is R language" }, { "code": null, "e": 3359, "s": 3105, "text": "Another way to print something in R by using message() function. This is not used for print output but its use for showing simple diagnostic messages which are no warnings or errors in the program. But it can be used for normal uses for printing output." }, { "code": null, "e": 3425, "s": 3359, "text": "Syntax: message(β€œany string”) or, message(β€œany string”, variable)" }, { "code": null, "e": 3435, "s": 3425, "text": "Example: " }, { "code": null, "e": 3437, "s": 3435, "text": "R" }, { "code": "# R program to illustrate# printing output of an R program x = \"GeeksforGeeks\"# print string with variablemessage(x, \"is best\") # print normal stringmessage(\"This is R language\")", "e": 3616, "s": 3437, "text": null }, { "code": null, "e": 3624, "s": 3616, "text": "Output:" }, { "code": null, "e": 3666, "s": 3624, "text": "GeeksforGeeks is best\nThis is R language " }, { "code": null, "e": 3815, "s": 3666, "text": "To print or write a file with a value of a variable there is a function called write(). This function is used a option called table to write a file." }, { "code": null, "e": 3915, "s": 3815, "text": "Syntax: write.table(variable, file = β€œfile1.txt”) or, write.table(β€œany string”, file = β€œfile1.txt”)" }, { "code": null, "e": 3925, "s": 3915, "text": "Example: " }, { "code": null, "e": 3927, "s": 3925, "text": "R" }, { "code": "# R program to illustrate# printing output of an R program x = \"GeeksforGeeks\"# write variablewrite.table(x, file = \"my_data1.txt\") # write normal stringwrite.table(\"GFG is best\", file = \"my_data2.txt\")", "e": 4130, "s": 3927, "text": null }, { "code": null, "e": 4139, "s": 4130, "text": "Output: " }, { "code": null, "e": 4152, "s": 4139, "text": "simmytarika5" }, { "code": null, "e": 4159, "s": 4152, "text": "Picked" }, { "code": null, "e": 4170, "s": 4159, "text": "R Language" }, { "code": null, "e": 4268, "s": 4170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4313, "s": 4268, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 4365, "s": 4313, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 4423, "s": 4365, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 4475, "s": 4423, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 4533, "s": 4475, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 4565, "s": 4533, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 4628, "s": 4565, "text": "Adding elements in a vector in R programming - append() method" }, { "code": null, "e": 4663, "s": 4628, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 4707, "s": 4663, "text": "How to change Row Names of DataFrame in R ?" } ]
List methods in Python
07 Jun, 2022 This article is extension of below articles :Python ListList Methods in Python | Set 1 (in, not in, len(), min(), max()...)List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...) Adding and Appending append(): Used for appending and adding elements to List.It is used to add elements to the last position of List.Syntax: list.append (element)# Adds List Element as value of List.List = ['Mathematics', 'chemistry', 1997, 2000]List.append(20544)print(List)Output:['Mathematics', 'chemistry', 1997, 2000, 20544] list.append (element) # Adds List Element as value of List.List = ['Mathematics', 'chemistry', 1997, 2000]List.append(20544)print(List) Output: ['Mathematics', 'chemistry', 1997, 2000, 20544] insert(): Inserts an elements at specified position.Syntax: list.insert(<position, element)Note: Position mentioned should be within the range of List, as in this case between 0 and 4, elsewise would throw IndexError.List = ['Mathematics', 'chemistry', 1997, 2000]# Insert at index 2 value 10087List.insert(2,10087) print(List) Output:['Mathematics', 'chemistry', 10087, 1997, 2000, 20544] list.insert(<position, element) Note: Position mentioned should be within the range of List, as in this case between 0 and 4, elsewise would throw IndexError. List = ['Mathematics', 'chemistry', 1997, 2000]# Insert at index 2 value 10087List.insert(2,10087) print(List) Output: ['Mathematics', 'chemistry', 10087, 1997, 2000, 20544] extend(): Adds contents to List2 to the end of List1.Syntax:List1.extend(List2)List1 = [1, 2, 3]List2 = [2, 3, 4, 5] # Add List2 to List1List1.extend(List2) print(List1) # Add List1 to List2 nowList2.extend(List1) print(List2)Output:[1, 2, 3, 2, 3, 4, 5] [2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5] List1.extend(List2) List1 = [1, 2, 3]List2 = [2, 3, 4, 5] # Add List2 to List1List1.extend(List2) print(List1) # Add List1 to List2 nowList2.extend(List1) print(List2) Output: [1, 2, 3, 2, 3, 4, 5] [2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5] sum(), count(), index(), min() and max() functions of List sum() : Calculates sum of all the elements of List.Syntax: sum(List)List = [1, 2, 3, 4, 5]print(sum(List))Output:15 What happens if numeric value is not used a parameter?Sum is calculated only for Numeric values, elsewise throws TypeError.See example:List = ['gfg', 'abc', 3]print(sum(List))Output:Traceback (most recent call last): File "", line 1, in sum(List) TypeError: unsupported operand type(s) for +: 'int' and 'str' sum(List) List = [1, 2, 3, 4, 5]print(sum(List)) Output: 15 What happens if numeric value is not used a parameter?Sum is calculated only for Numeric values, elsewise throws TypeError.See example: List = ['gfg', 'abc', 3]print(sum(List)) Output: Traceback (most recent call last): File "", line 1, in sum(List) TypeError: unsupported operand type(s) for +: 'int' and 'str' count():Calculates total occurrence of given element of List.Syntax:List.count(element)List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.count(1))Output:4 List.count(element) List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.count(1)) Output: 4 length:Calculates total length of List.Syntax:len(list_name)List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(len(List))Output:10 len(list_name) List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(len(List)) Output: 10 index(): Returns the index of first occurrence. Start and End index are not necessary parameters.Syntax:List.index(element[,start[,end]])List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2))Output:1 Another example:List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2,2))Output:4 List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] """index(element, start, end) : It will calculate till index end-1. """ # will check from index 2 to 4.print("After checking in index range 2 to 4")print(List.index(2,2,5)) # will check from index 2 to 3.print("After checking in index range 2 to 3")print(List.index(2,2,4)) Output:After checking in index range 2 to 4 4 After checking in index range 2 to 3 Traceback (most recent call last): File "", line 1, in List.index(2,2,4) ValueError: tuple.index(x): x not in tuple List.index(element[,start[,end]]) List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2)) Output: 1 Another example: List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2,2)) Output: 4 List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] """index(element, start, end) : It will calculate till index end-1. """ # will check from index 2 to 4.print("After checking in index range 2 to 4")print(List.index(2,2,5)) # will check from index 2 to 3.print("After checking in index range 2 to 3")print(List.index(2,2,4)) Output: After checking in index range 2 to 4 4 After checking in index range 2 to 3 Traceback (most recent call last): File "", line 1, in List.index(2,2,4) ValueError: tuple.index(x): x not in tuple min() : Calculates minimum of all the elements of List.Syntax:min(List)List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(min(List))Output:1.054 min(List) List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(min(List)) Output: 1.054 max(): Calculates maximum of all the elements of List.Syntax:max(List)List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(max(List))Output:5.33 max(List) List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(max(List)) Output: 5.33 sort() and reverse() functions reverse(): Sort the given data structure (both tuple and list) in ascending order. Key and reverse_flag are not necessary parameter and reverse_flag is set to False, if nothing is passed through sorted().Syntax:sorted([list[,key[,Reverse_Flag]]]) list.sort([key,[Reverse_flag]])List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] #Reverse flag is set TrueList.sort(reverse=True) #List.sort().reverse(), reverses the sorted list print(List) Output:[5.33, 4.445, 3, 2.5, 2.3, 1.054] List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]sorted(List)print(List)Output:[1.054, 2.3, 2.5, 3, 4.445, 5.33] sorted([list[,key[,Reverse_Flag]]]) list.sort([key,[Reverse_flag]]) List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] #Reverse flag is set TrueList.sort(reverse=True) #List.sort().reverse(), reverses the sorted list print(List) Output: [5.33, 4.445, 3, 2.5, 2.3, 1.054] List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]sorted(List)print(List) Output: [1.054, 2.3, 2.5, 3, 4.445, 5.33] Deletion of List Elements To Delete one or more elements, i.e. remove an element, many built in functions can be used, such as pop() & remove() and keywords such as del. pop(): Index is not a necessary parameter, if not mentioned takes the last index.Syntax: list.pop([index])Note: Index must be in range of the List, elsewise IndexErrors occurs.List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop())Output:2.5 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop(0))Output:2.3 list.pop([index]) Note: Index must be in range of the List, elsewise IndexErrors occurs. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop()) Output: 2.5 List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop(0)) Output: 2.3 del() : Element to be deleted is mentioned using list name and index.Syntax:del list.[index]List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]del List[0]print(List)Output:[4.445, 3, 5.33, 1.054, 2.5] del list.[index] List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]del List[0]print(List) Output: [4.445, 3, 5.33, 1.054, 2.5] remove(): Element to be deleted is mentioned using list name and element.Syntax: list.remove(element)List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]List.remove(3)print(List)Output:[2.3, 4.445, 5.33, 1.054, 2.5] list.remove(element) List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]List.remove(3)print(List) Output: [2.3, 4.445, 5.33, 1.054, 2.5] \ bpvandana Sandip Shaw NiteshJyotishi nikhilaggarwal3 python-list python-list-functions 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 Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2022" }, { "code": null, "e": 260, "s": 52, "text": "This article is extension of below articles :Python ListList Methods in Python | Set 1 (in, not in, len(), min(), max()...)List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)" }, { "code": null, "e": 281, "s": 260, "text": "Adding and Appending" }, { "code": null, "e": 594, "s": 281, "text": "append(): Used for appending and adding elements to List.It is used to add elements to the last position of List.Syntax: list.append (element)# Adds List Element as value of List.List = ['Mathematics', 'chemistry', 1997, 2000]List.append(20544)print(List)Output:['Mathematics', 'chemistry', 1997, 2000, 20544]\n " }, { "code": null, "e": 617, "s": 594, "text": " list.append (element)" }, { "code": "# Adds List Element as value of List.List = ['Mathematics', 'chemistry', 1997, 2000]List.append(20544)print(List)", "e": 731, "s": 617, "text": null }, { "code": null, "e": 739, "s": 731, "text": "Output:" }, { "code": null, "e": 788, "s": 739, "text": "['Mathematics', 'chemistry', 1997, 2000, 20544]\n" }, { "code": null, "e": 1192, "s": 790, "text": "insert(): Inserts an elements at specified position.Syntax: list.insert(<position, element)Note: Position mentioned should be within the range of List, as in this case between 0 and 4, elsewise would throw IndexError.List = ['Mathematics', 'chemistry', 1997, 2000]# Insert at index 2 value 10087List.insert(2,10087) print(List) Output:['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]\n" }, { "code": null, "e": 1225, "s": 1192, "text": " list.insert(<position, element)" }, { "code": null, "e": 1352, "s": 1225, "text": "Note: Position mentioned should be within the range of List, as in this case between 0 and 4, elsewise would throw IndexError." }, { "code": "List = ['Mathematics', 'chemistry', 1997, 2000]# Insert at index 2 value 10087List.insert(2,10087) print(List) ", "e": 1475, "s": 1352, "text": null }, { "code": null, "e": 1483, "s": 1475, "text": "Output:" }, { "code": null, "e": 1539, "s": 1483, "text": "['Mathematics', 'chemistry', 10087, 1997, 2000, 20544]\n" }, { "code": null, "e": 1837, "s": 1539, "text": "extend(): Adds contents to List2 to the end of List1.Syntax:List1.extend(List2)List1 = [1, 2, 3]List2 = [2, 3, 4, 5] # Add List2 to List1List1.extend(List2) print(List1) # Add List1 to List2 nowList2.extend(List1) print(List2)Output:[1, 2, 3, 2, 3, 4, 5]\n[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]" }, { "code": null, "e": 1857, "s": 1837, "text": "List1.extend(List2)" }, { "code": "List1 = [1, 2, 3]List2 = [2, 3, 4, 5] # Add List2 to List1List1.extend(List2) print(List1) # Add List1 to List2 nowList2.extend(List1) print(List2)", "e": 2014, "s": 1857, "text": null }, { "code": null, "e": 2022, "s": 2014, "text": "Output:" }, { "code": null, "e": 2078, "s": 2022, "text": "[1, 2, 3, 2, 3, 4, 5]\n[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]" }, { "code": null, "e": 2137, "s": 2078, "text": "sum(), count(), index(), min() and max() functions of List" }, { "code": null, "e": 2570, "s": 2137, "text": "sum() : Calculates sum of all the elements of List.Syntax: sum(List)List = [1, 2, 3, 4, 5]print(sum(List))Output:15\nWhat happens if numeric value is not used a parameter?Sum is calculated only for Numeric values, elsewise throws TypeError.See example:List = ['gfg', 'abc', 3]print(sum(List))Output:Traceback (most recent call last):\n File \"\", line 1, in \n sum(List)\nTypeError: unsupported operand type(s) for +: 'int' and 'str'\n" }, { "code": null, "e": 2581, "s": 2570, "text": " sum(List)" }, { "code": "List = [1, 2, 3, 4, 5]print(sum(List))", "e": 2620, "s": 2581, "text": null }, { "code": null, "e": 2628, "s": 2620, "text": "Output:" }, { "code": null, "e": 2632, "s": 2628, "text": "15\n" }, { "code": null, "e": 2768, "s": 2632, "text": "What happens if numeric value is not used a parameter?Sum is calculated only for Numeric values, elsewise throws TypeError.See example:" }, { "code": "List = ['gfg', 'abc', 3]print(sum(List))", "e": 2809, "s": 2768, "text": null }, { "code": null, "e": 2817, "s": 2809, "text": "Output:" }, { "code": null, "e": 2952, "s": 2817, "text": "Traceback (most recent call last):\n File \"\", line 1, in \n sum(List)\nTypeError: unsupported operand type(s) for +: 'int' and 'str'\n" }, { "code": null, "e": 3106, "s": 2952, "text": "count():Calculates total occurrence of given element of List.Syntax:List.count(element)List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.count(1))Output:4\n" }, { "code": null, "e": 3126, "s": 3106, "text": "List.count(element)" }, { "code": "List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.count(1))", "e": 3184, "s": 3126, "text": null }, { "code": null, "e": 3192, "s": 3184, "text": "Output:" }, { "code": null, "e": 3195, "s": 3192, "text": "4\n" }, { "code": null, "e": 3319, "s": 3195, "text": "length:Calculates total length of List.Syntax:len(list_name)List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(len(List))Output:10\n" }, { "code": null, "e": 3334, "s": 3319, "text": "len(list_name)" }, { "code": "List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(len(List))", "e": 3388, "s": 3334, "text": null }, { "code": null, "e": 3396, "s": 3388, "text": "Output:" }, { "code": null, "e": 3400, "s": 3396, "text": "10\n" }, { "code": null, "e": 4213, "s": 3400, "text": "index(): Returns the index of first occurrence. Start and End index are not necessary parameters.Syntax:List.index(element[,start[,end]])List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2))Output:1\nAnother example:List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2,2))Output:4\nList = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] \"\"\"index(element, start, end) : It will calculate till index end-1. \"\"\" # will check from index 2 to 4.print(\"After checking in index range 2 to 4\")print(List.index(2,2,5)) # will check from index 2 to 3.print(\"After checking in index range 2 to 3\")print(List.index(2,2,4)) Output:After checking in index range 2 to 4\n4\nAfter checking in index range 2 to 3\nTraceback (most recent call last):\n File \"\", line 1, in \n List.index(2,2,4)\nValueError: tuple.index(x): x not in tuple\n" }, { "code": null, "e": 4247, "s": 4213, "text": "List.index(element[,start[,end]])" }, { "code": "List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2))", "e": 4305, "s": 4247, "text": null }, { "code": null, "e": 4313, "s": 4305, "text": "Output:" }, { "code": null, "e": 4316, "s": 4313, "text": "1\n" }, { "code": null, "e": 4333, "s": 4316, "text": "Another example:" }, { "code": "List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]print(List.index(2,2))", "e": 4393, "s": 4333, "text": null }, { "code": null, "e": 4401, "s": 4393, "text": "Output:" }, { "code": null, "e": 4404, "s": 4401, "text": "4\n" }, { "code": "List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] \"\"\"index(element, start, end) : It will calculate till index end-1. \"\"\" # will check from index 2 to 4.print(\"After checking in index range 2 to 4\")print(List.index(2,2,5)) # will check from index 2 to 3.print(\"After checking in index range 2 to 3\")print(List.index(2,2,4)) ", "e": 4724, "s": 4404, "text": null }, { "code": null, "e": 4732, "s": 4724, "text": "Output:" }, { "code": null, "e": 4932, "s": 4732, "text": "After checking in index range 2 to 4\n4\nAfter checking in index range 2 to 3\nTraceback (most recent call last):\n File \"\", line 1, in \n List.index(2,2,4)\nValueError: tuple.index(x): x not in tuple\n" }, { "code": null, "e": 5073, "s": 4932, "text": "min() : Calculates minimum of all the elements of List.Syntax:min(List)List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(min(List))Output:1.054\n" }, { "code": null, "e": 5083, "s": 5073, "text": "min(List)" }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(min(List))", "e": 5140, "s": 5083, "text": null }, { "code": null, "e": 5148, "s": 5140, "text": "Output:" }, { "code": null, "e": 5155, "s": 5148, "text": "1.054\n" }, { "code": null, "e": 5294, "s": 5155, "text": "max(): Calculates maximum of all the elements of List.Syntax:max(List)List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(max(List))Output:5.33\n" }, { "code": null, "e": 5304, "s": 5294, "text": "max(List)" }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(max(List))", "e": 5361, "s": 5304, "text": null }, { "code": null, "e": 5369, "s": 5361, "text": "Output:" }, { "code": null, "e": 5375, "s": 5369, "text": "5.33\n" }, { "code": null, "e": 5406, "s": 5375, "text": "sort() and reverse() functions" }, { "code": null, "e": 5993, "s": 5406, "text": "reverse(): Sort the given data structure (both tuple and list) in ascending order. Key and reverse_flag are not necessary parameter and reverse_flag is set to False, if nothing is passed through sorted().Syntax:sorted([list[,key[,Reverse_Flag]]])\n list.sort([key,[Reverse_flag]])List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] #Reverse flag is set TrueList.sort(reverse=True) #List.sort().reverse(), reverses the sorted list print(List) Output:[5.33, 4.445, 3, 2.5, 2.3, 1.054]\nList = [2.3, 4.445, 3, 5.33, 1.054, 2.5]sorted(List)print(List)Output:[1.054, 2.3, 2.5, 3, 4.445, 5.33]\n" }, { "code": null, "e": 6062, "s": 5993, "text": "sorted([list[,key[,Reverse_Flag]]])\n list.sort([key,[Reverse_flag]])" }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] #Reverse flag is set TrueList.sort(reverse=True) #List.sort().reverse(), reverses the sorted list print(List) ", "e": 6225, "s": 6062, "text": null }, { "code": null, "e": 6233, "s": 6225, "text": "Output:" }, { "code": null, "e": 6268, "s": 6233, "text": "[5.33, 4.445, 3, 2.5, 2.3, 1.054]\n" }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]sorted(List)print(List)", "e": 6332, "s": 6268, "text": null }, { "code": null, "e": 6340, "s": 6332, "text": "Output:" }, { "code": null, "e": 6375, "s": 6340, "text": "[1.054, 2.3, 2.5, 3, 4.445, 5.33]\n" }, { "code": null, "e": 6401, "s": 6375, "text": "Deletion of List Elements" }, { "code": null, "e": 6545, "s": 6401, "text": "To Delete one or more elements, i.e. remove an element, many built in functions can be used, such as pop() & remove() and keywords such as del." }, { "code": null, "e": 6859, "s": 6545, "text": "pop(): Index is not a necessary parameter, if not mentioned takes the last index.Syntax: list.pop([index])Note: Index must be in range of the List, elsewise IndexErrors occurs.List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop())Output:2.5\nList = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop(0))Output:2.3\n" }, { "code": null, "e": 6878, "s": 6859, "text": " list.pop([index])" }, { "code": null, "e": 6949, "s": 6878, "text": "Note: Index must be in range of the List, elsewise IndexErrors occurs." }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop())", "e": 7007, "s": 6949, "text": null }, { "code": null, "e": 7015, "s": 7007, "text": "Output:" }, { "code": null, "e": 7020, "s": 7015, "text": "2.5\n" }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]print(List.pop(0))", "e": 7079, "s": 7020, "text": null }, { "code": null, "e": 7087, "s": 7079, "text": "Output:" }, { "code": null, "e": 7092, "s": 7087, "text": "2.3\n" }, { "code": null, "e": 7282, "s": 7092, "text": "del() : Element to be deleted is mentioned using list name and index.Syntax:del list.[index]List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]del List[0]print(List)Output:[4.445, 3, 5.33, 1.054, 2.5]" }, { "code": null, "e": 7299, "s": 7282, "text": "del list.[index]" }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]del List[0]print(List)", "e": 7362, "s": 7299, "text": null }, { "code": null, "e": 7370, "s": 7362, "text": "Output:" }, { "code": null, "e": 7399, "s": 7370, "text": "[4.445, 3, 5.33, 1.054, 2.5]" }, { "code": null, "e": 7604, "s": 7399, "text": "remove(): Element to be deleted is mentioned using list name and element.Syntax: list.remove(element)List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]List.remove(3)print(List)Output:[2.3, 4.445, 5.33, 1.054, 2.5]\n" }, { "code": null, "e": 7626, "s": 7604, "text": " list.remove(element)" }, { "code": "List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]List.remove(3)print(List)", "e": 7692, "s": 7626, "text": null }, { "code": null, "e": 7700, "s": 7692, "text": "Output:" }, { "code": null, "e": 7732, "s": 7700, "text": "[2.3, 4.445, 5.33, 1.054, 2.5]\n" }, { "code": null, "e": 7734, "s": 7732, "text": "\\" }, { "code": null, "e": 7744, "s": 7734, "text": "bpvandana" }, { "code": null, "e": 7756, "s": 7744, "text": "Sandip Shaw" }, { "code": null, "e": 7771, "s": 7756, "text": "NiteshJyotishi" }, { "code": null, "e": 7787, "s": 7771, "text": "nikhilaggarwal3" }, { "code": null, "e": 7799, "s": 7787, "text": "python-list" }, { "code": null, "e": 7821, "s": 7799, "text": "python-list-functions" }, { "code": null, "e": 7828, "s": 7821, "text": "Python" }, { "code": null, "e": 7840, "s": 7828, "text": "python-list" }, { "code": null, "e": 7938, "s": 7840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7980, "s": 7938, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 8002, "s": 7980, "text": "Enumerate() in Python" }, { "code": null, "e": 8028, "s": 8002, "text": "Python String | replace()" }, { "code": null, "e": 8060, "s": 8028, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 8089, "s": 8060, "text": "*args and **kwargs in Python" }, { "code": null, "e": 8116, "s": 8089, "text": "Python Classes and Objects" }, { "code": null, "e": 8137, "s": 8116, "text": "Python OOPs Concepts" }, { "code": null, "e": 8173, "s": 8137, "text": "Convert integer to string in Python" }, { "code": null, "e": 8196, "s": 8173, "text": "Introduction To PYTHON" } ]
How to get the current URL using AngularJS ?
29 Sep, 2020 In this article, we are going to see how to get the current URL with the help of AngularJS. We will be using the $location.absURL() method to get the complete URL of the current page. Syntax: $location.absURL() Example 1: Just use the $location.absURL() method to get the complete URL of the current page. HTML <!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope, $location) { $scope.url = ''; $scope.getUrl = function () { $scope.url = $location.absUrl(); }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Get current URL in angularJS </p> <div ng-app="app"> <div ng-controller="controller"> <p>Url = {{url}}</p> <input type="button" value="Click to get URL" ng-click="getUrl()"> </div> </div></body> </html> Output: Example 2: Similar to the previous example but using the split() method to get the domain name of the URL. HTML <!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"> </script> <script> var myApp = angular.module("app", []); myApp.controller("controller", function ($scope, $location) { $scope.url = ''; $scope.getUrl = function () { // Will change the current url to // ide.geeksforgeeks.org $scope.url = $location .absUrl().split('/')[2];; }; }); </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p> Get current URL in angularJS </p> <div ng-app="app"> <div ng-controller="controller"> <p>Url = {{url}}</p> <input type="button" value="Click to get URL" ng-click="getUrl()"> </div> </div></body> </html> Output: AngularJS-Misc HTML-Misc AngularJS 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": 28, "s": 0, "text": "\n29 Sep, 2020" }, { "code": null, "e": 212, "s": 28, "text": "In this article, we are going to see how to get the current URL with the help of AngularJS. We will be using the $location.absURL() method to get the complete URL of the current page." }, { "code": null, "e": 220, "s": 212, "text": "Syntax:" }, { "code": null, "e": 239, "s": 220, "text": "$location.absURL()" }, { "code": null, "e": 334, "s": 239, "text": "Example 1: Just use the $location.absURL() method to get the complete URL of the current page." }, { "code": null, "e": 339, "s": 334, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope, $location) { $scope.url = ''; $scope.getUrl = function () { $scope.url = $location.absUrl(); }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Get current URL in angularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <p>Url = {{url}}</p> <input type=\"button\" value=\"Click to get URL\" ng-click=\"getUrl()\"> </div> </div></body> </html>", "e": 1193, "s": 339, "text": null }, { "code": null, "e": 1201, "s": 1193, "text": "Output:" }, { "code": null, "e": 1308, "s": 1201, "text": "Example 2: Similar to the previous example but using the split() method to get the domain name of the URL." }, { "code": null, "e": 1313, "s": 1308, "text": "HTML" }, { "code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js\"> </script> <script> var myApp = angular.module(\"app\", []); myApp.controller(\"controller\", function ($scope, $location) { $scope.url = ''; $scope.getUrl = function () { // Will change the current url to // ide.geeksforgeeks.org $scope.url = $location .absUrl().split('/')[2];; }; }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p> Get current URL in angularJS </p> <div ng-app=\"app\"> <div ng-controller=\"controller\"> <p>Url = {{url}}</p> <input type=\"button\" value=\"Click to get URL\" ng-click=\"getUrl()\"> </div> </div></body> </html>", "e": 2304, "s": 1313, "text": null }, { "code": null, "e": 2312, "s": 2304, "text": "Output:" }, { "code": null, "e": 2327, "s": 2312, "text": "AngularJS-Misc" }, { "code": null, "e": 2337, "s": 2327, "text": "HTML-Misc" }, { "code": null, "e": 2347, "s": 2337, "text": "AngularJS" }, { "code": null, "e": 2352, "s": 2347, "text": "HTML" }, { "code": null, "e": 2369, "s": 2352, "text": "Web Technologies" }, { "code": null, "e": 2396, "s": 2369, "text": "Web technologies Questions" }, { "code": null, "e": 2401, "s": 2396, "text": "HTML" } ]
Finding Maximum Element of Java ArrayList
11 May, 2021 For finding the maximum element in the ArrayList, complete traversal of the ArrayList is required. There is an inbuilt function in the ArrayList class to find the maximum element in the ArrayList, i.e. Time Complexity is O(N), where N is the size of ArrayList, Let’s discuss both the methods. Example: Input : ArrayList = {2, 9, 1, 3, 4} Output: Max = 9 Input : ArrayList = {6, 7, 2, 1} Output: Max = 7 Approach 1: Create on variable and initialize it with the first element of ArrayList.Start traversing the ArrayList.If the current element is greater than variable, then update the variable with the current element in ArrayList.In the end, print that variable. Create on variable and initialize it with the first element of ArrayList. Start traversing the ArrayList. If the current element is greater than variable, then update the variable with the current element in ArrayList. In the end, print that variable. Below is the implementation of the above approach: Java // Finding Maximum Element of Java ArrayListimport java.util.ArrayList;import java.util.Collections; class MinElementInArrayList { public static void main(String[] args) { // ArrayList of Numbers ArrayList<Integer> myList = new ArrayList<Integer>(); // adding elements to Java ArrayList myList.add(16); myList.add(26); myList.add(3); myList.add(52); myList.add(70); myList.add(12); int maximum = myList.get(0); for (int i = 1; i < myList.size(); i++) { if (maximum < myList.get(i)) maximum = myList.get(i); } System.out.println("Maximum Element in ArrayList = " + maximum); }} Maximum Element in ArrayList = 70 Approach 2: The max method of the Java collection class can be used to find ArrayList. The max method returns the maximum element of the collection according to the natural ordering of the elements. Java // Finding Maximum Element of Java ArrayListimport java.util.ArrayList;import java.util.Collections; class MinElementInArrayList { public static void main(String[] args) { // ArrayList of Numbers ArrayList<Integer> myList = new ArrayList<Integer>(); // adding elements to Java ArrayList myList.add(16); myList.add(26); myList.add(3); myList.add(52); myList.add(70); myList.add(12); // 'min' method is used to find the // minimum elementfrom Collections Class System.out.println("Maximum Element in ArrayList = " + Collections.max(myList)); }} Maximum Element in ArrayList = 70 shekharsaxena316 Java-ArrayList Picked Technical Scripter 2020 Java Java Programs Technical Scripter 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 Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2021" }, { "code": null, "e": 345, "s": 52, "text": "For finding the maximum element in the ArrayList, complete traversal of the ArrayList is required. There is an inbuilt function in the ArrayList class to find the maximum element in the ArrayList, i.e. Time Complexity is O(N), where N is the size of ArrayList, Let’s discuss both the methods." }, { "code": null, "e": 354, "s": 345, "text": "Example:" }, { "code": null, "e": 456, "s": 354, "text": "Input : ArrayList = {2, 9, 1, 3, 4}\nOutput: Max = 9\n\nInput : ArrayList = {6, 7, 2, 1}\nOutput: Max = 7" }, { "code": null, "e": 468, "s": 456, "text": "Approach 1:" }, { "code": null, "e": 717, "s": 468, "text": "Create on variable and initialize it with the first element of ArrayList.Start traversing the ArrayList.If the current element is greater than variable, then update the variable with the current element in ArrayList.In the end, print that variable." }, { "code": null, "e": 791, "s": 717, "text": "Create on variable and initialize it with the first element of ArrayList." }, { "code": null, "e": 823, "s": 791, "text": "Start traversing the ArrayList." }, { "code": null, "e": 936, "s": 823, "text": "If the current element is greater than variable, then update the variable with the current element in ArrayList." }, { "code": null, "e": 969, "s": 936, "text": "In the end, print that variable." }, { "code": null, "e": 1020, "s": 969, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1025, "s": 1020, "text": "Java" }, { "code": "// Finding Maximum Element of Java ArrayListimport java.util.ArrayList;import java.util.Collections; class MinElementInArrayList { public static void main(String[] args) { // ArrayList of Numbers ArrayList<Integer> myList = new ArrayList<Integer>(); // adding elements to Java ArrayList myList.add(16); myList.add(26); myList.add(3); myList.add(52); myList.add(70); myList.add(12); int maximum = myList.get(0); for (int i = 1; i < myList.size(); i++) { if (maximum < myList.get(i)) maximum = myList.get(i); } System.out.println(\"Maximum Element in ArrayList = \" + maximum); }}", "e": 1768, "s": 1025, "text": null }, { "code": null, "e": 1803, "s": 1768, "text": "Maximum Element in ArrayList = 70\n" }, { "code": null, "e": 1815, "s": 1803, "text": "Approach 2:" }, { "code": null, "e": 2002, "s": 1815, "text": "The max method of the Java collection class can be used to find ArrayList. The max method returns the maximum element of the collection according to the natural ordering of the elements." }, { "code": null, "e": 2007, "s": 2002, "text": "Java" }, { "code": "// Finding Maximum Element of Java ArrayListimport java.util.ArrayList;import java.util.Collections; class MinElementInArrayList { public static void main(String[] args) { // ArrayList of Numbers ArrayList<Integer> myList = new ArrayList<Integer>(); // adding elements to Java ArrayList myList.add(16); myList.add(26); myList.add(3); myList.add(52); myList.add(70); myList.add(12); // 'min' method is used to find the // minimum elementfrom Collections Class System.out.println(\"Maximum Element in ArrayList = \" + Collections.max(myList)); }}", "e": 2684, "s": 2007, "text": null }, { "code": null, "e": 2718, "s": 2684, "text": "Maximum Element in ArrayList = 70" }, { "code": null, "e": 2735, "s": 2718, "text": "shekharsaxena316" }, { "code": null, "e": 2750, "s": 2735, "text": "Java-ArrayList" }, { "code": null, "e": 2757, "s": 2750, "text": "Picked" }, { "code": null, "e": 2781, "s": 2757, "text": "Technical Scripter 2020" }, { "code": null, "e": 2786, "s": 2781, "text": "Java" }, { "code": null, "e": 2800, "s": 2786, "text": "Java Programs" }, { "code": null, "e": 2819, "s": 2800, "text": "Technical Scripter" }, { "code": null, "e": 2824, "s": 2819, "text": "Java" }, { "code": null, "e": 2922, "s": 2824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2937, "s": 2922, "text": "Stream In Java" }, { "code": null, "e": 2958, "s": 2937, "text": "Introduction to Java" }, { "code": null, "e": 2979, "s": 2958, "text": "Constructors in Java" }, { "code": null, "e": 2998, "s": 2979, "text": "Exceptions in Java" }, { "code": null, "e": 3015, "s": 2998, "text": "Generics in Java" }, { "code": null, "e": 3041, "s": 3015, "text": "Java Programming Examples" }, { "code": null, "e": 3075, "s": 3041, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3122, "s": 3075, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3160, "s": 3122, "text": "Factory method design pattern in Java" } ]
Convert Java object to JSON using the Gson library in Java?
A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert a bean/ java object to a JSON object. We can call the toJson() method of Gson class to convert a Java object to a JSON object. public java.lang.String toJson(java.lang.Object src) import com.google.gson.Gson; public class ConvertJavaObjectToJSONTest { public static void main(String[] args) { Gson gson = new Gson(); Student student = new Student("Raja", "Ramesh", 30, "Hyderabad"); System.out.println(gson.toJson(student)); // converts java object to json object. } } // student class class Student { private String firstName; private String lastName; private int age; private String address; public Student(String firstName, String lastName, int age, String address) { super(); this.firstName = firstName; this.lastName = lastName; this.age = age; this.address = address; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String toString() { return "Student[ " + " firstName = " + firstName + ", lastName = " + lastName + ", age = " + age + ", address = " + address + " ]"; } } {"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}
[ { "code": null, "e": 1463, "s": 1187, "text": "A Gson is a json library for java, which is created by Google and it can be used to generate a JSON. By using Gson, we can generate JSON and convert a bean/ java object to a JSON object. We can call the toJson() method of Gson class to convert a Java object to a JSON object." }, { "code": null, "e": 1516, "s": 1463, "text": "public java.lang.String toJson(java.lang.Object src)" }, { "code": null, "e": 2974, "s": 1516, "text": "import com.google.gson.Gson;\npublic class ConvertJavaObjectToJSONTest {\n public static void main(String[] args) {\n Gson gson = new Gson();\n Student student = new Student(\"Raja\", \"Ramesh\", 30, \"Hyderabad\");\n System.out.println(gson.toJson(student)); // converts java object to json object.\n }\n}\n// student class\nclass Student {\n private String firstName;\n private String lastName;\n private int age;\n private String address;\n public Student(String firstName, String lastName, int age, String address) {\n super();\n this.firstName = firstName;\n this.lastName = lastName;\n this.age = age;\n this.address = address;\n }\n public String getFirstName() {\n return firstName;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n public int getAge() {\n return age;\n }\n public void setAge(int age) {\n this.age = age;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n public String toString() {\n return \"Student[ \" +\n \" firstName = \" + firstName +\n \", lastName = \" + lastName +\n \", age = \" + age +\n \", address = \" + address +\n \" ]\";\n }\n}" }, { "code": null, "e": 3046, "s": 2974, "text": "{\"firstName\":\"Raja\",\"lastName\":\"Ramesh\",\"age\":30,\"address\":\"Hyderabad\"}" } ]
SQL Query to Replace a Column Values from β€˜male’ to β€˜female’ and β€˜female’ to β€˜male’
19 Oct, 2021 In this article, we will Implement a Query to Replace Column Values from β€˜male’ to β€˜female’ and β€˜female’ to β€˜male’. For a better explanation, we will Implement this Query with an Example. For Implementation of this Query first of all we will create a database. Name of Database β€œSample”. After that Inside the Database, We will Create a Table. The name of the table is β€œEMPDATA”. Here we will replace column values from β€˜Male’ to β€˜female’ and β€˜female’ to β€˜male’ with the help of UPDATE, CASE statement, and condition. Now, we have to follow the below statement for Implementing this Query. Step 1: Create a database For database creation, there is the query we will use in MS SQL Server. Query: CREATE DATABASE Sample; Step 2: Use a database for using the database Query: use database_name; for this database... use Sample; Step 3: Create a table For the creation data table, we will use this below query Query: CREATE TABLE EMPDATA ( EMPNAME VARCHAR(25), GENDER VARCHAR(6), DEPT VARCHAR(20), CONTACTNO BIGINT NOT NULL, CITY VARCHAR(15) ); Step 4: Structure of the table In SQL with the Help of the EXEX sp_help table name, we can see the structure of the table. Like a number of columns, data type, size, nullability, and constraints. EXEC Sp_ help Query is similar to DESC or DESCRIBE Query. Query: EXEC sp_help EMPDATA Output: Step 5: Insert a value into a table Query: INSERT INTO EMPDATA VALUES ('VISHAL','MALE','SALES',9193458625,'GAZIABAD'), ('DIVYA','FEMALE','MANAGER',7352158944,'BARIELLY'), ('REKHA','FEMALE','IT',7830246946,'KOLKATA'), ('RAHUL','MALE','MARKETING',9635688441,'MEERUT'), ('SANJAY','MALE','SALES',9149335694,'MORADABAD'), ('ROHAN','MALE','MANAGER',7352158944,'BENGALURU'), ('RAJSHREE','FEMALE','SALES',9193458625,'VODODARA'), ('AMAN','MALE','IT',78359941265,'RAMPUR'), ('RAKESH','MALE','MARKETING',9645956441,'BOKARO'), ('MOHINI','FEMALE','SALES',9147844694,'Dehli') SELECT * FROM EMPDATA; Output: Step 6: Implementation of the query to replace column values from β€˜Male’ to β€˜Female’ and β€˜Female’ to β€˜Male’. Finally, in this step, We will Implement the query to replace column values from β€˜male’ to β€˜female’ and β€˜female’ to β€˜male’.Here We are using UPDATE, and CASE statements. We can use an Update statement with WHERE Clause or Without WHERE CLAUSE. Update statement without where clause: The Update Statement Without the Where Clause is Used to Update all rows in a table. Query: UPDATE [EMPDATA] SET GENDER = β€˜FEMALE’; This Query will Update GENDER = β€˜FEMALE’ for all rows. Update statement with where clause: The Update Statement with the Where clause is used to Update a single or multiple rows on the basis of the WHERE clause in SQL Server. Query: UPDATE [EMPDATA] SET GENDER = β€˜FEMALE’ WHERE EMPNAME = β€˜AMAN’ For Multiple Column Updating: Query: UPDATE [EMPDATA] SET GENDER = β€˜FEMALE’ WHERE EMPNAME = β€˜AMAN’ or EMPNAME = β€˜VIJAY’; Now we will IMPLEMENTATION OF Query to Replace a Column Values from β€˜male’ to β€˜female’ and β€˜female’ to β€˜male’ Query: UPDATE [EMPDATA] SET GENDER = (CASE WHEN GENDER ='MALE' THEN 'FEMALE' WHEN GENDER = 'FEMALE' THEN 'MALE' END ) Execute the following code and notice that we want to evaluate CASE Gender in this query. Output: akshaysingh98088 Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL SQL | Sub queries in From Clause What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter RANK() Function in SQL Server SQL Query to Convert VARCHAR to INT SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Oct, 2021" }, { "code": null, "e": 316, "s": 28, "text": "In this article, we will Implement a Query to Replace Column Values from β€˜male’ to β€˜female’ and β€˜female’ to β€˜male’. For a better explanation, we will Implement this Query with an Example. For Implementation of this Query first of all we will create a database. Name of Database β€œSample”." }, { "code": null, "e": 547, "s": 316, "text": "After that Inside the Database, We will Create a Table. The name of the table is β€œEMPDATA”. Here we will replace column values from β€˜Male’ to β€˜female’ and β€˜female’ to β€˜male’ with the help of UPDATE, CASE statement, and condition. " }, { "code": null, "e": 620, "s": 547, "text": "Now, we have to follow the below statement for Implementing this Query. " }, { "code": null, "e": 646, "s": 620, "text": "Step 1: Create a database" }, { "code": null, "e": 719, "s": 646, "text": " For database creation, there is the query we will use in MS SQL Server." }, { "code": null, "e": 726, "s": 719, "text": "Query:" }, { "code": null, "e": 750, "s": 726, "text": "CREATE DATABASE Sample;" }, { "code": null, "e": 773, "s": 750, "text": "Step 2: Use a database" }, { "code": null, "e": 797, "s": 773, "text": " for using the database" }, { "code": null, "e": 804, "s": 797, "text": "Query:" }, { "code": null, "e": 860, "s": 804, "text": "use database_name;\nfor this database...\nuse Sample; " }, { "code": null, "e": 883, "s": 860, "text": "Step 3: Create a table" }, { "code": null, "e": 941, "s": 883, "text": "For the creation data table, we will use this below query" }, { "code": null, "e": 948, "s": 941, "text": "Query:" }, { "code": null, "e": 1076, "s": 948, "text": "CREATE TABLE EMPDATA\n(\nEMPNAME VARCHAR(25),\nGENDER VARCHAR(6),\nDEPT VARCHAR(20),\nCONTACTNO BIGINT NOT NULL,\nCITY VARCHAR(15)\n);" }, { "code": null, "e": 1107, "s": 1076, "text": "Step 4: Structure of the table" }, { "code": null, "e": 1331, "s": 1107, "text": " In SQL with the Help of the EXEX sp_help table name, we can see the structure of the table. Like a number of columns, data type, size, nullability, and constraints. EXEC Sp_ help Query is similar to DESC or DESCRIBE Query." }, { "code": null, "e": 1338, "s": 1331, "text": "Query:" }, { "code": null, "e": 1360, "s": 1338, "text": " EXEC sp_help EMPDATA" }, { "code": null, "e": 1368, "s": 1360, "text": "Output:" }, { "code": null, "e": 1404, "s": 1368, "text": "Step 5: Insert a value into a table" }, { "code": null, "e": 1411, "s": 1404, "text": "Query:" }, { "code": null, "e": 1955, "s": 1411, "text": "INSERT INTO EMPDATA\nVALUES ('VISHAL','MALE','SALES',9193458625,'GAZIABAD'),\n('DIVYA','FEMALE','MANAGER',7352158944,'BARIELLY'),\n('REKHA','FEMALE','IT',7830246946,'KOLKATA'),\n('RAHUL','MALE','MARKETING',9635688441,'MEERUT'),\n('SANJAY','MALE','SALES',9149335694,'MORADABAD'),\n('ROHAN','MALE','MANAGER',7352158944,'BENGALURU'),\n('RAJSHREE','FEMALE','SALES',9193458625,'VODODARA'),\n('AMAN','MALE','IT',78359941265,'RAMPUR'),\n('RAKESH','MALE','MARKETING',9645956441,'BOKARO'),\n('MOHINI','FEMALE','SALES',9147844694,'Dehli') \n SELECT * FROM EMPDATA;" }, { "code": null, "e": 1963, "s": 1955, "text": "Output:" }, { "code": null, "e": 2072, "s": 1963, "text": "Step 6: Implementation of the query to replace column values from β€˜Male’ to β€˜Female’ and β€˜Female’ to β€˜Male’." }, { "code": null, "e": 2242, "s": 2072, "text": "Finally, in this step, We will Implement the query to replace column values from β€˜male’ to β€˜female’ and β€˜female’ to β€˜male’.Here We are using UPDATE, and CASE statements." }, { "code": null, "e": 2318, "s": 2242, "text": "We can use an Update statement with WHERE Clause or Without WHERE CLAUSE. " }, { "code": null, "e": 2442, "s": 2318, "text": "Update statement without where clause: The Update Statement Without the Where Clause is Used to Update all rows in a table." }, { "code": null, "e": 2449, "s": 2442, "text": "Query:" }, { "code": null, "e": 2489, "s": 2449, "text": "UPDATE [EMPDATA] SET GENDER = β€˜FEMALE’;" }, { "code": null, "e": 2545, "s": 2489, "text": "This Query will Update GENDER = β€˜FEMALE’ for all rows. " }, { "code": null, "e": 2716, "s": 2545, "text": "Update statement with where clause: The Update Statement with the Where clause is used to Update a single or multiple rows on the basis of the WHERE clause in SQL Server." }, { "code": null, "e": 2723, "s": 2716, "text": "Query:" }, { "code": null, "e": 2785, "s": 2723, "text": "UPDATE [EMPDATA] SET GENDER = β€˜FEMALE’ WHERE EMPNAME = β€˜AMAN’" }, { "code": null, "e": 2815, "s": 2785, "text": "For Multiple Column Updating:" }, { "code": null, "e": 2822, "s": 2815, "text": "Query:" }, { "code": null, "e": 2907, "s": 2822, "text": "UPDATE [EMPDATA] SET GENDER = β€˜FEMALE’ WHERE EMPNAME = β€˜AMAN’ or EMPNAME = β€˜VIJAY’; " }, { "code": null, "e": 3017, "s": 2907, "text": "Now we will IMPLEMENTATION OF Query to Replace a Column Values from β€˜male’ to β€˜female’ and β€˜female’ to β€˜male’" }, { "code": null, "e": 3024, "s": 3017, "text": "Query:" }, { "code": null, "e": 3136, "s": 3024, "text": "UPDATE [EMPDATA] SET GENDER = (CASE WHEN GENDER ='MALE' THEN 'FEMALE'\nWHEN GENDER = 'FEMALE' THEN 'MALE'\nEND ) " }, { "code": null, "e": 3227, "s": 3136, "text": "Execute the following code and notice that we want to evaluate CASE Gender in this query. " }, { "code": null, "e": 3236, "s": 3227, "text": "Output: " }, { "code": null, "e": 3253, "s": 3236, "text": "akshaysingh98088" }, { "code": null, "e": 3260, "s": 3253, "text": "Picked" }, { "code": null, "e": 3270, "s": 3260, "text": "SQL-Query" }, { "code": null, "e": 3281, "s": 3270, "text": "SQL-Server" }, { "code": null, "e": 3285, "s": 3281, "text": "SQL" }, { "code": null, "e": 3289, "s": 3285, "text": "SQL" }, { "code": null, "e": 3387, "s": 3289, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3453, "s": 3387, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 3477, "s": 3453, "text": "Window functions in SQL" }, { "code": null, "e": 3510, "s": 3477, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 3542, "s": 3510, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 3559, "s": 3542, "text": "SQL using Python" }, { "code": null, "e": 3637, "s": 3559, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 3667, "s": 3637, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 3703, "s": 3667, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 3734, "s": 3703, "text": "SQL Query to Compare Two Dates" } ]
Hotword detection with Python
25 Oct, 2021 Most of us have heard about Alexa, Ok google or hey Siri and may have thought of creating your own Virtual Personal Assistant with your favorite name like, Hey Thanos!. So here’s the easiest way to do it without getting your hands dirty.Requirements: Linux pc with working microphones (I have tested on Arch Linux).Install python3, pyaudio, sox(and also swig for Arch Linux) with your package manager.: Linux pc with working microphones (I have tested on Arch Linux). Install python3, pyaudio, sox(and also swig for Arch Linux) with your package manager.: sudo apt-get update sudo apt-get install python3 python3-pip sudo apt-get install python-pyaudio python3-pyaudio sox Get snowboy packages from here. This file works with all Linux based OS. Snowboy also supports all versions of Raspberry Pi (1, 2, 3 and Zero). Supported OS is Raspbian 8.0.Now when you extracted with a folder named usr.Now navigate to usr/lib/python3.7/site-packages.Copy both folder(snowboy and snowboy-1.2.0b1-py3.7.egg-info) to /usr/lib/python3.7/site-packages either by using file manager or cp -r command. Get snowboy packages from here. This file works with all Linux based OS. Snowboy also supports all versions of Raspberry Pi (1, 2, 3 and Zero). Supported OS is Raspbian 8.0. Now when you extracted with a folder named usr.Now navigate to usr/lib/python3.7/site-packages. Copy both folder(snowboy and snowboy-1.2.0b1-py3.7.egg-info) to /usr/lib/python3.7/site-packages either by using file manager or cp -r command. cd Downloads tar -xf python-snowboy-1.3.0-1-x86_64.pkg.tar.xz cd usr/lib/python3.7/site-packages sudo cp -r snowboy /usr/lib/python3.7/site-packages sudo cp -r snowboy-1.2.0b1-py3.7.egg-info Now you can check if snowboy works or or not. Fire up your terminal and type Python to get the python shell. Python3 from snowboy import snowboydecode If this does not throw import error then you are ready to go further.Now go to snowboy website and do login. Once you login in, you will find create Hotword option and do further things as per instructions.once whole process is completed download the yourhotword.pmdl file which is generated.Copy the hotword.pmdl file to directory where you are going to create program. Python3 from snowboy import snowboydecoderdef detected_callback(): print ("hotword detected") # do your task here or call other program.detector = snowboydecoder.HotwordDetector("hotword.pmdl", sensitivity = 0.5, audio_gain = 1) detector.start(detected_callback) Output: Voice Input : hey thanos Output: INFO:snowboy:Keyword 1 detected at time: 2019-05-09 21:55:16 hotword detected This code will keep on running until you interrupt it with Ctrl+C or close terminal. As this code works offline (and does not connect to internet) so it does not stream your voice, so there is no risk of privacy. The hotword.pmdl file contains the model of your voice only. So, the above program will work with your voice only.You can implement this program to another program to and carry out tasks controlled by voice. prachisoda1234 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Oct, 2021" }, { "code": null, "e": 281, "s": 28, "text": "Most of us have heard about Alexa, Ok google or hey Siri and may have thought of creating your own Virtual Personal Assistant with your favorite name like, Hey Thanos!. So here’s the easiest way to do it without getting your hands dirty.Requirements: " }, { "code": null, "e": 435, "s": 281, "text": "Linux pc with working microphones (I have tested on Arch Linux).Install python3, pyaudio, sox(and also swig for Arch Linux) with your package manager.: " }, { "code": null, "e": 500, "s": 435, "text": "Linux pc with working microphones (I have tested on Arch Linux)." }, { "code": null, "e": 590, "s": 500, "text": "Install python3, pyaudio, sox(and also swig for Arch Linux) with your package manager.: " }, { "code": null, "e": 707, "s": 590, "text": "sudo apt-get update\nsudo apt-get install python3 python3-pip\nsudo apt-get install python-pyaudio python3-pyaudio sox" }, { "code": null, "e": 1121, "s": 707, "text": "Get snowboy packages from here. This file works with all Linux based OS. Snowboy also supports all versions of Raspberry Pi (1, 2, 3 and Zero). Supported OS is Raspbian 8.0.Now when you extracted with a folder named usr.Now navigate to usr/lib/python3.7/site-packages.Copy both folder(snowboy and snowboy-1.2.0b1-py3.7.egg-info) to /usr/lib/python3.7/site-packages either by using file manager or cp -r command. " }, { "code": null, "e": 1295, "s": 1121, "text": "Get snowboy packages from here. This file works with all Linux based OS. Snowboy also supports all versions of Raspberry Pi (1, 2, 3 and Zero). Supported OS is Raspbian 8.0." }, { "code": null, "e": 1391, "s": 1295, "text": "Now when you extracted with a folder named usr.Now navigate to usr/lib/python3.7/site-packages." }, { "code": null, "e": 1537, "s": 1391, "text": "Copy both folder(snowboy and snowboy-1.2.0b1-py3.7.egg-info) to /usr/lib/python3.7/site-packages either by using file manager or cp -r command. " }, { "code": null, "e": 1728, "s": 1537, "text": "cd Downloads\ntar -xf python-snowboy-1.3.0-1-x86_64.pkg.tar.xz\ncd usr/lib/python3.7/site-packages\nsudo cp -r snowboy /usr/lib/python3.7/site-packages\nsudo cp -r snowboy-1.2.0b1-py3.7.egg-info" }, { "code": null, "e": 1839, "s": 1728, "text": "Now you can check if snowboy works or or not. Fire up your terminal and type Python to get the python shell. " }, { "code": null, "e": 1847, "s": 1839, "text": "Python3" }, { "code": "from snowboy import snowboydecode", "e": 1881, "s": 1847, "text": null }, { "code": null, "e": 2254, "s": 1881, "text": "If this does not throw import error then you are ready to go further.Now go to snowboy website and do login. Once you login in, you will find create Hotword option and do further things as per instructions.once whole process is completed download the yourhotword.pmdl file which is generated.Copy the hotword.pmdl file to directory where you are going to create program. " }, { "code": null, "e": 2262, "s": 2254, "text": "Python3" }, { "code": "from snowboy import snowboydecoderdef detected_callback(): print (\"hotword detected\") # do your task here or call other program.detector = snowboydecoder.HotwordDetector(\"hotword.pmdl\", sensitivity = 0.5, audio_gain = 1) detector.start(detected_callback)", "e": 2546, "s": 2262, "text": null }, { "code": null, "e": 2556, "s": 2546, "text": "Output: " }, { "code": null, "e": 2668, "s": 2556, "text": "Voice Input : hey thanos\nOutput:\nINFO:snowboy:Keyword 1 detected at time: 2019-05-09 21:55:16\nhotword detected" }, { "code": null, "e": 3090, "s": 2668, "text": "This code will keep on running until you interrupt it with Ctrl+C or close terminal. As this code works offline (and does not connect to internet) so it does not stream your voice, so there is no risk of privacy. The hotword.pmdl file contains the model of your voice only. So, the above program will work with your voice only.You can implement this program to another program to and carry out tasks controlled by voice. " }, { "code": null, "e": 3105, "s": 3090, "text": "prachisoda1234" }, { "code": null, "e": 3120, "s": 3105, "text": "python-utility" }, { "code": null, "e": 3127, "s": 3120, "text": "Python" }, { "code": null, "e": 3225, "s": 3127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3257, "s": 3225, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3284, "s": 3257, "text": "Python Classes and Objects" }, { "code": null, "e": 3315, "s": 3284, "text": "Python | os.path.join() method" }, { "code": null, "e": 3336, "s": 3315, "text": "Python OOPs Concepts" }, { "code": null, "e": 3392, "s": 3336, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3415, "s": 3392, "text": "Introduction To PYTHON" }, { "code": null, "e": 3457, "s": 3415, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3499, "s": 3457, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3538, "s": 3499, "text": "Python | datetime.timedelta() function" } ]
Temple Offerings
30 May, 2022 Consider a devotee wishing to give offerings to temples along with a mountain range. The temples are located in a row at different heights. Each temple should receive at least one offer. If two adjacent temples are at different altitudes, then the temple that is higher up should receive more offerings than the one that is lower down. If two adjacent temples are at the same height, then their offerings relative to each other do not matter. Given the number of temples and the heights of the temples in order, find the minimum number of offerings to bring. Examples: Input : 3 1 2 2 Output : 4 All temples must receive at-least one offering. Now, the second temple is at a higher altitude compared to the first one. Thus it receives one extra offering. The second temple and third temple are at the same height, so we do not need to modify the offerings. Offerings given are therefore: 1, 2, 1 giving a total of 4. Input : 6 1 4 3 6 2 1 Output : 10 We can distribute the offerings in the following way, 1, 2, 1, 3, 2, 1. The second temple has to receive more offerings than the first due to its height being higher. The fourth must receive more than the fifth, which in turn must receive more than the sixth. Thus the total becomes 10. We notice that each temple can either be above, below or at the same level as the temple next to it. The offerings required at each temple are equal to the maximum length of the chain of temples at a lower height as shown in the image. Naive Approach To follow the given rule, a temple must be offered at least x+1 where x is the maximum of the following two. Number of temples on left in increasing order.Number of temples on right in increasing order. Number of temples on left in increasing order. Number of temples on right in increasing order. A naive method of solving this problem would be for each temple, go to the left until altitude increases, and do the same for the right. C++ Java Python3 C# PHP Javascript // Program to find minimum total offerings required#include <iostream>using namespace std; // Returns minimum offerings requiredint offeringNumber(int n, int templeHeight[]){ int sum = 0; // Initialize result // Go through all temples one by one for (int i = 0; i < n; ++i) { // Go to left while height keeps increasing int left = 0, right = 0; for (int j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while height keeps increasing for (int j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer maximum of two // values to follow the rule. sum += max(right, left) + 1; } return sum;} // Driver codeint main(){ int arr1[3] = {1, 2, 2}; cout << offeringNumber(3, arr1) << "\n"; int arr2[6] = {1, 4, 3, 6, 2, 1}; cout << offeringNumber(6, arr2) << "\n"; return 0;} // Program to find minimum// total offerings requiredimport java.io.*; class GFG{ // Returns minimum// offerings requiredstatic int offeringNumber(int n, int templeHeight[]){ int sum = 0; // Initialize result // Go through all // temples one by one for (int i = 0; i < n; ++i) { // Go to left while // height keeps increasing int left = 0, right = 0; for (int j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while // height keeps increasing for (int j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer // maximum of two values // to follow the rule. sum += Math.max(right, left) + 1; } return sum;} // Driver codepublic static void main (String[] args){int arr1[] = {1, 2, 2};System.out.println(offeringNumber(3, arr1));int arr2[] = {1, 4, 3, 6, 2, 1};System.out.println(offeringNumber(6, arr2));}} // This code is contributed by akt_mit # Program to find minimum total# offerings required. # Returns minimum offerings requireddef offeringNumber(n, templeHeight): sum = 0 # Initialize result # Go through all temples one by one for i in range(n): # Go to left while height # keeps increasing left = 0 right = 0 for j in range(i - 1, -1, -1): if (templeHeight[j] < templeHeight[j + 1]): left += 1 else: break # Go to right while height # keeps increasing for j in range(i + 1, n): if (templeHeight[j] < templeHeight[j - 1]): right += 1 else: break # This temple should offer maximum # of two values to follow the rule. sum += max(right, left) + 1 return sum # Driver Codearr1 = [1, 2, 2]print(offeringNumber(3, arr1))arr2 = [1, 4, 3, 6, 2, 1]print(offeringNumber(6, arr2)) # This code is contributed# by sahilshelangia // Program to find minimum// total offerings requiredusing System; class GFG{ // Returns minimum// offerings requiredstatic int offeringNumber(int n, int []templeHeight){ int sum = 0; // Initialize result // Go through all // temples one by one for (int i = 0; i < n; ++i) { // Go to left while // height keeps increasing int left = 0, right = 0; for (int j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while // height keeps increasing for (int j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer // maximum of two values // to follow the rule. sum += Math.Max(right, left) + 1; } return sum;} // Driver codestatic public void Main (){ int []arr1 = {1, 2, 2}; Console.WriteLine(offeringNumber(3, arr1)); int []arr2 = {1, 4, 3, 6, 2, 1}; Console.WriteLine(offeringNumber(6, arr2));}} // This code is contributed by aj_36 <?php// Program to find minimum total offerings required // Returns minimum offerings requiredfunction offeringNumber($n, $templeHeight){ $sum = 0; // Initialize result // Go through all temples one by one for ($i = 0; $i < $n; ++$i) { // Go to left while height keeps increasing $left = 0; $right = 0; for ($j = $i - 1; $j >= 0; --$j) { if ($templeHeight[$j] < $templeHeight[$j + 1]) ++$left; else break; } // Go to right while height keeps increasing for ($j = $i + 1; $j < $n; ++$j) { if ($templeHeight[$j] < $templeHeight[$j - 1]) ++$right; else break; } // This temple should offer maximum of two // values to follow the rule. $sum += max($right, $left) + 1; } return $sum;} // Driver code $arr1 = array (1, 2, 2); echo offeringNumber(3, $arr1) , "\n"; $arr2 = array (1, 4, 3, 6, 2, 1); echo offeringNumber(6, $arr2) ,"\n"; // This code is contributed by ajit?> <script> // Program to find minimum // total offerings required // Returns minimum // offerings required function offeringNumber(n, templeHeight) { let sum = 0; // Initialize result // Go through all // temples one by one for (let i = 0; i < n; ++i) { // Go to left while // height keeps increasing let left = 0, right = 0; for (let j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while // height keeps increasing for (let j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer // maximum of two values // to follow the rule. sum += Math.max(right, left) + 1; } return sum; } let arr1 = [1, 2, 2]; document.write(offeringNumber(3, arr1) + "</br>"); let arr2 = [1, 4, 3, 6, 2, 1]; document.write(offeringNumber(6, arr2));</script> 4 10 Time complexity: O(n2) Space complexity: O(1) Dynamic Programming Approach By using Dynamic Programming, we can improve the time complexity. In this method, we create a structure of length n which maintains the maximum decreasing chain to the left of each temple and the maximum decreasing chain to the right of each temple. We go through once from 0 to N setting the value of left for each temple. We then go from N to 0 setting the value of right for each temple. We then compare the two and pick the maximum for each temple. C++ Java Python3 C# // C++ Program to find total offerings required#include <iostream>using namespace std; // To store count of increasing order temples// on left and right (including current temple)struct Temple { int L; int R;}; // Returns count of minimum offerings for// n temples of given heights.int offeringNumber(int n, int templeHeight[]){ // Initialize counts for all temples Temple chainSize[n]; for (int i = 0; i < n; ++i) { chainSize[i].L = -1; chainSize[i].R = -1; } // Values corner temples chainSize[0].L = 1; chainSize[n - 1].R = 1; // Filling left and right values using same // values of previous(or next) for (int i = 1; i < n; ++i) { if (templeHeight[i - 1] < templeHeight[i]) chainSize[i].L = chainSize[i - 1].L + 1; else chainSize[i].L = 1; } for (int i = n - 2; i >= 0; --i) { if (templeHeight[i + 1] < templeHeight[i]) chainSize[i].R = chainSize[i + 1].R + 1; else chainSize[i].R = 1; } // Computing max of left and right for all // temples and returning sum. int sum = 0; for (int i = 0; i < n; ++i) sum += max(chainSize[i].L, chainSize[i].R); return sum;} // Driver functionint main(){ int arr1[3] = { 1, 2, 2 }; cout << offeringNumber(3, arr1) << "\n"; int arr2[6] = { 1, 4, 3, 6, 2, 1 }; cout << offeringNumber(6, arr2) << "\n"; return 0;} // Java program to find total offerings requiredimport java.util.*; class GFG { // To store count of increasing order temples // on left and right (including current temple) public static class Temple { public int L; public int R; }; // Returns count of minimum offerings for // n temples of given heights. static int offeringNumber(int n, int[] templeHeight) { // Initialize counts for all temples Temple[] chainSize = new Temple[n]; for (int i = 0; i < n; ++i) { chainSize[i] = new Temple(); chainSize[i].L = -1; chainSize[i].R = -1; } // Values corner temples chainSize[0].L = 1; chainSize[n - 1].R = 1; // Filling left and right values // using same values of // previous(or next) for (int i = 1; i < n; ++i) { if (templeHeight[i - 1] < templeHeight[i]) chainSize[i].L = chainSize[i - 1].L + 1; else chainSize[i].L = 1; } for (int i = n - 2; i >= 0; --i) { if (templeHeight[i + 1] < templeHeight[i]) chainSize[i].R = chainSize[i + 1].R + 1; else chainSize[i].R = 1; } // Computing max of left and right for all // temples and returning sum. int sum = 0; for (int i = 0; i < n; ++i) sum += Math.max(chainSize[i].L, chainSize[i].R); return sum; } // Driver code public static void main(String[] s) { int[] arr1 = { 1, 2, 2 }; System.out.println(offeringNumber(3, arr1)); int[] arr2 = { 1, 4, 3, 6, 2, 1 }; System.out.println(offeringNumber(6, arr2)); }} // This code is contributed by pratham76 # Python3 program to find temple# offerings requiredfrom typing import List # To store count of increasing order temples# on left and right (including current temple) class Temple: def __init__(self, l: int, r: int): self.L = l self.R = r # Returns count of minimum offerings for# n temples of given heights. def offeringNumber(n: int, templeHeight: List[int]) -> int: # Initialize counts for all temples chainSize = [0] * n for i in range(n): chainSize[i] = Temple(-1, -1) # Values corner temples chainSize[0].L = 1 chainSize[-1].R = 1 # Filling left and right values # using same values of previous(or next for i in range(1, n): if templeHeight[i - 1] < templeHeight[i]: chainSize[i].L = chainSize[i - 1].L + 1 else: chainSize[i].L = 1 for i in range(n - 2, -1, -1): if templeHeight[i + 1] < templeHeight[i]: chainSize[i].R = chainSize[i + 1].R + 1 else: chainSize[i].R = 1 # Computing max of left and right for all # temples and returning sum sm = 0 for i in range(n): sm += max(chainSize[i].L, chainSize[i].R) return sm # Driver codeif __name__ == '__main__': arr1 = [1, 2, 2] print(offeringNumber(3, arr1)) arr2 = [1, 4, 3, 6, 2, 1] print(offeringNumber(6, arr2)) # This code is contributed by Rajat Srivastava // C# program to find total offerings requiredusing System; class GFG { // To store count of increasing order temples // on left and right (including current temple) public class Temple { public int L; public int R; }; // Returns count of minimum offerings for // n temples of given heights. static int offeringNumber(int n, int[] templeHeight) { // Initialize counts for all temples Temple[] chainSize = new Temple[n]; for (int i = 0; i < n; ++i) { chainSize[i] = new Temple(); chainSize[i].L = -1; chainSize[i].R = -1; } // Values corner temples chainSize[0].L = 1; chainSize[n - 1].R = 1; // Filling left and right values // using same values of // previous(or next) for (int i = 1; i < n; ++i) { if (templeHeight[i - 1] < templeHeight[i]) chainSize[i].L = chainSize[i - 1].L + 1; else chainSize[i].L = 1; } for (int i = n - 2; i >= 0; --i) { if (templeHeight[i + 1] < templeHeight[i]) chainSize[i].R = chainSize[i + 1].R + 1; else chainSize[i].R = 1; } // Computing max of left and right for all // temples and returning sum. int sum = 0; for (int i = 0; i < n; ++i) sum += Math.Max(chainSize[i].L, chainSize[i].R); return sum; } // Driver code static void Main() { int[] arr1 = { 1, 2, 2 }; Console.Write(offeringNumber(3, arr1) + "\n"); int[] arr2 = { 1, 4, 3, 6, 2, 1 }; Console.Write(offeringNumber(6, arr2) + "\n"); }} // This code is contributed by rutvik_56 4 10 Time complexity: O(n) Space complexity: O(n) Greedy Approach: If we somehow manage to make sure that the temple at higher mountain is getting more offerings than our problem is solved. For this we can make use of greedy (since we have to compare only the neighbors of current index). The approach is to do two traversals (in two directions), first one to make sure that the temple gets more offerings than the left temple (at higher position) and second one to make sure that the temple at higher position from the right gets more offerings. C++ Java // C++ Program to find total offerings required#include <iostream>using namespace std; int templeOfferings(int nums[], int n){ // to find the total offerings in both directions int offerings[n]; // start off by giving one offering to the first // temple offerings[0] = 1; // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the left one for (int i = 1; i < n; i++) { if (nums[i] > nums[i - 1]) offerings[i] = offerings[i - 1] + 1; else offerings[i] = 1; } // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the right one for (int i = n - 2; i >= 0; i--) { if (nums[i] > nums[i + 1] && offerings[i] <= offerings[i + 1]) offerings[i] = offerings[i + 1] + 1; } // total offerings int sum = 0; for (int val : offerings) sum += val; return sum;} // Driver functionint main(){ int arr[] = { 1, 4, 3, 6, 2, 1 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (templeOfferings(arr, n)); return 0;} // This code is contributed by kothavvsaakash /*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { int[] arr = { 1, 4, 3, 6, 2, 1 }; int n = arr.length; System.out.println(templeOfferings(arr, n)); } private static int templeOfferings(int[] nums, int n) { // to find the total offerings in both directions int[] offerings = new int[n]; // start off by giving one offering to the first // temple offerings[0] = 1; // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the left one for (int i = 1; i < n; i++) { if (nums[i] > nums[i - 1]) offerings[i] = offerings[i - 1] + 1; else offerings[i] = 1; } // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the right one for (int i = n - 2; i >= 0; i--) { if (nums[i] > nums[i + 1] && offerings[i] <= offerings[i + 1]) offerings[i] = offerings[i + 1] + 1; } // total offerings int sum = 0; for (int val : offerings) sum += val; return sum; }} 10 Time complexity: O(n) Space complexity: O(n) This article is contributed by Aditya Kamath and improved by Vishal Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t sahilshelangia rajatsri94 rutvik_56 pratham76 mukesh07 sherlockvj kashishsoda sumitgumber28 rkbhola5 kothavvsaakash Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 May, 2022" }, { "code": null, "e": 611, "s": 52, "text": "Consider a devotee wishing to give offerings to temples along with a mountain range. The temples are located in a row at different heights. Each temple should receive at least one offer. If two adjacent temples are at different altitudes, then the temple that is higher up should receive more offerings than the one that is lower down. If two adjacent temples are at the same height, then their offerings relative to each other do not matter. Given the number of temples and the heights of the temples in order, find the minimum number of offerings to bring." }, { "code": null, "e": 621, "s": 611, "text": "Examples:" }, { "code": null, "e": 1317, "s": 621, "text": "Input : 3\n 1 2 2\nOutput : 4\nAll temples must receive at-least one offering.\nNow, the second temple is at a higher altitude\ncompared to the first one. Thus it receives one\nextra offering. \nThe second temple and third temple are at the \nsame height, so we do not need to modify the \nofferings. Offerings given are therefore: 1, 2,\n1 giving a total of 4.\n\nInput : 6\n 1 4 3 6 2 1\nOutput : 10\nWe can distribute the offerings in the following\nway, 1, 2, 1, 3, 2, 1. The second temple has to \nreceive more offerings than the first due to its \nheight being higher. The fourth must receive more\nthan the fifth, which in turn must receive more \nthan the sixth. Thus the total becomes 10." }, { "code": null, "e": 1553, "s": 1317, "text": "We notice that each temple can either be above, below or at the same level as the temple next to it. The offerings required at each temple are equal to the maximum length of the chain of temples at a lower height as shown in the image." }, { "code": null, "e": 1677, "s": 1553, "text": "Naive Approach To follow the given rule, a temple must be offered at least x+1 where x is the maximum of the following two." }, { "code": null, "e": 1771, "s": 1677, "text": "Number of temples on left in increasing order.Number of temples on right in increasing order." }, { "code": null, "e": 1818, "s": 1771, "text": "Number of temples on left in increasing order." }, { "code": null, "e": 1866, "s": 1818, "text": "Number of temples on right in increasing order." }, { "code": null, "e": 2003, "s": 1866, "text": "A naive method of solving this problem would be for each temple, go to the left until altitude increases, and do the same for the right." }, { "code": null, "e": 2007, "s": 2003, "text": "C++" }, { "code": null, "e": 2012, "s": 2007, "text": "Java" }, { "code": null, "e": 2020, "s": 2012, "text": "Python3" }, { "code": null, "e": 2023, "s": 2020, "text": "C#" }, { "code": null, "e": 2027, "s": 2023, "text": "PHP" }, { "code": null, "e": 2038, "s": 2027, "text": "Javascript" }, { "code": "// Program to find minimum total offerings required#include <iostream>using namespace std; // Returns minimum offerings requiredint offeringNumber(int n, int templeHeight[]){ int sum = 0; // Initialize result // Go through all temples one by one for (int i = 0; i < n; ++i) { // Go to left while height keeps increasing int left = 0, right = 0; for (int j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while height keeps increasing for (int j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer maximum of two // values to follow the rule. sum += max(right, left) + 1; } return sum;} // Driver codeint main(){ int arr1[3] = {1, 2, 2}; cout << offeringNumber(3, arr1) << \"\\n\"; int arr2[6] = {1, 4, 3, 6, 2, 1}; cout << offeringNumber(6, arr2) << \"\\n\"; return 0;}", "e": 3149, "s": 2038, "text": null }, { "code": "// Program to find minimum// total offerings requiredimport java.io.*; class GFG{ // Returns minimum// offerings requiredstatic int offeringNumber(int n, int templeHeight[]){ int sum = 0; // Initialize result // Go through all // temples one by one for (int i = 0; i < n; ++i) { // Go to left while // height keeps increasing int left = 0, right = 0; for (int j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while // height keeps increasing for (int j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer // maximum of two values // to follow the rule. sum += Math.max(right, left) + 1; } return sum;} // Driver codepublic static void main (String[] args){int arr1[] = {1, 2, 2};System.out.println(offeringNumber(3, arr1));int arr2[] = {1, 4, 3, 6, 2, 1};System.out.println(offeringNumber(6, arr2));}} // This code is contributed by akt_mit", "e": 4418, "s": 3149, "text": null }, { "code": "# Program to find minimum total# offerings required. # Returns minimum offerings requireddef offeringNumber(n, templeHeight): sum = 0 # Initialize result # Go through all temples one by one for i in range(n): # Go to left while height # keeps increasing left = 0 right = 0 for j in range(i - 1, -1, -1): if (templeHeight[j] < templeHeight[j + 1]): left += 1 else: break # Go to right while height # keeps increasing for j in range(i + 1, n): if (templeHeight[j] < templeHeight[j - 1]): right += 1 else: break # This temple should offer maximum # of two values to follow the rule. sum += max(right, left) + 1 return sum # Driver Codearr1 = [1, 2, 2]print(offeringNumber(3, arr1))arr2 = [1, 4, 3, 6, 2, 1]print(offeringNumber(6, arr2)) # This code is contributed# by sahilshelangia", "e": 5439, "s": 4418, "text": null }, { "code": "// Program to find minimum// total offerings requiredusing System; class GFG{ // Returns minimum// offerings requiredstatic int offeringNumber(int n, int []templeHeight){ int sum = 0; // Initialize result // Go through all // temples one by one for (int i = 0; i < n; ++i) { // Go to left while // height keeps increasing int left = 0, right = 0; for (int j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while // height keeps increasing for (int j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer // maximum of two values // to follow the rule. sum += Math.Max(right, left) + 1; } return sum;} // Driver codestatic public void Main (){ int []arr1 = {1, 2, 2}; Console.WriteLine(offeringNumber(3, arr1)); int []arr2 = {1, 4, 3, 6, 2, 1}; Console.WriteLine(offeringNumber(6, arr2));}} // This code is contributed by aj_36", "e": 6712, "s": 5439, "text": null }, { "code": "<?php// Program to find minimum total offerings required // Returns minimum offerings requiredfunction offeringNumber($n, $templeHeight){ $sum = 0; // Initialize result // Go through all temples one by one for ($i = 0; $i < $n; ++$i) { // Go to left while height keeps increasing $left = 0; $right = 0; for ($j = $i - 1; $j >= 0; --$j) { if ($templeHeight[$j] < $templeHeight[$j + 1]) ++$left; else break; } // Go to right while height keeps increasing for ($j = $i + 1; $j < $n; ++$j) { if ($templeHeight[$j] < $templeHeight[$j - 1]) ++$right; else break; } // This temple should offer maximum of two // values to follow the rule. $sum += max($right, $left) + 1; } return $sum;} // Driver code $arr1 = array (1, 2, 2); echo offeringNumber(3, $arr1) , \"\\n\"; $arr2 = array (1, 4, 3, 6, 2, 1); echo offeringNumber(6, $arr2) ,\"\\n\"; // This code is contributed by ajit?>", "e": 7805, "s": 6712, "text": null }, { "code": "<script> // Program to find minimum // total offerings required // Returns minimum // offerings required function offeringNumber(n, templeHeight) { let sum = 0; // Initialize result // Go through all // temples one by one for (let i = 0; i < n; ++i) { // Go to left while // height keeps increasing let left = 0, right = 0; for (let j = i - 1; j >= 0; --j) { if (templeHeight[j] < templeHeight[j + 1]) ++left; else break; } // Go to right while // height keeps increasing for (let j = i + 1; j < n; ++j) { if (templeHeight[j] < templeHeight[j - 1]) ++right; else break; } // This temple should offer // maximum of two values // to follow the rule. sum += Math.max(right, left) + 1; } return sum; } let arr1 = [1, 2, 2]; document.write(offeringNumber(3, arr1) + \"</br>\"); let arr2 = [1, 4, 3, 6, 2, 1]; document.write(offeringNumber(6, arr2));</script>", "e": 9066, "s": 7805, "text": null }, { "code": null, "e": 9071, "s": 9066, "text": "4\n10" }, { "code": null, "e": 9118, "s": 9071, "text": "Time complexity: O(n2) Space complexity: O(1) " }, { "code": null, "e": 9600, "s": 9118, "text": "Dynamic Programming Approach By using Dynamic Programming, we can improve the time complexity. In this method, we create a structure of length n which maintains the maximum decreasing chain to the left of each temple and the maximum decreasing chain to the right of each temple. We go through once from 0 to N setting the value of left for each temple. We then go from N to 0 setting the value of right for each temple. We then compare the two and pick the maximum for each temple." }, { "code": null, "e": 9604, "s": 9600, "text": "C++" }, { "code": null, "e": 9609, "s": 9604, "text": "Java" }, { "code": null, "e": 9617, "s": 9609, "text": "Python3" }, { "code": null, "e": 9620, "s": 9617, "text": "C#" }, { "code": "// C++ Program to find total offerings required#include <iostream>using namespace std; // To store count of increasing order temples// on left and right (including current temple)struct Temple { int L; int R;}; // Returns count of minimum offerings for// n temples of given heights.int offeringNumber(int n, int templeHeight[]){ // Initialize counts for all temples Temple chainSize[n]; for (int i = 0; i < n; ++i) { chainSize[i].L = -1; chainSize[i].R = -1; } // Values corner temples chainSize[0].L = 1; chainSize[n - 1].R = 1; // Filling left and right values using same // values of previous(or next) for (int i = 1; i < n; ++i) { if (templeHeight[i - 1] < templeHeight[i]) chainSize[i].L = chainSize[i - 1].L + 1; else chainSize[i].L = 1; } for (int i = n - 2; i >= 0; --i) { if (templeHeight[i + 1] < templeHeight[i]) chainSize[i].R = chainSize[i + 1].R + 1; else chainSize[i].R = 1; } // Computing max of left and right for all // temples and returning sum. int sum = 0; for (int i = 0; i < n; ++i) sum += max(chainSize[i].L, chainSize[i].R); return sum;} // Driver functionint main(){ int arr1[3] = { 1, 2, 2 }; cout << offeringNumber(3, arr1) << \"\\n\"; int arr2[6] = { 1, 4, 3, 6, 2, 1 }; cout << offeringNumber(6, arr2) << \"\\n\"; return 0;}", "e": 11040, "s": 9620, "text": null }, { "code": "// Java program to find total offerings requiredimport java.util.*; class GFG { // To store count of increasing order temples // on left and right (including current temple) public static class Temple { public int L; public int R; }; // Returns count of minimum offerings for // n temples of given heights. static int offeringNumber(int n, int[] templeHeight) { // Initialize counts for all temples Temple[] chainSize = new Temple[n]; for (int i = 0; i < n; ++i) { chainSize[i] = new Temple(); chainSize[i].L = -1; chainSize[i].R = -1; } // Values corner temples chainSize[0].L = 1; chainSize[n - 1].R = 1; // Filling left and right values // using same values of // previous(or next) for (int i = 1; i < n; ++i) { if (templeHeight[i - 1] < templeHeight[i]) chainSize[i].L = chainSize[i - 1].L + 1; else chainSize[i].L = 1; } for (int i = n - 2; i >= 0; --i) { if (templeHeight[i + 1] < templeHeight[i]) chainSize[i].R = chainSize[i + 1].R + 1; else chainSize[i].R = 1; } // Computing max of left and right for all // temples and returning sum. int sum = 0; for (int i = 0; i < n; ++i) sum += Math.max(chainSize[i].L, chainSize[i].R); return sum; } // Driver code public static void main(String[] s) { int[] arr1 = { 1, 2, 2 }; System.out.println(offeringNumber(3, arr1)); int[] arr2 = { 1, 4, 3, 6, 2, 1 }; System.out.println(offeringNumber(6, arr2)); }} // This code is contributed by pratham76", "e": 12810, "s": 11040, "text": null }, { "code": "# Python3 program to find temple# offerings requiredfrom typing import List # To store count of increasing order temples# on left and right (including current temple) class Temple: def __init__(self, l: int, r: int): self.L = l self.R = r # Returns count of minimum offerings for# n temples of given heights. def offeringNumber(n: int, templeHeight: List[int]) -> int: # Initialize counts for all temples chainSize = [0] * n for i in range(n): chainSize[i] = Temple(-1, -1) # Values corner temples chainSize[0].L = 1 chainSize[-1].R = 1 # Filling left and right values # using same values of previous(or next for i in range(1, n): if templeHeight[i - 1] < templeHeight[i]: chainSize[i].L = chainSize[i - 1].L + 1 else: chainSize[i].L = 1 for i in range(n - 2, -1, -1): if templeHeight[i + 1] < templeHeight[i]: chainSize[i].R = chainSize[i + 1].R + 1 else: chainSize[i].R = 1 # Computing max of left and right for all # temples and returning sum sm = 0 for i in range(n): sm += max(chainSize[i].L, chainSize[i].R) return sm # Driver codeif __name__ == '__main__': arr1 = [1, 2, 2] print(offeringNumber(3, arr1)) arr2 = [1, 4, 3, 6, 2, 1] print(offeringNumber(6, arr2)) # This code is contributed by Rajat Srivastava", "e": 14234, "s": 12810, "text": null }, { "code": "// C# program to find total offerings requiredusing System; class GFG { // To store count of increasing order temples // on left and right (including current temple) public class Temple { public int L; public int R; }; // Returns count of minimum offerings for // n temples of given heights. static int offeringNumber(int n, int[] templeHeight) { // Initialize counts for all temples Temple[] chainSize = new Temple[n]; for (int i = 0; i < n; ++i) { chainSize[i] = new Temple(); chainSize[i].L = -1; chainSize[i].R = -1; } // Values corner temples chainSize[0].L = 1; chainSize[n - 1].R = 1; // Filling left and right values // using same values of // previous(or next) for (int i = 1; i < n; ++i) { if (templeHeight[i - 1] < templeHeight[i]) chainSize[i].L = chainSize[i - 1].L + 1; else chainSize[i].L = 1; } for (int i = n - 2; i >= 0; --i) { if (templeHeight[i + 1] < templeHeight[i]) chainSize[i].R = chainSize[i + 1].R + 1; else chainSize[i].R = 1; } // Computing max of left and right for all // temples and returning sum. int sum = 0; for (int i = 0; i < n; ++i) sum += Math.Max(chainSize[i].L, chainSize[i].R); return sum; } // Driver code static void Main() { int[] arr1 = { 1, 2, 2 }; Console.Write(offeringNumber(3, arr1) + \"\\n\"); int[] arr2 = { 1, 4, 3, 6, 2, 1 }; Console.Write(offeringNumber(6, arr2) + \"\\n\"); }} // This code is contributed by rutvik_56", "e": 15975, "s": 14234, "text": null }, { "code": null, "e": 15980, "s": 15975, "text": "4\n10" }, { "code": null, "e": 16025, "s": 15980, "text": "Time complexity: O(n) Space complexity: O(n)" }, { "code": null, "e": 16042, "s": 16025, "text": "Greedy Approach:" }, { "code": null, "e": 16523, "s": 16042, "text": "If we somehow manage to make sure that the temple at higher mountain is getting more offerings than our problem is solved. For this we can make use of greedy (since we have to compare only the neighbors of current index). The approach is to do two traversals (in two directions), first one to make sure that the temple gets more offerings than the left temple (at higher position) and second one to make sure that the temple at higher position from the right gets more offerings. " }, { "code": null, "e": 16527, "s": 16523, "text": "C++" }, { "code": null, "e": 16532, "s": 16527, "text": "Java" }, { "code": "// C++ Program to find total offerings required#include <iostream>using namespace std; int templeOfferings(int nums[], int n){ // to find the total offerings in both directions int offerings[n]; // start off by giving one offering to the first // temple offerings[0] = 1; // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the left one for (int i = 1; i < n; i++) { if (nums[i] > nums[i - 1]) offerings[i] = offerings[i - 1] + 1; else offerings[i] = 1; } // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the right one for (int i = n - 2; i >= 0; i--) { if (nums[i] > nums[i + 1] && offerings[i] <= offerings[i + 1]) offerings[i] = offerings[i + 1] + 1; } // total offerings int sum = 0; for (int val : offerings) sum += val; return sum;} // Driver functionint main(){ int arr[] = { 1, 4, 3, 6, 2, 1 }; int n = sizeof(arr)/sizeof(arr[0]); cout << (templeOfferings(arr, n)); return 0;} // This code is contributed by kothavvsaakash", "e": 17634, "s": 16532, "text": null }, { "code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { int[] arr = { 1, 4, 3, 6, 2, 1 }; int n = arr.length; System.out.println(templeOfferings(arr, n)); } private static int templeOfferings(int[] nums, int n) { // to find the total offerings in both directions int[] offerings = new int[n]; // start off by giving one offering to the first // temple offerings[0] = 1; // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the left one for (int i = 1; i < n; i++) { if (nums[i] > nums[i - 1]) offerings[i] = offerings[i - 1] + 1; else offerings[i] = 1; } // to make sure that the temple at ith position gets // more offerings if it is at a greater height than // the right one for (int i = n - 2; i >= 0; i--) { if (nums[i] > nums[i + 1] && offerings[i] <= offerings[i + 1]) offerings[i] = offerings[i + 1] + 1; } // total offerings int sum = 0; for (int val : offerings) sum += val; return sum; }}", "e": 18939, "s": 17634, "text": null }, { "code": null, "e": 18942, "s": 18939, "text": "10" }, { "code": null, "e": 18965, "s": 18942, "text": "Time complexity: O(n) " }, { "code": null, "e": 18988, "s": 18965, "text": "Space complexity: O(n)" }, { "code": null, "e": 19437, "s": 18988, "text": "This article is contributed by Aditya Kamath and improved by Vishal Jha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 19443, "s": 19437, "text": "jit_t" }, { "code": null, "e": 19458, "s": 19443, "text": "sahilshelangia" }, { "code": null, "e": 19469, "s": 19458, "text": "rajatsri94" }, { "code": null, "e": 19479, "s": 19469, "text": "rutvik_56" }, { "code": null, "e": 19489, "s": 19479, "text": "pratham76" }, { "code": null, "e": 19498, "s": 19489, "text": "mukesh07" }, { "code": null, "e": 19509, "s": 19498, "text": "sherlockvj" }, { "code": null, "e": 19521, "s": 19509, "text": "kashishsoda" }, { "code": null, "e": 19535, "s": 19521, "text": "sumitgumber28" }, { "code": null, "e": 19544, "s": 19535, "text": "rkbhola5" }, { "code": null, "e": 19559, "s": 19544, "text": "kothavvsaakash" }, { "code": null, "e": 19579, "s": 19559, "text": "Dynamic Programming" }, { "code": null, "e": 19599, "s": 19579, "text": "Dynamic Programming" } ]
Python - Gaussian fit - GeeksforGeeks
14 Jan, 2022 When we plot a dataset such as a histogram, the shape of that charted plot is what we call its distribution. The most commonly observed shape of continuous values is the bell curve, also called the Gaussian or normal distribution. It is named after the German mathematician Carl Friedrich Gauss. Some common example datasets that follow Gaussian distribution are Body temperature, People’s height, Car mileage, IQ scores. Let’s try to generate the ideal normal distribution and plot it using Python. We have libraries like Numpy, scipy, and matplotlib to help us plot an ideal normal curve. Python3 import numpy as npimport scipy as spfrom scipy import statsimport matplotlib.pyplot as plt ## generate the data and plot it for an ideal normal curve ## x-axis for the plotx_data = np.arange(-5, 5, 0.001) ## y-axis as the gaussiany_data = stats.norm.pdf(x_data, 0, 1) ## plot dataplt.plot(x_data, y_data) Output: The points on the x-axis are the observations, and the y-axis is the likelihood of each observation. We generated regularly spaced observations in the range (-5, 5) using np.arange(). Then we ran it through the norm.pdf() function with a mean of 0.0 and a standard deviation of 1, which returned the likelihood of that observation. Observations around 0 are the most common, and the ones around -5.0 and 5.0 are rare. The technical term for the pdf() function is the probability density function. First, let’s fit the data to the Gaussian function. Our goal is to find the values of A and B that best fit our data. First, we need to write a python function for the Gaussian function equation. The function should accept the independent variable (the x-values) and all the parameters that will make it. Python3 #Define the Gaussian functiondef gauss(x, H, A, x0, sigma): return H + A * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2)) We will use the function curve_fit from the python module scipy.optimize to fit our data. It uses non-linear least squares to fit data to a functional form. You can learn more about curve_fit by using the help function within the Jupyter notebook or scipy online documentation. The curve_fit function has three required inputs: the function you want to fit, the x-data, and the y-data you fit. There are two outputs. The first is an array of the optimal values of the parameters. The second is a matrix of the estimated covariance of the parameters from which you can calculate the standard error for the parameters. Example 1: Python3 from __future__ import print_functionimport numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fitxdata = [ -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]ydata = [1.2, 4.2, 6.7, 8.3, 10.6, 11.7, 13.5, 14.5, 15.7, 16.1, 16.6, 16.0, 15.4, 14.4, 14.2, 12.7, 10.3, 8.6, 6.1, 3.9, 2.1] # Recast xdata and ydata into numpy arrays so we can use their handy featuresxdata = np.asarray(xdata)ydata = np.asarray(ydata)plt.plot(xdata, ydata, 'o') # Define the Gaussian functiondef Gauss(x, A, B): y = A*np.exp(-1*B*x**2) return yparameters, covariance = curve_fit(Gauss, xdata, ydata) fit_A = parameters[0]fit_B = parameters[1] fit_y = Gauss(xdata, fit_A, fit_B)plt.plot(xdata, ydata, 'o', label='data')plt.plot(xdata, fit_y, '-', label='fit')plt.legend() Example 2: Python3 import numpy as npfrom scipy.optimize import curve_fitimport matplotlib.pyplot as mpl # Let's create a function to model and create datadef func(x, a, x0, sigma): return a*np.exp(-(x-x0)**2/(2*sigma**2)) # Generating clean datax = np.linspace(0, 10, 100)y = func(x, 1, 5, 2) # Adding noise to the datayn = y + 0.2 * np.random.normal(size=len(x)) # Plot out the current state of the data and modelfig = mpl.figure()ax = fig.add_subplot(111)ax.plot(x, y, c='k', label='Function')ax.scatter(x, yn) # Executing curve_fit on noisy datapopt, pcov = curve_fit(func, x, yn) #popt returns the best fit values for parameters of the given model (func)print (popt) ym = func(x, popt[0], popt[1], popt[2])ax.plot(x, ym, c='r', label='Best fit')ax.legend()fig.savefig('model_fit.png') Output: varshagumber28 simmytarika5 Blogathon-2021 Picked Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? How to Create a Table With Multiple Foreign Keys in SQL? How to Install Tkinter in Windows? SQL Query to Convert Datetime to Date SQL Query to Create Table With a Primary Key Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24794, "s": 24766, "text": "\n14 Jan, 2022" }, { "code": null, "e": 25025, "s": 24794, "text": "When we plot a dataset such as a histogram, the shape of that charted plot is what we call its distribution. The most commonly observed shape of continuous values is the bell curve, also called the Gaussian or normal distribution." }, { "code": null, "e": 25217, "s": 25025, "text": "It is named after the German mathematician Carl Friedrich Gauss. Some common example datasets that follow Gaussian distribution are Body temperature, People’s height, Car mileage, IQ scores. " }, { "code": null, "e": 25295, "s": 25217, "text": "Let’s try to generate the ideal normal distribution and plot it using Python." }, { "code": null, "e": 25386, "s": 25295, "text": "We have libraries like Numpy, scipy, and matplotlib to help us plot an ideal normal curve." }, { "code": null, "e": 25394, "s": 25386, "text": "Python3" }, { "code": "import numpy as npimport scipy as spfrom scipy import statsimport matplotlib.pyplot as plt ## generate the data and plot it for an ideal normal curve ## x-axis for the plotx_data = np.arange(-5, 5, 0.001) ## y-axis as the gaussiany_data = stats.norm.pdf(x_data, 0, 1) ## plot dataplt.plot(x_data, y_data)", "e": 25704, "s": 25394, "text": null }, { "code": null, "e": 25712, "s": 25704, "text": "Output:" }, { "code": null, "e": 25813, "s": 25712, "text": "The points on the x-axis are the observations, and the y-axis is the likelihood of each observation." }, { "code": null, "e": 26209, "s": 25813, "text": "We generated regularly spaced observations in the range (-5, 5) using np.arange(). Then we ran it through the norm.pdf() function with a mean of 0.0 and a standard deviation of 1, which returned the likelihood of that observation. Observations around 0 are the most common, and the ones around -5.0 and 5.0 are rare. The technical term for the pdf() function is the probability density function." }, { "code": null, "e": 26514, "s": 26209, "text": "First, let’s fit the data to the Gaussian function. Our goal is to find the values of A and B that best fit our data. First, we need to write a python function for the Gaussian function equation. The function should accept the independent variable (the x-values) and all the parameters that will make it." }, { "code": null, "e": 26522, "s": 26514, "text": "Python3" }, { "code": "#Define the Gaussian functiondef gauss(x, H, A, x0, sigma): return H + A * np.exp(-(x - x0) ** 2 / (2 * sigma ** 2))", "e": 26642, "s": 26522, "text": null }, { "code": null, "e": 26920, "s": 26642, "text": "We will use the function curve_fit from the python module scipy.optimize to fit our data. It uses non-linear least squares to fit data to a functional form. You can learn more about curve_fit by using the help function within the Jupyter notebook or scipy online documentation." }, { "code": null, "e": 27259, "s": 26920, "text": "The curve_fit function has three required inputs: the function you want to fit, the x-data, and the y-data you fit. There are two outputs. The first is an array of the optimal values of the parameters. The second is a matrix of the estimated covariance of the parameters from which you can calculate the standard error for the parameters." }, { "code": null, "e": 27270, "s": 27259, "text": "Example 1:" }, { "code": null, "e": 27278, "s": 27270, "text": "Python3" }, { "code": "from __future__ import print_functionimport numpy as npimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fitxdata = [ -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]ydata = [1.2, 4.2, 6.7, 8.3, 10.6, 11.7, 13.5, 14.5, 15.7, 16.1, 16.6, 16.0, 15.4, 14.4, 14.2, 12.7, 10.3, 8.6, 6.1, 3.9, 2.1] # Recast xdata and ydata into numpy arrays so we can use their handy featuresxdata = np.asarray(xdata)ydata = np.asarray(ydata)plt.plot(xdata, ydata, 'o') # Define the Gaussian functiondef Gauss(x, A, B): y = A*np.exp(-1*B*x**2) return yparameters, covariance = curve_fit(Gauss, xdata, ydata) fit_A = parameters[0]fit_B = parameters[1] fit_y = Gauss(xdata, fit_A, fit_B)plt.plot(xdata, ydata, 'o', label='data')plt.plot(xdata, fit_y, '-', label='fit')plt.legend()", "e": 28127, "s": 27278, "text": null }, { "code": null, "e": 28138, "s": 28127, "text": "Example 2:" }, { "code": null, "e": 28146, "s": 28138, "text": "Python3" }, { "code": "import numpy as npfrom scipy.optimize import curve_fitimport matplotlib.pyplot as mpl # Let's create a function to model and create datadef func(x, a, x0, sigma): return a*np.exp(-(x-x0)**2/(2*sigma**2)) # Generating clean datax = np.linspace(0, 10, 100)y = func(x, 1, 5, 2) # Adding noise to the datayn = y + 0.2 * np.random.normal(size=len(x)) # Plot out the current state of the data and modelfig = mpl.figure()ax = fig.add_subplot(111)ax.plot(x, y, c='k', label='Function')ax.scatter(x, yn) # Executing curve_fit on noisy datapopt, pcov = curve_fit(func, x, yn) #popt returns the best fit values for parameters of the given model (func)print (popt) ym = func(x, popt[0], popt[1], popt[2])ax.plot(x, ym, c='r', label='Best fit')ax.legend()fig.savefig('model_fit.png')", "e": 28927, "s": 28146, "text": null }, { "code": null, "e": 28935, "s": 28927, "text": "Output:" }, { "code": null, "e": 28950, "s": 28935, "text": "varshagumber28" }, { "code": null, "e": 28963, "s": 28950, "text": "simmytarika5" }, { "code": null, "e": 28978, "s": 28963, "text": "Blogathon-2021" }, { "code": null, "e": 28985, "s": 28978, "text": "Picked" }, { "code": null, "e": 28995, "s": 28985, "text": "Blogathon" }, { "code": null, "e": 29002, "s": 28995, "text": "Python" }, { "code": null, "e": 29100, "s": 29002, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29141, "s": 29100, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 29198, "s": 29141, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 29233, "s": 29198, "text": "How to Install Tkinter in Windows?" }, { "code": null, "e": 29271, "s": 29233, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 29316, "s": 29271, "text": "SQL Query to Create Table With a Primary Key" }, { "code": null, "e": 29344, "s": 29316, "text": "Read JSON file using Python" }, { "code": null, "e": 29394, "s": 29344, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 29416, "s": 29394, "text": "Python map() function" } ]
MySQLi - Using Joins
In the previous chapters, we were getting data from one table at a time. This is good enough for simple takes, but in most of the real world MySQL usages, you will often need to get data from multiple tables in a single query. You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table. You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables. We will see an example of the LEFT JOIN also which is different from the simple MySQL JOIN. Assume we have two tables tcount_tbl and tutorials_tbl, in TUTORIALS. Now take a look at the examples given below βˆ’ The following examples βˆ’ root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * FROM tcount_tbl; +-----------------+----------------+ | tutorial_author | tutorial_count | +-----------------+----------------+ | mahran | 20 | | mahnaz | NULL | | Jen | NULL | | Gill | 20 | | John Poul | 1 | | Sanjay | 1 | +-----------------+----------------+ 6 rows in set (0.01 sec) mysql> SELECT * from tutorials_tbl; +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 1 | Learn PHP | John Poul | 2007-05-24 | | 2 | Learn MySQL | Abdul S | 2007-05-24 | | 3 | JAVA Tutorial | Sanjay | 2007-05-06 | +-------------+----------------+-----------------+-----------------+ 3 rows in set (0.00 sec) mysql> Now we can write an SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pick up the corresponding number of tutorials from the tcount_tbl. mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count β†’ FROM tutorials_tbl a, tcount_tbl b β†’ WHERE a.tutorial_author = b.tutorial_author; +-------------+-----------------+----------------+ | tutorial_id | tutorial_author | tutorial_count | +-------------+-----------------+----------------+ | 1 | John Poul | 1 | | 3 | Sanjay | 1 | +-------------+-----------------+----------------+ 2 rows in set (0.01 sec) mysql> PHP uses mysqli query() or mysql_query() function to get records from a MySQL tables using Joins. This function takes two parameters and returns TRUE on success or FALSE on failure. $mysqliβ†’query($sql,$resultmode) $sql Required - SQL query to get records from multiple tables using Join. $resultmode Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. First create a table in MySQL using following script and insert two records. create table tcount_tbl( tutorial_author VARCHAR(40) NOT NULL, tutorial_count int ); insert into tcount_tbl values('Mahesh', 3); insert into tcount_tbl values('Suresh', 1); Try the following example to get records from a two tables using Join. βˆ’ Copy and paste the following example as mysql_example.php βˆ’ <html> <head> <title>Using joins on MySQL Tables</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqliβ†’connect_errno ) { printf("Connect failed: %s<br />", $mysqliβ†’connect_error); exit(); } printf('Connected successfully.<br />'); $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count FROM tutorials_tbl a, tcount_tbl b WHERE a.tutorial_author = b.tutorial_author'; $result = $mysqliβ†’query($sql); if ($resultβ†’num_rows > 0) { while($row = $resultβ†’fetch_assoc()) { printf("Id: %s, Author: %s, Count: %d <br />", $row["tutorial_id"], $row["tutorial_author"], $row["tutorial_count"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqliβ†’close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Connected successfully. Id: 1, Author: Mahesh, Count: 3 Id: 2, Author: Mahesh, Count: 3 Id: 3, Author: Mahesh, Count: 3 Id: 5, Author: Suresh, Count: 1 A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives some extra consideration to the table that is on the left. If I do a LEFT JOIN, I get all the records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join: thus ensuring (in my example) that every AUTHOR gets a mention. Try the following example to understand the LEFT JOIN. root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count β†’ FROM tutorials_tbl a LEFT JOIN tcount_tbl b β†’ ON a.tutorial_author = b.tutorial_author; +-------------+-----------------+----------------+ | tutorial_id | tutorial_author | tutorial_count | +-------------+-----------------+----------------+ | 1 | John Poul | 1 | | 2 | Abdul S | NULL | | 3 | Sanjay | 1 | +-------------+-----------------+----------------+ 3 rows in set (0.02 sec) You would need to do more practice to become familiar with JOINS. This is slightly a bit complex concept in MySQL/SQL and will become more clear while doing real examples. 14 Lectures 1.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2490, "s": 2263, "text": "In the previous chapters, we were getting data from one table at a time. This is good enough for simple takes, but in most of the real world MySQL usages, you will often need to get data from multiple tables in a single query." }, { "code": null, "e": 2631, "s": 2490, "text": "You can use multiple tables in your single SQL query. The act of joining in MySQL refers to smashing two or more tables into a single table." }, { "code": null, "e": 2811, "s": 2631, "text": "You can use JOINS in the SELECT, UPDATE and DELETE statements to join the MySQL tables. We will see an example of the LEFT JOIN also which is different from the simple MySQL JOIN." }, { "code": null, "e": 2927, "s": 2811, "text": "Assume we have two tables tcount_tbl and tutorials_tbl, in TUTORIALS. Now take a look at the examples given below βˆ’" }, { "code": null, "e": 2952, "s": 2927, "text": "The following examples βˆ’" }, { "code": null, "e": 4087, "s": 2952, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT * FROM tcount_tbl;\n+-----------------+----------------+\n| tutorial_author | tutorial_count |\n+-----------------+----------------+\n| mahran | 20 | \n| mahnaz | NULL | \n| Jen | NULL | \n| Gill | 20 | \n| John Poul | 1 | \n| Sanjay | 1 | \n+-----------------+----------------+\n6 rows in set (0.01 sec)\nmysql> SELECT * from tutorials_tbl;\n+-------------+----------------+-----------------+-----------------+\n| tutorial_id | tutorial_title | tutorial_author | submission_date |\n+-------------+----------------+-----------------+-----------------+\n| 1 | Learn PHP | John Poul | 2007-05-24 | \n| 2 | Learn MySQL | Abdul S | 2007-05-24 | \n| 3 | JAVA Tutorial | Sanjay | 2007-05-06 | \n+-------------+----------------+-----------------+-----------------+\n3 rows in set (0.00 sec)\nmysql>" }, { "code": null, "e": 4283, "s": 4087, "text": "Now we can write an SQL query to join these two tables. This query will select all the authors from table tutorials_tbl and will pick up the corresponding number of tutorials from the tcount_tbl." }, { "code": null, "e": 4776, "s": 4283, "text": "mysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count\n β†’ FROM tutorials_tbl a, tcount_tbl b\n β†’ WHERE a.tutorial_author = b.tutorial_author;\n+-------------+-----------------+----------------+\n| tutorial_id | tutorial_author | tutorial_count |\n+-------------+-----------------+----------------+\n| 1 | John Poul | 1 |\n| 3 | Sanjay | 1 |\n+-------------+-----------------+----------------+\n2 rows in set (0.01 sec)\nmysql>" }, { "code": null, "e": 4958, "s": 4776, "text": "PHP uses mysqli query() or mysql_query() function to get records from a MySQL tables using Joins. This function takes two parameters and returns TRUE on success or FALSE on failure." }, { "code": null, "e": 4991, "s": 4958, "text": "$mysqliβ†’query($sql,$resultmode)\n" }, { "code": null, "e": 4996, "s": 4991, "text": "$sql" }, { "code": null, "e": 5065, "s": 4996, "text": "Required - SQL query to get records from multiple tables using Join." }, { "code": null, "e": 5077, "s": 5065, "text": "$resultmode" }, { "code": null, "e": 5225, "s": 5077, "text": "Optional - Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used." }, { "code": null, "e": 5302, "s": 5225, "text": "First create a table in MySQL using following script and insert two records." }, { "code": null, "e": 5481, "s": 5302, "text": "create table tcount_tbl(\n tutorial_author VARCHAR(40) NOT NULL,\n tutorial_count int\n);\ninsert into tcount_tbl values('Mahesh', 3);\ninsert into tcount_tbl values('Suresh', 1);" }, { "code": null, "e": 5554, "s": 5481, "text": "Try the following example to get records from a two tables using Join. βˆ’" }, { "code": null, "e": 5614, "s": 5554, "text": "Copy and paste the following example as mysql_example.php βˆ’" }, { "code": null, "e": 6799, "s": 5614, "text": "<html>\n <head>\n <title>Using joins on MySQL Tables</title>\n </head>\n <body>\n <?php\n $dbhost = 'localhost';\n $dbuser = 'root';\n $dbpass = 'root@123';\n $dbname = 'TUTORIALS';\n $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);\n \n if($mysqliβ†’connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqliβ†’connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n \n $sql = 'SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count\n\t\t\t\tFROM tutorials_tbl a, tcount_tbl b\n\t\t\t\tWHERE a.tutorial_author = b.tutorial_author';\n\t\t \n $result = $mysqliβ†’query($sql);\n \n if ($resultβ†’num_rows > 0) {\n while($row = $resultβ†’fetch_assoc()) {\n printf(\"Id: %s, Author: %s, Count: %d <br />\", \n $row[\"tutorial_id\"], \n $row[\"tutorial_author\"], \n $row[\"tutorial_count\"]); \n }\n } else {\n printf('No record found.<br />');\n }\n mysqli_free_result($result);\n $mysqliβ†’close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 6881, "s": 6799, "text": "Access the mysql_example.php deployed on apache web server and verify the output." }, { "code": null, "e": 7034, "s": 6881, "text": "Connected successfully.\nId: 1, Author: Mahesh, Count: 3\nId: 2, Author: Mahesh, Count: 3\nId: 3, Author: Mahesh, Count: 3\nId: 5, Author: Suresh, Count: 1\n" }, { "code": null, "e": 7168, "s": 7034, "text": "A MySQL left join is different from a simple join. A MySQL LEFT JOIN gives some extra consideration to the table that is on the left." }, { "code": null, "e": 7397, "s": 7168, "text": "If I do a LEFT JOIN, I get all the records that match in the same way and IN ADDITION I get an extra record for each unmatched record in the left table of the join: thus ensuring (in my example) that every AUTHOR gets a mention." }, { "code": null, "e": 7452, "s": 7397, "text": "Try the following example to understand the LEFT JOIN." }, { "code": null, "e": 8095, "s": 7452, "text": "root@host# mysql -u root -p password;\nEnter password:*******\nmysql> use TUTORIALS;\nDatabase changed\nmysql> SELECT a.tutorial_id, a.tutorial_author, b.tutorial_count\n β†’ FROM tutorials_tbl a LEFT JOIN tcount_tbl b\n β†’ ON a.tutorial_author = b.tutorial_author;\n+-------------+-----------------+----------------+\n| tutorial_id | tutorial_author | tutorial_count |\n+-------------+-----------------+----------------+\n| 1 | John Poul | 1 |\n| 2 | Abdul S | NULL |\n| 3 | Sanjay | 1 |\n+-------------+-----------------+----------------+\n3 rows in set (0.02 sec)" }, { "code": null, "e": 8267, "s": 8095, "text": "You would need to do more practice to become familiar with JOINS. This is slightly a bit complex concept in MySQL/SQL and will become more clear while doing real examples." }, { "code": null, "e": 8302, "s": 8267, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8325, "s": 8302, "text": " Stone River ELearning" }, { "code": null, "e": 8332, "s": 8325, "text": " Print" }, { "code": null, "e": 8343, "s": 8332, "text": " Add Notes" } ]
Ant - Building Projects
Now that we have learnt about the data types in Ant, it is time to put that knowledge into practice. We will build a project in this chapter. The aim of this chapter is to build an Ant file that compiles the java classes and places them in the WEB-INF\classes folder. Consider the following project structure βˆ’ The database scripts are stored in the db folder. The database scripts are stored in the db folder. The java source code is stored in the src folder. The java source code is stored in the src folder. The images, js, META-INF, styles (css) are stored in the war folder. The images, js, META-INF, styles (css) are stored in the war folder. The Java Server Pages (JSPs) are stored in the jsp folder. The Java Server Pages (JSPs) are stored in the jsp folder. The third party jar files are stored in the lib folder. The third party jar files are stored in the lib folder. The java class files are stored in the WEB-INF\classes folder. The java class files are stored in the WEB-INF\classes folder. This project forms the Hello World Fax Application for the rest of this tutorial. C:\work\FaxWebApplication>tree Folder PATH listing Volume serial number is 00740061 EC1C:ADB1 C:. +---db +---src . +---faxapp . +---dao . +---entity . +---util . +---web +---war +---images +---js +---META-INF +---styles +---WEB-INF +---classes +---jsp +---lib Here is the build.xml required for this project. Let us consider it piece by piece. <?xml version="1.0"?> <project name="fax" basedir="." default="build"> <property name="src.dir" value="src"/> <property name="web.dir" value="war"/> <property name="build.dir" value="${web.dir}/WEB-INF/classes"/> <property name="name" value="fax"/> <path id="master-classpath"> <fileset dir="${web.dir}/WEB-INF/lib"> <include name="*.jar"/> </fileset> <pathelement path="${build.dir}"/> </path> <target name="build" description="Compile source tree java files"> <mkdir dir="${build.dir}"/> <javac destdir="${build.dir}" source="1.5" target="1.5"> <src path="${src.dir}"/> <classpath refid="master-classpath"/> </javac> </target> <target name="clean" description="Clean output directories"> <delete> <fileset dir="${build.dir}"> <include name="**/*.class"/> </fileset> </delete> </target> </project> First, let us declare some properties for the source, web, and build folders. <property name="src.dir" value="src"/> <property name="web.dir" value="war"/> <property name="build.dir" value="${web.dir}/WEB-INF/classes"/> In the above mentioned example βˆ’ src.dir refers to the source folder of the project, where the java source files can be found. src.dir refers to the source folder of the project, where the java source files can be found. web.dir refers to the web source folder of the project, where you can find the JSPs,web.xml, css, javascript and other web related files web.dir refers to the web source folder of the project, where you can find the JSPs,web.xml, css, javascript and other web related files build.dir refers to the output folder of the project compilation. build.dir refers to the output folder of the project compilation. Properties can refer to other properties. As shown in the above example, the build.dir property makes a reference to the web.dir property. In this example, the src.dir refers to the source folder of the project. The default target of our project is the compile target. But first, let us look at the clean target. The clean target, as the name suggests, deletes the files in the build folder. <target name="clean" description="Clean output directories"> <delete> <fileset dir="${build.dir}"> <include name="**/*.class"/> </fileset> </delete> </target> The master-classpath holds the classpath information. In this case, it includes the classes in the build folder and the jar files in the lib folder. <path id="master-classpath"> <fileset dir="${web.dir}/WEB-INF/lib"> <include name="*.jar"/> </fileset> <pathelement path="${build.dir}"/> </path> Finally, the build targets to build the files. First of all, we create the build directory, if it does not exist, then, we execute the javac command (specifying jdk1.5 as our target compilation). We supply the source folder and the classpath to the javac task and ask it to drop the class files in the build folder. <target name="build" description="Compile main source tree java files"> <mkdir dir="${build.dir}"/> <javac destdir="${build.dir}" source="1.5" target="1.5" debug="true" deprecation="false" optimize="false" failonerror="true"> <src path="${src.dir}"/> <classpath refid="master-classpath"/> </javac> </target> Executing Ant on this file compiles the java source files and places the classes in the build folder. The following outcome is the result of running the Ant file βˆ’ C:\>ant Buildfile: C:\build.xml BUILD SUCCESSFUL Total time: 6.3 seconds The files are compiled and placed in the build.dir folder. 20 Lectures 2 hours Deepti Trivedi 19 Lectures 2.5 hours Deepti Trivedi 139 Lectures 14 hours Er. Himanshu Vasishta 30 Lectures 1.5 hours Pushpendu Mondal 65 Lectures 6.5 hours Ridhi Arora 10 Lectures 2 hours Manish Gupta Print Add Notes Bookmark this page
[ { "code": null, "e": 2365, "s": 2097, "text": "Now that we have learnt about the data types in Ant, it is time to put that knowledge into practice. We will build a project in this chapter. The aim of this chapter is to build an Ant file that compiles the java classes and places them in the WEB-INF\\classes folder." }, { "code": null, "e": 2408, "s": 2365, "text": "Consider the following project structure βˆ’" }, { "code": null, "e": 2458, "s": 2408, "text": "The database scripts are stored in the db folder." }, { "code": null, "e": 2508, "s": 2458, "text": "The database scripts are stored in the db folder." }, { "code": null, "e": 2558, "s": 2508, "text": "The java source code is stored in the src folder." }, { "code": null, "e": 2608, "s": 2558, "text": "The java source code is stored in the src folder." }, { "code": null, "e": 2677, "s": 2608, "text": "The images, js, META-INF, styles (css) are stored in the war folder." }, { "code": null, "e": 2746, "s": 2677, "text": "The images, js, META-INF, styles (css) are stored in the war folder." }, { "code": null, "e": 2805, "s": 2746, "text": "The Java Server Pages (JSPs) are stored in the jsp folder." }, { "code": null, "e": 2864, "s": 2805, "text": "The Java Server Pages (JSPs) are stored in the jsp folder." }, { "code": null, "e": 2920, "s": 2864, "text": "The third party jar files are stored in the lib folder." }, { "code": null, "e": 2976, "s": 2920, "text": "The third party jar files are stored in the lib folder." }, { "code": null, "e": 3039, "s": 2976, "text": "The java class files are stored in the WEB-INF\\classes folder." }, { "code": null, "e": 3102, "s": 3039, "text": "The java class files are stored in the WEB-INF\\classes folder." }, { "code": null, "e": 3184, "s": 3102, "text": "This project forms the Hello World Fax Application for the rest of this tutorial." }, { "code": null, "e": 3478, "s": 3184, "text": "C:\\work\\FaxWebApplication>tree\nFolder PATH listing\nVolume serial number is 00740061 EC1C:ADB1\nC:.\n+---db\n+---src\n. +---faxapp\n. +---dao\n. +---entity\n. +---util\n. +---web\n+---war\n +---images\n +---js\n +---META-INF\n +---styles\n +---WEB-INF\n +---classes\n +---jsp\n +---lib\n" }, { "code": null, "e": 3562, "s": 3478, "text": "Here is the build.xml required for this project. Let us consider it piece by piece." }, { "code": null, "e": 4505, "s": 3562, "text": "<?xml version=\"1.0\"?>\n<project name=\"fax\" basedir=\".\" default=\"build\">\n <property name=\"src.dir\" value=\"src\"/>\n <property name=\"web.dir\" value=\"war\"/>\n <property name=\"build.dir\" value=\"${web.dir}/WEB-INF/classes\"/>\n <property name=\"name\" value=\"fax\"/>\n \n <path id=\"master-classpath\">\n <fileset dir=\"${web.dir}/WEB-INF/lib\">\n <include name=\"*.jar\"/>\n </fileset>\n <pathelement path=\"${build.dir}\"/>\n </path>\n\n <target name=\"build\" description=\"Compile source tree java files\">\n <mkdir dir=\"${build.dir}\"/>\n <javac destdir=\"${build.dir}\" source=\"1.5\" target=\"1.5\">\n <src path=\"${src.dir}\"/>\n <classpath refid=\"master-classpath\"/>\n </javac>\n </target>\n \n <target name=\"clean\" description=\"Clean output directories\">\n <delete>\n <fileset dir=\"${build.dir}\">\n <include name=\"**/*.class\"/>\n </fileset>\n </delete>\n </target>\n</project>" }, { "code": null, "e": 4583, "s": 4505, "text": "First, let us declare some properties for the source, web, and build folders." }, { "code": null, "e": 4726, "s": 4583, "text": "<property name=\"src.dir\" value=\"src\"/>\n<property name=\"web.dir\" value=\"war\"/>\n<property name=\"build.dir\" value=\"${web.dir}/WEB-INF/classes\"/>\n" }, { "code": null, "e": 4759, "s": 4726, "text": "In the above mentioned example βˆ’" }, { "code": null, "e": 4853, "s": 4759, "text": "src.dir refers to the source folder of the project, where the java source files can be found." }, { "code": null, "e": 4947, "s": 4853, "text": "src.dir refers to the source folder of the project, where the java source files can be found." }, { "code": null, "e": 5084, "s": 4947, "text": "web.dir refers to the web source folder of the project, where you can find the JSPs,web.xml, css, javascript and other web related files" }, { "code": null, "e": 5221, "s": 5084, "text": "web.dir refers to the web source folder of the project, where you can find the JSPs,web.xml, css, javascript and other web related files" }, { "code": null, "e": 5287, "s": 5221, "text": "build.dir refers to the output folder of the project compilation." }, { "code": null, "e": 5353, "s": 5287, "text": "build.dir refers to the output folder of the project compilation." }, { "code": null, "e": 5492, "s": 5353, "text": "Properties can refer to other properties. As shown in the above example, the build.dir property makes a reference to the web.dir property." }, { "code": null, "e": 5565, "s": 5492, "text": "In this example, the src.dir refers to the source folder of the project." }, { "code": null, "e": 5666, "s": 5565, "text": "The default target of our project is the compile target. But first, let us look at the clean target." }, { "code": null, "e": 5745, "s": 5666, "text": "The clean target, as the name suggests, deletes the files in the build folder." }, { "code": null, "e": 5931, "s": 5745, "text": "<target name=\"clean\" description=\"Clean output directories\">\n <delete>\n <fileset dir=\"${build.dir}\">\n <include name=\"**/*.class\"/>\n </fileset>\n </delete>\n</target>" }, { "code": null, "e": 6080, "s": 5931, "text": "The master-classpath holds the classpath information. In this case, it includes the classes in the build folder and the jar files in the lib folder." }, { "code": null, "e": 6241, "s": 6080, "text": "<path id=\"master-classpath\">\n <fileset dir=\"${web.dir}/WEB-INF/lib\">\n <include name=\"*.jar\"/>\n </fileset>\n <pathelement path=\"${build.dir}\"/>\n</path>" }, { "code": null, "e": 6288, "s": 6241, "text": "Finally, the build targets to build the files." }, { "code": null, "e": 6557, "s": 6288, "text": "First of all, we create the build directory, if it does not exist, then, we execute the javac command (specifying jdk1.5 as our target compilation). We supply the source folder and the classpath to the javac task and ask it to drop the class files in the build folder." }, { "code": null, "e": 6900, "s": 6557, "text": "<target name=\"build\" description=\"Compile main source tree java files\">\n <mkdir dir=\"${build.dir}\"/>\n <javac destdir=\"${build.dir}\" source=\"1.5\" target=\"1.5\" \n debug=\"true\" deprecation=\"false\" optimize=\"false\" failonerror=\"true\">\n \n <src path=\"${src.dir}\"/>\n <classpath refid=\"master-classpath\"/>\n </javac>\n</target>" }, { "code": null, "e": 7002, "s": 6900, "text": "Executing Ant on this file compiles the java source files and places the classes in the build folder." }, { "code": null, "e": 7064, "s": 7002, "text": "The following outcome is the result of running the Ant file βˆ’" }, { "code": null, "e": 7138, "s": 7064, "text": "C:\\>ant\nBuildfile: C:\\build.xml\n\nBUILD SUCCESSFUL\nTotal time: 6.3 seconds" }, { "code": null, "e": 7197, "s": 7138, "text": "The files are compiled and placed in the build.dir folder." }, { "code": null, "e": 7230, "s": 7197, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 7246, "s": 7230, "text": " Deepti Trivedi" }, { "code": null, "e": 7281, "s": 7246, "text": "\n 19 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7297, "s": 7281, "text": " Deepti Trivedi" }, { "code": null, "e": 7332, "s": 7297, "text": "\n 139 Lectures \n 14 hours \n" }, { "code": null, "e": 7355, "s": 7332, "text": " Er. Himanshu Vasishta" }, { "code": null, "e": 7390, "s": 7355, "text": "\n 30 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7408, "s": 7390, "text": " Pushpendu Mondal" }, { "code": null, "e": 7443, "s": 7408, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7456, "s": 7443, "text": " Ridhi Arora" }, { "code": null, "e": 7489, "s": 7456, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 7503, "s": 7489, "text": " Manish Gupta" }, { "code": null, "e": 7510, "s": 7503, "text": " Print" }, { "code": null, "e": 7521, "s": 7510, "text": " Add Notes" } ]
alias - Unix, Linux Command
alias - This command creates an alias. Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. alias [-p] [name[=value] ...] If arguments are supplied, an alias is defined for each name whose value is given. If no value is given, alias will print the current value of the alias. Without arguments or with the -p option, alias prints the list of aliases on the standard output in a form that allows them to be reused as input. The value cannot contain any positional parameters ($1 etc), if you need to do that use a shell function instead. To create an alias to clear the screen. $ alias cls='clear' Use the alias $ cls To create an alias to clear the screen. $ alias cls='clear' Use the alias $ cls To create an alias 'ls' to change the default action of ls. $ alias ls='ls --a' Use the alias $ ls . .. sample.txt To create an alias 'ls' to change the default action of ls. $ alias ls='ls --a' Use the alias $ ls . .. sample.txt To create various alias using cd command to go into to sub-sub directories. $ alias ..='cd ..' $ alias ...='cd ../..' $ alias ....='cd ../../..' Use the alias $ mkdir sample $ cd sample $ pwd /sample $ .. $ pwd / To create various alias using cd command to go into to sub-sub directories. $ alias ..='cd ..' $ alias ...='cd ../..' $ alias ....='cd ../../..' Use the alias $ mkdir sample $ cd sample $ pwd /sample $ .. $ pwd / To create alias to display present working directory. $ alias .='echo $PWD' Use the alias $ . / To create alias to display present working directory. $ alias .='echo $PWD' Use the alias $ . / To create alias to prevent accidental deletion. $ alias rm='rm -i' First create a sample.txt file sample text Remove the sample.txt file interactively $ rm sample.txt rm: remove regular file 'sample.txt' ? To create alias to prevent accidental deletion. $ alias rm='rm -i' First create a sample.txt file sample text Remove the sample.txt file interactively $ rm sample.txt rm: remove regular file 'sample.txt' ? 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10723, "s": 10577, "text": "alias - This command creates an alias. Aliases allow a string to be substituted for a word when it is used as the first word of a simple command." }, { "code": null, "e": 10753, "s": 10723, "text": "alias [-p] [name[=value] ...]" }, { "code": null, "e": 11169, "s": 10753, "text": "If arguments are supplied, an alias is defined for each name whose value is given. If no value is given, alias will print the current value of the alias. Without arguments or with the -p option, alias prints the list of aliases on the standard output in a form that allows them to be reused as input. The value cannot contain any positional parameters ($1 etc), if you need to do that use a shell function instead.\n" }, { "code": null, "e": 11252, "s": 11169, "text": "To create an alias to clear the screen.\n$ alias cls='clear'\n\nUse the alias\n$ cls\n\n" }, { "code": null, "e": 11292, "s": 11252, "text": "To create an alias to clear the screen." }, { "code": null, "e": 11313, "s": 11292, "text": "$ alias cls='clear'\n" }, { "code": null, "e": 11327, "s": 11313, "text": "Use the alias" }, { "code": null, "e": 11334, "s": 11327, "text": "$ cls\n" }, { "code": null, "e": 11452, "s": 11334, "text": "To create an alias 'ls' to change the default action of ls.\n$ alias ls='ls --a'\n\nUse the alias\n$ ls\n. .. sample.txt\n\n" }, { "code": null, "e": 11512, "s": 11452, "text": "To create an alias 'ls' to change the default action of ls." }, { "code": null, "e": 11533, "s": 11512, "text": "$ alias ls='ls --a'\n" }, { "code": null, "e": 11547, "s": 11533, "text": "Use the alias" }, { "code": null, "e": 11569, "s": 11547, "text": "$ ls\n. .. sample.txt\n" }, { "code": null, "e": 11786, "s": 11569, "text": "To create various alias using cd command to go into to sub-sub directories.\n$ alias ..='cd ..' \n$ alias ...='cd ../..'\n$ alias ....='cd ../../..'\n\nUse the alias\n$ mkdir sample\n$ cd sample\n$ pwd\n/sample\n$ ..\n$ pwd\n/\n\n" }, { "code": null, "e": 11862, "s": 11786, "text": "To create various alias using cd command to go into to sub-sub directories." }, { "code": null, "e": 11933, "s": 11862, "text": "$ alias ..='cd ..' \n$ alias ...='cd ../..'\n$ alias ....='cd ../../..'\n" }, { "code": null, "e": 11947, "s": 11933, "text": "Use the alias" }, { "code": null, "e": 12002, "s": 11947, "text": "$ mkdir sample\n$ cd sample\n$ pwd\n/sample\n$ ..\n$ pwd\n/\n" }, { "code": null, "e": 12101, "s": 12002, "text": "To create alias to display present working directory.\n$ alias .='echo $PWD'\n\nUse the alias\n$ .\n/\n\n" }, { "code": null, "e": 12155, "s": 12101, "text": "To create alias to display present working directory." }, { "code": null, "e": 12178, "s": 12155, "text": "$ alias .='echo $PWD'\n" }, { "code": null, "e": 12192, "s": 12178, "text": "Use the alias" }, { "code": null, "e": 12199, "s": 12192, "text": "$ .\n/\n" }, { "code": null, "e": 12410, "s": 12199, "text": "To create alias to prevent accidental deletion.\n$ alias rm='rm -i'\n\nFirst create a sample.txt file\nsample text\n\nRemove the sample.txt file interactively\n$ rm sample.txt\nrm: remove regular file 'sample.txt' ? \n\n" }, { "code": null, "e": 12458, "s": 12410, "text": "To create alias to prevent accidental deletion." }, { "code": null, "e": 12478, "s": 12458, "text": "$ alias rm='rm -i'\n" }, { "code": null, "e": 12509, "s": 12478, "text": "First create a sample.txt file" }, { "code": null, "e": 12522, "s": 12509, "text": "sample text\n" }, { "code": null, "e": 12563, "s": 12522, "text": "Remove the sample.txt file interactively" }, { "code": null, "e": 12620, "s": 12563, "text": "$ rm sample.txt\nrm: remove regular file 'sample.txt' ? \n" }, { "code": null, "e": 12655, "s": 12620, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 12683, "s": 12655, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12717, "s": 12683, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12734, "s": 12717, "text": " Frahaan Hussain" }, { "code": null, "e": 12767, "s": 12734, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 12778, "s": 12767, "text": " Pradeep D" }, { "code": null, "e": 12813, "s": 12778, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12829, "s": 12813, "text": " Musab Zayadneh" }, { "code": null, "e": 12862, "s": 12829, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 12874, "s": 12862, "text": " GUHARAJANM" }, { "code": null, "e": 12906, "s": 12874, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 12914, "s": 12906, "text": " Uplatz" }, { "code": null, "e": 12921, "s": 12914, "text": " Print" }, { "code": null, "e": 12932, "s": 12921, "text": " Add Notes" } ]
Reverse an array in Java - GeeksforGeeks
08 Apr, 2022 Given an array, the task is to reverse the given array in Java. Examples: Input : 1, 2, 3, 4, 5 Output :5, 4, 3, 2, 1 Input : 10, 20, 30, 40 Output : 40, 30, 20, 10 To know about the basics of Array, refer to Array Data Structure. There are numerous approaches to reverse an array in Java. These are: Using Temp array Using Swapping Using Collections.reverse() method Using StringBuilder.append() method The first method is as follows: Take input the size of the array and the elements of the array. Consider a function reverse which takes the parameters-the array(say arr) and the size of the array(say n). Inside the function, a new array (with the array size of the first array, arr) is initialized. The array arr[] is iterated from the first element, and each element of array arr[] is placed in the new array from the back, i.e., the new array is iterated from its last element. In this way, all the elements of the array arr[] are placed reversely in the new array. Further, we can iterate through the new array from the beginning and print the elements of the array. Java // Basic Java program that reverses an array public class reverseArray { // function that reverses array and stores it // in another array static void reverse(int a[], int n) { int[] b = new int[n]; int j = n; for (int i = 0; i < n; i++) { b[j - 1] = a[i]; j = j - 1; } // printing the reversed array System.out.println("Reversed array is: \n"); for (int k = 0; k < n; k++) { System.out.println(b[k]); } } public static void main(String[] args) { int [] arr = {10, 20, 30, 40, 50}; reverse(arr, arr.length); }} Reversed array is: 50 40 30 20 10 The second method uses a similar code for the inputting and printing of the array. However, we don’t create a new array like the above method. Instead, we reverse the original array itself. In this method, we swap the elements of the array. The first element is swapped with the last element. The second element is swapped with the last but one element and so on. For instance, consider array [1, 2, 3, ...., n-2, n-1, n]. We swap 1 with n, 2 with n-1, 3 with n-2 and further. Java // Java Program that reverses array// in less number of swaps public class arrayReverse { // function swaps the array's first element with last // element, second element with last second element and // so on static void reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } // printing the reversed array System.out.println("Reversed array is: \n"); for (k = 0; k < n; k++) { System.out.println(a[k]); } } public static void main(String[] args) { int[] arr = { 10, 20, 30, 40, 50 }; reverse(arr, arr.length); }} Reversed array is: 50 40 30 20 10 The third method is to use the function java.util.Collections.reverse(List list) method. This method reverses the elements in the specified list. Hence, we convert the array into a list first by using java.util.Arrays.asList(array) and then reverse the list. Java // Reversing an array using Java collectionsimport java.util.*; public class reversingArray { // function reverses the elements of the array static void reverse(Integer a[]) { Collections.reverse(Arrays.asList(a)); System.out.println(Arrays.asList(a)); } public static void main(String[] args) { Integer [] arr = {10, 20, 30, 40, 50}; reverse(arr); }} [50, 40, 30, 20, 10] As a fourth method, If you are working with a String array, we can use a StringBuilder and append each array element with a for loop decrementing from the array’s length, convert the StringBuilder to a string, and split back into an array. Java // Java Program for Reversing an array using StringBuilder import java.util.Arrays; class GFG { public static void main (String[] args) { String[] arr = {"Hello", "World"}; StringBuilder reversed = new StringBuilder(); for (int i = arr.length; i > 0; i--) { reversed.append(arr[i - 1]).append(" "); }; String[] reversedArray = reversed.toString().split(" "); System.out.println(Arrays.toString(reversedArray)); }} [World, Hello] briangaedu nishkarshgandhi Java-Array-Programs Java-Arrays Picked Technical Scripter 2018 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java Stack Class in Java Stream In Java Singleton Class in Java
[ { "code": null, "e": 24492, "s": 24464, "text": "\n08 Apr, 2022" }, { "code": null, "e": 24556, "s": 24492, "text": "Given an array, the task is to reverse the given array in Java." }, { "code": null, "e": 24567, "s": 24556, "text": "Examples: " }, { "code": null, "e": 24660, "s": 24567, "text": "Input : 1, 2, 3, 4, 5\nOutput :5, 4, 3, 2, 1\n\nInput : 10, 20, 30, 40\nOutput : 40, 30, 20, 10" }, { "code": null, "e": 24726, "s": 24660, "text": "To know about the basics of Array, refer to Array Data Structure." }, { "code": null, "e": 24796, "s": 24726, "text": "There are numerous approaches to reverse an array in Java. These are:" }, { "code": null, "e": 24813, "s": 24796, "text": "Using Temp array" }, { "code": null, "e": 24828, "s": 24813, "text": "Using Swapping" }, { "code": null, "e": 24863, "s": 24828, "text": "Using Collections.reverse() method" }, { "code": null, "e": 24899, "s": 24863, "text": "Using StringBuilder.append() method" }, { "code": null, "e": 24932, "s": 24899, "text": "The first method is as follows: " }, { "code": null, "e": 24996, "s": 24932, "text": "Take input the size of the array and the elements of the array." }, { "code": null, "e": 25104, "s": 24996, "text": "Consider a function reverse which takes the parameters-the array(say arr) and the size of the array(say n)." }, { "code": null, "e": 25380, "s": 25104, "text": "Inside the function, a new array (with the array size of the first array, arr) is initialized. The array arr[] is iterated from the first element, and each element of array arr[] is placed in the new array from the back, i.e., the new array is iterated from its last element." }, { "code": null, "e": 25468, "s": 25380, "text": "In this way, all the elements of the array arr[] are placed reversely in the new array." }, { "code": null, "e": 25570, "s": 25468, "text": "Further, we can iterate through the new array from the beginning and print the elements of the array." }, { "code": null, "e": 25575, "s": 25570, "text": "Java" }, { "code": "// Basic Java program that reverses an array public class reverseArray { // function that reverses array and stores it // in another array static void reverse(int a[], int n) { int[] b = new int[n]; int j = n; for (int i = 0; i < n; i++) { b[j - 1] = a[i]; j = j - 1; } // printing the reversed array System.out.println(\"Reversed array is: \\n\"); for (int k = 0; k < n; k++) { System.out.println(b[k]); } } public static void main(String[] args) { int [] arr = {10, 20, 30, 40, 50}; reverse(arr, arr.length); }}", "e": 26221, "s": 25575, "text": null }, { "code": null, "e": 26257, "s": 26221, "text": "Reversed array is: \n\n50\n40\n30\n20\n10" }, { "code": null, "e": 26736, "s": 26257, "text": "The second method uses a similar code for the inputting and printing of the array. However, we don’t create a new array like the above method. Instead, we reverse the original array itself. In this method, we swap the elements of the array. The first element is swapped with the last element. The second element is swapped with the last but one element and so on. For instance, consider array [1, 2, 3, ...., n-2, n-1, n]. We swap 1 with n, 2 with n-1, 3 with n-2 and further. " }, { "code": null, "e": 26741, "s": 26736, "text": "Java" }, { "code": "// Java Program that reverses array// in less number of swaps public class arrayReverse { // function swaps the array's first element with last // element, second element with last second element and // so on static void reverse(int a[], int n) { int i, k, t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } // printing the reversed array System.out.println(\"Reversed array is: \\n\"); for (k = 0; k < n; k++) { System.out.println(a[k]); } } public static void main(String[] args) { int[] arr = { 10, 20, 30, 40, 50 }; reverse(arr, arr.length); }}", "e": 27461, "s": 26741, "text": null }, { "code": null, "e": 27497, "s": 27461, "text": "Reversed array is: \n\n50\n40\n30\n20\n10" }, { "code": null, "e": 27758, "s": 27497, "text": "The third method is to use the function java.util.Collections.reverse(List list) method. This method reverses the elements in the specified list. Hence, we convert the array into a list first by using java.util.Arrays.asList(array) and then reverse the list. " }, { "code": null, "e": 27763, "s": 27758, "text": "Java" }, { "code": "// Reversing an array using Java collectionsimport java.util.*; public class reversingArray { // function reverses the elements of the array static void reverse(Integer a[]) { Collections.reverse(Arrays.asList(a)); System.out.println(Arrays.asList(a)); } public static void main(String[] args) { Integer [] arr = {10, 20, 30, 40, 50}; reverse(arr); }}", "e": 28169, "s": 27763, "text": null }, { "code": null, "e": 28190, "s": 28169, "text": "[50, 40, 30, 20, 10]" }, { "code": null, "e": 28430, "s": 28190, "text": "As a fourth method, If you are working with a String array, we can use a StringBuilder and append each array element with a for loop decrementing from the array’s length, convert the StringBuilder to a string, and split back into an array." }, { "code": null, "e": 28435, "s": 28430, "text": "Java" }, { "code": "// Java Program for Reversing an array using StringBuilder import java.util.Arrays; class GFG { public static void main (String[] args) { String[] arr = {\"Hello\", \"World\"}; StringBuilder reversed = new StringBuilder(); for (int i = arr.length; i > 0; i--) { reversed.append(arr[i - 1]).append(\" \"); }; String[] reversedArray = reversed.toString().split(\" \"); System.out.println(Arrays.toString(reversedArray)); }}", "e": 28914, "s": 28435, "text": null }, { "code": null, "e": 28929, "s": 28914, "text": "[World, Hello]" }, { "code": null, "e": 28940, "s": 28929, "text": "briangaedu" }, { "code": null, "e": 28956, "s": 28940, "text": "nishkarshgandhi" }, { "code": null, "e": 28976, "s": 28956, "text": "Java-Array-Programs" }, { "code": null, "e": 28988, "s": 28976, "text": "Java-Arrays" }, { "code": null, "e": 28995, "s": 28988, "text": "Picked" }, { "code": null, "e": 29019, "s": 28995, "text": "Technical Scripter 2018" }, { "code": null, "e": 29024, "s": 29019, "text": "Java" }, { "code": null, "e": 29043, "s": 29024, "text": "Technical Scripter" }, { "code": null, "e": 29048, "s": 29043, "text": "Java" }, { "code": null, "e": 29146, "s": 29048, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29178, "s": 29146, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29229, "s": 29178, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29259, "s": 29229, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29278, "s": 29259, "text": "Interfaces in Java" }, { "code": null, "e": 29296, "s": 29278, "text": "ArrayList in Java" }, { "code": null, "e": 29327, "s": 29296, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29359, "s": 29327, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29379, "s": 29359, "text": "Stack Class in Java" }, { "code": null, "e": 29394, "s": 29379, "text": "Stream In Java" } ]
Image forgery detection. Using the power of CNN's to detect... | by Vishal Singh | Towards Data Science
With the advent of social networking services such as Facebook and Instagram, there has been a huge increase in the volume of image data generated in the last decade. Use of image (and video) processing software like GNU Gimp, Adobe Photoshop to create doctored images and videos is a major concern for internet companies like Facebook. These images are prime sources of fake news and are often used in malevolent ways such as for mob incitement. Before action can be taken on basis of a questionable image, we must verify its authenticity. The IEEE Information Forensics and Security Technical Committee (IFS-TC) launched a detection and localization forensics challenge, the First Image Forensics Challenge in 2013 to solve this problem. They provided an open dataset of digital images comprising of images taken under different lighting conditions and forged images created using algorithms such as: Content-Aware Fill and PatchMatch (for copy/pasting) Content-Aware Healing (for copy/pasting and splicing) Clone-Stamp (for copy/pasting) Seam carving (image retargeting) Inpainting (image reconstruction of damaged parts β€” a special case of copy/pasting) Alpha Matting (for splicing) The challenge consisted of 2 phases. Phase 1 required participating teams to classify images as forged or pristine (never manipulated)Phase 2 required them to detect/localize areas of forgery in forged images Phase 1 required participating teams to classify images as forged or pristine (never manipulated) Phase 2 required them to detect/localize areas of forgery in forged images This post will be about a deep learning approach to solve the first phase of the challenge. Everything from data cleaning, pre-processing, CNN architecture to training and evaluation will be elaborated. During the pre deep learning era of artificial intelligence i.e. before the Image Net challenge of 2012, researchers in image processing used to design hand made features for solving problems of image processing in general and image classification in particular. One such example is the Sobel kernel used for edge detection. The set of image forensic tools used earlier can be grouped into 5 categories namely Pixel-based techniques that detect statistical anomalies introduced at the pixel levelFormat-based techniques that leverage the statistical correlations introduced by a specific lossy compression schemeCamera-based techniques that exploit artifacts introduced by the camera lens, sensor, or on-chip postprocessingPhysics-based techniques that explicitly model and detect anomalies in the three-dimensional interaction between physical objects, light, and the cameraGeometry-based techniques that make measurements of objects in the world and their positions relative to the camera Pixel-based techniques that detect statistical anomalies introduced at the pixel level Format-based techniques that leverage the statistical correlations introduced by a specific lossy compression scheme Camera-based techniques that exploit artifacts introduced by the camera lens, sensor, or on-chip postprocessing Physics-based techniques that explicitly model and detect anomalies in the three-dimensional interaction between physical objects, light, and the camera Geometry-based techniques that make measurements of objects in the world and their positions relative to the camera Courtesy: https://ieeexplore.ieee.org/abstract/document/4806202 Almost all these techniques exploit the content-based features of an image i.e. the visual information present in the image. CNN's are inspired by visual cortex. Technically, these networks are designed to extract features meaningful for classification i.e. the ones which minimize the loss function. The network parameters β€” kernel weights are learned by Gradient Descent so as to generate the most discriminating features from images fed to the network. These features are then fed to a fully connected layer that performs the final task of classification. After looking at a few forged images, it was evident that locating the forged areas by human visual cortex is possible. CNN is thus the perfect deep learning model for this job. If a human visual cortex can detect it, certainly there is more power in a network which would be specifically designed for that task. Before going into the dataset overview, the terminology used will be made clear Fake image: An image that has been manipulated/doctored using the two most common manipulation operations namely: copy/pasting and image splicing. Pristine image: An image that has not been manipulated except for the resizing needed to bring all images to a standard size as per competition rules. Image splicing: The splicing operations can combine images of people, adding doors to buildings, adding trees and cars to parking lots etc. The spliced images can also contain resulting parts from copy/pasting operations. The image receiving a spliced part is called a β€œhost” image. The parts being spliced together with the host image are referred to as β€œaliens”. The entire dataset for both the first and second phase can be found here. For this project, we will be using only the train set. It contains 2 directories β€” one containing fake images and their corresponding masks and the other containing pristine images. Mask of a fake image is a black and white (not grayscale) image describing the spliced area of the fake image. The black pixels in the mask represent the area where manipulation was performed in the source image to get the forged image, specifically it represents the spliced region. The dataset consists of 1050 pristine and 450 fake images. Color images are usually 3 channel images one channel for each red, green and blue colors, however sometimes the fourth channel for yellow may be present. Images in our dataset are a mix of 1, 3 and 4 channel images. After looking at a couple of 1 channel images i.e. grayscale images, it was evident that these images were very few in numberwere streams of black or blue color were very few in number were streams of black or blue color The challenge setters added these images on purpose as they wanted solutions robust to such noise. Although some of the blue images can be images of a clear sky. Hence some of them were included while others discarded as noise. Coming to four channel images β€” they too didn’t have any useful information. They were simply grids of pixels filled with 0 values. Thus our pristine dataset after cleaning contained about 1025 RGB images. Fake images are a mix of 3 and 4 channel images, however, none of them are noisy. Corresponding masks are a mix of 1, 3 and 4 channel images. The feature extraction we will be using requires information from only one channel of the masks. Thus our fake image corpus has 450 fakes. Next up we did a train-test split to keep 20% of 1475 images for final testing. The dataset in its present state is not apt for training a model. It must be transformed into a state which is well suited for the task at hand i.e. detection of anomalies at the pixel level introduced due to forging operations. Taking ideas from here, we designed the following methodology to create relevant images from the given data. For every fake image, we have a corresponding mask. We use that mask to sample the fake image along the boundary of the spliced region in such a way so as to ensure at least a 25% contribution from both forged part and unforged part of the image. These samples will have the distinguishing boundaries that would be present only in fake images. These boundaries are to be learned by the CNN we design. Since all 3 channels of the mask contain the same information (fake part of an image in different pixels), we need only 1 channel to extract samples. To make boundaries even more distinct, the grayscale images were converted to binary using Otsu’s thresholding (implemented in OpenCV) after denoising using a Gaussian filter. After this operation, sampling was merely a matter of moving a 64Γ—64 window (with a stride of 8) through the fake image and counting 0 valued (black) pixels in the corresponding mask and sampling in case the value lies in a certain interval. # Convert grayscale images to binary binaries=[] for grayscale in x_train_masks: blur = cv2.GaussianBlur(grayscale,(5,5),0) ret,th = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) binaries.append(th) ~binaries[28] array([[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]], dtype=uint8) After sampling, we got 175,119 64Γ—64 patches from fake images. In order to generate 0 labeled (pristine) patches, we sampled roughly the same number from authentic images. Finally, we had 350,728 patches which were split into train and cross-validation sets. Now we have a large dataset of good quality input images. It is time to experiment with various CNN architectures. The first architecture we tried was inspired by the architecture given in the original research paper. They had input images of size 128Γ—128Γ—3 and hence a large network. Since we have half the spatial size, our network was also smaller. This is the first tried architecture. Here green layers are convolutional and blue ones are Max pool. This network was trained on 150,000 train samples (for testing purpose) and 25,000 validation samples. The network had 8,536 parameters which were relatively less compared to the train samples, hence avoiding the need for a more aggressive dropout. A dropout rate of 0.2 was applied to the flattened output of 20 units. We used Adam optimizer with a default value of learning rate (0.001) and beta_1, beta_2. After about ___ epochs the results were as follows Train accuracy : 77.13%, Train loss : 0.4678 Validation accuracy : 75.68%, Validation loss : 0.5121 These numbers are not very impressive given the fact that in 2012 a CNN beat year long researched features developed by experts, by a huge margin. However, these numbers are not very bad either given the fact that we used absolutely no knowledge of image forensics (pixel statistics and related concepts) to get a ___ accuracy on unseen data. Since it was a CNN which beat all classical machine learning algorithms at the ImageNet classification task, why not leverage the working of one of these powerful machines to solve the problem at hand? This is the idea behind Transfer learning. In a nutshell, we use the weights of a pre-trained model, which probably was trained on a much larger dataset and gave much better results in solving its problem, to solve our problem. In other words, we β€˜transfer’ the learning of one model to build ours. In our case, we use the VGG16 network, trained on ImageNet dataset to vectorize images in our dataset. Taking ideas from here, we tried 2 approaches Use bottleneck features output by VGG16 and build a shallow network on top of thatFine tune the last convolutional layer of the VGG16+Shallow model in (1) above Use bottleneck features output by VGG16 and build a shallow network on top of that Fine tune the last convolutional layer of the VGG16+Shallow model in (1) above As is intuitive, 2 gave much better results than 1. We tried multiple architectures for the shallow network before finally arriving on this The input to the flattening layer is bottleneck features output by VGG16. These are tensors of shape (2Γ—2Γ—512) since we have used 64Γ—64 input images. Above architecture gave the following results Train accuracy : 83.18%, Train loss : 0.3230 Validation accuracy : 84.26%, Validation loss : 0.3833 It was trained using Adam optimizer with a custom learning rate that reduced after every 10 epochs (besides regular updates by Adam after every batch). The second approach requires the fine-tuning of the last layers. The important thing to note here is that we must use a pre-trained top layer model for fine tuning purpose. The objective is to change already learned weights slightly so as to fit the data better. If we use some randomly initialized weights, slight variations won’t do them any good and large variations would wreck the learned weights of the convolutional layer. We also need a very small learning rate to fine tune our model (for the same reason as mentioned above). In this post, it is suggested to use SGD optimizer for fine-tuning. However, we observed Adam outperforming SGD at this task. Fine-tuned model gave the following results Train accuracy : 99.16%, Train loss : 0.018 Validation accuracy : 94.77%, Validation loss : 0.30 Slightly overfit model which can be remedied by using an even smaller learning rate (we used 1e-6). Apart from VGG16 we also tried bottleneck features from ResNet50 and VGG19 models pre-trained on Image-Net dataset. Features from ResNet50 outperform VGG16. VGG19 didn’t give a very satisfactory performance. We fine-tuned the ResNet50 architecture (last convolution layer) in a way similar to that of VGG16 using the same learning rate update strategy and it gave more promising results with lesser overfit problem. Train accuracy : 98.65%, Train loss : 0.048 Validation accuracy : 95.22%, Validation loss : 0.18 To sample images from the test set created earlier, we employed a similar strategy as used to create the train and cross-validation sets i.e. sampling fake images at boundaries using their masks and sampling an equal number of pristine images having same dimensions. The fine-tuned VGG16 model was used to predict labels for these patches and gave the following results Test accuracy : 94.65%, Test loss : 0.31 ResNet50, on the other hand, gave the following results on test data Test accuracy : 95.09%, Test loss : 0.19 As we can see, our models are performing decently. We still have much room for improvement. If more data can be generated through data augmentation (shear, resize, rotate, and other operations) perhaps we can fine tune more layers of SOTA networks. In this post, we talked about detecting a fake image. However, once a fake image has been detected, we must determine the forged area in that image. Localization of spliced area in a fake image will be the topic of next post. The whole code for this part can be found here. That’s it for this post. Do let me know other good techniques to detect fake images in the comments section. Until next time...Farewell.
[ { "code": null, "e": 949, "s": 46, "text": "With the advent of social networking services such as Facebook and Instagram, there has been a huge increase in the volume of image data generated in the last decade. Use of image (and video) processing software like GNU Gimp, Adobe Photoshop to create doctored images and videos is a major concern for internet companies like Facebook. These images are prime sources of fake news and are often used in malevolent ways such as for mob incitement. Before action can be taken on basis of a questionable image, we must verify its authenticity. The IEEE Information Forensics and Security Technical Committee (IFS-TC) launched a detection and localization forensics challenge, the First Image Forensics Challenge in 2013 to solve this problem. They provided an open dataset of digital images comprising of images taken under different lighting conditions and forged images created using algorithms such as:" }, { "code": null, "e": 1002, "s": 949, "text": "Content-Aware Fill and PatchMatch (for copy/pasting)" }, { "code": null, "e": 1056, "s": 1002, "text": "Content-Aware Healing (for copy/pasting and splicing)" }, { "code": null, "e": 1087, "s": 1056, "text": "Clone-Stamp (for copy/pasting)" }, { "code": null, "e": 1120, "s": 1087, "text": "Seam carving (image retargeting)" }, { "code": null, "e": 1204, "s": 1120, "text": "Inpainting (image reconstruction of damaged parts β€” a special case of copy/pasting)" }, { "code": null, "e": 1233, "s": 1204, "text": "Alpha Matting (for splicing)" }, { "code": null, "e": 1270, "s": 1233, "text": "The challenge consisted of 2 phases." }, { "code": null, "e": 1442, "s": 1270, "text": "Phase 1 required participating teams to classify images as forged or pristine (never manipulated)Phase 2 required them to detect/localize areas of forgery in forged images" }, { "code": null, "e": 1540, "s": 1442, "text": "Phase 1 required participating teams to classify images as forged or pristine (never manipulated)" }, { "code": null, "e": 1615, "s": 1540, "text": "Phase 2 required them to detect/localize areas of forgery in forged images" }, { "code": null, "e": 1818, "s": 1615, "text": "This post will be about a deep learning approach to solve the first phase of the challenge. Everything from data cleaning, pre-processing, CNN architecture to training and evaluation will be elaborated." }, { "code": null, "e": 2228, "s": 1818, "text": "During the pre deep learning era of artificial intelligence i.e. before the Image Net challenge of 2012, researchers in image processing used to design hand made features for solving problems of image processing in general and image classification in particular. One such example is the Sobel kernel used for edge detection. The set of image forensic tools used earlier can be grouped into 5 categories namely" }, { "code": null, "e": 2809, "s": 2228, "text": "Pixel-based techniques that detect statistical anomalies introduced at the pixel levelFormat-based techniques that leverage the statistical correlations introduced by a specific lossy compression schemeCamera-based techniques that exploit artifacts introduced by the camera lens, sensor, or on-chip postprocessingPhysics-based techniques that explicitly model and detect anomalies in the three-dimensional interaction between physical objects, light, and the cameraGeometry-based techniques that make measurements of objects in the world and their positions relative to the camera" }, { "code": null, "e": 2896, "s": 2809, "text": "Pixel-based techniques that detect statistical anomalies introduced at the pixel level" }, { "code": null, "e": 3013, "s": 2896, "text": "Format-based techniques that leverage the statistical correlations introduced by a specific lossy compression scheme" }, { "code": null, "e": 3125, "s": 3013, "text": "Camera-based techniques that exploit artifacts introduced by the camera lens, sensor, or on-chip postprocessing" }, { "code": null, "e": 3278, "s": 3125, "text": "Physics-based techniques that explicitly model and detect anomalies in the three-dimensional interaction between physical objects, light, and the camera" }, { "code": null, "e": 3394, "s": 3278, "text": "Geometry-based techniques that make measurements of objects in the world and their positions relative to the camera" }, { "code": null, "e": 3458, "s": 3394, "text": "Courtesy: https://ieeexplore.ieee.org/abstract/document/4806202" }, { "code": null, "e": 4017, "s": 3458, "text": "Almost all these techniques exploit the content-based features of an image i.e. the visual information present in the image. CNN's are inspired by visual cortex. Technically, these networks are designed to extract features meaningful for classification i.e. the ones which minimize the loss function. The network parameters β€” kernel weights are learned by Gradient Descent so as to generate the most discriminating features from images fed to the network. These features are then fed to a fully connected layer that performs the final task of classification." }, { "code": null, "e": 4330, "s": 4017, "text": "After looking at a few forged images, it was evident that locating the forged areas by human visual cortex is possible. CNN is thus the perfect deep learning model for this job. If a human visual cortex can detect it, certainly there is more power in a network which would be specifically designed for that task." }, { "code": null, "e": 4410, "s": 4330, "text": "Before going into the dataset overview, the terminology used will be made clear" }, { "code": null, "e": 4557, "s": 4410, "text": "Fake image: An image that has been manipulated/doctored using the two most common manipulation operations namely: copy/pasting and image splicing." }, { "code": null, "e": 4708, "s": 4557, "text": "Pristine image: An image that has not been manipulated except for the resizing needed to bring all images to a standard size as per competition rules." }, { "code": null, "e": 5073, "s": 4708, "text": "Image splicing: The splicing operations can combine images of people, adding doors to buildings, adding trees and cars to parking lots etc. The spliced images can also contain resulting parts from copy/pasting operations. The image receiving a spliced part is called a β€œhost” image. The parts being spliced together with the host image are referred to as β€œaliens”." }, { "code": null, "e": 5613, "s": 5073, "text": "The entire dataset for both the first and second phase can be found here. For this project, we will be using only the train set. It contains 2 directories β€” one containing fake images and their corresponding masks and the other containing pristine images. Mask of a fake image is a black and white (not grayscale) image describing the spliced area of the fake image. The black pixels in the mask represent the area where manipulation was performed in the source image to get the forged image, specifically it represents the spliced region." }, { "code": null, "e": 5991, "s": 5613, "text": "The dataset consists of 1050 pristine and 450 fake images. Color images are usually 3 channel images one channel for each red, green and blue colors, however sometimes the fourth channel for yellow may be present. Images in our dataset are a mix of 1, 3 and 4 channel images. After looking at a couple of 1 channel images i.e. grayscale images, it was evident that these images" }, { "code": null, "e": 6050, "s": 5991, "text": "were very few in numberwere streams of black or blue color" }, { "code": null, "e": 6074, "s": 6050, "text": "were very few in number" }, { "code": null, "e": 6110, "s": 6074, "text": "were streams of black or blue color" }, { "code": null, "e": 6544, "s": 6110, "text": "The challenge setters added these images on purpose as they wanted solutions robust to such noise. Although some of the blue images can be images of a clear sky. Hence some of them were included while others discarded as noise. Coming to four channel images β€” they too didn’t have any useful information. They were simply grids of pixels filled with 0 values. Thus our pristine dataset after cleaning contained about 1025 RGB images." }, { "code": null, "e": 6905, "s": 6544, "text": "Fake images are a mix of 3 and 4 channel images, however, none of them are noisy. Corresponding masks are a mix of 1, 3 and 4 channel images. The feature extraction we will be using requires information from only one channel of the masks. Thus our fake image corpus has 450 fakes. Next up we did a train-test split to keep 20% of 1475 images for final testing." }, { "code": null, "e": 7243, "s": 6905, "text": "The dataset in its present state is not apt for training a model. It must be transformed into a state which is well suited for the task at hand i.e. detection of anomalies at the pixel level introduced due to forging operations. Taking ideas from here, we designed the following methodology to create relevant images from the given data." }, { "code": null, "e": 7794, "s": 7243, "text": "For every fake image, we have a corresponding mask. We use that mask to sample the fake image along the boundary of the spliced region in such a way so as to ensure at least a 25% contribution from both forged part and unforged part of the image. These samples will have the distinguishing boundaries that would be present only in fake images. These boundaries are to be learned by the CNN we design. Since all 3 channels of the mask contain the same information (fake part of an image in different pixels), we need only 1 channel to extract samples." }, { "code": null, "e": 8212, "s": 7794, "text": "To make boundaries even more distinct, the grayscale images were converted to binary using Otsu’s thresholding (implemented in OpenCV) after denoising using a Gaussian filter. After this operation, sampling was merely a matter of moving a 64Γ—64 window (with a stride of 8) through the fake image and counting 0 valued (black) pixels in the corresponding mask and sampling in case the value lies in a certain interval." }, { "code": null, "e": 8439, "s": 8212, "text": "# Convert grayscale images to binary\nbinaries=[]\n\nfor grayscale in x_train_masks:\n blur = cv2.GaussianBlur(grayscale,(5,5),0)\n ret,th = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n binaries.append(th)\n" }, { "code": null, "e": 8454, "s": 8439, "text": "~binaries[28]\n" }, { "code": null, "e": 8672, "s": 8454, "text": "array([[0, 0, 0, ..., 0, 0, 0],\n [0, 0, 0, ..., 0, 0, 0],\n [0, 0, 0, ..., 0, 0, 0],\n ...,\n [0, 0, 0, ..., 0, 0, 0],\n [0, 0, 0, ..., 0, 0, 0],\n [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)" }, { "code": null, "e": 8931, "s": 8672, "text": "After sampling, we got 175,119 64Γ—64 patches from fake images. In order to generate 0 labeled (pristine) patches, we sampled roughly the same number from authentic images. Finally, we had 350,728 patches which were split into train and cross-validation sets." }, { "code": null, "e": 9046, "s": 8931, "text": "Now we have a large dataset of good quality input images. It is time to experiment with various CNN architectures." }, { "code": null, "e": 9321, "s": 9046, "text": "The first architecture we tried was inspired by the architecture given in the original research paper. They had input images of size 128Γ—128Γ—3 and hence a large network. Since we have half the spatial size, our network was also smaller. This is the first tried architecture." }, { "code": null, "e": 9845, "s": 9321, "text": "Here green layers are convolutional and blue ones are Max pool. This network was trained on 150,000 train samples (for testing purpose) and 25,000 validation samples. The network had 8,536 parameters which were relatively less compared to the train samples, hence avoiding the need for a more aggressive dropout. A dropout rate of 0.2 was applied to the flattened output of 20 units. We used Adam optimizer with a default value of learning rate (0.001) and beta_1, beta_2. After about ___ epochs the results were as follows" }, { "code": null, "e": 9890, "s": 9845, "text": "Train accuracy : 77.13%, Train loss : 0.4678" }, { "code": null, "e": 9945, "s": 9890, "text": "Validation accuracy : 75.68%, Validation loss : 0.5121" }, { "code": null, "e": 10288, "s": 9945, "text": "These numbers are not very impressive given the fact that in 2012 a CNN beat year long researched features developed by experts, by a huge margin. However, these numbers are not very bad either given the fact that we used absolutely no knowledge of image forensics (pixel statistics and related concepts) to get a ___ accuracy on unseen data." }, { "code": null, "e": 10892, "s": 10288, "text": "Since it was a CNN which beat all classical machine learning algorithms at the ImageNet classification task, why not leverage the working of one of these powerful machines to solve the problem at hand? This is the idea behind Transfer learning. In a nutshell, we use the weights of a pre-trained model, which probably was trained on a much larger dataset and gave much better results in solving its problem, to solve our problem. In other words, we β€˜transfer’ the learning of one model to build ours. In our case, we use the VGG16 network, trained on ImageNet dataset to vectorize images in our dataset." }, { "code": null, "e": 10938, "s": 10892, "text": "Taking ideas from here, we tried 2 approaches" }, { "code": null, "e": 11099, "s": 10938, "text": "Use bottleneck features output by VGG16 and build a shallow network on top of thatFine tune the last convolutional layer of the VGG16+Shallow model in (1) above" }, { "code": null, "e": 11182, "s": 11099, "text": "Use bottleneck features output by VGG16 and build a shallow network on top of that" }, { "code": null, "e": 11261, "s": 11182, "text": "Fine tune the last convolutional layer of the VGG16+Shallow model in (1) above" }, { "code": null, "e": 11401, "s": 11261, "text": "As is intuitive, 2 gave much better results than 1. We tried multiple architectures for the shallow network before finally arriving on this" }, { "code": null, "e": 11551, "s": 11401, "text": "The input to the flattening layer is bottleneck features output by VGG16. These are tensors of shape (2Γ—2Γ—512) since we have used 64Γ—64 input images." }, { "code": null, "e": 11597, "s": 11551, "text": "Above architecture gave the following results" }, { "code": null, "e": 11642, "s": 11597, "text": "Train accuracy : 83.18%, Train loss : 0.3230" }, { "code": null, "e": 11697, "s": 11642, "text": "Validation accuracy : 84.26%, Validation loss : 0.3833" }, { "code": null, "e": 11849, "s": 11697, "text": "It was trained using Adam optimizer with a custom learning rate that reduced after every 10 epochs (besides regular updates by Adam after every batch)." }, { "code": null, "e": 12510, "s": 11849, "text": "The second approach requires the fine-tuning of the last layers. The important thing to note here is that we must use a pre-trained top layer model for fine tuning purpose. The objective is to change already learned weights slightly so as to fit the data better. If we use some randomly initialized weights, slight variations won’t do them any good and large variations would wreck the learned weights of the convolutional layer. We also need a very small learning rate to fine tune our model (for the same reason as mentioned above). In this post, it is suggested to use SGD optimizer for fine-tuning. However, we observed Adam outperforming SGD at this task." }, { "code": null, "e": 12554, "s": 12510, "text": "Fine-tuned model gave the following results" }, { "code": null, "e": 12598, "s": 12554, "text": "Train accuracy : 99.16%, Train loss : 0.018" }, { "code": null, "e": 12651, "s": 12598, "text": "Validation accuracy : 94.77%, Validation loss : 0.30" }, { "code": null, "e": 12751, "s": 12651, "text": "Slightly overfit model which can be remedied by using an even smaller learning rate (we used 1e-6)." }, { "code": null, "e": 13167, "s": 12751, "text": "Apart from VGG16 we also tried bottleneck features from ResNet50 and VGG19 models pre-trained on Image-Net dataset. Features from ResNet50 outperform VGG16. VGG19 didn’t give a very satisfactory performance. We fine-tuned the ResNet50 architecture (last convolution layer) in a way similar to that of VGG16 using the same learning rate update strategy and it gave more promising results with lesser overfit problem." }, { "code": null, "e": 13211, "s": 13167, "text": "Train accuracy : 98.65%, Train loss : 0.048" }, { "code": null, "e": 13264, "s": 13211, "text": "Validation accuracy : 95.22%, Validation loss : 0.18" }, { "code": null, "e": 13634, "s": 13264, "text": "To sample images from the test set created earlier, we employed a similar strategy as used to create the train and cross-validation sets i.e. sampling fake images at boundaries using their masks and sampling an equal number of pristine images having same dimensions. The fine-tuned VGG16 model was used to predict labels for these patches and gave the following results" }, { "code": null, "e": 13675, "s": 13634, "text": "Test accuracy : 94.65%, Test loss : 0.31" }, { "code": null, "e": 13744, "s": 13675, "text": "ResNet50, on the other hand, gave the following results on test data" }, { "code": null, "e": 13785, "s": 13744, "text": "Test accuracy : 95.09%, Test loss : 0.19" }, { "code": null, "e": 14034, "s": 13785, "text": "As we can see, our models are performing decently. We still have much room for improvement. If more data can be generated through data augmentation (shear, resize, rotate, and other operations) perhaps we can fine tune more layers of SOTA networks." }, { "code": null, "e": 14308, "s": 14034, "text": "In this post, we talked about detecting a fake image. However, once a fake image has been detected, we must determine the forged area in that image. Localization of spliced area in a fake image will be the topic of next post. The whole code for this part can be found here." } ]
Check three or more consecutive identical characters or numbers - GeeksforGeeks
01 Feb, 2021 Given string str, the task is to check whether the given string contains 3 or more consecutive identical characters/numbers or not by using Regular Expression. Examples: Input: str = β€œaaa”; Output: true Explanation: The given string contains a, a, a which are consecutive identical characters.Input: str = β€œabc”; Output: false Explanation: The given string contains a, b, c which are not consecutive identical characters.Input: str = β€œ11”; Output: false Explanation: The given string contains 1, 1 which are not 3 or more consecutive identical numbers. Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. Get the String. Create a regular expression to check 3 or more consecutive identical characters or numbers as mentioned below: regex = β€œ\\b([a-zA-Z0-9])\\1\\1+\\b”; Where: \\b represents the word boundary.( represents the starting of the group 1.[a-zA-Z0-9] represents a letter or a digit.) represents the ending of the group 1.\\1 represents the same character as group 1.\\1+ represents the same character as group 1 one or more times.\\b represents the word boundary. \\b represents the word boundary. ( represents the starting of the group 1. [a-zA-Z0-9] represents a letter or a digit. ) represents the ending of the group 1. \\1 represents the same character as group 1. \\1+ represents the same character as group 1 one or more times. \\b represents the word boundary. Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().Return true if the string matches with the given regular expression, else return false. Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher(). Return true if the string matches with the given regular expression, else return false. Below is the implementation of the above approach: C++ Java Python3 // C++ program to check// three or more consecutive identical// characters or numbers using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to check three or more// consecutive identical characters or numbers.bool isIdentical(string str){ // Regex to check valid three or more // consecutive identical characters or numbers. const regex pattern("\\b([a-zA-Z0-9])\\1\\1+\\b"); // If the three or more consecutive // identical characters or numbers // is empty return false if (str.empty()) { return false; } // Return true if the three or more // consecutive identical characters or numbers // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "aaa"; cout << isIdentical(str1) << endl; // Test Case 2: string str2 = "11111"; cout << isIdentical(str2) << endl; // Test Case 3: string str3 = "aaab"; cout << isIdentical(str3) << endl; // Test Case 4: string str4 = "abc"; cout << isIdentical(str4) << endl; // Test Case 5: string str5 = "aa"; cout << isIdentical(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra // Java program to check three or// more consecutive identical// characters or numbers// using regular expression import java.util.regex.*;class GFG { // Function to check three or // more consecutive identical // characters or numbers // using regular expression public static boolean isIdentical(String str) { // Regex to check three or // more consecutive identical // characters or numbers String regex = "\\b([a-zA-Z0-9])\\1\\1+\\b"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = "aaa"; System.out.println( isIdentical(str1)); // Test Case 2: String str2 = "11111"; System.out.println( isIdentical(str2)); // Test Case 3: String str3 = "aaab"; System.out.println( isIdentical(str3)); // Test Case 4: String str4 = "abc"; System.out.println( isIdentical(str4)); // Test Case 5: String str5 = "aa"; System.out.println( isIdentical(str5)); }} # Python3 program to check three or# more consecutiveidentical# characters or numbers# using regular expressionimport re # Function to check three or# more consecutiveidentical# characters or numbers# using regular expressiondef isValidGUID(str): # Regex to check three or # more consecutive identical # characters or numbers regex = "\\b([a-zA-Z0-9])\\1\\1+\\b" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = "aaa"print(isValidGUID(str1)) # Test Case 2:str2 = "11111"print(isValidGUID(str2)) # Test Case 3:str3 = "aaab"print(isValidGUID(str3)) # Test Case 4:str4 = "abc"print(isValidGUID(str4)) # Test Case 4:str5 = "aa"print(isValidGUID(str5)) # This code is contributed by avanitrachhadiya2155 true true false false false avanitrachhadiya2155 yuvraj_chandra regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Check if an URL is valid or not using Regular Expression Check if a string contains uppercase, lowercase, special characters and numeric values How to check if string contains only digits in Java Pattern Searching using Suffix Tree String matching where one string contains wildcard characters Reverse a string in Java Write a program to reverse an array or string C++ Data Types Write a program to print all permutations of a given string Python program to check if a string is palindrome or not
[ { "code": null, "e": 25358, "s": 25330, "text": "\n01 Feb, 2021" }, { "code": null, "e": 25529, "s": 25358, "text": "Given string str, the task is to check whether the given string contains 3 or more consecutive identical characters/numbers or not by using Regular Expression. Examples: " }, { "code": null, "e": 25913, "s": 25529, "text": "Input: str = β€œaaa”; Output: true Explanation: The given string contains a, a, a which are consecutive identical characters.Input: str = β€œabc”; Output: false Explanation: The given string contains a, b, c which are not consecutive identical characters.Input: str = β€œ11”; Output: false Explanation: The given string contains 1, 1 which are not 3 or more consecutive identical numbers. " }, { "code": null, "e": 26044, "s": 25913, "text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. " }, { "code": null, "e": 26060, "s": 26044, "text": "Get the String." }, { "code": null, "e": 26173, "s": 26060, "text": "Create a regular expression to check 3 or more consecutive identical characters or numbers as mentioned below: " }, { "code": null, "e": 26213, "s": 26173, "text": "regex = β€œ\\\\b([a-zA-Z0-9])\\\\1\\\\1+\\\\b”; " }, { "code": null, "e": 26519, "s": 26213, "text": "Where: \\\\b represents the word boundary.( represents the starting of the group 1.[a-zA-Z0-9] represents a letter or a digit.) represents the ending of the group 1.\\\\1 represents the same character as group 1.\\\\1+ represents the same character as group 1 one or more times.\\\\b represents the word boundary." }, { "code": null, "e": 26553, "s": 26519, "text": "\\\\b represents the word boundary." }, { "code": null, "e": 26595, "s": 26553, "text": "( represents the starting of the group 1." }, { "code": null, "e": 26639, "s": 26595, "text": "[a-zA-Z0-9] represents a letter or a digit." }, { "code": null, "e": 26679, "s": 26639, "text": ") represents the ending of the group 1." }, { "code": null, "e": 26725, "s": 26679, "text": "\\\\1 represents the same character as group 1." }, { "code": null, "e": 26790, "s": 26725, "text": "\\\\1+ represents the same character as group 1 one or more times." }, { "code": null, "e": 26824, "s": 26790, "text": "\\\\b represents the word boundary." }, { "code": null, "e": 27017, "s": 26824, "text": "Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 27123, "s": 27017, "text": "Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher()." }, { "code": null, "e": 27211, "s": 27123, "text": "Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 27263, "s": 27211, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27267, "s": 27263, "text": "C++" }, { "code": null, "e": 27272, "s": 27267, "text": "Java" }, { "code": null, "e": 27280, "s": 27272, "text": "Python3" }, { "code": "// C++ program to check// three or more consecutive identical// characters or numbers using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to check three or more// consecutive identical characters or numbers.bool isIdentical(string str){ // Regex to check valid three or more // consecutive identical characters or numbers. const regex pattern(\"\\\\b([a-zA-Z0-9])\\\\1\\\\1+\\\\b\"); // If the three or more consecutive // identical characters or numbers // is empty return false if (str.empty()) { return false; } // Return true if the three or more // consecutive identical characters or numbers // matched the ReGex if(regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"aaa\"; cout << isIdentical(str1) << endl; // Test Case 2: string str2 = \"11111\"; cout << isIdentical(str2) << endl; // Test Case 3: string str3 = \"aaab\"; cout << isIdentical(str3) << endl; // Test Case 4: string str4 = \"abc\"; cout << isIdentical(str4) << endl; // Test Case 5: string str5 = \"aa\"; cout << isIdentical(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 28500, "s": 27280, "text": null }, { "code": "// Java program to check three or// more consecutive identical// characters or numbers// using regular expression import java.util.regex.*;class GFG { // Function to check three or // more consecutive identical // characters or numbers // using regular expression public static boolean isIdentical(String str) { // Regex to check three or // more consecutive identical // characters or numbers String regex = \"\\\\b([a-zA-Z0-9])\\\\1\\\\1+\\\\b\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = \"aaa\"; System.out.println( isIdentical(str1)); // Test Case 2: String str2 = \"11111\"; System.out.println( isIdentical(str2)); // Test Case 3: String str3 = \"aaab\"; System.out.println( isIdentical(str3)); // Test Case 4: String str4 = \"abc\"; System.out.println( isIdentical(str4)); // Test Case 5: String str5 = \"aa\"; System.out.println( isIdentical(str5)); }}", "e": 30058, "s": 28500, "text": null }, { "code": "# Python3 program to check three or# more consecutiveidentical# characters or numbers# using regular expressionimport re # Function to check three or# more consecutiveidentical# characters or numbers# using regular expressiondef isValidGUID(str): # Regex to check three or # more consecutive identical # characters or numbers regex = \"\\\\b([a-zA-Z0-9])\\\\1\\\\1+\\\\b\" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (str == None): return False # Return if the string # matched the ReGex if(re.search(p, str)): return True else: return False # Driver code # Test Case 1:str1 = \"aaa\"print(isValidGUID(str1)) # Test Case 2:str2 = \"11111\"print(isValidGUID(str2)) # Test Case 3:str3 = \"aaab\"print(isValidGUID(str3)) # Test Case 4:str4 = \"abc\"print(isValidGUID(str4)) # Test Case 4:str5 = \"aa\"print(isValidGUID(str5)) # This code is contributed by avanitrachhadiya2155", "e": 31021, "s": 30058, "text": null }, { "code": null, "e": 31049, "s": 31021, "text": "true\ntrue\nfalse\nfalse\nfalse" }, { "code": null, "e": 31072, "s": 31051, "text": "avanitrachhadiya2155" }, { "code": null, "e": 31087, "s": 31072, "text": "yuvraj_chandra" }, { "code": null, "e": 31106, "s": 31087, "text": "regular-expression" }, { "code": null, "e": 31124, "s": 31106, "text": "Pattern Searching" }, { "code": null, "e": 31132, "s": 31124, "text": "Strings" }, { "code": null, "e": 31140, "s": 31132, "text": "Strings" }, { "code": null, "e": 31158, "s": 31140, "text": "Pattern Searching" }, { "code": null, "e": 31256, "s": 31158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31265, "s": 31256, "text": "Comments" }, { "code": null, "e": 31278, "s": 31265, "text": "Old Comments" }, { "code": null, "e": 31335, "s": 31278, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 31422, "s": 31335, "text": "Check if a string contains uppercase, lowercase, special characters and numeric values" }, { "code": null, "e": 31474, "s": 31422, "text": "How to check if string contains only digits in Java" }, { "code": null, "e": 31510, "s": 31474, "text": "Pattern Searching using Suffix Tree" }, { "code": null, "e": 31572, "s": 31510, "text": "String matching where one string contains wildcard characters" }, { "code": null, "e": 31597, "s": 31572, "text": "Reverse a string in Java" }, { "code": null, "e": 31643, "s": 31597, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31658, "s": 31643, "text": "C++ Data Types" }, { "code": null, "e": 31718, "s": 31658, "text": "Write a program to print all permutations of a given string" } ]
Enum for days of week in Java
To set enum for days of the week, set them as constants enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } Now create objects and set the above constants βˆ’ Days today = Days.Wednesday; Days holiday = Days.Sunday; The following is an example βˆ’ Live Demo public class Demo { enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } public static void main(String[] args) { Days today = Days.Wednesday; Days holiday = Days.Sunday; System.out.println("Today = " + today); System.out.println(holiday+ " is holiday"); } } Today = Wednesday Sunday is holiday
[ { "code": null, "e": 1118, "s": 1062, "text": "To set enum for days of the week, set them as constants" }, { "code": null, "e": 1195, "s": 1118, "text": "enum Days {\nMonday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday\n}" }, { "code": null, "e": 1244, "s": 1195, "text": "Now create objects and set the above constants βˆ’" }, { "code": null, "e": 1301, "s": 1244, "text": "Days today = Days.Wednesday;\nDays holiday = Days.Sunday;" }, { "code": null, "e": 1331, "s": 1301, "text": "The following is an example βˆ’" }, { "code": null, "e": 1342, "s": 1331, "text": " Live Demo" }, { "code": null, "e": 1667, "s": 1342, "text": "public class Demo {\n enum Days {\n Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday\n }\n public static void main(String[] args) {\n Days today = Days.Wednesday;\n Days holiday = Days.Sunday;\n System.out.println(\"Today = \" + today);\n System.out.println(holiday+ \" is holiday\");\n }\n}" }, { "code": null, "e": 1703, "s": 1667, "text": "Today = Wednesday\nSunday is holiday" } ]
C++ Program to Implement Next_Permutation in STL
Next_permutation in STL is used to rearrange the elements in the range [first, last] into the next lexicographically greater permutation. A permutation is each one of the N! possible arrangements the elements can take. This is C++ program to implement Next_permutation in STL. Begin Define one integer array variable elements[]. Get the number of data e from the user. Initialize the array elements[] with e number of data from the keyboard. Sort all the array elements. do show(elements, e) //to display the current content of the array while (next_permutation(elements, elements + e)) End #include<iostream> #include <algorithm> using namespace std; void show(int a[], int n) { for(int i = 0; i < n; i++) { cout<<a[i]<<" "; } cout<<endl; } int main () { int e, i; cout<<"Enter number of elements to be inserted: "; cin>>e; int elements[e]; for (i = 0; i < e; i++) { cout<<"Enter "<<i + 1<<" element: "; cin>>elements[i]; } sort (elements, elements + e); cout << "The "<<e<<"! possible permutations with "; cout<<e<<" elements: "<<endl; do { show(elements, e); } while (next_permutation(elements, elements + e)); return 0; } Enter number of elements to be inserted: 4 Enter 1 element: 7 Enter 2 element: 6 Enter 3 element: 2 Enter 4 element: 10 The 4! possible permutations with 4 elements: 2 6 7 10 2 6 10 7 2 7 6 10 2 7 10 6 2 10 6 7 2 10 7 6 6 2 7 10 6 2 10 7 6 7 2 10 6 7 10 2 6 10 2 7 6 10 7 2 7 2 6 10 7 2 10 6 7 6 2 10 7 6 10 2 7 10 2 6 7 10 6 2 10 2 6 7 10 2 7 6 10 6 2 7 10 6 7 2 10 7 2 6 10 7 6 2
[ { "code": null, "e": 1339, "s": 1062, "text": "Next_permutation in STL is used to rearrange the elements in the range [first, last] into the next lexicographically greater permutation. A permutation is each one of the N! possible arrangements the elements can take. This is C++ program to implement Next_permutation in STL." }, { "code": null, "e": 1677, "s": 1339, "text": "Begin\n Define one integer array variable elements[].\n Get the number of data e from the user.\n Initialize the array elements[] with e number of data from the keyboard.\n Sort all the array elements.\n do\n show(elements, e) //to display the current content of the array\n while (next_permutation(elements, elements + e))\nEnd" }, { "code": null, "e": 2284, "s": 1677, "text": "#include<iostream>\n#include <algorithm>\nusing namespace std;\nvoid show(int a[], int n) {\n for(int i = 0; i < n; i++) {\n cout<<a[i]<<\" \";\n }\n cout<<endl;\n}\nint main () {\n int e, i;\n cout<<\"Enter number of elements to be inserted: \";\n cin>>e;\n int elements[e];\n for (i = 0; i < e; i++) {\n cout<<\"Enter \"<<i + 1<<\" element: \";\n cin>>elements[i];\n }\n sort (elements, elements + e);\n cout << \"The \"<<e<<\"! possible permutations with \";\n cout<<e<<\" elements: \"<<endl;\n do {\n show(elements, e);\n }\n while (next_permutation(elements, elements + e));\n return 0;\n}" }, { "code": null, "e": 2666, "s": 2284, "text": "Enter number of elements to be inserted: 4\nEnter 1 element: 7\nEnter 2 element: 6\nEnter 3 element: 2\nEnter 4 element: 10\nThe 4! possible permutations with 4 elements:\n2 6 7 10\n2 6 10 7\n2 7 6 10\n2 7 10 6\n2 10 6 7\n2 10 7 6\n6 2 7 10\n6 2 10 7\n6 7 2 10\n6 7 10 2\n6 10 2 7\n6 10 7 2\n7 2 6 10\n7 2 10 6\n7 6 2 10\n7 6 10 2\n7 10 2 6\n7 10 6 2\n10 2 6 7\n10 2 7 6\n10 6 2 7\n10 6 7 2\n10 7 2 6\n10 7 6 2" } ]
Maximum absolute difference of value and index sums - GeeksforGeeks
23 Jul, 2021 Given an unsorted array A of N integers, Return maximum value of f(i, j) for all 1 ≀ i, j ≀ N. f(i, j) or absolute difference of two elements of an array A is defined as |A[i] – A[j]| + |i – j|, where |A| denotes the absolute value of A.Examples: We will calculate the value of f(i, j) for each pair of (i, j) and return the maximum value thus obtained. Input : A = {1, 3, -1} Output : 5 f(1, 1) = f(2, 2) = f(3, 3) = 0 f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3 f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4 f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5 So, we return 5. Input : A = {3, -2, 5, -4} Output : 10 f(1, 1) = f(2, 2) = f(3, 3) = f(4, 4) = 0 f(1, 2) = f(2, 1) = |3 - (-2)| + |1 - 2| = 6 f(1, 3) = f(3, 1) = |3 - 5| + |1 - 3| = 4 f(1, 4) = f(4, 1) = |3 - (-4)| + |1 - 4| = 10 f(2, 3) = f(3, 2) = |(-2) - 5| + |2 - 3| = 8 f(2, 4) = f(4, 2) = |(-2) - (-4)| + |2 - 4| = 4 f(3, 4) = f(4, 3) = |5 - (-4)| + |3 - 4| = 10 So, we return 10 A naive brute force approach is to calculate the value f(i, j) by iterating over all such pairs (i, j) and calculating the maximum absolute difference which is implemented below. C++ Java Python3 C# PHP Javascript // Brute force C++ program to calculate the// maximum absolute difference of an array.#include <bits/stdc++.h>using namespace std; int calculateDiff(int i, int j, int arr[]){ // Utility function to calculate // the value of absolute difference // for the pair (i, j). return abs(arr[i] - arr[j]) + abs(i - j);} // Function to return maximum absolute// difference in brute force.int maxDistance(int arr[], int n){ // Variable for storing the maximum // absolute distance throughout the // traversal of loops. int result = 0; // Iterate through all pairs. for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. if (calculateDiff(i, j, arr) > result) result = calculateDiff(i, j, arr); } } return result;} // Driver program to test the above function.int main(){ int arr[] = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxDistance(arr, n) << endl; return 0;} // Java program to calculate the maximum// absolute difference of an array.public class MaximumAbsoluteDifference{ private static int calculateDiff(int i, int j, int[] array) { // Utility function to calculate // the value of absolute difference // for the pair (i, j). return Math.abs(array[i] - array[j]) + Math.abs(i - j); } // Function to return maximum absolute // difference in brute force. private static int maxDistance(int[] array) { // Variable for storing the maximum // absolute distance throughout the // traversal of loops. int result = 0; // Iterate through all pairs. for (int i = 0; i < array.length; i++) { for (int j = i; j < array.length; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. result = Math.max(result, calculateDiff(i, j, array)); } } return result; } // Driver program to test above function public static void main(String[] args) { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; System.out.println(maxDistance(array)); }} // This code is contributed by Harikrishnan Rajan # Brute force Python 3 program# to calculate the maximum# absolute difference of an array. def calculateDiff(i, j, arr): # Utility function to calculate # the value of absolute difference # for the pair (i, j). return abs(arr[i] - arr[j]) + abs(i - j) # Function to return maximum# absolute difference in# brute force.def maxDistance(arr, n): # Variable for storing the # maximum absolute distance # throughout the traversal # of loops. result = 0 # Iterate through all pairs. for i in range(0,n): for j in range(i, n): # If the absolute difference of # current pair (i, j) is greater # than the maximum difference # calculated till now, update # the value of result. if (calculateDiff(i, j, arr) > result): result = calculateDiff(i, j, arr) return result # Driver programarr = [ -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ]n = len(arr) print(maxDistance(arr, n)) # This code is contributed by Smitha Dinesh Semwal // C# program to calculate the maximum// absolute difference of an array.using System; public class MaximumAbsoluteDifference{ private static int calculateDiff(int i, int j, int[] array) { // Utility function to calculate // the value of absolute difference // for the pair (i, j). return Math.Abs(array[i] - array[j]) + Math.Abs(i - j); } // Function to return maximum absolute // difference in brute force. private static int maxDistance(int[] array) { // Variable for storing the maximum // absolute distance throughout the // traversal of loops. int result = 0; // Iterate through all pairs. for (int i = 0; i < array.Length; i++) { for (int j = i; j < array.Length; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. result = Math.Max(result, calculateDiff(i, j, array)); } } return result; } // Driver program public static void Main() { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; Console.WriteLine(maxDistance(array)); }} // This code is contributed by vt_m <?php// Brute force PHP program to// calculate the maximum absolute// difference of an array. function calculateDiff($i, $j, $arr){ // Utility function to calculate // the value of absolute difference // for the pair (i, j). return abs($arr[$i] - $arr[$j]) + abs($i - $j);} // Function to return maximum// absolute difference in brute force.function maxDistance($arr, $n){ // Variable for storing the maximum // absolute distance throughout the // traversal of loops. $result = 0; // Iterate through all pairs. for ($i = 0; $i < $n; $i++) { for ($j = $i; $j < $n; $j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. if (calculateDiff($i, $j, $arr) > $result) $result = calculateDiff($i, $j, $arr); } } return $result;} // Driver Code$arr = array( -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ); $n = sizeof($arr); echo maxDistance($arr, $n); // This Code is contributed by mits?> <script> // javascript program to calculate the maximum// absolute difference of an array. let MAX = 256; // Function to count the number of equal pairs function calculateDiff(i, j, array) { // Utility function to calculate // the value of absolute difference // for the pair (i, j). return Math.abs(array[i] - array[j]) + Math.abs(i - j); } // Function to return maximum absolute // difference in brute force. function maxDistance(array) { // Variable for storing the maximum // absolute distance throughout the // traversal of loops. let result = 0; // Iterate through all pairs. for (let i = 0; i < array.length; i++) { for (let j = i; j < array.length; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. result = Math.max(result, calculateDiff(i, j, array)); } } return result; } // Driver Function let array = [-70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ]; document.write(maxDistance(array)); // This code is contributed by susmitakundugoaldanga.</script> Output: 167 Time complexity: O(n^2)An efficient solution in O(n) time complexity can be worked out using the properties of absolute values. f(i, j) = |A[i] – A[j]| + |i – j| can be written in 4 ways (Since we are looking at max value, we don’t even care if the value becomes negative as long as we are also covering the max value in some way). Case 1: A[i] > A[j] and i > j |A[i] - A[j]| = A[i] - A[j] |i -j| = i - j hence, f(i, j) = (A[i] + i) - (A[j] + j) Case 2: A[i] < A[j] and i < j |A[i] - A[j]| = -(A[i]) + A[j] |i -j| = -(i) + j hence, f(i, j) = -(A[i] + i) + (A[j] + j) Case 3: A[i] > A[j] and i < j |A[i] - A[j]| = A[i] - A[j] |i -j| = -(i) + j hence, f(i, j) = (A[i] - i) - (A[j] - j) Case 4: A[i] < A[j] and i > j |A[i] - A[j]| = -(A[i]) + A[j] |i -j| = i - j hence, f(i, j) = -(A[i] - i) + (A[j] - j) Note that cases 1 and 2 are equivalent and so are cases 3 and 4 and hence we can design our algorithm only for two cases as it will cover all the possible cases. 1. Calculate the value of A[i] + i and A[i] – i for every element of the array while traversing through the array.2. Then for the two equivalent cases, we find the maximum possible value. For that, we have to store minimum and maximum values of expressions A[i] + i and A[i] – i for all i.3. Hence the required maximum absolute difference is maximum of two values i.e. max((A[i] + i) – (A[j] + j)) and max((A[i] – i) – (A[j] – j)). These values can be found easily in linear time. a. For max((A[i] + i) – (A[j] + j)) Maintain two variables max1 and min1 which will store maximum and minimum values of A[i] + i respectively. max((A[i] + i) – (A[j] + j)) = max1 – min1 b. For max((A[i] – i) – (A[j] – j)). Maintain two variables max2 and min2 which will store maximum and minimum values of A[i] – i respectively. max((A[i] – i) – (A[j] – j)) = max2 – min2 Implementation using the above fast algorithm is given below. C++ Java Python3 C# PHP Javascript // C++ program to calculate the maximum// absolute difference of an array.#include <bits/stdc++.h>using namespace std; // Function to return maximum absolute// difference in linear time.int maxDistance(int arr[], int n){ // max and min variables as described // in algorithm. int max1 = INT_MIN, min1 = INT_MAX; int max2 = INT_MIN, min2 = INT_MAX; for (int i = 0; i < n; i++) { // Updating max and min variables // as described in algorithm. max1 = max(max1, arr[i] + i); min1 = min(min1, arr[i] + i); max2 = max(max2, arr[i] - i); min2 = min(min2, arr[i] - i); } // Calculating maximum absolute difference. return max(max1 - min1, max2 - min2);} // Driver program to test the above function.int main(){ int arr[] = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxDistance(arr, n) << endl; return 0;} // Java program to calculate the maximum// absolute difference of an array.public class MaximumAbsoluteDifference{ // Function to return maximum absolute // difference in linear time. private static int maxDistance(int[] array) { // max and min variables as described // in algorithm. int max1 = Integer.MIN_VALUE; int min1 = Integer.MAX_VALUE; int max2 = Integer.MIN_VALUE; int min2 = Integer.MAX_VALUE; for (int i = 0; i < array.length; i++) { // Updating max and min variables // as described in algorithm. max1 = Math.max(max1, array[i] + i); min1 = Math.min(min1, array[i] + i); max2 = Math.max(max2, array[i] - i); min2 = Math.min(min2, array[i] - i); } // Calculating maximum absolute difference. return Math.max(max1 - min1, max2 - min2); } // Driver program to test above function public static void main(String[] args) { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; System.out.println(maxDistance(array)); }} // This code is contributed by Harikrishnan Rajan # Python program to# calculate the maximum# absolute difference# of an array. # Function to return# maximum absolute# difference in linear time.def maxDistance(array): # max and min variables as described # in algorithm. max1 = -2147483648 min1 = +2147483647 max2 = -2147483648 min2 = +2147483647 for i in range(len(array)): # Updating max and min variables # as described in algorithm. max1 = max(max1, array[i] + i) min1 = min(min1, array[i] + i) max2 = max(max2, array[i] - i) min2 = min(min2, array[i] - i) # Calculating maximum absolute difference. return max(max1 - min1, max2 - min2) # Driver program to# test above function array = [ -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ] print(maxDistance(array)) # This code is contributed# by Anant Agarwal. // C# program to calculate the maximum// absolute difference of an array.using System; public class MaximumAbsoluteDifference{ // Function to return maximum absolute // difference in linear time. private static int maxDistance(int[] array) { // max and min variables as described // in algorithm. int max1 = int.MinValue ; int min1 = int.MaxValue ; int max2 = int.MinValue ; int min2 =int.MaxValue ; for (int i = 0; i < array.Length; i++) { // Updating max and min variables // as described in algorithm. max1 = Math.Max(max1, array[i] + i); min1 = Math.Min(min1, array[i] + i); max2 = Math.Max(max2, array[i] - i); min2 = Math.Min(min2, array[i] - i); } // Calculating maximum absolute difference. return Math.Max(max1 - min1, max2 - min2); } // Driver program public static void Main() { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; Console.WriteLine(maxDistance(array)); }} // This code is contributed by vt_m <?php// PHP program to calculate the maximum// absolute difference of an array. // Function to return maximum absolute// difference in linear time.function maxDistance( $arr, $n){ // max and min variables as // described in algorithm. $max1 = PHP_INT_MIN; $min1 = PHP_INT_MAX; $max2 = PHP_INT_MIN;$min2 = PHP_INT_MAX; for($i = 0; $i < $n; $i++) { // Updating max and min variables // as described in algorithm. $max1 = max($max1, $arr[$i] + $i); $min1 = min($min1, $arr[$i] + $i); $max2 = max($max2, $arr[$i] - $i); $min2 = min($min2, $arr[$i] - $i); } // Calculating maximum // absolute difference. return max($max1 - $min1, $max2 - $min2);} // Driver Code $arr = array(-70, -64, -6, -56, 64, 61, -57, 16, 48, -98); $n = count($arr); echo maxDistance($arr, $n); // This code is contributed by anuj_67.?> <script> // JavaScript program to calculate the maximum // absolute difference of an array. // Function to return maximum absolute // difference in linear time. function maxDistance(array) { // max and min variables as described // in algorithm. let max1 = Number.MIN_VALUE; let min1 = Number.MAX_VALUE; let max2 = Number.MIN_VALUE; let min2 = Number.MAX_VALUE; for (let i = 0; i < array.length; i++) { // Updating max and min variables // as described in algorithm. max1 = Math.max(max1, array[i] + i); min1 = Math.min(min1, array[i] + i); max2 = Math.max(max2, array[i] - i); min2 = Math.min(min2, array[i] - i); } // Calculating maximum absolute difference. return Math.max(max1 - min1, max2 - min2); } let array = [ -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ]; document.write(maxDistance(array)); </script> Output: 167 Time Complexity: O(n) vt_m Mithun Kumar SumitJadiya susmitakundugoaldanga mukesh07 simmytarika5 Arrays Searching Arrays Searching 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 Binary Search Linear Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 24934, "s": 24906, "text": "\n23 Jul, 2021" }, { "code": null, "e": 25183, "s": 24934, "text": "Given an unsorted array A of N integers, Return maximum value of f(i, j) for all 1 ≀ i, j ≀ N. f(i, j) or absolute difference of two elements of an array A is defined as |A[i] – A[j]| + |i – j|, where |A| denotes the absolute value of A.Examples: " }, { "code": null, "e": 25878, "s": 25183, "text": "We will calculate the value of f(i, j) for each pair\nof (i, j) and return the maximum value thus obtained.\n\nInput : A = {1, 3, -1}\nOutput : 5\nf(1, 1) = f(2, 2) = f(3, 3) = 0\nf(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3\nf(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4\nf(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5\nSo, we return 5.\n\nInput : A = {3, -2, 5, -4}\nOutput : 10\nf(1, 1) = f(2, 2) = f(3, 3) = f(4, 4) = 0\nf(1, 2) = f(2, 1) = |3 - (-2)| + |1 - 2| = 6\nf(1, 3) = f(3, 1) = |3 - 5| + |1 - 3| = 4\nf(1, 4) = f(4, 1) = |3 - (-4)| + |1 - 4| = 10\nf(2, 3) = f(3, 2) = |(-2) - 5| + |2 - 3| = 8\nf(2, 4) = f(4, 2) = |(-2) - (-4)| + |2 - 4| = 4\nf(3, 4) = f(4, 3) = |5 - (-4)| + |3 - 4| = 10\n\nSo, we return 10" }, { "code": null, "e": 26060, "s": 25880, "text": "A naive brute force approach is to calculate the value f(i, j) by iterating over all such pairs (i, j) and calculating the maximum absolute difference which is implemented below. " }, { "code": null, "e": 26064, "s": 26060, "text": "C++" }, { "code": null, "e": 26069, "s": 26064, "text": "Java" }, { "code": null, "e": 26077, "s": 26069, "text": "Python3" }, { "code": null, "e": 26080, "s": 26077, "text": "C#" }, { "code": null, "e": 26084, "s": 26080, "text": "PHP" }, { "code": null, "e": 26095, "s": 26084, "text": "Javascript" }, { "code": "// Brute force C++ program to calculate the// maximum absolute difference of an array.#include <bits/stdc++.h>using namespace std; int calculateDiff(int i, int j, int arr[]){ // Utility function to calculate // the value of absolute difference // for the pair (i, j). return abs(arr[i] - arr[j]) + abs(i - j);} // Function to return maximum absolute// difference in brute force.int maxDistance(int arr[], int n){ // Variable for storing the maximum // absolute distance throughout the // traversal of loops. int result = 0; // Iterate through all pairs. for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. if (calculateDiff(i, j, arr) > result) result = calculateDiff(i, j, arr); } } return result;} // Driver program to test the above function.int main(){ int arr[] = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxDistance(arr, n) << endl; return 0;}", "e": 27325, "s": 26095, "text": null }, { "code": "// Java program to calculate the maximum// absolute difference of an array.public class MaximumAbsoluteDifference{ private static int calculateDiff(int i, int j, int[] array) { // Utility function to calculate // the value of absolute difference // for the pair (i, j). return Math.abs(array[i] - array[j]) + Math.abs(i - j); } // Function to return maximum absolute // difference in brute force. private static int maxDistance(int[] array) { // Variable for storing the maximum // absolute distance throughout the // traversal of loops. int result = 0; // Iterate through all pairs. for (int i = 0; i < array.length; i++) { for (int j = i; j < array.length; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. result = Math.max(result, calculateDiff(i, j, array)); } } return result; } // Driver program to test above function public static void main(String[] args) { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; System.out.println(maxDistance(array)); }} // This code is contributed by Harikrishnan Rajan", "e": 28812, "s": 27325, "text": null }, { "code": "# Brute force Python 3 program# to calculate the maximum# absolute difference of an array. def calculateDiff(i, j, arr): # Utility function to calculate # the value of absolute difference # for the pair (i, j). return abs(arr[i] - arr[j]) + abs(i - j) # Function to return maximum# absolute difference in# brute force.def maxDistance(arr, n): # Variable for storing the # maximum absolute distance # throughout the traversal # of loops. result = 0 # Iterate through all pairs. for i in range(0,n): for j in range(i, n): # If the absolute difference of # current pair (i, j) is greater # than the maximum difference # calculated till now, update # the value of result. if (calculateDiff(i, j, arr) > result): result = calculateDiff(i, j, arr) return result # Driver programarr = [ -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ]n = len(arr) print(maxDistance(arr, n)) # This code is contributed by Smitha Dinesh Semwal", "e": 29877, "s": 28812, "text": null }, { "code": "// C# program to calculate the maximum// absolute difference of an array.using System; public class MaximumAbsoluteDifference{ private static int calculateDiff(int i, int j, int[] array) { // Utility function to calculate // the value of absolute difference // for the pair (i, j). return Math.Abs(array[i] - array[j]) + Math.Abs(i - j); } // Function to return maximum absolute // difference in brute force. private static int maxDistance(int[] array) { // Variable for storing the maximum // absolute distance throughout the // traversal of loops. int result = 0; // Iterate through all pairs. for (int i = 0; i < array.Length; i++) { for (int j = i; j < array.Length; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. result = Math.Max(result, calculateDiff(i, j, array)); } } return result; } // Driver program public static void Main() { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; Console.WriteLine(maxDistance(array)); }} // This code is contributed by vt_m", "e": 31324, "s": 29877, "text": null }, { "code": "<?php// Brute force PHP program to// calculate the maximum absolute// difference of an array. function calculateDiff($i, $j, $arr){ // Utility function to calculate // the value of absolute difference // for the pair (i, j). return abs($arr[$i] - $arr[$j]) + abs($i - $j);} // Function to return maximum// absolute difference in brute force.function maxDistance($arr, $n){ // Variable for storing the maximum // absolute distance throughout the // traversal of loops. $result = 0; // Iterate through all pairs. for ($i = 0; $i < $n; $i++) { for ($j = $i; $j < $n; $j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. if (calculateDiff($i, $j, $arr) > $result) $result = calculateDiff($i, $j, $arr); } } return $result;} // Driver Code$arr = array( -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ); $n = sizeof($arr); echo maxDistance($arr, $n); // This Code is contributed by mits?>", "e": 32479, "s": 31324, "text": null }, { "code": "<script> // javascript program to calculate the maximum// absolute difference of an array. let MAX = 256; // Function to count the number of equal pairs function calculateDiff(i, j, array) { // Utility function to calculate // the value of absolute difference // for the pair (i, j). return Math.abs(array[i] - array[j]) + Math.abs(i - j); } // Function to return maximum absolute // difference in brute force. function maxDistance(array) { // Variable for storing the maximum // absolute distance throughout the // traversal of loops. let result = 0; // Iterate through all pairs. for (let i = 0; i < array.length; i++) { for (let j = i; j < array.length; j++) { // If the absolute difference of // current pair (i, j) is greater // than the maximum difference // calculated till now, update // the value of result. result = Math.max(result, calculateDiff(i, j, array)); } } return result; } // Driver Function let array = [-70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ]; document.write(maxDistance(array)); // This code is contributed by susmitakundugoaldanga.</script>", "e": 33879, "s": 32479, "text": null }, { "code": null, "e": 33889, "s": 33879, "text": "Output: " }, { "code": null, "e": 33893, "s": 33889, "text": "167" }, { "code": null, "e": 34227, "s": 33893, "text": "Time complexity: O(n^2)An efficient solution in O(n) time complexity can be worked out using the properties of absolute values. f(i, j) = |A[i] – A[j]| + |i – j| can be written in 4 ways (Since we are looking at max value, we don’t even care if the value becomes negative as long as we are also covering the max value in some way). " }, { "code": null, "e": 34700, "s": 34227, "text": "Case 1: A[i] > A[j] and i > j\n|A[i] - A[j]| = A[i] - A[j]\n|i -j| = i - j\nhence, f(i, j) = (A[i] + i) - (A[j] + j)\n\nCase 2: A[i] < A[j] and i < j\n|A[i] - A[j]| = -(A[i]) + A[j]\n|i -j| = -(i) + j\nhence, f(i, j) = -(A[i] + i) + (A[j] + j)\n\nCase 3: A[i] > A[j] and i < j\n|A[i] - A[j]| = A[i] - A[j]\n|i -j| = -(i) + j\nhence, f(i, j) = (A[i] - i) - (A[j] - j)\n\nCase 4: A[i] < A[j] and i > j\n|A[i] - A[j]| = -(A[i]) + A[j]\n|i -j| = i - j\nhence, f(i, j) = -(A[i] - i) + (A[j] - j)" }, { "code": null, "e": 34863, "s": 34700, "text": "Note that cases 1 and 2 are equivalent and so are cases 3 and 4 and hence we can design our algorithm only for two cases as it will cover all the possible cases. " }, { "code": null, "e": 35727, "s": 34863, "text": "1. Calculate the value of A[i] + i and A[i] – i for every element of the array while traversing through the array.2. Then for the two equivalent cases, we find the maximum possible value. For that, we have to store minimum and maximum values of expressions A[i] + i and A[i] – i for all i.3. Hence the required maximum absolute difference is maximum of two values i.e. max((A[i] + i) – (A[j] + j)) and max((A[i] – i) – (A[j] – j)). These values can be found easily in linear time. a. For max((A[i] + i) – (A[j] + j)) Maintain two variables max1 and min1 which will store maximum and minimum values of A[i] + i respectively. max((A[i] + i) – (A[j] + j)) = max1 – min1 b. For max((A[i] – i) – (A[j] – j)). Maintain two variables max2 and min2 which will store maximum and minimum values of A[i] – i respectively. max((A[i] – i) – (A[j] – j)) = max2 – min2" }, { "code": null, "e": 35791, "s": 35727, "text": "Implementation using the above fast algorithm is given below. " }, { "code": null, "e": 35795, "s": 35791, "text": "C++" }, { "code": null, "e": 35800, "s": 35795, "text": "Java" }, { "code": null, "e": 35808, "s": 35800, "text": "Python3" }, { "code": null, "e": 35811, "s": 35808, "text": "C#" }, { "code": null, "e": 35815, "s": 35811, "text": "PHP" }, { "code": null, "e": 35826, "s": 35815, "text": "Javascript" }, { "code": "// C++ program to calculate the maximum// absolute difference of an array.#include <bits/stdc++.h>using namespace std; // Function to return maximum absolute// difference in linear time.int maxDistance(int arr[], int n){ // max and min variables as described // in algorithm. int max1 = INT_MIN, min1 = INT_MAX; int max2 = INT_MIN, min2 = INT_MAX; for (int i = 0; i < n; i++) { // Updating max and min variables // as described in algorithm. max1 = max(max1, arr[i] + i); min1 = min(min1, arr[i] + i); max2 = max(max2, arr[i] - i); min2 = min(min2, arr[i] - i); } // Calculating maximum absolute difference. return max(max1 - min1, max2 - min2);} // Driver program to test the above function.int main(){ int arr[] = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxDistance(arr, n) << endl; return 0;}", "e": 36775, "s": 35826, "text": null }, { "code": "// Java program to calculate the maximum// absolute difference of an array.public class MaximumAbsoluteDifference{ // Function to return maximum absolute // difference in linear time. private static int maxDistance(int[] array) { // max and min variables as described // in algorithm. int max1 = Integer.MIN_VALUE; int min1 = Integer.MAX_VALUE; int max2 = Integer.MIN_VALUE; int min2 = Integer.MAX_VALUE; for (int i = 0; i < array.length; i++) { // Updating max and min variables // as described in algorithm. max1 = Math.max(max1, array[i] + i); min1 = Math.min(min1, array[i] + i); max2 = Math.max(max2, array[i] - i); min2 = Math.min(min2, array[i] - i); } // Calculating maximum absolute difference. return Math.max(max1 - min1, max2 - min2); } // Driver program to test above function public static void main(String[] args) { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; System.out.println(maxDistance(array)); }} // This code is contributed by Harikrishnan Rajan", "e": 37974, "s": 36775, "text": null }, { "code": "# Python program to# calculate the maximum# absolute difference# of an array. # Function to return# maximum absolute# difference in linear time.def maxDistance(array): # max and min variables as described # in algorithm. max1 = -2147483648 min1 = +2147483647 max2 = -2147483648 min2 = +2147483647 for i in range(len(array)): # Updating max and min variables # as described in algorithm. max1 = max(max1, array[i] + i) min1 = min(min1, array[i] + i) max2 = max(max2, array[i] - i) min2 = min(min2, array[i] - i) # Calculating maximum absolute difference. return max(max1 - min1, max2 - min2) # Driver program to# test above function array = [ -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ] print(maxDistance(array)) # This code is contributed# by Anant Agarwal.", "e": 38832, "s": 37974, "text": null }, { "code": "// C# program to calculate the maximum// absolute difference of an array.using System; public class MaximumAbsoluteDifference{ // Function to return maximum absolute // difference in linear time. private static int maxDistance(int[] array) { // max and min variables as described // in algorithm. int max1 = int.MinValue ; int min1 = int.MaxValue ; int max2 = int.MinValue ; int min2 =int.MaxValue ; for (int i = 0; i < array.Length; i++) { // Updating max and min variables // as described in algorithm. max1 = Math.Max(max1, array[i] + i); min1 = Math.Min(min1, array[i] + i); max2 = Math.Max(max2, array[i] - i); min2 = Math.Min(min2, array[i] - i); } // Calculating maximum absolute difference. return Math.Max(max1 - min1, max2 - min2); } // Driver program public static void Main() { int[] array = { -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 }; Console.WriteLine(maxDistance(array)); }} // This code is contributed by vt_m", "e": 39974, "s": 38832, "text": null }, { "code": "<?php// PHP program to calculate the maximum// absolute difference of an array. // Function to return maximum absolute// difference in linear time.function maxDistance( $arr, $n){ // max and min variables as // described in algorithm. $max1 = PHP_INT_MIN; $min1 = PHP_INT_MAX; $max2 = PHP_INT_MIN;$min2 = PHP_INT_MAX; for($i = 0; $i < $n; $i++) { // Updating max and min variables // as described in algorithm. $max1 = max($max1, $arr[$i] + $i); $min1 = min($min1, $arr[$i] + $i); $max2 = max($max2, $arr[$i] - $i); $min2 = min($min2, $arr[$i] - $i); } // Calculating maximum // absolute difference. return max($max1 - $min1, $max2 - $min2);} // Driver Code $arr = array(-70, -64, -6, -56, 64, 61, -57, 16, 48, -98); $n = count($arr); echo maxDistance($arr, $n); // This code is contributed by anuj_67.?>", "e": 40941, "s": 39974, "text": null }, { "code": "<script> // JavaScript program to calculate the maximum // absolute difference of an array. // Function to return maximum absolute // difference in linear time. function maxDistance(array) { // max and min variables as described // in algorithm. let max1 = Number.MIN_VALUE; let min1 = Number.MAX_VALUE; let max2 = Number.MIN_VALUE; let min2 = Number.MAX_VALUE; for (let i = 0; i < array.length; i++) { // Updating max and min variables // as described in algorithm. max1 = Math.max(max1, array[i] + i); min1 = Math.min(min1, array[i] + i); max2 = Math.max(max2, array[i] - i); min2 = Math.min(min2, array[i] - i); } // Calculating maximum absolute difference. return Math.max(max1 - min1, max2 - min2); } let array = [ -70, -64, -6, -56, 64, 61, -57, 16, 48, -98 ]; document.write(maxDistance(array)); </script>", "e": 41948, "s": 40941, "text": null }, { "code": null, "e": 41958, "s": 41948, "text": "Output: " }, { "code": null, "e": 41962, "s": 41958, "text": "167" }, { "code": null, "e": 41985, "s": 41962, "text": "Time Complexity: O(n) " }, { "code": null, "e": 41990, "s": 41985, "text": "vt_m" }, { "code": null, "e": 42003, "s": 41990, "text": "Mithun Kumar" }, { "code": null, "e": 42015, "s": 42003, "text": "SumitJadiya" }, { "code": null, "e": 42037, "s": 42015, "text": "susmitakundugoaldanga" }, { "code": null, "e": 42046, "s": 42037, "text": "mukesh07" }, { "code": null, "e": 42059, "s": 42046, "text": "simmytarika5" }, { "code": null, "e": 42066, "s": 42059, "text": "Arrays" }, { "code": null, "e": 42076, "s": 42066, "text": "Searching" }, { "code": null, "e": 42083, "s": 42076, "text": "Arrays" }, { "code": null, "e": 42093, "s": 42083, "text": "Searching" }, { "code": null, "e": 42191, "s": 42093, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42200, "s": 42191, "text": "Comments" }, { "code": null, "e": 42213, "s": 42200, "text": "Old Comments" }, { "code": null, "e": 42261, "s": 42213, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 42305, "s": 42261, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 42328, "s": 42305, "text": "Introduction to Arrays" }, { "code": null, "e": 42360, "s": 42328, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 42374, "s": 42360, "text": "Linear Search" }, { "code": null, "e": 42388, "s": 42374, "text": "Binary Search" }, { "code": null, "e": 42402, "s": 42388, "text": "Linear Search" }, { "code": null, "e": 42470, "s": 42402, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 42494, "s": 42470, "text": "Find the Missing Number" } ]
Wand push() and pop() in Python
16 Oct, 2021 We can use ImageMagick’s internal graphic context stack to manage different styles and operations in Wand. There are total four push functions for context stack. push() push_clip_path() push_defs() push_pattern() push() function is used to grow context stack and pop() is another function and used to restore stack to previous push. Syntax : # for push() wand.drawing.push() # for pop() wand.drawing.pop() Parameters : No parameters for push() as well as for pop() function Example #1: Python3 from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as ctx: ctx.fill_color = Color('RED') ctx.stroke_color = Color('BLACK') ctx.push() ctx.circle((50, 50), (25, 25)) ctx.pop() ctx.fill_color = Color('YELLOW') ctx.stroke_color = Color('GREEN') ctx.push() ctx.circle((150, 150), (125, 125)) ctx.pop() with Image(width = 200, height = 200, background = Color('lightgreen')) as image: ctx(image) image.save(filename = "push.png") Output: Example #2: Python3 from wand.color import Colorfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.compat import nestedfrom math import cos, pi, sin with nested(Color('lightblue'), Color('transparent'), Drawing()) as (bg, fg, draw): draw.stroke_width = 3 draw.fill_color = fg for degree in range(0, 360, 15): draw.push() # Grow stack draw.stroke_color = Color('hsl({0}%, 100 %, 50 %)'.format(degree * 100 / 360)) t = degree / 180.0 * pi x = 35 * cos(t) + 50 y = 35 * sin(t) + 50 draw.line((50, 50), (x, y)) draw.pop() # Restore stack with Image(width = 100, height = 100, background = Color('green')) as img: draw(img) img.save(filename = "pushpop.png") Output: saurabh1990aror Python-wand Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Oct, 2021" }, { "code": null, "e": 192, "s": 28, "text": "We can use ImageMagick’s internal graphic context stack to manage different styles and operations in Wand. There are total four push functions for context stack. " }, { "code": null, "e": 199, "s": 192, "text": "push()" }, { "code": null, "e": 216, "s": 199, "text": "push_clip_path()" }, { "code": null, "e": 228, "s": 216, "text": "push_defs()" }, { "code": null, "e": 243, "s": 228, "text": "push_pattern()" }, { "code": null, "e": 364, "s": 243, "text": "push() function is used to grow context stack and pop() is another function and used to restore stack to previous push. " }, { "code": null, "e": 375, "s": 364, "text": "Syntax : " }, { "code": null, "e": 440, "s": 375, "text": "# for push()\nwand.drawing.push()\n\n# for pop()\nwand.drawing.pop()" }, { "code": null, "e": 508, "s": 440, "text": "Parameters : No parameters for push() as well as for pop() function" }, { "code": null, "e": 522, "s": 508, "text": "Example #1: " }, { "code": null, "e": 530, "s": 522, "text": "Python3" }, { "code": "from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as ctx: ctx.fill_color = Color('RED') ctx.stroke_color = Color('BLACK') ctx.push() ctx.circle((50, 50), (25, 25)) ctx.pop() ctx.fill_color = Color('YELLOW') ctx.stroke_color = Color('GREEN') ctx.push() ctx.circle((150, 150), (125, 125)) ctx.pop() with Image(width = 200, height = 200, background = Color('lightgreen')) as image: ctx(image) image.save(filename = \"push.png\")", "e": 1059, "s": 530, "text": null }, { "code": null, "e": 1069, "s": 1059, "text": "Output: " }, { "code": null, "e": 1083, "s": 1069, "text": "Example #2: " }, { "code": null, "e": 1091, "s": 1083, "text": "Python3" }, { "code": "from wand.color import Colorfrom wand.image import Imagefrom wand.drawing import Drawingfrom wand.compat import nestedfrom math import cos, pi, sin with nested(Color('lightblue'), Color('transparent'), Drawing()) as (bg, fg, draw): draw.stroke_width = 3 draw.fill_color = fg for degree in range(0, 360, 15): draw.push() # Grow stack draw.stroke_color = Color('hsl({0}%, 100 %, 50 %)'.format(degree * 100 / 360)) t = degree / 180.0 * pi x = 35 * cos(t) + 50 y = 35 * sin(t) + 50 draw.line((50, 50), (x, y)) draw.pop() # Restore stack with Image(width = 100, height = 100, background = Color('green')) as img: draw(img) img.save(filename = \"pushpop.png\")", "e": 1845, "s": 1091, "text": null }, { "code": null, "e": 1854, "s": 1845, "text": "Output: " }, { "code": null, "e": 1872, "s": 1856, "text": "saurabh1990aror" }, { "code": null, "e": 1884, "s": 1872, "text": "Python-wand" }, { "code": null, "e": 1891, "s": 1884, "text": "Python" } ]
Using Async Await in Node.js
19 Feb, 2019 Before Node version 7.6, the callbacks were the only official way provided by Node to run one function after another. As Node architecture is single-threaded and asynchronous, the community devised the callback functions, which would fire (or run) after the first function (to which the callbacks were assigned) run is completed. Example of a Callback: app.get('/', function(){ function1(arg1, function(){ ... }) }); The problem with this kind of code is that this kind of situations can cause a lot of trouble and the code can get messy when there are several functions. This situation is called what is commonly known as a callback hell.So, to find a way out, the idea of Promises and function chaining was introduced. Example: Before async/await function fun1(req, res){ return request.get('http://localhost:3000') .catch((err) =>{ console.log('found error'); }).then((res) =>{ console.log('get request returned.'); }); Explanation:The above code demos a function implemented with function chaining instead of callbacks. It can be observed that the code is now more easy to understand and readable. The code basically says that GET localhost:3000, catch the error if there is any; if there is no error then implement the following statement:console.log(β€˜get request returned.’); With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise. The code now looks like below. Example: After async/await async function fun1(req, res){ let response = await request.get('http://localhost:3000'); if (response.err) { console.log('error');} else { console.log('fetched response'); } Explanation:The code above basically asks the javascript engine running the code to wait for the request.get() function to complete before moving on to the next line to execute it. The request.get() function returns a Promise for which user will await . Before async/await, if it needs to be made sure that the functions are running in the desired sequence, that is one after the another, chain them one after the another or register callbacks.Code writing and understanding becomes easy with async/await as can be observed from both the examples. JavaScript-Misc Node.js JavaScript Technical Scripter 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 How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Roadmap to Learn JavaScript For Beginners How to get character array from string in JavaScript? How do you run JavaScript script through the Terminal? JavaScript | console.log() with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Feb, 2019" }, { "code": null, "e": 384, "s": 54, "text": "Before Node version 7.6, the callbacks were the only official way provided by Node to run one function after another. As Node architecture is single-threaded and asynchronous, the community devised the callback functions, which would fire (or run) after the first function (to which the callbacks were assigned) run is completed." }, { "code": null, "e": 407, "s": 384, "text": "Example of a Callback:" }, { "code": null, "e": 476, "s": 407, "text": "app.get('/', function(){\n function1(arg1, function(){\n ...\n})\n});\n" }, { "code": null, "e": 780, "s": 476, "text": "The problem with this kind of code is that this kind of situations can cause a lot of trouble and the code can get messy when there are several functions. This situation is called what is commonly known as a callback hell.So, to find a way out, the idea of Promises and function chaining was introduced." }, { "code": null, "e": 808, "s": 780, "text": "Example: Before async/await" }, { "code": null, "e": 996, "s": 808, "text": "function fun1(req, res){\n return request.get('http://localhost:3000')\n .catch((err) =>{\n console.log('found error');\n}).then((res) =>{\n console.log('get request returned.');\n});\n" }, { "code": null, "e": 1355, "s": 996, "text": "Explanation:The above code demos a function implemented with function chaining instead of callbacks. It can be observed that the code is now more easy to understand and readable. The code basically says that GET localhost:3000, catch the error if there is any; if there is no error then implement the following statement:console.log(β€˜get request returned.’);" }, { "code": null, "e": 1707, "s": 1355, "text": "With Node v8, the async/await feature was officially rolled out by the Node to deal with Promises and function chaining. The functions need not to be chained one after another, simply await the function that returns the Promise. But the function async needs to be declared before awaiting a function returning a Promise. The code now looks like below." }, { "code": null, "e": 1734, "s": 1707, "text": "Example: After async/await" }, { "code": null, "e": 1920, "s": 1734, "text": "async function fun1(req, res){\n let response = await request.get('http://localhost:3000');\n if (response.err) { console.log('error');}\n else { console.log('fetched response');\n}\n" }, { "code": null, "e": 2468, "s": 1920, "text": "Explanation:The code above basically asks the javascript engine running the code to wait for the request.get() function to complete before moving on to the next line to execute it. The request.get() function returns a Promise for which user will await . Before async/await, if it needs to be made sure that the functions are running in the desired sequence, that is one after the another, chain them one after the another or register callbacks.Code writing and understanding becomes easy with async/await as can be observed from both the examples." }, { "code": null, "e": 2484, "s": 2468, "text": "JavaScript-Misc" }, { "code": null, "e": 2492, "s": 2484, "text": "Node.js" }, { "code": null, "e": 2503, "s": 2492, "text": "JavaScript" }, { "code": null, "e": 2522, "s": 2503, "text": "Technical Scripter" }, { "code": null, "e": 2620, "s": 2522, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2681, "s": 2620, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2753, "s": 2681, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2793, "s": 2753, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2834, "s": 2793, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2886, "s": 2834, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2932, "s": 2886, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 2974, "s": 2932, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3028, "s": 2974, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 3083, "s": 3028, "text": "How do you run JavaScript script through the Terminal?" } ]
What’s the difference between super() and super(props) in React ?
22 Jan, 2021 Before going deep into the main difference, let us understand what is Super() and Props as shown below: Super(): It is used to call the constructor of its parent class. This is required when we need to access some variables of its parent class. Props: It is a special keyword that is used in react stands for properties. Used for passing data from one component to another. Props data is read-only, which means that data coming from the parent should not be changed by child components. Keyword β€˜this’: The JavaScript this keyword refers to the object it belongs to. Creating React Application: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Project Structure: It will look like the following. Project Structure Example of Super(): Simple component demonstrating the use of Super() function. Filename-App.js: Javascript import React from 'react' class MyComponent extends React.Component { constructor(props) { super() console.log(this.props) // Undefined console.log(props) // Defined Props Will Be Logged } render() { return <div>Hello {this.props.message}</div>; // Defined }} export default MyComponent; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Explanation: Here when we are not using props in super() then, when doing console.log(this.props) in console, we will get an undefined message because we are using this.props inside the constructor. But if we just console.log(props) this will give us a proper message in the console on the webpage. Example of Super(props): Simple component demonstrating the use of Super(props) function. Filename-App.js: Javascript import React from 'react' class MyComponent extends React.Component { constructor(props) { super(props) console.log(this.props) // {name:'Bob' , .....} Props Will Be Logged } render() { return <div>Hello {this.props.message}</div>; // defined }} export default MyComponent; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Explanation: If we want to use this in the constructor, we need to pass it to super. If we want to use this.props inside the constructor we need to pass it with the super() function. Otherwise, we don’t want to pass props to super() because we see this.Props are available inside the render function. Note: Outside Constructor() Both will display same value for 'this.props' Picked JavaScript ReactJS 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 Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? Axios in React: A Guide for Beginners ReactJS Functional Components
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jan, 2021" }, { "code": null, "e": 132, "s": 28, "text": "Before going deep into the main difference, let us understand what is Super() and Props as shown below:" }, { "code": null, "e": 273, "s": 132, "text": "Super(): It is used to call the constructor of its parent class. This is required when we need to access some variables of its parent class." }, { "code": null, "e": 515, "s": 273, "text": "Props: It is a special keyword that is used in react stands for properties. Used for passing data from one component to another. Props data is read-only, which means that data coming from the parent should not be changed by child components." }, { "code": null, "e": 595, "s": 515, "text": "Keyword β€˜this’: The JavaScript this keyword refers to the object it belongs to." }, { "code": null, "e": 623, "s": 595, "text": "Creating React Application:" }, { "code": null, "e": 687, "s": 623, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 719, "s": 687, "text": "npx create-react-app foldername" }, { "code": null, "e": 819, "s": 719, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 833, "s": 819, "text": "cd foldername" }, { "code": null, "e": 885, "s": 833, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 903, "s": 885, "text": "Project Structure" }, { "code": null, "e": 985, "s": 905, "text": "Example of Super(): Simple component demonstrating the use of Super() function." }, { "code": null, "e": 1002, "s": 985, "text": "Filename-App.js:" }, { "code": null, "e": 1013, "s": 1002, "text": "Javascript" }, { "code": "import React from 'react' class MyComponent extends React.Component { constructor(props) { super() console.log(this.props) // Undefined console.log(props) // Defined Props Will Be Logged } render() { return <div>Hello {this.props.message}</div>; // Defined }} export default MyComponent;", "e": 1326, "s": 1013, "text": null }, { "code": null, "e": 1439, "s": 1326, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 1449, "s": 1439, "text": "npm start" }, { "code": null, "e": 1548, "s": 1449, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 1847, "s": 1548, "text": "Explanation: Here when we are not using props in super() then, when doing console.log(this.props) in console, we will get an undefined message because we are using this.props inside the constructor. But if we just console.log(props) this will give us a proper message in the console on the webpage." }, { "code": null, "e": 1937, "s": 1847, "text": "Example of Super(props): Simple component demonstrating the use of Super(props) function." }, { "code": null, "e": 1954, "s": 1937, "text": "Filename-App.js:" }, { "code": null, "e": 1965, "s": 1954, "text": "Javascript" }, { "code": "import React from 'react' class MyComponent extends React.Component { constructor(props) { super(props) console.log(this.props) // {name:'Bob' , .....} Props Will Be Logged } render() { return <div>Hello {this.props.message}</div>; // defined }} export default MyComponent;", "e": 2257, "s": 1965, "text": null }, { "code": null, "e": 2370, "s": 2257, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2380, "s": 2370, "text": "npm start" }, { "code": null, "e": 2479, "s": 2380, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2780, "s": 2479, "text": "Explanation: If we want to use this in the constructor, we need to pass it to super. If we want to use this.props inside the constructor we need to pass it with the super() function. Otherwise, we don’t want to pass props to super() because we see this.Props are available inside the render function." }, { "code": null, "e": 2854, "s": 2780, "text": "Note: Outside Constructor() Both will display same value for 'this.props'" }, { "code": null, "e": 2861, "s": 2854, "text": "Picked" }, { "code": null, "e": 2872, "s": 2861, "text": "JavaScript" }, { "code": null, "e": 2880, "s": 2872, "text": "ReactJS" }, { "code": null, "e": 2897, "s": 2880, "text": "Web Technologies" }, { "code": null, "e": 2995, "s": 2897, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3056, "s": 2995, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3096, "s": 3056, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3137, "s": 3096, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3179, "s": 3137, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3201, "s": 3179, "text": "JavaScript | Promises" }, { "code": null, "e": 3244, "s": 3201, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3289, "s": 3244, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 3327, "s": 3289, "text": "Axios in React: A Guide for Beginners" } ]
Preorder Tree Traversal in Data Structures
In this section we will see the pre-order traversal technique (recursive) for binary search tree. Suppose we have one tree like this βˆ’ The traversal sequence will be like: 10, 5, 8, 16, 15, 20, 23 preorderTraverse(root): Begin if root is not empty, then print the value of root preorderTraversal(left of root) preorderTraversal(right of root) end if End Live Demo #include<iostream> using namespace std; class node{ public: int h_left, h_right, bf, value; node *left, *right; }; class tree{ private: node *get_node(int key); public: node *root; tree(){ root = NULL; //set root as NULL at the beginning } void preorder_traversal(node *r); node *insert_node(node *root, int key); }; node *tree::get_node(int key){ node *new_node; new_node = new node; //create a new node dynamically new_node->h_left = 0; new_node->h_right = 0; new_node->bf = 0; new_node->value = key; //store the value from given key new_node->left = NULL; new_node->right = NULL; return new_node; } void tree::preorder_traversal(node *r){ if(r != NULL){ //When root is present, visit left - root - right cout << r->value << " "; preorder_traversal(r->left); preorder_traversal(r->right); } } node *tree::insert_node(node *root, int key){ if(root == NULL){ return (get_node(key)); //when tree is empty, create a node as root } if(key < root->value){ //when key is smaller than root value, go to the left root->left = insert_node(root->left, key); }else if(key > root->value){ //when key is greater than root value, go to the right root->right = insert_node(root->right, key); } return root; //when key is already present, do not insert it again } main(){ node *root; tree my_tree; //Insert some keys into the tree. my_tree.root = my_tree.insert_node(my_tree.root, 10); my_tree.root = my_tree.insert_node(my_tree.root, 5); my_tree.root = my_tree.insert_node(my_tree.root, 16); my_tree.root = my_tree.insert_node(my_tree.root, 20); my_tree.root = my_tree.insert_node(my_tree.root, 15); my_tree.root = my_tree.insert_node(my_tree.root, 8); my_tree.root = my_tree.insert_node(my_tree.root, 23); cout << "Pre-Order Traversal: "; my_tree.preorder_traversal(my_tree.root); } Pre-Order Traversal: 10 5 8 16 15 20 23
[ { "code": null, "e": 1285, "s": 1187, "text": "In this section we will see the pre-order traversal technique (recursive) for binary search tree." }, { "code": null, "e": 1322, "s": 1285, "text": "Suppose we have one tree like this βˆ’" }, { "code": null, "e": 1384, "s": 1322, "text": "The traversal sequence will be like: 10, 5, 8, 16, 15, 20, 23" }, { "code": null, "e": 1565, "s": 1384, "text": "preorderTraverse(root):\nBegin\n if root is not empty, then\n print the value of root\n preorderTraversal(left of root)\n preorderTraversal(right of root)\n end if\nEnd" }, { "code": null, "e": 1576, "s": 1565, "text": " Live Demo" }, { "code": null, "e": 3529, "s": 1576, "text": "#include<iostream>\nusing namespace std;\nclass node{\n public:\n int h_left, h_right, bf, value;\n node *left, *right;\n};\nclass tree{\n private:\n node *get_node(int key);\n public:\n node *root;\n tree(){\n root = NULL; //set root as NULL at the beginning\n }\n void preorder_traversal(node *r);\n node *insert_node(node *root, int key);\n};\nnode *tree::get_node(int key){\n node *new_node;\n new_node = new node; //create a new node dynamically\n new_node->h_left = 0; new_node->h_right = 0;\n new_node->bf = 0;\n new_node->value = key; //store the value from given key\n new_node->left = NULL; new_node->right = NULL;\n return new_node;\n}\nvoid tree::preorder_traversal(node *r){\n if(r != NULL){ //When root is present, visit left - root - right\n cout << r->value << \" \";\n preorder_traversal(r->left);\n preorder_traversal(r->right);\n }\n}\nnode *tree::insert_node(node *root, int key){\n if(root == NULL){\n return (get_node(key)); //when tree is empty, create a node as root\n }\n if(key < root->value){ //when key is smaller than root value, go to the left\n root->left = insert_node(root->left, key);\n }else if(key > root->value){ //when key is greater than root value, go to the right\n root->right = insert_node(root->right, key);\n }\n return root; //when key is already present, do not insert it again\n}\nmain(){\n node *root;\n tree my_tree;\n //Insert some keys into the tree.\n my_tree.root = my_tree.insert_node(my_tree.root, 10);\n my_tree.root = my_tree.insert_node(my_tree.root, 5);\n my_tree.root = my_tree.insert_node(my_tree.root, 16);\n my_tree.root = my_tree.insert_node(my_tree.root, 20);\n my_tree.root = my_tree.insert_node(my_tree.root, 15);\n my_tree.root = my_tree.insert_node(my_tree.root, 8);\n my_tree.root = my_tree.insert_node(my_tree.root, 23);\n cout << \"Pre-Order Traversal: \";\n my_tree.preorder_traversal(my_tree.root);\n}" }, { "code": null, "e": 3569, "s": 3529, "text": "Pre-Order Traversal: 10 5 8 16 15 20 23" } ]
Python | sympy.is_complex method
13 May, 2022 With the help of sympy.is_complex method, we can check whether element is complex or not this method will return the boolean value i.e True or False. Syntax : sympy.is_complexReturn : Return True if complex else False. Example #1 :In this example we can see that by using sympy.is_complex method, we are able to check the complex value and it will return a boolean value. # import sympyfrom sympy import * # Use sympy.is_complex methodgfg = simplify(2 * I).is_complex print(gfg) Output : True Example #2 : # import sympyfrom sympy import * # Use sympy.is_complex methodgfg = simplify(5).is_complex print(gfg) Output : True ankita_saini SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n13 May, 2022" }, { "code": null, "e": 178, "s": 28, "text": "With the help of sympy.is_complex method, we can check whether element is complex or not this method will return the boolean value i.e True or False." }, { "code": null, "e": 247, "s": 178, "text": "Syntax : sympy.is_complexReturn : Return True if complex else False." }, { "code": null, "e": 400, "s": 247, "text": "Example #1 :In this example we can see that by using sympy.is_complex method, we are able to check the complex value and it will return a boolean value." }, { "code": "# import sympyfrom sympy import * # Use sympy.is_complex methodgfg = simplify(2 * I).is_complex print(gfg)", "e": 511, "s": 400, "text": null }, { "code": null, "e": 520, "s": 511, "text": "Output :" }, { "code": null, "e": 525, "s": 520, "text": "True" }, { "code": null, "e": 538, "s": 525, "text": "Example #2 :" }, { "code": "# import sympyfrom sympy import * # Use sympy.is_complex methodgfg = simplify(5).is_complex print(gfg)", "e": 645, "s": 538, "text": null }, { "code": null, "e": 654, "s": 645, "text": "Output :" }, { "code": null, "e": 659, "s": 654, "text": "True" }, { "code": null, "e": 672, "s": 659, "text": "ankita_saini" }, { "code": null, "e": 678, "s": 672, "text": "SymPy" }, { "code": null, "e": 685, "s": 678, "text": "Python" }, { "code": null, "e": 783, "s": 685, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 815, "s": 783, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 842, "s": 815, "text": "Python Classes and Objects" }, { "code": null, "e": 863, "s": 842, "text": "Python OOPs Concepts" }, { "code": null, "e": 886, "s": 863, "text": "Introduction To PYTHON" }, { "code": null, "e": 942, "s": 886, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 973, "s": 942, "text": "Python | os.path.join() method" }, { "code": null, "e": 1015, "s": 973, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1057, "s": 1015, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1096, "s": 1057, "text": "Python | Get unique values from a list" } ]
What is Unobtrusive Validation in jQuery?
23 Jul, 2020 jQuery is a Javascript library. An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side. Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files. These unobtrusive validation libraries need to be added: jquery.validate.min.js jquery.validate.unobtrusive.js Installation via Package Managers: Bower: bower install jquery-validation Bower: bower install jquery-validation NuGet: Install-Package jQuery.Validation NuGet: Install-Package jQuery.Validation NPM : npm i jquery-validation NPM : npm i jquery-validation List of some data validation attribute:Requireddata-val-required=”This is required.”data-val=”true/false”EmailAddressdata-val-email=”Error message”MaxLengthdata-val-maxlength=”Error message”data-val-maxlength-max=”Maximum length (e.g. 5)”MinLengthdata-val-minlength=”Error message”data-val-minlength-min=”Minimum length (e.g. 2)” List of some data validation attribute: Requireddata-val-required=”This is required.”data-val=”true/false” data-val-required=”This is required.” data-val=”true/false” EmailAddressdata-val-email=”Error message” data-val-email=”Error message” MaxLengthdata-val-maxlength=”Error message”data-val-maxlength-max=”Maximum length (e.g. 5)” MaxLength data-val-maxlength=”Error message” data-val-maxlength-max=”Maximum length (e.g. 5)” MinLengthdata-val-minlength=”Error message”data-val-minlength-min=”Minimum length (e.g. 2)” data-val-minlength=”Error message” data-val-minlength-min=”Minimum length (e.g. 2)” Method for unobtrusive validation: Firstly, we need to add those libraries in the script of HTML files. These libraries provide a list of data attributes (data-val, data-val-required, and many more) for validation. Then the form should be built according to the requirements in which different types of data attributes can be used. Example: <!DOCTYPE html><html> <head> <!--These validation libraries need to be included for unobtrusive validation --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"> </script> <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"> </script> </head> <body> <form id="myform"> <p> <label for="roll">Roll no.</label> <!-- data-val-required is used to specify the msg for each rule --> <!-- data-val is used to add rules to the input elements --> <input name="roll" type="number" data-val-required="Roll no. is required." data-val="true" style="margin-left: 15px;" /><br /> <span data-valmsg-for="roll" data-valmsg-replace="true" style="margin-left: 75px; color: red;" /> </p> <p> <label for="name">Name</label> <input name="name" type="text" data-val-required="Name is required." data-val="true" style="margin-left: 30px;" /><br /> <span data-valmsg-for="name" data-valmsg-replace="true" style="margin-left: 75px; color: red;" /> </p> <p> <label for="mobile">Mobile no.</label> <input name="mobile" type="number" data-val-required="Mobile no. is required." data-val="true" /><br /> <span data-valmsg-for="mobile" data-valmsg-replace="true" style="margin-left: 78px; color: red;" /> </p> <p> <label for="email">E-Mail </label> <input type="email" name="email" data-val-required="Email is required." data-val="true" style="margin-left: 30px;" /><br /> <span data-valmsg-for="email" data-valmsg-replace="true" style="margin-left: 80px; color: red;" /> </p> <p> <input class="submit" type="submit" value="Submit" /> </p> </form> </body></html> Output: Before submit: After submit: jQuery-Misc Picked JQuery 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": "\n23 Jul, 2020" }, { "code": null, "e": 268, "s": 28, "text": "jQuery is a Javascript library. An unobtrusive validation in jQuery is a set of ASP.Net MVC HTML helper extensions.By using jQuery Validation data attributes along with HTML 5 data attributes, you can perform validation to the client-side." }, { "code": null, "e": 460, "s": 268, "text": "Unobtrusive Validation means without writing a lot of validation code, you can perform simple client-side validation by adding the suitable attributes and including the suitable script files." }, { "code": null, "e": 517, "s": 460, "text": "These unobtrusive validation libraries need to be added:" }, { "code": null, "e": 540, "s": 517, "text": "jquery.validate.min.js" }, { "code": null, "e": 571, "s": 540, "text": "jquery.validate.unobtrusive.js" }, { "code": null, "e": 606, "s": 571, "text": "Installation via Package Managers:" }, { "code": null, "e": 645, "s": 606, "text": "Bower: bower install jquery-validation" }, { "code": null, "e": 684, "s": 645, "text": "Bower: bower install jquery-validation" }, { "code": null, "e": 725, "s": 684, "text": "NuGet: Install-Package jQuery.Validation" }, { "code": null, "e": 766, "s": 725, "text": "NuGet: Install-Package jQuery.Validation" }, { "code": null, "e": 798, "s": 766, "text": "NPM : npm i jquery-validation " }, { "code": null, "e": 830, "s": 798, "text": "NPM : npm i jquery-validation " }, { "code": null, "e": 1160, "s": 830, "text": "List of some data validation attribute:Requireddata-val-required=”This is required.”data-val=”true/false”EmailAddressdata-val-email=”Error message”MaxLengthdata-val-maxlength=”Error message”data-val-maxlength-max=”Maximum length (e.g. 5)”MinLengthdata-val-minlength=”Error message”data-val-minlength-min=”Minimum length (e.g. 2)”" }, { "code": null, "e": 1200, "s": 1160, "text": "List of some data validation attribute:" }, { "code": null, "e": 1267, "s": 1200, "text": "Requireddata-val-required=”This is required.”data-val=”true/false”" }, { "code": null, "e": 1305, "s": 1267, "text": "data-val-required=”This is required.”" }, { "code": null, "e": 1327, "s": 1305, "text": "data-val=”true/false”" }, { "code": null, "e": 1370, "s": 1327, "text": "EmailAddressdata-val-email=”Error message”" }, { "code": null, "e": 1401, "s": 1370, "text": "data-val-email=”Error message”" }, { "code": null, "e": 1493, "s": 1401, "text": "MaxLengthdata-val-maxlength=”Error message”data-val-maxlength-max=”Maximum length (e.g. 5)”" }, { "code": null, "e": 1503, "s": 1493, "text": "MaxLength" }, { "code": null, "e": 1538, "s": 1503, "text": "data-val-maxlength=”Error message”" }, { "code": null, "e": 1587, "s": 1538, "text": "data-val-maxlength-max=”Maximum length (e.g. 5)”" }, { "code": null, "e": 1679, "s": 1587, "text": "MinLengthdata-val-minlength=”Error message”data-val-minlength-min=”Minimum length (e.g. 2)”" }, { "code": null, "e": 1714, "s": 1679, "text": "data-val-minlength=”Error message”" }, { "code": null, "e": 1763, "s": 1714, "text": "data-val-minlength-min=”Minimum length (e.g. 2)”" }, { "code": null, "e": 1798, "s": 1763, "text": "Method for unobtrusive validation:" }, { "code": null, "e": 2095, "s": 1798, "text": "Firstly, we need to add those libraries in the script of HTML files. These libraries provide a list of data attributes (data-val, data-val-required, and many more) for validation. Then the form should be built according to the requirements in which different types of data attributes can be used." }, { "code": null, "e": 2104, "s": 2095, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <!--These validation libraries need to be included for unobtrusive validation --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js\"> </script> <script src=\"https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js\"> </script> </head> <body> <form id=\"myform\"> <p> <label for=\"roll\">Roll no.</label> <!-- data-val-required is used to specify the msg for each rule --> <!-- data-val is used to add rules to the input elements --> <input name=\"roll\" type=\"number\" data-val-required=\"Roll no. is required.\" data-val=\"true\" style=\"margin-left: 15px;\" /><br /> <span data-valmsg-for=\"roll\" data-valmsg-replace=\"true\" style=\"margin-left: 75px; color: red;\" /> </p> <p> <label for=\"name\">Name</label> <input name=\"name\" type=\"text\" data-val-required=\"Name is required.\" data-val=\"true\" style=\"margin-left: 30px;\" /><br /> <span data-valmsg-for=\"name\" data-valmsg-replace=\"true\" style=\"margin-left: 75px; color: red;\" /> </p> <p> <label for=\"mobile\">Mobile no.</label> <input name=\"mobile\" type=\"number\" data-val-required=\"Mobile no. is required.\" data-val=\"true\" /><br /> <span data-valmsg-for=\"mobile\" data-valmsg-replace=\"true\" style=\"margin-left: 78px; color: red;\" /> </p> <p> <label for=\"email\">E-Mail </label> <input type=\"email\" name=\"email\" data-val-required=\"Email is required.\" data-val=\"true\" style=\"margin-left: 30px;\" /><br /> <span data-valmsg-for=\"email\" data-valmsg-replace=\"true\" style=\"margin-left: 80px; color: red;\" /> </p> <p> <input class=\"submit\" type=\"submit\" value=\"Submit\" /> </p> </form> </body></html>", "e": 4808, "s": 2104, "text": null }, { "code": null, "e": 4816, "s": 4808, "text": "Output:" }, { "code": null, "e": 4831, "s": 4816, "text": "Before submit:" }, { "code": null, "e": 4845, "s": 4831, "text": "After submit:" }, { "code": null, "e": 4857, "s": 4845, "text": "jQuery-Misc" }, { "code": null, "e": 4864, "s": 4857, "text": "Picked" }, { "code": null, "e": 4871, "s": 4864, "text": "JQuery" }, { "code": null, "e": 4888, "s": 4871, "text": "Web Technologies" } ]
How to get URL Parameters using JavaScript ?
24 Nov, 2021 In this article, we will learn how to get the URL parameters in Javascript, along with understanding their implementation through the examples. For getting the URL parameters, there are 2 ways: By using the URLSearchParams Object By using Separating and accessing each parameter pair Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the β€œ?” separator. It will separate the string into 2 parts. The second part is selected with only the parameters. It is then passed to the URLSearchParams constructor. The entries() method of this object returns an iterator with the key/value pairs. The key part of the pair can then be retrieved by accessing the first index of the pair and the value can be retrieved by accessing the second index. This can be used to get all the parameters in the URL which can be used as required. Syntax: let paramString = urlString.split('?')[1]; let queryString = new URLSearchParams(paramString); for (let pair of queryString.entries()) { console.log("Key is: " + pair[0]); console.log("Value is: " + pair[1]); } Example: This example illustrates the use of the URLSearchParams Object to get the URL parameter. HTML <!DOCTYPE html><html> <head> <title>How To Get URL Parameters using JavaScript?</title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <b> How To Get URL Parameters With JavaScript? </b> <p> The url used is: https://www.example.com/login.php? a=GeeksforGeeks&b=500&c=Hello Geeks </p> <p> Click on the button to get the url parameters in the console. </p> <button onclick="getParameters()"> Get URL parameters </button> <script> function getParameters() { let urlString = "https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks"; let paramString = urlString.split('?')[1]; let queryString = new URLSearchParams(paramString); for(let pair of queryString.entries()) { console.log("Key is:" + pair[0]); console.log("Value is:" + pair[1]); } } </script></body> </html> Output: entries() Method Method 2: Separating and accessing each parameter pair The query string is first separated to get only the parameters portion of the string. The split() method is used on the given URL with the β€œ?” separator. This will separate the URL into 2 parts and the second part is selected with only the parameters. This string is separated into the parameters by using the split() method again with β€œ&” as the separator. This will separate each parameter string into an array. This array is looped through each of the keys and values are separated by splitting with β€œ=” as the separator. It will separate the pairs into an array. The key part of the pair can be retrieved by accessing the first index of the pair and the value can be retrieved by accessing the second index. This can be used to get all the parameters in the URL which can be used as required. Syntax: let paramString = urlString.split('?')[1]; let params_arr = paramString.split('&'); for (let i = 0; i < params_arr.length; i++) { let pair = params_arr[i].split('='); console.log("Key is:", pair[0]); console.log("Value is:", pair[1]); } Example: This example illustrates the Separate access for each parameter pair. HTML <!DOCTYPE html><html> <head> <title> How To Get URL Parameters using JavaScript? </title></head> <body> <h1 style="color:green;"> GeeksforGeeks </h1> <b> How To Get URL Parameters With JavaScript? </b> <p> The url used is: https://www.example.com/login.php? a=GeeksforGeeks&b=500&c=Hello Geeks </p> <p> Click on the button to get the url parameters in the console. </p> <button onclick="getParameters()"> Get URL parameters </button> <script> function getParameters() { let urlString = "https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks"; let paramString = urlString.split('?')[1]; let params_arr = paramString.split('&'); for(let i = 0; i < params_arr.length; i++) { let pair = params_arr[i].split('='); console.log("Key is:" + pair[0]); console.log("Value is:" + pair[1]); } } </script></body> </html> Output: bhaskargeeksforgeeks JavaScript-Questions Picked JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 172, "s": 28, "text": "In this article, we will learn how to get the URL parameters in Javascript, along with understanding their implementation through the examples." }, { "code": null, "e": 222, "s": 172, "text": "For getting the URL parameters, there are 2 ways:" }, { "code": null, "e": 258, "s": 222, "text": "By using the URLSearchParams Object" }, { "code": null, "e": 312, "s": 258, "text": "By using Separating and accessing each parameter pair" }, { "code": null, "e": 355, "s": 312, "text": "Method 1: Using the URLSearchParams Object" }, { "code": null, "e": 752, "s": 355, "text": "The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the β€œ?” separator. It will separate the string into 2 parts. The second part is selected with only the parameters. It is then passed to the URLSearchParams constructor." }, { "code": null, "e": 1069, "s": 752, "text": "The entries() method of this object returns an iterator with the key/value pairs. The key part of the pair can then be retrieved by accessing the first index of the pair and the value can be retrieved by accessing the second index. This can be used to get all the parameters in the URL which can be used as required." }, { "code": null, "e": 1077, "s": 1069, "text": "Syntax:" }, { "code": null, "e": 1295, "s": 1077, "text": "let paramString = urlString.split('?')[1];\nlet queryString = new URLSearchParams(paramString);\n\nfor (let pair of queryString.entries()) {\n console.log(\"Key is: \" + pair[0]);\n console.log(\"Value is: \" + pair[1]);\n}" }, { "code": null, "e": 1393, "s": 1295, "text": "Example: This example illustrates the use of the URLSearchParams Object to get the URL parameter." }, { "code": null, "e": 1398, "s": 1393, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>How To Get URL Parameters using JavaScript?</title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> How To Get URL Parameters With JavaScript? </b> <p> The url used is: https://www.example.com/login.php? a=GeeksforGeeks&b=500&c=Hello Geeks </p> <p> Click on the button to get the url parameters in the console. </p> <button onclick=\"getParameters()\"> Get URL parameters </button> <script> function getParameters() { let urlString = \"https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks\"; let paramString = urlString.split('?')[1]; let queryString = new URLSearchParams(paramString); for(let pair of queryString.entries()) { console.log(\"Key is:\" + pair[0]); console.log(\"Value is:\" + pair[1]); } } </script></body> </html>", "e": 2316, "s": 1398, "text": null }, { "code": null, "e": 2324, "s": 2316, "text": "Output:" }, { "code": null, "e": 2342, "s": 2324, "text": " entries() Method" }, { "code": null, "e": 2397, "s": 2342, "text": "Method 2: Separating and accessing each parameter pair" }, { "code": null, "e": 2811, "s": 2397, "text": "The query string is first separated to get only the parameters portion of the string. The split() method is used on the given URL with the β€œ?” separator. This will separate the URL into 2 parts and the second part is selected with only the parameters. This string is separated into the parameters by using the split() method again with β€œ&” as the separator. This will separate each parameter string into an array." }, { "code": null, "e": 3194, "s": 2811, "text": "This array is looped through each of the keys and values are separated by splitting with β€œ=” as the separator. It will separate the pairs into an array. The key part of the pair can be retrieved by accessing the first index of the pair and the value can be retrieved by accessing the second index. This can be used to get all the parameters in the URL which can be used as required." }, { "code": null, "e": 3202, "s": 3194, "text": "Syntax:" }, { "code": null, "e": 3449, "s": 3202, "text": "let paramString = urlString.split('?')[1];\nlet params_arr = paramString.split('&');\n\nfor (let i = 0; i < params_arr.length; i++) {\n let pair = params_arr[i].split('=');\n console.log(\"Key is:\", pair[0]);\n console.log(\"Value is:\", pair[1]);\n}" }, { "code": null, "e": 3528, "s": 3449, "text": "Example: This example illustrates the Separate access for each parameter pair." }, { "code": null, "e": 3533, "s": 3528, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How To Get URL Parameters using JavaScript? </title></head> <body> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <b> How To Get URL Parameters With JavaScript? </b> <p> The url used is: https://www.example.com/login.php? a=GeeksforGeeks&b=500&c=Hello Geeks </p> <p> Click on the button to get the url parameters in the console. </p> <button onclick=\"getParameters()\"> Get URL parameters </button> <script> function getParameters() { let urlString = \"https://www.example.com/login.php?a=GeeksforGeeks&b=500&c=Hello Geeks\"; let paramString = urlString.split('?')[1]; let params_arr = paramString.split('&'); for(let i = 0; i < params_arr.length; i++) { let pair = params_arr[i].split('='); console.log(\"Key is:\" + pair[0]); console.log(\"Value is:\" + pair[1]); } } </script></body> </html>", "e": 4490, "s": 3533, "text": null }, { "code": null, "e": 4498, "s": 4490, "text": "Output:" }, { "code": null, "e": 4519, "s": 4498, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 4540, "s": 4519, "text": "JavaScript-Questions" }, { "code": null, "e": 4547, "s": 4540, "text": "Picked" }, { "code": null, "e": 4558, "s": 4547, "text": "JavaScript" }, { "code": null, "e": 4575, "s": 4558, "text": "Web Technologies" }, { "code": null, "e": 4602, "s": 4575, "text": "Web technologies Questions" } ]
Concatenate Pandas DataFrames Without Duplicates
16 Feb, 2022 In this article, we are going to concatenate two dataframes using pandas module. In order to perform concatenation of two dataframes, we are going to use the pandas.concat().drop_duplicates() method in pandas module. Step-by-step Approach: Import module. Load two sample dataframes as variables. Concatenate the dataframes using pandas.concat().drop_duplicates() method. Display the new dataframe generated. Below are some examples which depict how to perform concatenation between two dataframes using pandas module without duplicates: Example 1: Python3 # Importing pandas libraryimport pandas as pd # loading dataframesdataframe1 = pd.DataFrame({'columnA': [20, 30, 40], 'columnB': [200, 300, 400]}) dataframe2 = pd.DataFrame({'columnA': [50, 20, 60], 'columnB': [500, 200, 600]}) # Concatenating dataframes without duplicatesnew_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates() # Display concatenated dataframenew_dataframe Output: Here, we have concatenated two dataframes using pandas.concat() method. Example 2: Python3 # Importing pandas libraryimport pandas as pd # loading dataframesdataframe1 = pd.DataFrame({'name': ['rahul', 'anjali', 'kajal'], 'age': [23, 28, 30]}) dataframe2 = pd.DataFrame({'name': ['devesh', 'rashi', 'anjali'], 'age': [20, 15, 28]}) # Concatenating two dataframes without duplicatesnew_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates() # Resetting indexnew_dataframe = new_dataframe.reset_index(drop=True) # Display dataframe generatednew_dataframe Output: As shown in the output image, we get the concatenation of dataframes without removing duplicates. Example 3: Python3 # Importing pandas libraryimport pandas as pd # Loading dataframesdataframe1 = pd.DataFrame({'empname': ['rohan', 'hina', 'alisa', ], 'department': ['IT', 'admin', 'finance', ], 'designation': ['Sr.developer', 'administrator', 'executive', ]}) dataframe2 = pd.DataFrame({'empname': ['rishi', 'huma', 'alisa', ], 'department': ['cyber security', 'HR', 'finance', ], 'designation': ['penetration tester', 'HR executive', 'executive', ]}) # Concatenating two dataframes without duplicatesnew_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates() # Resetting indexnew_dataframe = new_dataframe.reset_index(drop=True) # Display dataframe generatednew_dataframe Output: Here is another example, which depicts how to concatenate two dataframes. Output dataset for the Example 3 idevesh germanshephered48 Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n16 Feb, 2022" }, { "code": null, "e": 135, "s": 54, "text": "In this article, we are going to concatenate two dataframes using pandas module." }, { "code": null, "e": 271, "s": 135, "text": "In order to perform concatenation of two dataframes, we are going to use the pandas.concat().drop_duplicates() method in pandas module." }, { "code": null, "e": 295, "s": 271, "text": "Step-by-step Approach: " }, { "code": null, "e": 310, "s": 295, "text": "Import module." }, { "code": null, "e": 351, "s": 310, "text": "Load two sample dataframes as variables." }, { "code": null, "e": 426, "s": 351, "text": "Concatenate the dataframes using pandas.concat().drop_duplicates() method." }, { "code": null, "e": 463, "s": 426, "text": "Display the new dataframe generated." }, { "code": null, "e": 592, "s": 463, "text": "Below are some examples which depict how to perform concatenation between two dataframes using pandas module without duplicates:" }, { "code": null, "e": 603, "s": 592, "text": "Example 1:" }, { "code": null, "e": 611, "s": 603, "text": "Python3" }, { "code": "# Importing pandas libraryimport pandas as pd # loading dataframesdataframe1 = pd.DataFrame({'columnA': [20, 30, 40], 'columnB': [200, 300, 400]}) dataframe2 = pd.DataFrame({'columnA': [50, 20, 60], 'columnB': [500, 200, 600]}) # Concatenating dataframes without duplicatesnew_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates() # Display concatenated dataframenew_dataframe", "e": 1052, "s": 611, "text": null }, { "code": null, "e": 1060, "s": 1052, "text": "Output:" }, { "code": null, "e": 1132, "s": 1060, "text": "Here, we have concatenated two dataframes using pandas.concat() method." }, { "code": null, "e": 1143, "s": 1132, "text": "Example 2:" }, { "code": null, "e": 1151, "s": 1143, "text": "Python3" }, { "code": "# Importing pandas libraryimport pandas as pd # loading dataframesdataframe1 = pd.DataFrame({'name': ['rahul', 'anjali', 'kajal'], 'age': [23, 28, 30]}) dataframe2 = pd.DataFrame({'name': ['devesh', 'rashi', 'anjali'], 'age': [20, 15, 28]}) # Concatenating two dataframes without duplicatesnew_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates() # Resetting indexnew_dataframe = new_dataframe.reset_index(drop=True) # Display dataframe generatednew_dataframe", "e": 1676, "s": 1151, "text": null }, { "code": null, "e": 1684, "s": 1676, "text": "Output:" }, { "code": null, "e": 1782, "s": 1684, "text": "As shown in the output image, we get the concatenation of dataframes without removing duplicates." }, { "code": null, "e": 1793, "s": 1782, "text": "Example 3:" }, { "code": null, "e": 1801, "s": 1793, "text": "Python3" }, { "code": "# Importing pandas libraryimport pandas as pd # Loading dataframesdataframe1 = pd.DataFrame({'empname': ['rohan', 'hina', 'alisa', ], 'department': ['IT', 'admin', 'finance', ], 'designation': ['Sr.developer', 'administrator', 'executive', ]}) dataframe2 = pd.DataFrame({'empname': ['rishi', 'huma', 'alisa', ], 'department': ['cyber security', 'HR', 'finance', ], 'designation': ['penetration tester', 'HR executive', 'executive', ]}) # Concatenating two dataframes without duplicatesnew_dataframe = pd.concat([dataframe1, dataframe2]).drop_duplicates() # Resetting indexnew_dataframe = new_dataframe.reset_index(drop=True) # Display dataframe generatednew_dataframe", "e": 2573, "s": 1801, "text": null }, { "code": null, "e": 2581, "s": 2573, "text": "Output:" }, { "code": null, "e": 2655, "s": 2581, "text": "Here is another example, which depicts how to concatenate two dataframes." }, { "code": null, "e": 2688, "s": 2655, "text": "Output dataset for the Example 3" }, { "code": null, "e": 2696, "s": 2688, "text": "idevesh" }, { "code": null, "e": 2714, "s": 2696, "text": "germanshephered48" }, { "code": null, "e": 2721, "s": 2714, "text": "Picked" }, { "code": null, "e": 2745, "s": 2721, "text": "Python pandas-dataFrame" }, { "code": null, "e": 2759, "s": 2745, "text": "Python-pandas" }, { "code": null, "e": 2766, "s": 2759, "text": "Python" }, { "code": null, "e": 2864, "s": 2766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2896, "s": 2864, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2923, "s": 2896, "text": "Python Classes and Objects" }, { "code": null, "e": 2944, "s": 2923, "text": "Python OOPs Concepts" }, { "code": null, "e": 2967, "s": 2944, "text": "Introduction To PYTHON" }, { "code": null, "e": 3023, "s": 2967, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 3054, "s": 3023, "text": "Python | os.path.join() method" }, { "code": null, "e": 3096, "s": 3054, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3138, "s": 3096, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 3177, "s": 3138, "text": "Python | Get unique values from a list" } ]
When can we use the pack() method in Java?
The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes. An alternative to the pack() method is to establish a frame size explicitly by calling the setSize() or setBounds() methods. In general, using the pack() method is preferable to call than setSize() method, since pack leaves the frame layout manager in charge of the frame size and layout managers are good at adjusting to platform dependencies and other factors that affect the component size. public void pack() import java.awt.*; import javax.swing.*; public class PackMethodTest extends JFrame { public PackMethodTest() { setTitle("Pack() method Test"); setLayout(new FlowLayout()); setButton(); pack(); // calling the pack() method setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } void setButton() { for(int i=1; i < 6; i++) { add(new JButton("Button" +i)); } } public static void main(String args[]) { new PackMethodTest(); } }
[ { "code": null, "e": 1721, "s": 1187, "text": "The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes. An alternative to the pack() method is to establish a frame size explicitly by calling the setSize() or setBounds() methods. In general, using the pack() method is preferable to call than setSize() method, since pack leaves the frame layout manager in charge of the frame size and layout managers are good at adjusting to platform dependencies and other factors that affect the component size." }, { "code": null, "e": 1740, "s": 1721, "text": "public void pack()" }, { "code": null, "e": 2295, "s": 1740, "text": "import java.awt.*;\nimport javax.swing.*;\npublic class PackMethodTest extends JFrame {\n public PackMethodTest() {\n setTitle(\"Pack() method Test\");\n setLayout(new FlowLayout());\n setButton();\n pack(); // calling the pack() method\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n void setButton() {\n for(int i=1; i < 6; i++) {\n add(new JButton(\"Button\" +i));\n }\n }\n public static void main(String args[]) {\n new PackMethodTest();\n }\n}" } ]
PyQt5 QSpinBox – Setting step type
06 May, 2020 In this article we will see how we can set the step type to the spin box, there are two types of step types i.e default one which increment value normally and other is adaptive decimal. Adaptive decimal step means that the step size will continuously be adjusted to one power of ten below the current value i.e if value is 900 it get next increment will be off 10 for value equals to 1000 increment will be of 100. By default it is set to default step type although we can change. In order to do this we will use setStepType method Note : This feature was introduced in Qt 5.12. so lower versions don’t have this feature. Syntax :spin_box.setStepType(QAbstractSpinBox.AdaptiveDecimalStepType)orspin_box.setStepType(1) Argument : It takes QAbstractionSpinBox object or we can pass 1 i.e its value as argument Return : It returns None Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.Qt import PYQT_VERSION_STR print("PyQt version:", PYQT_VERSION_STR) import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 150, 40) # setting range self.spin.setRange(0, 10000) # setting value self.spin.setValue(950) # setting step type self.spin.setStepType(QAbstractSpinBox.AdaptiveDecimalStepType) # creating label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 160, 200, 30) # getting single step size step = self.spin.singleStep() # setting text to the label label.setText("Step Size : " + str(step)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python PyQt-SpinBox Python-gui Python-PyQt Python 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 Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2020" }, { "code": null, "e": 509, "s": 28, "text": "In this article we will see how we can set the step type to the spin box, there are two types of step types i.e default one which increment value normally and other is adaptive decimal. Adaptive decimal step means that the step size will continuously be adjusted to one power of ten below the current value i.e if value is 900 it get next increment will be off 10 for value equals to 1000 increment will be of 100. By default it is set to default step type although we can change." }, { "code": null, "e": 560, "s": 509, "text": "In order to do this we will use setStepType method" }, { "code": null, "e": 650, "s": 560, "text": "Note : This feature was introduced in Qt 5.12. so lower versions don’t have this feature." }, { "code": null, "e": 746, "s": 650, "text": "Syntax :spin_box.setStepType(QAbstractSpinBox.AdaptiveDecimalStepType)orspin_box.setStepType(1)" }, { "code": null, "e": 836, "s": 746, "text": "Argument : It takes QAbstractionSpinBox object or we can pass 1 i.e its value as argument" }, { "code": null, "e": 861, "s": 836, "text": "Return : It returns None" }, { "code": null, "e": 889, "s": 861, "text": "Below is the implementation" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.Qt import PYQT_VERSION_STR print(\"PyQt version:\", PYQT_VERSION_STR) import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating spin box self.spin = QSpinBox(self) # setting geometry to spin box self.spin.setGeometry(100, 100, 150, 40) # setting range self.spin.setRange(0, 10000) # setting value self.spin.setValue(950) # setting step type self.spin.setStepType(QAbstractSpinBox.AdaptiveDecimalStepType) # creating label label = QLabel(self) # setting geometry to the label label.setGeometry(100, 160, 200, 30) # getting single step size step = self.spin.singleStep() # setting text to the label label.setText(\"Step Size : \" + str(step)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 2297, "s": 889, "text": null }, { "code": null, "e": 2306, "s": 2297, "text": "Output :" }, { "code": null, "e": 2326, "s": 2306, "text": "Python PyQt-SpinBox" }, { "code": null, "e": 2337, "s": 2326, "text": "Python-gui" }, { "code": null, "e": 2349, "s": 2337, "text": "Python-PyQt" }, { "code": null, "e": 2356, "s": 2349, "text": "Python" }, { "code": null, "e": 2454, "s": 2356, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2496, "s": 2454, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2518, "s": 2496, "text": "Enumerate() in Python" }, { "code": null, "e": 2544, "s": 2518, "text": "Python String | replace()" }, { "code": null, "e": 2576, "s": 2544, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2605, "s": 2576, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2632, "s": 2605, "text": "Python Classes and Objects" }, { "code": null, "e": 2653, "s": 2632, "text": "Python OOPs Concepts" }, { "code": null, "e": 2689, "s": 2653, "text": "Convert integer to string in Python" }, { "code": null, "e": 2712, "s": 2689, "text": "Introduction To PYTHON" } ]
Fetch specific values from array of objects in JavaScript?
Let’s say the following are our array of objects: const details = [ { employeeFirstName: "John", employeeLastName: "Doe" }, { employeeFirstName: "David", employeeLastName: "Miller" }, { employeeFirstName: "John", employeeLastName: "Smith" } ] Following is the code to fetch specific values, in this case with first name β€œJohn” βˆ’ const details = [ { employeeFirstName: "John", employeeLastName: "Doe" }, { employeeFirstName: "David", employeeLastName: "Miller" }, { employeeFirstName: "John", employeeLastName: "Smith" } ] for (var index = 0; index < details.length; index++) { if (details[index].employeeFirstName === "John") { console.log("FirstName=" + details[index].employeeFirstName + " LastName= " + details[index].employeeLastName); } } To run the above program, you need to use the following command βˆ’ node fileName.js. Here, my file name is demo223.js. The output is as follows βˆ’ PS C:\Users\Amit\JavaScript-code> node demo223.js FirstName=John LastName= Doe FirstName=John LastName= Smith
[ { "code": null, "e": 1237, "s": 1187, "text": "Let’s say the following are our array of objects:" }, { "code": null, "e": 1526, "s": 1237, "text": "const details =\n [\n {\n employeeFirstName: \"John\",\n employeeLastName: \"Doe\"\n },\n {\n employeeFirstName: \"David\",\n employeeLastName: \"Miller\"\n },\n {\n employeeFirstName: \"John\",\n employeeLastName: \"Smith\"\n }\n ]" }, { "code": null, "e": 1612, "s": 1526, "text": "Following is the code to fetch specific values, in this case with first name β€œJohn” βˆ’" }, { "code": null, "e": 2141, "s": 1612, "text": "const details =\n [\n {\n employeeFirstName: \"John\",\n employeeLastName: \"Doe\"\n },\n {\n employeeFirstName: \"David\",\n employeeLastName: \"Miller\"\n },\n {\n employeeFirstName: \"John\",\n employeeLastName: \"Smith\"\n }\n ]\nfor (var index = 0; index < details.length; index++) {\n if (details[index].employeeFirstName === \"John\") {\n console.log(\"FirstName=\" + details[index].employeeFirstName + \" LastName= \" + details[index].employeeLastName);\n }\n}" }, { "code": null, "e": 2207, "s": 2141, "text": "To run the above program, you need to use the following command βˆ’" }, { "code": null, "e": 2225, "s": 2207, "text": "node fileName.js." }, { "code": null, "e": 2259, "s": 2225, "text": "Here, my file name is demo223.js." }, { "code": null, "e": 2286, "s": 2259, "text": "The output is as follows βˆ’" }, { "code": null, "e": 2396, "s": 2286, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo223.js\nFirstName=John LastName= Doe\nFirstName=John LastName= Smith" } ]
How to create a gridView layout in an Android app?
This example demonstrates how do I gridView layout in an android app. Step 1 βˆ’ Create a new project in Android Studio, go to File β‡’ New Project and fill all required details to create a new project. Step 2 βˆ’ Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <GridView android:id="@+id/gridView" android:layout_width="match_parent" android:layout_height="match_parent" android:numColumns="2"/> </RelativeLayout> Step 3 – Open build.gradle(Module: app) and add the following dependency βˆ’ implementation 'com.android.support:gridlayout-v7:28.0.0' Step 4 βˆ’ Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { GridView gridView; String[] numberInWords = {"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"}; int[] numberImage = {R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four, R.drawable.five,R.drawable.six,R.drawable.seven,R.drawable.eight,R.drawable.nine, R.drawable.ten}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridView = findViewById(R.id.gridView); MainAdapter mainAdapter = new MainAdapter(MainActivity.this, numberInWords,numberImage); gridView.setAdapter(mainAdapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getApplicationContext(), "You CLicked " + numberInWords[+position], Toast.LENGTH_SHORT).show(); } }); } } Step 5 – Add the following code to MainAdapter.java import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; class MainAdapter extends BaseAdapter { private Context context; private LayoutInflater layoutInflater; private String[] numbersInWords; private int[] numberImage; private ImageView imageView; private TextView textView; public MainAdapter(Context c, String[] numbersInWords,int[] numberImage){ context = c; this.numberImage = numberImage; this.numbersInWords = numbersInWords; } @Override public int getCount() { return numbersInWords.length; } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (layoutInflater==null) { layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } if (convertView==null){ convertView = layoutInflater.inflate(R.layout.rowitem, null); } imageView = convertView.findViewById(R.id.imageView); textView = convertView.findViewById(R.id.textView); imageView.setImageResource(numberImage[position]); textView.setText(numbersInWords[position]); return convertView; } } Step 6 – Create a new layout resource file(rowItem) and add the following code in rowitem.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" android:padding="24sp" android:gravity="center"> <ImageView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageView" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textView" android:text="Numbers" android:textSize="24sp" android:layout_marginTop="8dp" /> </LinearLayout> Step 7 - Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1257, "s": 1187, "text": "This example demonstrates how do I gridView layout in an android app." }, { "code": null, "e": 1386, "s": 1257, "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": 1451, "s": 1386, "text": "Step 2 βˆ’ Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1908, "s": 1451, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <GridView\n android:id=\"@+id/gridView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:numColumns=\"2\"/>\n</RelativeLayout>" }, { "code": null, "e": 1983, "s": 1908, "text": "Step 3 – Open build.gradle(Module: app) and add the following dependency βˆ’" }, { "code": null, "e": 2041, "s": 1983, "text": "implementation 'com.android.support:gridlayout-v7:28.0.0'" }, { "code": null, "e": 2098, "s": 2041, "text": "Step 4 βˆ’ Add the following code to src/MainActivity.java" }, { "code": null, "e": 3354, "s": 2098, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.GridView;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n GridView gridView;\n String[] numberInWords = {\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\"};\n int[] numberImage = {R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four,\n R.drawable.five,R.drawable.six,R.drawable.seven,R.drawable.eight,R.drawable.nine,\n R.drawable.ten};\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n gridView = findViewById(R.id.gridView);\n MainAdapter mainAdapter = new MainAdapter(MainActivity.this, numberInWords,numberImage);\n gridView.setAdapter(mainAdapter);\n gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {\n @Override\n public void onItemClick(AdapterView<?> parent, View view, int position, long id) {\n Toast.makeText(getApplicationContext(), \"You CLicked \" + numberInWords[+position],\n Toast.LENGTH_SHORT).show();\n }\n });\n }\n}" }, { "code": null, "e": 3406, "s": 3354, "text": "Step 5 – Add the following code to MainAdapter.java" }, { "code": null, "e": 4885, "s": 3406, "text": "import android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseAdapter;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nclass MainAdapter extends BaseAdapter {\n private Context context;\n private LayoutInflater layoutInflater;\n private String[] numbersInWords;\n private int[] numberImage;\n private ImageView imageView;\n private TextView textView;\n public MainAdapter(Context c, String[] numbersInWords,int[] numberImage){\n context = c;\n this.numberImage = numberImage;\n this.numbersInWords = numbersInWords;\n }\n @Override\n public int getCount() {\n return numbersInWords.length;\n }\n @Override\n public Object getItem(int position) {\n return null;\n }\n @Override\n public long getItemId(int position) {\n return 0;\n }\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n if (layoutInflater==null) {\n layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n }\n if (convertView==null){\n convertView = layoutInflater.inflate(R.layout.rowitem, null);\n }\n imageView = convertView.findViewById(R.id.imageView);\n textView = convertView.findViewById(R.id.textView);\n imageView.setImageResource(numberImage[position]);\n textView.setText(numbersInWords[position]);\n return convertView;\n }\n}" }, { "code": null, "e": 4979, "s": 4885, "text": "Step 6 – Create a new layout resource file(rowItem) and add the following code in rowitem.xml" }, { "code": null, "e": 5627, "s": 4979, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"vertical\"\n android:padding=\"24sp\"\n android:gravity=\"center\">\n <ImageView\n android:layout_width=\"100dp\"\n android:layout_height=\"100dp\"\n android:id=\"@+id/imageView\" />\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/textView\"\n android:text=\"Numbers\"\n android:textSize=\"24sp\"\n android:layout_marginTop=\"8dp\" />\n</LinearLayout>" }, { "code": null, "e": 5682, "s": 5627, "text": "Step 7 - Add the following code to androidManifest.xml" }, { "code": null, "e": 6355, "s": 5682, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6702, "s": 6355, "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": 6743, "s": 6702, "text": "Click here to download the project code." } ]
Scala | flatMap Method
29 Apr, 2019 In Scala, flatMap() method is identical to the map() method, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method. The output obtained by running the map method followed by the flatten method is same as obtained by the flatMap(). So, we can say that flatMap first runs the map method and then the flatten method to generate the desired result.Note: It has a built-in Option class as an Option can be expressed as a sequence which has at most one element i.e, either its empty or has only one element. The flatten() method is utilized to disintegrate the elements of a Scala collection in order to construct a single collection with the elements of similar type. Let’s see an example to illustrate, how the flatMap is working. val name = Seq("Nidhi", "Singh") Case 1:let’s apply map() and flatten() on the stated sequence. // Applying map()val result1 = name.map(_.toLowerCase) // OutputList(nidhi, singh) // Applying flatten() now,val result2 = result1.flatten // OutputList(n, i, d, h, i, s, i, n, g, h) Case 2:let’s apply flatMap() directly on the given sequence. name.flatMap(_.toLowerCase) // Output List(n, i, d, h, i, s, i, n, g, h) So, we can see here that the output obtained in both the cases is same therefore, we can say that flatMap is a combination of map and flatten method.Now, let’s see some examples of flatMap method. Utilizing flatMap on a sequence of Strings.Example:// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of strings val portal = Seq("Geeks", "for", "Geeks") // Applying flatMap val result = portal.flatMap(_.toUpperCase) // Displays output println(result) }}Output:List(G, E, E, K, S, F, O, R, G, E, E, K, S) Here, flatMap is applied to the stated sequence so, a list of sequence of characters is generated. // Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of strings val portal = Seq("Geeks", "for", "Geeks") // Applying flatMap val result = portal.flatMap(_.toUpperCase) // Displays output println(result) }} List(G, E, E, K, S, F, O, R, G, E, E, K, S) Here, flatMap is applied to the stated sequence so, a list of sequence of characters is generated. Applying flatMap with another functions.Example :// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list of numbers val list = List(2, 3, 4) // Defining a function def f(x:Int) = List(x-1, x, x+1) // Applying flatMap val result = list.flatMap(y => f(y)) // Displays output println(result) }}Output:List(1, 2, 3, 2, 3, 4, 3, 4, 5) Here, flatMap is applied on the another function defined in the program and so a list of sequence of numbers is generated. Let’s see how the output is computed.List(List(2-1, 2, 2+1), List(3-1, 3, 3+1), List(4-1, 4, 4+1)) // After evaluation we get, List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5)) So, first step works like applying map method on the another function stated.List(1, 2, 3, 2, 3, 4, 3, 4, 5) The second step works like applying flatten to the output obtained by the map method at the first step.Example :// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(4, 5, 6, 7) // Applying flatMap on another // function val result = seq flatMap { s => Seq(s, s-1) } // Displays output println(result) }}Output:List(4, 3, 5, 4, 6, 5, 7, 6) Here, also output is obtained like the first example of the flatMap with another functions. // Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list of numbers val list = List(2, 3, 4) // Defining a function def f(x:Int) = List(x-1, x, x+1) // Applying flatMap val result = list.flatMap(y => f(y)) // Displays output println(result) }} List(1, 2, 3, 2, 3, 4, 3, 4, 5) Here, flatMap is applied on the another function defined in the program and so a list of sequence of numbers is generated. Let’s see how the output is computed. List(List(2-1, 2, 2+1), List(3-1, 3, 3+1), List(4-1, 4, 4+1)) // After evaluation we get, List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5)) So, first step works like applying map method on the another function stated. List(1, 2, 3, 2, 3, 4, 3, 4, 5) The second step works like applying flatten to the output obtained by the map method at the first step.Example : // Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(4, 5, 6, 7) // Applying flatMap on another // function val result = seq flatMap { s => Seq(s, s-1) } // Displays output println(result) }} List(4, 3, 5, 4, 6, 5, 7, 6) Here, also output is obtained like the first example of the flatMap with another functions. Utilizing flatMap on if-else statements.Example :// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(8, 15, 22, 23, 24) // Applying flatMap on if-else // statement val result = seq flatMap { s => if (s % 3 == 0) Seq(s) else Seq(-s) } // Displays output println(result) }}Output:List(-8, 15, -22, -23, 24) Here, if an element of the sequence given satisfies the stated condition then that element is returned else negative of that element is obtained. // Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(8, 15, 22, 23, 24) // Applying flatMap on if-else // statement val result = seq flatMap { s => if (s % 3 == 0) Seq(s) else Seq(-s) } // Displays output println(result) }} List(-8, 15, -22, -23, 24) Here, if an element of the sequence given satisfies the stated condition then that element is returned else negative of that element is obtained. Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Apr, 2019" }, { "code": null, "e": 499, "s": 28, "text": "In Scala, flatMap() method is identical to the map() method, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method. The output obtained by running the map method followed by the flatten method is same as obtained by the flatMap(). So, we can say that flatMap first runs the map method and then the flatten method to generate the desired result.Note:" }, { "code": null, "e": 651, "s": 499, "text": "It has a built-in Option class as an Option can be expressed as a sequence which has at most one element i.e, either its empty or has only one element." }, { "code": null, "e": 812, "s": 651, "text": "The flatten() method is utilized to disintegrate the elements of a Scala collection in order to construct a single collection with the elements of similar type." }, { "code": null, "e": 876, "s": 812, "text": "Let’s see an example to illustrate, how the flatMap is working." }, { "code": null, "e": 910, "s": 876, "text": "val name = Seq(\"Nidhi\", \"Singh\")\n" }, { "code": null, "e": 973, "s": 910, "text": "Case 1:let’s apply map() and flatten() on the stated sequence." }, { "code": null, "e": 1028, "s": 973, "text": "// Applying map()val result1 = name.map(_.toLowerCase)" }, { "code": null, "e": 1056, "s": 1028, "text": "// OutputList(nidhi, singh)" }, { "code": null, "e": 1112, "s": 1056, "text": "// Applying flatten() now,val result2 = result1.flatten" }, { "code": null, "e": 1156, "s": 1112, "text": "// OutputList(n, i, d, h, i, s, i, n, g, h)" }, { "code": null, "e": 1217, "s": 1156, "text": "Case 2:let’s apply flatMap() directly on the given sequence." }, { "code": null, "e": 1293, "s": 1217, "text": "name.flatMap(_.toLowerCase)\n \n// Output\nList(n, i, d, h, i, s, i, n, g, h)\n" }, { "code": null, "e": 1490, "s": 1293, "text": "So, we can see here that the output obtained in both the cases is same therefore, we can say that flatMap is a combination of map and flatten method.Now, let’s see some examples of flatMap method." }, { "code": null, "e": 2037, "s": 1490, "text": "Utilizing flatMap on a sequence of Strings.Example:// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of strings val portal = Seq(\"Geeks\", \"for\", \"Geeks\") // Applying flatMap val result = portal.flatMap(_.toUpperCase) // Displays output println(result) }}Output:List(G, E, E, K, S, F, O, R, G, E, E, K, S)\nHere, flatMap is applied to the stated sequence so, a list of sequence of characters is generated." }, { "code": "// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of strings val portal = Seq(\"Geeks\", \"for\", \"Geeks\") // Applying flatMap val result = portal.flatMap(_.toUpperCase) // Displays output println(result) }}", "e": 2384, "s": 2037, "text": null }, { "code": null, "e": 2429, "s": 2384, "text": "List(G, E, E, K, S, F, O, R, G, E, E, K, S)\n" }, { "code": null, "e": 2528, "s": 2429, "text": "Here, flatMap is applied to the stated sequence so, a list of sequence of characters is generated." }, { "code": null, "e": 4050, "s": 2528, "text": "Applying flatMap with another functions.Example :// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list of numbers val list = List(2, 3, 4) // Defining a function def f(x:Int) = List(x-1, x, x+1) // Applying flatMap val result = list.flatMap(y => f(y)) // Displays output println(result) }}Output:List(1, 2, 3, 2, 3, 4, 3, 4, 5)\nHere, flatMap is applied on the another function defined in the program and so a list of sequence of numbers is generated. Let’s see how the output is computed.List(List(2-1, 2, 2+1), List(3-1, 3, 3+1), List(4-1, 4, 4+1))\n\n// After evaluation we get,\nList(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))\nSo, first step works like applying map method on the another function stated.List(1, 2, 3, 2, 3, 4, 3, 4, 5)\nThe second step works like applying flatten to the output obtained by the map method at the first step.Example :// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(4, 5, 6, 7) // Applying flatMap on another // function val result = seq flatMap { s => Seq(s, s-1) } // Displays output println(result) }}Output:List(4, 3, 5, 4, 6, 5, 7, 6)\nHere, also output is obtained like the first example of the flatMap with another functions." }, { "code": "// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a list of numbers val list = List(2, 3, 4) // Defining a function def f(x:Int) = List(x-1, x, x+1) // Applying flatMap val result = list.flatMap(y => f(y)) // Displays output println(result) }}", "e": 4442, "s": 4050, "text": null }, { "code": null, "e": 4475, "s": 4442, "text": "List(1, 2, 3, 2, 3, 4, 3, 4, 5)\n" }, { "code": null, "e": 4636, "s": 4475, "text": "Here, flatMap is applied on the another function defined in the program and so a list of sequence of numbers is generated. Let’s see how the output is computed." }, { "code": null, "e": 4778, "s": 4636, "text": "List(List(2-1, 2, 2+1), List(3-1, 3, 3+1), List(4-1, 4, 4+1))\n\n// After evaluation we get,\nList(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))\n" }, { "code": null, "e": 4856, "s": 4778, "text": "So, first step works like applying map method on the another function stated." }, { "code": null, "e": 4889, "s": 4856, "text": "List(1, 2, 3, 2, 3, 4, 3, 4, 5)\n" }, { "code": null, "e": 5002, "s": 4889, "text": "The second step works like applying flatten to the output obtained by the map method at the first step.Example :" }, { "code": "// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(4, 5, 6, 7) // Applying flatMap on another // function val result = seq flatMap { s => Seq(s, s-1) } // Displays output println(result) }}", "e": 5396, "s": 5002, "text": null }, { "code": null, "e": 5426, "s": 5396, "text": "List(4, 3, 5, 4, 6, 5, 7, 6)\n" }, { "code": null, "e": 5518, "s": 5426, "text": "Here, also output is obtained like the first example of the flatMap with another functions." }, { "code": null, "e": 6177, "s": 5518, "text": "Utilizing flatMap on if-else statements.Example :// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(8, 15, 22, 23, 24) // Applying flatMap on if-else // statement val result = seq flatMap { s => if (s % 3 == 0) Seq(s) else Seq(-s) } // Displays output println(result) }}Output:List(-8, 15, -22, -23, 24)\nHere, if an element of the sequence given satisfies the stated condition then that element is returned else negative of that element is obtained." }, { "code": "// Scala program of flatMap // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a sequence of numbers val seq = Seq(8, 15, 22, 23, 24) // Applying flatMap on if-else // statement val result = seq flatMap { s => if (s % 3 == 0) Seq(s) else Seq(-s) } // Displays output println(result) }}", "e": 6608, "s": 6177, "text": null }, { "code": null, "e": 6636, "s": 6608, "text": "List(-8, 15, -22, -23, 24)\n" }, { "code": null, "e": 6782, "s": 6636, "text": "Here, if an element of the sequence given satisfies the stated condition then that element is returned else negative of that element is obtained." }, { "code": null, "e": 6788, "s": 6782, "text": "Scala" }, { "code": null, "e": 6801, "s": 6788, "text": "Scala-Method" }, { "code": null, "e": 6807, "s": 6801, "text": "Scala" } ]
Change figure size and figure format in Matplotlib
Using the figsize attribute of figure(), we can change the figure size. To change the format of a figure, we can use the savefig method. Store the figure size in the variable. Store the figure size in the variable. Create a new figure, or activate an existing figure, with given figure size. Create a new figure, or activate an existing figure, with given figure size. Plot the line using x. Plot the line using x. Set the image title with its size. Set the image title with its size. Save the figure using savefig() method. Save the figure using savefig() method. from matplotlib import pyplot as plt figure_size = (10, 10) plt.figure(figsize=figure_size) x = [1, 2, 3] plt.plot(x, x) plt.title("Figure dimension is: {}".format(figure_size)) plt.savefig("imgae.png", format="png")
[ { "code": null, "e": 1199, "s": 1062, "text": "Using the figsize attribute of figure(), we can change the figure size. To change the format of a figure, we can use the savefig method." }, { "code": null, "e": 1238, "s": 1199, "text": "Store the figure size in the variable." }, { "code": null, "e": 1277, "s": 1238, "text": "Store the figure size in the variable." }, { "code": null, "e": 1354, "s": 1277, "text": "Create a new figure, or activate an existing figure, with given figure size." }, { "code": null, "e": 1431, "s": 1354, "text": "Create a new figure, or activate an existing figure, with given figure size." }, { "code": null, "e": 1454, "s": 1431, "text": "Plot the line using x." }, { "code": null, "e": 1477, "s": 1454, "text": "Plot the line using x." }, { "code": null, "e": 1512, "s": 1477, "text": "Set the image title with its size." }, { "code": null, "e": 1547, "s": 1512, "text": "Set the image title with its size." }, { "code": null, "e": 1587, "s": 1547, "text": "Save the figure using savefig() method." }, { "code": null, "e": 1627, "s": 1587, "text": "Save the figure using savefig() method." }, { "code": null, "e": 1845, "s": 1627, "text": "from matplotlib import pyplot as plt\n\nfigure_size = (10, 10)\nplt.figure(figsize=figure_size)\nx = [1, 2, 3]\nplt.plot(x, x)\nplt.title(\"Figure dimension is: {}\".format(figure_size))\nplt.savefig(\"imgae.png\", format=\"png\")" } ]
Python 3 - List extend() Method
The extend() method appends the contents of seq to list. Following is the syntax for extend() method βˆ’ list.extend(seq) seq βˆ’ This is the list of elements This method does not return any value but add the content to existing list. The following example shows the usage of extend() method. #!/usr/bin/python3 list1 = ['physics', 'chemistry', 'maths'] list2 = list(range(5)) #creates list of numbers between 0-4 list1.extend(list2) print ('Extended List :', list1) When we run above program, it produces the following result βˆ’ Extended List : ['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4] 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": 2397, "s": 2340, "text": "The extend() method appends the contents of seq to list." }, { "code": null, "e": 2443, "s": 2397, "text": "Following is the syntax for extend() method βˆ’" }, { "code": null, "e": 2461, "s": 2443, "text": "list.extend(seq)\n" }, { "code": null, "e": 2497, "s": 2461, "text": "seq βˆ’ This is the list of elements" }, { "code": null, "e": 2573, "s": 2497, "text": "This method does not return any value but add the content to existing list." }, { "code": null, "e": 2631, "s": 2573, "text": "The following example shows the usage of extend() method." }, { "code": null, "e": 2810, "s": 2631, "text": "#!/usr/bin/python3\n\nlist1 = ['physics', 'chemistry', 'maths']\nlist2 = list(range(5)) #creates list of numbers between 0-4\nlist1.extend(list2)\nprint ('Extended List :', list1)" }, { "code": null, "e": 2872, "s": 2810, "text": "When we run above program, it produces the following result βˆ’" }, { "code": null, "e": 2939, "s": 2872, "text": "Extended List : ['physics', 'chemistry', 'maths', 0, 1, 2, 3, 4]\n" }, { "code": null, "e": 2976, "s": 2939, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 2992, "s": 2976, "text": " Malhar Lathkar" }, { "code": null, "e": 3025, "s": 2992, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3044, "s": 3025, "text": " Arnab Chakraborty" }, { "code": null, "e": 3079, "s": 3044, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3101, "s": 3079, "text": " In28Minutes Official" }, { "code": null, "e": 3135, "s": 3101, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3163, "s": 3135, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3198, "s": 3163, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3212, "s": 3198, "text": " Lets Kode It" }, { "code": null, "e": 3245, "s": 3212, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3262, "s": 3245, "text": " Abhilash Nelson" }, { "code": null, "e": 3269, "s": 3262, "text": " Print" }, { "code": null, "e": 3280, "s": 3269, "text": " Add Notes" } ]
How can I delete an item from an Object in MongoDB?
To delete an item from an object in MongoDB, use $unset. Let us create a collection with documents βˆ’ > db.demo467.insertOne( ... { ... _id:101, ... "Information":{"Name":"Chris"} ... } ... ); { "acknowledged" : true, "insertedId" : 101 } > db.demo467.insertOne( ... { ... _id:102, ... "Information":{"Name":"David"} ... } ... ); { "acknowledged" : true, "insertedId" : 102 } Display all documents from a collection with the help of find() method βˆ’ > db.demo467.find(); This will produce the following output βˆ’ { "_id" : 101, "Information" : { "Name" : "Chris" } } { "_id" : 102, "Information" : { "Name" : "David" } } Following is the query to delete an item from an Object βˆ’ > db.demo467.update({_id:102},{$unset: {"Information.Name":1}},{multi: true}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method βˆ’ > db.demo467.find(); This will produce the following output βˆ’ { "_id" : 101, "Information" : { "Name" : "Chris" } } { "_id" : 102, "Information" : { } }
[ { "code": null, "e": 1163, "s": 1062, "text": "To delete an item from an object in MongoDB, use $unset. Let us create a collection with documents βˆ’" }, { "code": null, "e": 1437, "s": 1163, "text": "> db.demo467.insertOne(\n... {\n... _id:101,\n... \"Information\":{\"Name\":\"Chris\"}\n... }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : 101 }\n> db.demo467.insertOne(\n... {\n... _id:102,\n... \"Information\":{\"Name\":\"David\"}\n... }\n... );\n{ \"acknowledged\" : true, \"insertedId\" : 102 }" }, { "code": null, "e": 1510, "s": 1437, "text": "Display all documents from a collection with the help of find() method βˆ’" }, { "code": null, "e": 1531, "s": 1510, "text": "> db.demo467.find();" }, { "code": null, "e": 1572, "s": 1531, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 1680, "s": 1572, "text": "{ \"_id\" : 101, \"Information\" : { \"Name\" : \"Chris\" } }\n{ \"_id\" : 102, \"Information\" : { \"Name\" : \"David\" } }" }, { "code": null, "e": 1738, "s": 1680, "text": "Following is the query to delete an item from an Object βˆ’" }, { "code": null, "e": 1883, "s": 1738, "text": "> db.demo467.update({_id:102},{$unset: {\"Information.Name\":1}},{multi: true});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 1956, "s": 1883, "text": "Display all documents from a collection with the help of find() method βˆ’" }, { "code": null, "e": 1977, "s": 1956, "text": "> db.demo467.find();" }, { "code": null, "e": 2018, "s": 1977, "text": "This will produce the following output βˆ’" }, { "code": null, "e": 2109, "s": 2018, "text": "{ \"_id\" : 101, \"Information\" : { \"Name\" : \"Chris\" } }\n{ \"_id\" : 102, \"Information\" : { } }" } ]
Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers
When it is required to create a class to get all the possible subsets of integers from a list, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations. Below is a demonstration for the same βˆ’ Live Demo class get_subset: def sort_list(self, my_list): return self. subset_find([], sorted(my_list)) def subset_find(self, curr, my_list): if my_list: return self. subset_find(curr, my_list[1:]) + self. subset_find(curr + [my_list[0]], my_list[1:]) return [curr] my_list = [] num_elem = int(input("Enter the number of elements in the list.. ")) for i in range(0,num_elem): elem=int(input("Enter the element..")) my_list.append(elem) print("Subsets of the list are : ") print(get_subset().sort_list(my_list)) Enter the number of elements in the list.. 3 Enter the element..45 Enter the element..12 Enter the element..67 Subsets of the list are : [[], [67], [45], [45, 67], [12], [12, 67], [12, 45], [12, 45, 67]] A class named β€˜get_subset’ class is defined, that has functions like β€˜sort_list’, and β€˜subset_find’. These are used to perform operations such as sort the list, and get all the possible subsets from the list data respectively. An instance of this class is created. The list data is entered, and operations are performed on it. Relevant messages and output is displayed on the console.
[ { "code": null, "e": 1413, "s": 1062, "text": "When it is required to create a class to get all the possible subsets of integers from a list, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform calculator operations." }, { "code": null, "e": 1453, "s": 1413, "text": "Below is a demonstration for the same βˆ’" }, { "code": null, "e": 1464, "s": 1453, "text": " Live Demo" }, { "code": null, "e": 2004, "s": 1464, "text": "class get_subset:\n def sort_list(self, my_list):\n return self. subset_find([], sorted(my_list))\n def subset_find(self, curr, my_list):\n if my_list:\n return self. subset_find(curr, my_list[1:]) + self. subset_find(curr + [my_list[0]], my_list[1:])\n return [curr]\nmy_list = []\nnum_elem = int(input(\"Enter the number of elements in the list.. \"))\nfor i in range(0,num_elem):\n elem=int(input(\"Enter the element..\"))\n my_list.append(elem)\nprint(\"Subsets of the list are : \")\nprint(get_subset().sort_list(my_list))" }, { "code": null, "e": 2208, "s": 2004, "text": "Enter the number of elements in the list.. 3\nEnter the element..45\nEnter the element..12\nEnter the element..67\nSubsets of the list are :\n[[], [67], [45], [45, 67], [12], [12, 67], [12, 45], [12, 45, 67]]" }, { "code": null, "e": 2309, "s": 2208, "text": "A class named β€˜get_subset’ class is defined, that has functions like β€˜sort_list’, and β€˜subset_find’." }, { "code": null, "e": 2435, "s": 2309, "text": "These are used to perform operations such as sort the list, and get all the possible subsets from the list data respectively." }, { "code": null, "e": 2473, "s": 2435, "text": "An instance of this class is created." }, { "code": null, "e": 2535, "s": 2473, "text": "The list data is entered, and operations are performed on it." }, { "code": null, "e": 2593, "s": 2535, "text": "Relevant messages and output is displayed on the console." } ]
C# | TrimStart() and TrimEnd() Method - GeeksforGeeks
10 Jul, 2021 In C#, TrimStart() & TrimEnd() are the string methods. TrimStart() method is used to remove the occurrences of a set of characters specified in an array from the starting of the current String object. TrimEnd() method is used to remove the occurrences of a set of characters specified in an array from the ending of the current String object. Syntax for TrimStart() Method : public string TrimStart(params char[] trimChars) Syntax for TrimEnd() Method : public string TrimEnd(params char[] trimChars) Explanation: Both the method will take an array of Unicode characters or null as a parameter. Null is because of params keyword. And the return type value for both the methods is System.String. Below are the programs to demonstrate the above methods : Example 1: Program to demonstrate the public string TrimStart(params char[] trimChars) method. This method removes all leading white-space characters from the current string object. Each leading trim operation stops when a non-white-space character is encountered. For example, if the current string is β€œ*****0000abc000****” and trimChars contains the β€œ*” and β€œ0”, then TrimStart method returns β€œabc000****”. C# // C# program to illustrate the// TrimStart() methodusing System; class GFG { // Main Method public static void Main() { // string to be trimmed string s1 = "*****0000abc000****"; char[] charsToTrim1 = { '*', '0' }; // string to be trimmed string s2 = " abc"; string s3 = " -GFG-"; string s4 = " GeeksforGeeks"; // Before TrimStart method call Console.WriteLine("Before:"); Console.WriteLine(s1); Console.WriteLine(s2); Console.WriteLine(s3); Console.WriteLine(s4); Console.WriteLine(""); // After TrimStart method call Console.WriteLine("After:"); // argument as char array Console.WriteLine(s1.TrimStart(charsToTrim1)); // if there is no argument then it // takes default as null, ' ', // '\t', '\r' Console.WriteLine(s2.TrimStart()); // White space is not remove Console.WriteLine(s3.TrimStart('-')); // not take char array but Argument only character Console.WriteLine(s4.TrimStart(' ', 'G', 'e', 'k', 's')); }} Before: *****0000abc000**** abc -GFG- GeeksforGeeks After: abc000**** abc -GFG- forGeeks Example 2: Program to demonstrate the public string TrimEnd(params char[] trimChars) method. This method removes all trailing characters which are present in the parameter list. Each trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is β€œ*****0000abc000****” and trimChars contains the β€œ*” and β€œ0”, then TrimEnd method returns β€œ*****0000abc”. C# // C# program to illustrate the// TrimEnd() methodusing System; class GFG { // Main Method public static void Main() { // String to be trimmed string s1 = "*****0000abc000****"; char[] charsToTrim1 = { '*', '0'}; // string to be trimmed string s2 = "abc "; string s3 = " -GFG- "; string s4 = " GeeksforGeeks"; // Before TrimEnd method call Console.WriteLine("Before:"); Console.WriteLine(s1); Console.WriteLine(s2); Console.WriteLine(s3); Console.WriteLine(s4); Console.WriteLine(""); // After TrimEnd method call Console.WriteLine("After:"); // argument as char array Console.WriteLine(s1.TrimEnd(charsToTrim1)); // if there is no argument then it // takes default as null, ' ', // '\t', '\r' Console.WriteLine(s2.TrimEnd()); // White space is not remove Console.WriteLine(s3.TrimEnd('-')); // not take char array but // Argument only character Console.WriteLine(s4.TrimEnd(' ','G','e','k','s')); }} Before: *****0000abc000**** abc -GFG- GeeksforGeeks After: *****0000abc abc -GFG- Geeksfor Note: If no parameter will pass in both the method’s arguments list then Null , TAB, Carriage Return and White Space will automatically remove from starting(for TrimStart() method) and ending(for TrimEnd() method) from the current string object. And If any parameter will pass to both the methods then the only specified character(which passed as arguments) will removed from the current string object. Null, TAB, Carriage Return, and White Space will not remove automatically if they are not specified in the arguments list of both the methods. References: https://msdn.microsoft.com/en-us/library/system.string.trimstart https://msdn.microsoft.com/en-us/library/system.string.trimend rajeev0719singh CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object Difference between Ref and Out keywords in C# C# | Constructors Introduction to .NET Framework Extension Method in C# C# | Delegates C# | Abstract Classes C# | Data Types
[ { "code": null, "e": 24436, "s": 24408, "text": "\n10 Jul, 2021" }, { "code": null, "e": 24780, "s": 24436, "text": "In C#, TrimStart() & TrimEnd() are the string methods. TrimStart() method is used to remove the occurrences of a set of characters specified in an array from the starting of the current String object. TrimEnd() method is used to remove the occurrences of a set of characters specified in an array from the ending of the current String object. " }, { "code": null, "e": 24812, "s": 24780, "text": "Syntax for TrimStart() Method :" }, { "code": null, "e": 24861, "s": 24812, "text": "public string TrimStart(params char[] trimChars)" }, { "code": null, "e": 24891, "s": 24861, "text": "Syntax for TrimEnd() Method :" }, { "code": null, "e": 24938, "s": 24891, "text": "public string TrimEnd(params char[] trimChars)" }, { "code": null, "e": 25132, "s": 24938, "text": "Explanation: Both the method will take an array of Unicode characters or null as a parameter. Null is because of params keyword. And the return type value for both the methods is System.String." }, { "code": null, "e": 25192, "s": 25132, "text": "Below are the programs to demonstrate the above methods : " }, { "code": null, "e": 25601, "s": 25192, "text": "Example 1: Program to demonstrate the public string TrimStart(params char[] trimChars) method. This method removes all leading white-space characters from the current string object. Each leading trim operation stops when a non-white-space character is encountered. For example, if the current string is β€œ*****0000abc000****” and trimChars contains the β€œ*” and β€œ0”, then TrimStart method returns β€œabc000****”." }, { "code": null, "e": 25604, "s": 25601, "text": "C#" }, { "code": "// C# program to illustrate the// TrimStart() methodusing System; class GFG { // Main Method public static void Main() { // string to be trimmed string s1 = \"*****0000abc000****\"; char[] charsToTrim1 = { '*', '0' }; // string to be trimmed string s2 = \" abc\"; string s3 = \" -GFG-\"; string s4 = \" GeeksforGeeks\"; // Before TrimStart method call Console.WriteLine(\"Before:\"); Console.WriteLine(s1); Console.WriteLine(s2); Console.WriteLine(s3); Console.WriteLine(s4); Console.WriteLine(\"\"); // After TrimStart method call Console.WriteLine(\"After:\"); // argument as char array Console.WriteLine(s1.TrimStart(charsToTrim1)); // if there is no argument then it // takes default as null, ' ', // '\\t', '\\r' Console.WriteLine(s2.TrimStart()); // White space is not remove Console.WriteLine(s3.TrimStart('-')); // not take char array but Argument only character Console.WriteLine(s4.TrimStart(' ', 'G', 'e', 'k', 's')); }}", "e": 26728, "s": 25604, "text": null }, { "code": null, "e": 26826, "s": 26728, "text": "Before:\n*****0000abc000****\n abc\n -GFG-\n GeeksforGeeks\n\nAfter:\nabc000****\nabc\n -GFG-\nforGeeks" }, { "code": null, "e": 27234, "s": 26828, "text": "Example 2: Program to demonstrate the public string TrimEnd(params char[] trimChars) method. This method removes all trailing characters which are present in the parameter list. Each trailing trim operation stops when a non-white-space character is encountered. For example, if the current string is β€œ*****0000abc000****” and trimChars contains the β€œ*” and β€œ0”, then TrimEnd method returns β€œ*****0000abc”." }, { "code": null, "e": 27237, "s": 27234, "text": "C#" }, { "code": "// C# program to illustrate the// TrimEnd() methodusing System; class GFG { // Main Method public static void Main() { // String to be trimmed string s1 = \"*****0000abc000****\"; char[] charsToTrim1 = { '*', '0'}; // string to be trimmed string s2 = \"abc \"; string s3 = \" -GFG- \"; string s4 = \" GeeksforGeeks\"; // Before TrimEnd method call Console.WriteLine(\"Before:\"); Console.WriteLine(s1); Console.WriteLine(s2); Console.WriteLine(s3); Console.WriteLine(s4); Console.WriteLine(\"\"); // After TrimEnd method call Console.WriteLine(\"After:\"); // argument as char array Console.WriteLine(s1.TrimEnd(charsToTrim1)); // if there is no argument then it // takes default as null, ' ', // '\\t', '\\r' Console.WriteLine(s2.TrimEnd()); // White space is not remove Console.WriteLine(s3.TrimEnd('-')); // not take char array but // Argument only character Console.WriteLine(s4.TrimEnd(' ','G','e','k','s')); }}", "e": 28458, "s": 27237, "text": null }, { "code": null, "e": 28564, "s": 28458, "text": "Before:\n*****0000abc000****\nabc \n -GFG- \n GeeksforGeeks\n\nAfter:\n*****0000abc\nabc\n -GFG- \n Geeksfor" }, { "code": null, "e": 29112, "s": 28566, "text": "Note: If no parameter will pass in both the method’s arguments list then Null , TAB, Carriage Return and White Space will automatically remove from starting(for TrimStart() method) and ending(for TrimEnd() method) from the current string object. And If any parameter will pass to both the methods then the only specified character(which passed as arguments) will removed from the current string object. Null, TAB, Carriage Return, and White Space will not remove automatically if they are not specified in the arguments list of both the methods." }, { "code": null, "e": 29126, "s": 29112, "text": "References: " }, { "code": null, "e": 29191, "s": 29126, "text": "https://msdn.microsoft.com/en-us/library/system.string.trimstart" }, { "code": null, "e": 29254, "s": 29191, "text": "https://msdn.microsoft.com/en-us/library/system.string.trimend" }, { "code": null, "e": 29272, "s": 29256, "text": "rajeev0719singh" }, { "code": null, "e": 29286, "s": 29272, "text": "CSharp-method" }, { "code": null, "e": 29300, "s": 29286, "text": "CSharp-string" }, { "code": null, "e": 29303, "s": 29300, "text": "C#" }, { "code": null, "e": 29401, "s": 29303, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29410, "s": 29401, "text": "Comments" }, { "code": null, "e": 29423, "s": 29410, "text": "Old Comments" }, { "code": null, "e": 29451, "s": 29423, "text": "C# Dictionary with examples" }, { "code": null, "e": 29474, "s": 29451, "text": "C# | Method Overriding" }, { "code": null, "e": 29496, "s": 29474, "text": "C# | Class and Object" }, { "code": null, "e": 29542, "s": 29496, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 29560, "s": 29542, "text": "C# | Constructors" }, { "code": null, "e": 29591, "s": 29560, "text": "Introduction to .NET Framework" }, { "code": null, "e": 29614, "s": 29591, "text": "Extension Method in C#" }, { "code": null, "e": 29629, "s": 29614, "text": "C# | Delegates" }, { "code": null, "e": 29651, "s": 29629, "text": "C# | Abstract Classes" } ]
C++ Program to Create a Random Graph Using Random Edge Generation
In this program a random graph is generated for random vertices and edges. The time complexity of this program is O(v * e). Where v is the number of vertices and e is the number of edges. Begin Develop a function GenRandomGraphs(), with β€˜e’ as the number of edges and β€˜v’ as the number of vertexes, in the argument list. Assign random values to the number of vertex and edges of the graph, using rand() function. Print the connections of each vertex, irrespective of the direction. Print β€œIsolated vertex” for the vertex having no degree. End #include<iostream> #include<stdlib.h> using namespace std; void GenRandomGraphs(int NOEdge, int NOVertex) { int i, j, edge[NOEdge][2], count; i = 0; //Assign random values to the number of vertex and edges of the graph, Using rand(). while(i < NOEdge) { edge[i][0] = rand()%NOVertex+1; edge[i][1] = rand()%NOVertex+1; //Print the connections of each vertex, irrespective of the direction. if(edge[i][0] == edge[i][1]) continue; else { for(j = 0; j < i; j++) { if((edge[i][0] == edge[j][0] && edge[i][1] == edge[j][1]) || (edge[i][0] == edge[j][1] && edge[i][1] == edge[j][0])) i--; } }i ++; } cout<<"\nThe generated random graph is: "; for(i = 0; i < NOVertex; i++) { count = 0; cout<<"\n\t"<<i+1<<"-> { "; for(j = 0; j < NOEdge; j++) { if(edge[j][0] == i+1) { cout<<edge[j][1]<<" "; count++; } else if(edge[j][1] == i+1) { cout<<edge[j][0]<<" "; count++; } else if(j== NOEdge-1 && count == 0) cout<<"Isolated Vertex!"; //Print β€œIsolated vertex” for the vertex having no degree. } cout<<" }"; } } int main() { int i, e, n; cout<<"Random graph generation: "; n= 7 + rand()%6; cout<<"\nThe graph has "<<n<<" vertices"; e = rand()%((n*(n-1))/2); cout<<"\nand has "<<e<<" edges."; GenRandomGraphs(e, n); } Random graph generation: The graph has 8 vertices and has 18 edges. The generated random graph is: 1-> { 5 4 2 } 2-> { 4 8 6 3 1 5 } 3-> { 5 4 7 2 } 4-> { 2 3 7 1 8 5 } 5-> { 3 1 7 4 2 8 } 6-> { 2 8 7 } 7-> { 4 3 5 6 } 8-> { 2 6 4 5 }
[ { "code": null, "e": 1250, "s": 1062, "text": "In this program a random graph is generated for random vertices and edges. The time complexity of this program is O(v * e). Where v is the number of vertices and e is the number of edges." }, { "code": null, "e": 1638, "s": 1250, "text": "Begin\n Develop a function GenRandomGraphs(), with β€˜e’ as the\n number of edges and β€˜v’ as the number of vertexes, in the argument list.\n Assign random values to the number of vertex and edges of the graph,\n using rand() function.\n Print the connections of each vertex, irrespective of the\n direction.\n Print β€œIsolated vertex” for the vertex having no degree.\nEnd" }, { "code": null, "e": 3170, "s": 1638, "text": "#include<iostream>\n#include<stdlib.h>\nusing namespace std;\nvoid GenRandomGraphs(int NOEdge, int NOVertex)\n{\n int i, j, edge[NOEdge][2], count;\n i = 0;\n //Assign random values to the number of vertex and edges\n of the graph, Using rand().\n while(i < NOEdge)\n {\n edge[i][0] = rand()%NOVertex+1;\n edge[i][1] = rand()%NOVertex+1;\n //Print the connections of each vertex, irrespective of\n the direction.\n if(edge[i][0] == edge[i][1])\n continue;\n else\n {\n for(j = 0; j < i; j++)\n {\n if((edge[i][0] == edge[j][0] &&\n edge[i][1] == edge[j][1]) || (edge[i][0] == edge[j][1] &&\n edge[i][1] == edge[j][0]))\n i--;\n }\n }i\n ++;\n }\n cout<<\"\\nThe generated random graph is: \";\n for(i = 0; i < NOVertex; i++)\n {\n count = 0;\n cout<<\"\\n\\t\"<<i+1<<\"-> { \";\n for(j = 0; j < NOEdge; j++)\n {\n if(edge[j][0] == i+1)\n {\n cout<<edge[j][1]<<\" \";\n count++;\n } else if(edge[j][1] == i+1)\n {\n cout<<edge[j][0]<<\" \";\n count++;\n } else if(j== NOEdge-1 && count == 0)\n cout<<\"Isolated Vertex!\"; //Print β€œIsolated vertex” for the vertex having no degree.\n }\n cout<<\" }\";\n }\n}\nint main()\n{\n int i, e, n;\n cout<<\"Random graph generation: \";\n n= 7 + rand()%6;\n cout<<\"\\nThe graph has \"<<n<<\" vertices\";\n e = rand()%((n*(n-1))/2);\n cout<<\"\\nand has \"<<e<<\" edges.\";\n GenRandomGraphs(e, n);\n}" }, { "code": null, "e": 3405, "s": 3170, "text": "Random graph generation:\nThe graph has 8 vertices\nand has 18 edges.\nThe generated random graph is:\n1-> { 5 4 2 }\n2-> { 4 8 6 3 1 5 }\n3-> { 5 4 7 2 }\n4-> { 2 3 7 1 8 5 }\n5-> { 3 1 7 4 2 8 }\n6-> { 2 8 7 }\n7-> { 4 3 5 6 }\n8-> { 2 6 4 5 }" } ]
Find Maximum difference pair in Python
Data analysis can throw a variety of challenges. In this article we will take a list with numbers as its elements. Then we will find such pairs of elements in the list which has maximum difference in value between them. The approach here is to first find out all possible combinations of elements and then subtract the second element from the first. Finally apply the nlargest function form heapq module to get those pairs where the difference is maximum. Live Demo from itertools import combinations from heapq import nlargest listA = [21, 14, 30, 11, 17, 18] # Given list print("Given list : ",listA) # using nlargest and combinations() res = nlargest(2, combinations(listA, 2), key=lambda sub: abs(sub[0] - sub[1])) # print result print("Pairs with maximum difference are : ",res) Running the above code gives us the following result βˆ’ Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : [(30, 11), (14, 30)] Here we also take the same approach as above but we get one pair as a result because we apply the max function which gives us one pair as the result. Live Demo from itertools import combinations listA = [21, 14, 30, 11, 17, 18] # Given list print("Given list : ",listA) # using combinations() and lambda res = max(combinations(listA, 2), key = lambda sub: abs(sub[0]-sub[1])) # print result print("Pairs with maximum difference are : ",res) Running the above code gives us the following result βˆ’ Given list : [21, 14, 30, 11, 17, 18] Pairs with maximum difference are : (30, 11)
[ { "code": null, "e": 1282, "s": 1062, "text": "Data analysis can throw a variety of challenges. In this article we will take a list with numbers as its elements. Then we will find such pairs of elements in the list which has maximum difference in value between them." }, { "code": null, "e": 1518, "s": 1282, "text": "The approach here is to first find out all possible combinations of elements and then subtract the second element from the first. Finally apply the nlargest function form heapq module to get those pairs where the difference is maximum." }, { "code": null, "e": 1529, "s": 1518, "text": " Live Demo" }, { "code": null, "e": 1867, "s": 1529, "text": "from itertools import combinations\nfrom heapq import nlargest\n\nlistA = [21, 14, 30, 11, 17, 18]\n\n# Given list\nprint(\"Given list : \",listA)\n\n# using nlargest and combinations()\nres = nlargest(2, combinations(listA, 2),\n key=lambda sub: abs(sub[0] - sub[1]))\n\n# print result\nprint(\"Pairs with maximum difference are : \",res)\n" }, { "code": null, "e": 1922, "s": 1867, "text": "Running the above code gives us the following result βˆ’" }, { "code": null, "e": 2017, "s": 1922, "text": "Given list : [21, 14, 30, 11, 17, 18]\nPairs with maximum difference are : [(30, 11), (14, 30)]" }, { "code": null, "e": 2167, "s": 2017, "text": "Here we also take the same approach as above but we get one pair as a result because we apply the max function which gives us one pair as the result." }, { "code": null, "e": 2178, "s": 2167, "text": " Live Demo" }, { "code": null, "e": 2463, "s": 2178, "text": "from itertools import combinations\n\nlistA = [21, 14, 30, 11, 17, 18]\n\n# Given list\nprint(\"Given list : \",listA)\n\n# using combinations() and lambda\nres = max(combinations(listA, 2), key = lambda sub: abs(sub[0]-sub[1]))\n\n# print result\nprint(\"Pairs with maximum difference are : \",res)" }, { "code": null, "e": 2518, "s": 2463, "text": "Running the above code gives us the following result βˆ’" }, { "code": null, "e": 2601, "s": 2518, "text": "Given list : [21, 14, 30, 11, 17, 18]\nPairs with maximum difference are : (30, 11)" } ]
Cassandra - Drop Table
You can drop a table using the command Drop Table. Its syntax is as follows βˆ’ DROP TABLE <tablename> The following code drops an existing table from a KeySpace. cqlsh:tutorialspoint> DROP TABLE emp; Use the Describe command to verify whether the table is deleted or not. Since the emp table has been deleted, you will not find it in the column families list. cqlsh:tutorialspoint> DESCRIBE COLUMNFAMILIES; employee You can delete a table using the execute() method of Session class. Follow the steps given below to delete a table using Java API. First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below βˆ’ //Creating Cluster.Builder object Cluster.Builder builder1 = Cluster.builder(); Add a contact point (IP address of the node) using addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder. //Adding contact point to the Cluster.Builder object Cluster.Builder builder2 = build.addContactPoint( "127.0.0.1" ); Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object. //Building a cluster Cluster cluster = builder.build(); You can build a cluster object using a single line of code as shown below. Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); Create an instance of Session object using the connect() method of Cluster class as shown below. Session session = cluster.connect( ); This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the KeySpace name in string format to this method as shown below. Session session = cluster.connect(β€œYour keyspace name”); Here we are using the keyspace named tp. Therefore, create the session object as shown below. Session session = cluster.connect(β€œtp”); You can execute CQL queries using execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh. In the following example, we are deleting a table named emp. You have to store the query in a string variable and pass it to the execute() method as shown below. // Query String query = "DROP TABLE emp1;”; session.execute(query); Given below is the complete program to drop a table in Cassandra using Java API. import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class Drop_Table { public static void main(String args[]){ //Query String query = "DROP TABLE emp1;"; Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build(); //Creating Session object Session session = cluster.connect("tp"); //Executing the query session.execute(query); System.out.println("Table dropped"); } } Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below. $javac Drop_Table.java $java Drop_Table Under normal conditions, it should produce the following output βˆ’ Table dropped 27 Lectures 2 hours Navdeep Kaur 34 Lectures 1.5 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2365, "s": 2287, "text": "You can drop a table using the command Drop Table. Its syntax is as follows βˆ’" }, { "code": null, "e": 2389, "s": 2365, "text": "DROP TABLE <tablename>\n" }, { "code": null, "e": 2449, "s": 2389, "text": "The following code drops an existing table from a KeySpace." }, { "code": null, "e": 2488, "s": 2449, "text": "cqlsh:tutorialspoint> DROP TABLE emp;\n" }, { "code": null, "e": 2648, "s": 2488, "text": "Use the Describe command to verify whether the table is deleted or not. Since the emp table has been deleted, you will not find it in the column families list." }, { "code": null, "e": 2705, "s": 2648, "text": "cqlsh:tutorialspoint> DESCRIBE COLUMNFAMILIES;\nemployee\n" }, { "code": null, "e": 2836, "s": 2705, "text": "You can delete a table using the execute() method of Session class. Follow the steps given below to delete a table using Java API." }, { "code": null, "e": 2947, "s": 2836, "text": "First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below βˆ’" }, { "code": null, "e": 3028, "s": 2947, "text": "//Creating Cluster.Builder object\nCluster.Builder builder1 = Cluster.builder();\n" }, { "code": null, "e": 3168, "s": 3028, "text": "Add a contact point (IP address of the node) using addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder." }, { "code": null, "e": 3287, "s": 3168, "text": "//Adding contact point to the Cluster.Builder object\nCluster.Builder builder2 = build.addContactPoint( \"127.0.0.1\" );\n" }, { "code": null, "e": 3472, "s": 3287, "text": "Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object." }, { "code": null, "e": 3529, "s": 3472, "text": "//Building a cluster\nCluster cluster = builder.build();\n" }, { "code": null, "e": 3604, "s": 3529, "text": "You can build a cluster object using a single line of code as shown below." }, { "code": null, "e": 3679, "s": 3604, "text": "Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n" }, { "code": null, "e": 3776, "s": 3679, "text": "Create an instance of Session object using the connect() method of Cluster class\nas shown below." }, { "code": null, "e": 3815, "s": 3776, "text": "Session session = cluster.connect( );\n" }, { "code": null, "e": 4013, "s": 3815, "text": "This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the KeySpace name in string format to this method as shown below." }, { "code": null, "e": 4071, "s": 4013, "text": "Session session = cluster.connect(β€œYour keyspace name”);\n" }, { "code": null, "e": 4165, "s": 4071, "text": "Here we are using the keyspace named tp. Therefore, create the session object as shown below." }, { "code": null, "e": 4207, "s": 4165, "text": "Session session = cluster.connect(β€œtp”);\n" }, { "code": null, "e": 4452, "s": 4207, "text": "You can execute CQL queries using execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh." }, { "code": null, "e": 4614, "s": 4452, "text": "In the following example, we are deleting a table named emp. You have to store the query in a string variable and pass it to the execute() method as shown below." }, { "code": null, "e": 4684, "s": 4614, "text": "// Query\n\nString query = \"DROP TABLE emp1;”;\nsession.execute(query);\n" }, { "code": null, "e": 4765, "s": 4684, "text": "Given below is the complete program to drop a table in Cassandra using Java API." }, { "code": null, "e": 5256, "s": 4765, "text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n \npublic class Drop_Table {\n\n public static void main(String args[]){\n\n //Query\n String query = \"DROP TABLE emp1;\";\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n \n //Creating Session object\n Session session = cluster.connect(\"tp\");\n \n //Executing the query\n session.execute(query);\n \n System.out.println(\"Table dropped\");\n }\n}" }, { "code": null, "e": 5408, "s": 5256, "text": "Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below." }, { "code": null, "e": 5449, "s": 5408, "text": "$javac Drop_Table.java\n$java Drop_Table\n" }, { "code": null, "e": 5515, "s": 5449, "text": "Under normal conditions, it should produce the following output βˆ’" }, { "code": null, "e": 5530, "s": 5515, "text": "Table dropped\n" }, { "code": null, "e": 5563, "s": 5530, "text": "\n 27 Lectures \n 2 hours \n" }, { "code": null, "e": 5577, "s": 5563, "text": " Navdeep Kaur" }, { "code": null, "e": 5612, "s": 5577, "text": "\n 34 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5630, "s": 5612, "text": " Bigdata Engineer" }, { "code": null, "e": 5637, "s": 5630, "text": " Print" }, { "code": null, "e": 5648, "s": 5637, "text": " Add Notes" } ]