title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Spring Boot Redis Data Example CRUD Operations - 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
In this tutorial, I am going to introduce the most popular in-memory data store spring boot redis.
In the previous tutorial, we discussed what redis is and how to install redis server on windows 10 operating system. We also talk about rediscli and done some of the basic operations on both the redis server and rediscli.
As part of this article, I am going to implement a simple spring boot data redis application with necessary CRUD operations. To make this application up and running, initially, you should have redis server setup in your local and it should be in running mode.
To define the connection settings from the application client to Redis server, we need a redis client which will be helpful to interact with redis server; it is something similar like JdbcTemplate to connect with the SQL server.
There are several redis client implementations available in the market for Java. For this tutorial, I choose Jedis – A simple and powerful implementation for redis client.
A simple example to understand Spring boot data redis.
Spring Boot 2.0.5
Spring Boot Data Redis
Redis server 2.4.5
Jedis
Java8
Maven
Below are the redis and Jedis maven dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.3</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>SpringBoot-Redis-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>SpringBoot-Redis-Example</name>
<description>Spring Boot Redis Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Creating a simple rest controller to provide CRUD endpoints
package com.onlinetutorialspoint.controller;
import com.onlinetutorialspoint.model.Item;
import com.onlinetutorialspoint.repo.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Map;
@RestController
public class ItemController {
@Autowired
ItemRepository itemRepo;
@RequestMapping("/getAllItems")
@ResponseBody
public ResponseEntity<Map<Integer,Item>> getAllItems(){
Map<Integer,Item> items = itemRepo.getAllItems();
return new ResponseEntity<Map<Integer,Item>>(items, HttpStatus.OK);
}
@GetMapping("/item/{itemId}")
@ResponseBody
public ResponseEntity<Item> getItem(@PathVariable int itemId){
Item item = itemRepo.getItem(itemId);
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
@PostMapping(value = "/addItem",consumes = {"application/json"},produces = {"application/json"})
@ResponseBody
public ResponseEntity<Item> addItem(@RequestBody Item item,UriComponentsBuilder builder){
itemRepo.addItem(item);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(builder.path("/addItem/{id}").buildAndExpand(item.getId()).toUri());
return new ResponseEntity<Item>(headers, HttpStatus.CREATED);
}
@PutMapping("/updateItem")
@ResponseBody
public ResponseEntity<Item> updateItem(@RequestBody Item item){
if(item != null){
itemRepo.updateItem(item);
}
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
@DeleteMapping("/delete/{id}")
@ResponseBody
public ResponseEntity<Void> deleteItem(@PathVariable int id){
itemRepo.deleteItem(id);
return new ResponseEntity<Void>(HttpStatus.ACCEPTED);
}
}
Creating an Item model
package com.onlinetutorialspoint.model;
import java.io.Serializable;
public class Item implements Serializable {
private int id;
private String name;
private String category;
public Item() {
}
public Item(int id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
Redis java configuration is as simple as defining a @Bean in spring. Initially create JedisConnectionFactory then create a RedisTemplate using JedisConnectionFacory object.
For simplicity, I am not separating this config in a different class; I am just defining beans inside the Spring boot main class.
package com.onlinetutorialspoint;
import com.onlinetutorialspoint.model.Item;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootApplication
public class SpringBootRedisExample {
@Bean
JedisConnectionFactory jedisConnectionFactory(){
return new JedisConnectionFactory();
}
@Bean
RedisTemplate<String, Item> redisTemplate(){
RedisTemplate<String,Item> redisTemplate = new RedisTemplate<String, Item>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootRedisExample.class, args);
}
}
On the above redisConnectionFactory() method created RedisConnectionFactory object and return it. It means the RedisConnectioFactory is created with default connection properties such as host as localhost and port as 8080, etc.
If you wanted to provide your application-specific configuration, you can even freely configure it like below.
@Bean
public JedisConnectionFactory connectionFactory() {
JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
connectionFactory.setHostName("somehost");
connectionFactory.setPort(9000);
return connectionFactory;
}
Creating Item Repository, it is responsible for reading and writing data into redis server using RedisTemplate.
package com.onlinetutorialspoint.repo;
import com.onlinetutorialspoint.model.Item;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public class ItemRepository {
public static final String KEY = "ITEM";
private RedisTemplate<String,Item> redisTemplate;
private HashOperations hashOperations;
public ItemRepository(RedisTemplate<String, Item> redisTemplate) {
this.redisTemplate = redisTemplate;
hashOperations = redisTemplate.opsForHash();
}
/*Getting all Items from tSable*/
public Map<Integer,Item> getAllItems(){
return hashOperations.entries(KEY);
}
/*Getting a specific item by item id from table*/
public Item getItem(int itemId){
return (Item) hashOperations.get(KEY,itemId);
}
/*Adding an item into redis database*/
public void addItem(Item item){
hashOperations.put(KEY,item.getId(),item);
}
/*delete an item from database*/
public void deleteItem(int id){
hashOperations.delete(KEY,id);
}
/*update an item from database*/
public void updateItem(Item item){
addItem(item);
}
}
As we are dealing with Item class, we can opt for opsForhash().
opsForHash() gives the hashOperations instance, and it provides different methods to read/write data into redis server.
Accessing the application from the postman, and adding an item using a POST request.
Getting all items from redis
updating Item -3
After updating Item -3
Deleting Item -3
Spring Data Redis Docs
Install Redis on windows
Happy Learning 🙂
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring boot exception handling rest service (CRUD) operations
Spring Boot How to change the Tomcat to Jetty Server
How to change Spring Boot Tomcat Port Number
Simple Spring Boot Example
Spring Boot MockMvc JUnit Test Example
MicroServices Spring Boot Eureka Server Example
How to use Spring Boot Random Port
Spring Boot Redis Cache Example – Redis Server
How to set Spring Boot SetTimeZone
Spring Boot JNDI Configuration – External Tomcat
Spring Boot MongoDB + Spring Data Example
Spring Boot Multiple Data Sources Example
Setup/Install Redis Server on Windows 10
Spring Boot DataRest Example RepositoryRestResource
Spring Boot JdbcTemplate CRUD Operations Mysql
Spring boot exception handling rest service (CRUD) operations
Spring Boot How to change the Tomcat to Jetty Server
How to change Spring Boot Tomcat Port Number
Simple Spring Boot Example
Spring Boot MockMvc JUnit Test Example
MicroServices Spring Boot Eureka Server Example
How to use Spring Boot Random Port
Spring Boot Redis Cache Example – Redis Server
How to set Spring Boot SetTimeZone
Spring Boot JNDI Configuration – External Tomcat
Spring Boot MongoDB + Spring Data Example
Spring Boot Multiple Data Sources Example
Setup/Install Redis Server on Windows 10
Spring Boot DataRest Example RepositoryRestResource
yaghob
February 18, 2019 at 1:12 pm - Reply
Hi dear this learning is so valuable and many thanks,
but when i start application i get this error:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘redisTemplate’ defined in class path resource [com/my_app/config/RedisConfig.class]: Unsatisfied dependency expressed through method ‘redisTemplate’ parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method ‘redisConnectionFactory’ threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig.
i hope give recommendation tome.
Adriano
August 8, 2020 at 6:41 am - Reply
Great Sample! I spent some time searching for a sample like yours.
Tks a lot!
yaghob
February 18, 2019 at 1:12 pm - Reply
Hi dear this learning is so valuable and many thanks,
but when i start application i get this error:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘redisTemplate’ defined in class path resource [com/my_app/config/RedisConfig.class]: Unsatisfied dependency expressed through method ‘redisTemplate’ parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method ‘redisConnectionFactory’ threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig.
i hope give recommendation tome.
Hi dear this learning is so valuable and many thanks,
but when i start application i get this error:
ConfigServletWebServerApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘redisTemplate’ defined in class path resource [com/my_app/config/RedisConfig.class]: Unsatisfied dependency expressed through method ‘redisTemplate’ parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method ‘redisConnectionFactory’ threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig.
i hope give recommendation tome.
Adriano
August 8, 2020 at 6:41 am - Reply
Great Sample! I spent some time searching for a sample like yours.
Tks a lot!
Great Sample! I spent some time searching for a sample like yours.
Tks a lot!
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment | [
{
"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": 498,
"s": 398,
"text": "In this tutorial, I am going to introduce the most popular in-memory data store spring boot redis. "
},
{
"code": null,
"e": 720,
"s": 498,
"text": "In the previous tutorial, we discussed what redis is and how to install redis server on windows 10 operating system. We also talk about rediscli and done some of the basic operations on both the redis server and rediscli."
},
{
"code": null,
"e": 980,
"s": 720,
"text": "As part of this article, I am going to implement a simple spring boot data redis application with necessary CRUD operations. To make this application up and running, initially, you should have redis server setup in your local and it should be in running mode."
},
{
"code": null,
"e": 1209,
"s": 980,
"text": "To define the connection settings from the application client to Redis server, we need a redis client which will be helpful to interact with redis server; it is something similar like JdbcTemplate to connect with the SQL server."
},
{
"code": null,
"e": 1381,
"s": 1209,
"text": "There are several redis client implementations available in the market for Java. For this tutorial, I choose Jedis – A simple and powerful implementation for redis client."
},
{
"code": null,
"e": 1436,
"s": 1381,
"text": "A simple example to understand Spring boot data redis."
},
{
"code": null,
"e": 1454,
"s": 1436,
"text": "Spring Boot 2.0.5"
},
{
"code": null,
"e": 1477,
"s": 1454,
"text": "Spring Boot Data Redis"
},
{
"code": null,
"e": 1496,
"s": 1477,
"text": "Redis server 2.4.5"
},
{
"code": null,
"e": 1502,
"s": 1496,
"text": "Jedis"
},
{
"code": null,
"e": 1508,
"s": 1502,
"text": "Java8"
},
{
"code": null,
"e": 1514,
"s": 1508,
"text": "Maven"
},
{
"code": null,
"e": 1564,
"s": 1514,
"text": "Below are the redis and Jedis maven dependencies."
},
{
"code": null,
"e": 1817,
"s": 1564,
"text": "<dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-redis</artifactId>\n</dependency>\n<dependency>\n <groupId>redis.clients</groupId>\n <artifactId>jedis</artifactId>\n <version>2.9.3</version>\n</dependency>"
},
{
"code": null,
"e": 3474,
"s": 1817,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>SpringBoot-Redis-Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>SpringBoot-Redis-Example</name>\n <description>Spring Boot Redis Example</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.5.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-data-redis</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>redis.clients</groupId>\n <artifactId>jedis</artifactId>\n <version>RELEASE</version>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>\n"
},
{
"code": null,
"e": 3534,
"s": 3474,
"text": "Creating a simple rest controller to provide CRUD endpoints"
},
{
"code": null,
"e": 5542,
"s": 3534,
"text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.util.UriComponentsBuilder;\n\nimport java.util.Map;\n\n@RestController\npublic class ItemController {\n @Autowired\n ItemRepository itemRepo;\n\n @RequestMapping(\"/getAllItems\")\n @ResponseBody\n public ResponseEntity<Map<Integer,Item>> getAllItems(){\n Map<Integer,Item> items = itemRepo.getAllItems();\n return new ResponseEntity<Map<Integer,Item>>(items, HttpStatus.OK);\n }\n\n @GetMapping(\"/item/{itemId}\")\n @ResponseBody\n public ResponseEntity<Item> getItem(@PathVariable int itemId){\n Item item = itemRepo.getItem(itemId);\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @PostMapping(value = \"/addItem\",consumes = {\"application/json\"},produces = {\"application/json\"})\n @ResponseBody\n public ResponseEntity<Item> addItem(@RequestBody Item item,UriComponentsBuilder builder){\n itemRepo.addItem(item);\n HttpHeaders headers = new HttpHeaders();\n headers.setLocation(builder.path(\"/addItem/{id}\").buildAndExpand(item.getId()).toUri());\n return new ResponseEntity<Item>(headers, HttpStatus.CREATED);\n }\n\n @PutMapping(\"/updateItem\")\n @ResponseBody\n public ResponseEntity<Item> updateItem(@RequestBody Item item){\n if(item != null){\n itemRepo.updateItem(item);\n }\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @DeleteMapping(\"/delete/{id}\")\n @ResponseBody\n public ResponseEntity<Void> deleteItem(@PathVariable int id){\n itemRepo.deleteItem(id);\n return new ResponseEntity<Void>(HttpStatus.ACCEPTED);\n }\n}\n"
},
{
"code": null,
"e": 5565,
"s": 5542,
"text": "Creating an Item model"
},
{
"code": null,
"e": 6325,
"s": 5565,
"text": "package com.onlinetutorialspoint.model;\n\nimport java.io.Serializable;\n\npublic class Item implements Serializable {\n private int id;\n private String name;\n private String category;\n\n public Item() {\n }\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n}\n"
},
{
"code": null,
"e": 6498,
"s": 6325,
"text": "Redis java configuration is as simple as defining a @Bean in spring. Initially create JedisConnectionFactory then create a RedisTemplate using JedisConnectionFacory object."
},
{
"code": null,
"e": 6628,
"s": 6498,
"text": "For simplicity, I am not separating this config in a different class; I am just defining beans inside the Spring boot main class."
},
{
"code": null,
"e": 7531,
"s": 6628,
"text": "package com.onlinetutorialspoint;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.data.redis.connection.jedis.JedisConnectionFactory;\nimport org.springframework.data.redis.core.RedisTemplate;\n\n@SpringBootApplication\npublic class SpringBootRedisExample {\n\n @Bean\n JedisConnectionFactory jedisConnectionFactory(){\n return new JedisConnectionFactory();\n }\n\n @Bean\n RedisTemplate<String, Item> redisTemplate(){\n RedisTemplate<String,Item> redisTemplate = new RedisTemplate<String, Item>();\n redisTemplate.setConnectionFactory(jedisConnectionFactory());\n return redisTemplate;\n }\n\n public static void main(String[] args) {\n SpringApplication.run(SpringBootRedisExample.class, args);\n }\n}\n"
},
{
"code": null,
"e": 7759,
"s": 7531,
"text": "On the above redisConnectionFactory() method created RedisConnectionFactory object and return it. It means the RedisConnectioFactory is created with default connection properties such as host as localhost and port as 8080, etc."
},
{
"code": null,
"e": 7870,
"s": 7759,
"text": "If you wanted to provide your application-specific configuration, you can even freely configure it like below."
},
{
"code": null,
"e": 8113,
"s": 7870,
"text": "@Bean\npublic JedisConnectionFactory connectionFactory() {\n JedisConnectionFactory connectionFactory = new JedisConnectionFactory();\n connectionFactory.setHostName(\"somehost\");\n connectionFactory.setPort(9000);\n return connectionFactory;\n}"
},
{
"code": null,
"e": 8225,
"s": 8113,
"text": "Creating Item Repository, it is responsible for reading and writing data into redis server using RedisTemplate."
},
{
"code": null,
"e": 9510,
"s": 8225,
"text": "package com.onlinetutorialspoint.repo;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.data.redis.core.HashOperations;\nimport org.springframework.data.redis.core.RedisTemplate;\nimport org.springframework.stereotype.Repository;\n\nimport java.util.Map;\n\n@Repository\npublic class ItemRepository {\n\n public static final String KEY = \"ITEM\";\n private RedisTemplate<String,Item> redisTemplate;\n private HashOperations hashOperations;\n\n public ItemRepository(RedisTemplate<String, Item> redisTemplate) {\n this.redisTemplate = redisTemplate;\n hashOperations = redisTemplate.opsForHash();\n }\n\n /*Getting all Items from tSable*/\n public Map<Integer,Item> getAllItems(){\n return hashOperations.entries(KEY);\n }\n\n /*Getting a specific item by item id from table*/\n public Item getItem(int itemId){\n return (Item) hashOperations.get(KEY,itemId);\n }\n\n /*Adding an item into redis database*/\n public void addItem(Item item){\n hashOperations.put(KEY,item.getId(),item);\n }\n\n /*delete an item from database*/\n public void deleteItem(int id){\n hashOperations.delete(KEY,id);\n }\n\n /*update an item from database*/\n public void updateItem(Item item){\n addItem(item);\n }\n}\n"
},
{
"code": null,
"e": 9574,
"s": 9510,
"text": "As we are dealing with Item class, we can opt for opsForhash()."
},
{
"code": null,
"e": 9694,
"s": 9574,
"text": "opsForHash() gives the hashOperations instance, and it provides different methods to read/write data into redis server."
},
{
"code": null,
"e": 9779,
"s": 9694,
"text": "Accessing the application from the postman, and adding an item using a POST request."
},
{
"code": null,
"e": 9808,
"s": 9779,
"text": "Getting all items from redis"
},
{
"code": null,
"e": 9825,
"s": 9808,
"text": "updating Item -3"
},
{
"code": null,
"e": 9848,
"s": 9825,
"text": "After updating Item -3"
},
{
"code": null,
"e": 9865,
"s": 9848,
"text": "Deleting Item -3"
},
{
"code": null,
"e": 9888,
"s": 9865,
"text": "Spring Data Redis Docs"
},
{
"code": null,
"e": 9913,
"s": 9888,
"text": "Install Redis on windows"
},
{
"code": null,
"e": 9930,
"s": 9913,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 10596,
"s": 9930,
"text": "\nSpring Boot JdbcTemplate CRUD Operations Mysql\nSpring boot exception handling rest service (CRUD) operations\nSpring Boot How to change the Tomcat to Jetty Server\nHow to change Spring Boot Tomcat Port Number\nSimple Spring Boot Example\nSpring Boot MockMvc JUnit Test Example\nMicroServices Spring Boot Eureka Server Example\nHow to use Spring Boot Random Port\nSpring Boot Redis Cache Example – Redis Server\nHow to set Spring Boot SetTimeZone\nSpring Boot JNDI Configuration – External Tomcat\nSpring Boot MongoDB + Spring Data Example\nSpring Boot Multiple Data Sources Example\nSetup/Install Redis Server on Windows 10\nSpring Boot DataRest Example RepositoryRestResource\n"
},
{
"code": null,
"e": 10643,
"s": 10596,
"text": "Spring Boot JdbcTemplate CRUD Operations Mysql"
},
{
"code": null,
"e": 10705,
"s": 10643,
"text": "Spring boot exception handling rest service (CRUD) operations"
},
{
"code": null,
"e": 10758,
"s": 10705,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 10803,
"s": 10758,
"text": "How to change Spring Boot Tomcat Port Number"
},
{
"code": null,
"e": 10830,
"s": 10803,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 10869,
"s": 10830,
"text": "Spring Boot MockMvc JUnit Test Example"
},
{
"code": null,
"e": 10917,
"s": 10869,
"text": "MicroServices Spring Boot Eureka Server Example"
},
{
"code": null,
"e": 10952,
"s": 10917,
"text": "How to use Spring Boot Random Port"
},
{
"code": null,
"e": 10999,
"s": 10952,
"text": "Spring Boot Redis Cache Example – Redis Server"
},
{
"code": null,
"e": 11034,
"s": 10999,
"text": "How to set Spring Boot SetTimeZone"
},
{
"code": null,
"e": 11083,
"s": 11034,
"text": "Spring Boot JNDI Configuration – External Tomcat"
},
{
"code": null,
"e": 11125,
"s": 11083,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 11167,
"s": 11125,
"text": "Spring Boot Multiple Data Sources Example"
},
{
"code": null,
"e": 11208,
"s": 11167,
"text": "Setup/Install Redis Server on Windows 10"
},
{
"code": null,
"e": 11260,
"s": 11208,
"text": "Spring Boot DataRest Example RepositoryRestResource"
},
{
"code": null,
"e": 12603,
"s": 11260,
"text": "\n\n\n\n\n\nyaghob\nFebruary 18, 2019 at 1:12 pm - Reply \n\nHi dear this learning is so valuable and many thanks,\nbut when i start application i get this error:\nConfigServletWebServerApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘redisTemplate’ defined in class path resource [com/my_app/config/RedisConfig.class]: Unsatisfied dependency expressed through method ‘redisTemplate’ parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method ‘redisConnectionFactory’ threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig.\ni hope give recommendation tome.\n\n\n\n\n\n\n\n\n\nAdriano\nAugust 8, 2020 at 6:41 am - Reply \n\nGreat Sample! I spent some time searching for a sample like yours.\nTks a lot!\n\n\n\n\n"
},
{
"code": null,
"e": 13813,
"s": 12603,
"text": "\n\n\n\n\nyaghob\nFebruary 18, 2019 at 1:12 pm - Reply \n\nHi dear this learning is so valuable and many thanks,\nbut when i start application i get this error:\nConfigServletWebServerApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘redisTemplate’ defined in class path resource [com/my_app/config/RedisConfig.class]: Unsatisfied dependency expressed through method ‘redisTemplate’ parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method ‘redisConnectionFactory’ threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig.\ni hope give recommendation tome.\n\n\n\n"
},
{
"code": null,
"e": 14968,
"s": 13813,
"text": "Hi dear this learning is so valuable and many thanks,\nbut when i start application i get this error:\nConfigServletWebServerApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘redisTemplate’ defined in class path resource [com/my_app/config/RedisConfig.class]: Unsatisfied dependency expressed through method ‘redisTemplate’ parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘redisConnectionFactory’ defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method ‘redisConnectionFactory’ threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig.\ni hope give recommendation tome."
},
{
"code": null,
"e": 15099,
"s": 14968,
"text": "\n\n\n\n\nAdriano\nAugust 8, 2020 at 6:41 am - Reply \n\nGreat Sample! I spent some time searching for a sample like yours.\nTks a lot!\n\n\n\n"
},
{
"code": null,
"e": 15177,
"s": 15099,
"text": "Great Sample! I spent some time searching for a sample like yours.\nTks a lot!"
},
{
"code": null,
"e": 15183,
"s": 15181,
"text": "Δ"
},
{
"code": null,
"e": 15210,
"s": 15183,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 15237,
"s": 15210,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 15271,
"s": 15237,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 15312,
"s": 15271,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 15357,
"s": 15312,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 15395,
"s": 15357,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 15429,
"s": 15395,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 15460,
"s": 15429,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 15494,
"s": 15460,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 15527,
"s": 15494,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 15560,
"s": 15527,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 15600,
"s": 15560,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 15625,
"s": 15600,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 15656,
"s": 15625,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 15680,
"s": 15656,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 15726,
"s": 15680,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 15749,
"s": 15726,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 15776,
"s": 15749,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 15822,
"s": 15776,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 15862,
"s": 15822,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 15891,
"s": 15862,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 15925,
"s": 15891,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 15955,
"s": 15925,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 15991,
"s": 15955,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 16024,
"s": 15991,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 16057,
"s": 16024,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 16101,
"s": 16057,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 16135,
"s": 16101,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 16167,
"s": 16135,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 16195,
"s": 16167,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 16226,
"s": 16195,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 16267,
"s": 16226,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 16301,
"s": 16267,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 16326,
"s": 16301,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 16360,
"s": 16326,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 16396,
"s": 16360,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 16442,
"s": 16396,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 16493,
"s": 16442,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 16535,
"s": 16493,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 16566,
"s": 16535,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 16589,
"s": 16566,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 16619,
"s": 16589,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 16649,
"s": 16619,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 16698,
"s": 16649,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 16732,
"s": 16698,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 16765,
"s": 16732,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 16794,
"s": 16765,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 16826,
"s": 16794,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 16863,
"s": 16826,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 16892,
"s": 16863,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 16921,
"s": 16892,
"text": " Spring Boot – MockMvc JUnit"
}
] |
Analyze Customer Behavior the Right Way Using a Sunburst Chart Built with Python, Pandas and Plotly | by Giordan Pretelin | Towards Data Science | Sunburst charts, sometimes also called Ring Charts, Multi-Level Pie Charts or Radial Treemaps (Anychart, n.d.) are a fantastic way to visualize and understand hierarchical or sequential data.
Sunburst charts have two main use cases:
Understand largest contributors to a whole and the proportions of the components of theseUnderstand flow of individuals among sequential steps of a process
Understand largest contributors to a whole and the proportions of the components of these
Understand flow of individuals among sequential steps of a process
To illustrate a use case of a sunburst chart I’ll use a dataset I generated to simulate a simple path customers could follow in a website to finish a purchase. (The dataset can be found in my Kaggle datasets if you want to replicate my example)
In this hypothetical use case we’d like to understand what’s the most frequent path our customers follow to finish a purchase in our website and to compare whether the customers that visit us organically behave different than the ones that arrive through ad platforms.
It is important to mention that Sunburst charts are not ideal for time-series or continuous data but rather for data of hierarchical or sequential nature.
With the basics out of the way, let’s turn that boring pandas DataFrame into an interactive Sunburst chart that will allow us to find some insights.
To follow this tutorial you are going to need the following libraries installed in your current environment:
Numpy
Pandas
Plolty
I do most of my work in Jupyter Notebook and Jupyter Lab but feel free to follow in whichever IDE you prefer. Please refer to the Plotly getting started documentation, especially if you use Jupyter tools as I do. There’s a few lines of code you have to run the first time you use Plotly in Jupyter but I assure you it’s nothing complicated.
When you’re confident you can display Plotly figures you can start by importing the aforementioned libraries with their usual aliases, Plotly provides a high-level API called Plotly Express which we’ll be using.
import numpy as npimport pandas as pdimport plotly.express as px
If you are using my dataset and have it in the same working directory you can import it the following way, if you are using other dataset feel free to use your favorite method to have it as a pandas dataframe.
df = pd.read_csv(‘path_to_purchase.csv’)
Sunburst charts are fairly straightforward to build using Plotly Express, especially from a Pandas dataframe. The key things we have to specify are the dataframe using the data_frame argument, the columns to use and the hierarchy of them with the path argument and the column that will determine the size of the parts in our sunburst chart
fig = px.sunburst( data_frame = df, path = ['Segment', 'Customer Origin', 'First Click', 'Coupon Usage'], values = 'Customer Count')fig.show()
The code above generates the following chart:
There’s room for some formatting improvements, I won’t go into the details of the arguments but the keywords are explicit about what they do so they shouldn’t represent a problem to you.
By adding the following lines of code we can generate a better-looking chart:
fig =px.sunburst( data_frame = df, path = [‘Segment’, ‘Customer Origin’, ‘First Click’, ‘Coupon Usage’], values = ‘Customer Count’, title = ‘Paths to purchase’, height = 700, template = ‘ggplot2’)fig.show()
One of the best aspects of Plotly is that, unlike Matplotlib, the charts it generates are interactive. This adds a usability layer that can enhance your exploratory analysis and provide that wow factor when presenting. Think Tableau or Power BI but available through Python.
By leveraging this visualizations and interactivity now we can see the following in our chart:
Most of the customers arrive organically to our websiteCustomers who arrive organically tend to shop more items without discount but customers who come from platforms ad prefer items with discountOn top of that, customers who come from ad platforms and buy discounted items, tend to use coupons with their purchases much more than other types of customers
Most of the customers arrive organically to our website
Customers who arrive organically tend to shop more items without discount but customers who come from platforms ad prefer items with discount
On top of that, customers who come from ad platforms and buy discounted items, tend to use coupons with their purchases much more than other types of customers
Of course this would trigger additional questions which we could then use to drive further analysis but the sunburst chart enabled us to perform a quick exploration of the data. | [
{
"code": null,
"e": 363,
"s": 171,
"text": "Sunburst charts, sometimes also called Ring Charts, Multi-Level Pie Charts or Radial Treemaps (Anychart, n.d.) are a fantastic way to visualize and understand hierarchical or sequential data."
},
{
"code": null,
"e": 404,
"s": 363,
"text": "Sunburst charts have two main use cases:"
},
{
"code": null,
"e": 560,
"s": 404,
"text": "Understand largest contributors to a whole and the proportions of the components of theseUnderstand flow of individuals among sequential steps of a process"
},
{
"code": null,
"e": 650,
"s": 560,
"text": "Understand largest contributors to a whole and the proportions of the components of these"
},
{
"code": null,
"e": 717,
"s": 650,
"text": "Understand flow of individuals among sequential steps of a process"
},
{
"code": null,
"e": 962,
"s": 717,
"text": "To illustrate a use case of a sunburst chart I’ll use a dataset I generated to simulate a simple path customers could follow in a website to finish a purchase. (The dataset can be found in my Kaggle datasets if you want to replicate my example)"
},
{
"code": null,
"e": 1231,
"s": 962,
"text": "In this hypothetical use case we’d like to understand what’s the most frequent path our customers follow to finish a purchase in our website and to compare whether the customers that visit us organically behave different than the ones that arrive through ad platforms."
},
{
"code": null,
"e": 1386,
"s": 1231,
"text": "It is important to mention that Sunburst charts are not ideal for time-series or continuous data but rather for data of hierarchical or sequential nature."
},
{
"code": null,
"e": 1535,
"s": 1386,
"text": "With the basics out of the way, let’s turn that boring pandas DataFrame into an interactive Sunburst chart that will allow us to find some insights."
},
{
"code": null,
"e": 1644,
"s": 1535,
"text": "To follow this tutorial you are going to need the following libraries installed in your current environment:"
},
{
"code": null,
"e": 1650,
"s": 1644,
"text": "Numpy"
},
{
"code": null,
"e": 1657,
"s": 1650,
"text": "Pandas"
},
{
"code": null,
"e": 1664,
"s": 1657,
"text": "Plolty"
},
{
"code": null,
"e": 2005,
"s": 1664,
"text": "I do most of my work in Jupyter Notebook and Jupyter Lab but feel free to follow in whichever IDE you prefer. Please refer to the Plotly getting started documentation, especially if you use Jupyter tools as I do. There’s a few lines of code you have to run the first time you use Plotly in Jupyter but I assure you it’s nothing complicated."
},
{
"code": null,
"e": 2217,
"s": 2005,
"text": "When you’re confident you can display Plotly figures you can start by importing the aforementioned libraries with their usual aliases, Plotly provides a high-level API called Plotly Express which we’ll be using."
},
{
"code": null,
"e": 2282,
"s": 2217,
"text": "import numpy as npimport pandas as pdimport plotly.express as px"
},
{
"code": null,
"e": 2492,
"s": 2282,
"text": "If you are using my dataset and have it in the same working directory you can import it the following way, if you are using other dataset feel free to use your favorite method to have it as a pandas dataframe."
},
{
"code": null,
"e": 2533,
"s": 2492,
"text": "df = pd.read_csv(‘path_to_purchase.csv’)"
},
{
"code": null,
"e": 2873,
"s": 2533,
"text": "Sunburst charts are fairly straightforward to build using Plotly Express, especially from a Pandas dataframe. The key things we have to specify are the dataframe using the data_frame argument, the columns to use and the hierarchy of them with the path argument and the column that will determine the size of the parts in our sunburst chart"
},
{
"code": null,
"e": 3025,
"s": 2873,
"text": "fig = px.sunburst( data_frame = df, path = ['Segment', 'Customer Origin', 'First Click', 'Coupon Usage'], values = 'Customer Count')fig.show()"
},
{
"code": null,
"e": 3071,
"s": 3025,
"text": "The code above generates the following chart:"
},
{
"code": null,
"e": 3258,
"s": 3071,
"text": "There’s room for some formatting improvements, I won’t go into the details of the arguments but the keywords are explicit about what they do so they shouldn’t represent a problem to you."
},
{
"code": null,
"e": 3336,
"s": 3258,
"text": "By adding the following lines of code we can generate a better-looking chart:"
},
{
"code": null,
"e": 3543,
"s": 3336,
"text": "fig =px.sunburst( data_frame = df, path = [‘Segment’, ‘Customer Origin’, ‘First Click’, ‘Coupon Usage’], values = ‘Customer Count’, title = ‘Paths to purchase’, height = 700, template = ‘ggplot2’)fig.show()"
},
{
"code": null,
"e": 3818,
"s": 3543,
"text": "One of the best aspects of Plotly is that, unlike Matplotlib, the charts it generates are interactive. This adds a usability layer that can enhance your exploratory analysis and provide that wow factor when presenting. Think Tableau or Power BI but available through Python."
},
{
"code": null,
"e": 3913,
"s": 3818,
"text": "By leveraging this visualizations and interactivity now we can see the following in our chart:"
},
{
"code": null,
"e": 4269,
"s": 3913,
"text": "Most of the customers arrive organically to our websiteCustomers who arrive organically tend to shop more items without discount but customers who come from platforms ad prefer items with discountOn top of that, customers who come from ad platforms and buy discounted items, tend to use coupons with their purchases much more than other types of customers"
},
{
"code": null,
"e": 4325,
"s": 4269,
"text": "Most of the customers arrive organically to our website"
},
{
"code": null,
"e": 4467,
"s": 4325,
"text": "Customers who arrive organically tend to shop more items without discount but customers who come from platforms ad prefer items with discount"
},
{
"code": null,
"e": 4627,
"s": 4467,
"text": "On top of that, customers who come from ad platforms and buy discounted items, tend to use coupons with their purchases much more than other types of customers"
}
] |
Find if an expression has duplicate parenthesis or not - GeeksforGeeks | 25 Jul, 2021
Given a balanced expression, find if it contains duplicate parenthesis or not. A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis.
Examples:
Below expressions have duplicate parenthesis -
((a+b)+((c+d)))
The subexpression "c+d" is surrounded by two
pairs of brackets.
(((a+(b)))+(c+d))
The subexpression "a+(b)" is surrounded by two
pairs of brackets.
(((a+(b))+c+d))
The whole expression is surrounded by two
pairs of brackets.
((a+(b))+(c+d))
(b) and ((a+(b)) is surrounded by two
pairs of brackets.
Below expressions don't have any duplicate parenthesis -
((a+b)+(c+d))
No subsexpression is surrounded by duplicate
brackets.
It may be assumed that the given expression is valid and there are not any white spaces present.
The idea is to use stack. Iterate through the given expression and for each character in the expression, if the character is a open parenthesis ‘(‘ or any of the operators or operands, push it to the top of the stack. If the character is close parenthesis ‘)’, then pop characters from the stack till matching open parenthesis ‘(‘ is found and a counter is used, whose value is incremented for every character encountered till the opening parenthesis ‘(‘ is found. If the number of characters encountered between the opening and closing parenthesis pair, which is equal to the value of the counter, is less than 1, then a pair of duplicate parenthesis is found else there is no occurrence of redundant parenthesis pairs. For example, (((a+b))+c) has duplicate brackets around “a+b”. When the second “)” after a+b is encountered, the stack contains “((“. Since the top of stack is a opening bracket, it can be concluded that there are duplicate brackets.
Below is the implementation of above idea :
C++
Java
Python3
C#
Javascript
// C++ program to find duplicate parenthesis in a// balanced expression#include <bits/stdc++.h>using namespace std; // Function to find duplicate parenthesis in a// balanced expressionbool findDuplicateparenthesis(string str){ // create a stack of characters stack<char> Stack; // Iterate through the given expression for (char ch : str) { // if current character is close parenthesis ')' if (ch == ')') { // pop character from the stack char top = Stack.top(); Stack.pop(); // stores the number of characters between a // closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not int elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.top(); Stack.pop(); } if(elementsInside < 1) { return 1; } } // push open parenthesis '(', operators and // operands to stack else Stack.push(ch); } // No duplicates found return false;} // Driver codeint main(){ // input balanced expression string str = "(((a+(b))+(c+d)))"; if (findDuplicateparenthesis(str)) cout << "Duplicate Found "; else cout << "No Duplicates Found "; return 0;}
import java.util.Stack; // Java program to find duplicate parenthesis in a// balanced expressionpublic class GFG { // Function to find duplicate parenthesis in a// balanced expression static boolean findDuplicateparenthesis(String s) { // create a stack of characters Stack<Character> Stack = new Stack<>(); // Iterate through the given expression char[] str = s.toCharArray(); for (char ch : str) { // if current character is close parenthesis ')' if (ch == ')') { // pop character from the stack char top = Stack.peek(); Stack.pop(); // stores the number of characters between a // closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not int elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.peek(); Stack.pop(); } if (elementsInside < 1) { return true; } } // push open parenthesis '(', operators and // operands to stack else { Stack.push(ch); } } // No duplicates found return false; } // Driver codepublic static void main(String[] args) { // input balanced expression String str = "(((a+(b))+(c+d)))"; if (findDuplicateparenthesis(str)) { System.out.println("Duplicate Found "); } else { System.out.println("No Duplicates Found "); } }}
# Python3 program to find duplicate# parenthesis in a balanced expression # Function to find duplicate parenthesis# in a balanced expressiondef findDuplicateparenthesis(string): # create a stack of characters Stack = [] # Iterate through the given expression for ch in string: # if current character is # close parenthesis ')' if ch == ')': # pop character from the stack top = Stack.pop() # stores the number of characters between # a closing and opening parenthesis # if this count is less than or equal to 1 # then the brackets are redundant else not elementsInside = 0 while top != '(': elementsInside += 1 top = Stack.pop() if elementsInside < 1: return True # push open parenthesis '(', operators # and operands to stack else: Stack.append(ch) # No duplicates found return False # Driver Codeif __name__ == "__main__": # input balanced expression string = "(((a+(b))+(c+d)))" if findDuplicateparenthesis(string) == True: print("Duplicate Found") else: print("No Duplicates Found") # This code is contributed by Rituraj Jain
// C# program to find duplicate parenthesis// in a balanced expressionusing System;using System.Collections.Generic; class GFG{ // Function to find duplicate parenthesis // in a balanced expressionstatic Boolean findDuplicateparenthesis(String s){ // create a stack of characters Stack<char> Stack = new Stack<char>(); // Iterate through the given expression char[] str = s.ToCharArray(); foreach (char ch in str) { // if current character is // close parenthesis ')' if (ch == ')') { // pop character from the stack char top = Stack.Peek(); Stack.Pop(); // stores the number of characters between // a closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not int elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.Peek(); Stack.Pop(); } if (elementsInside < 1) { return true; } } // push open parenthesis '(', // operators and operands to stack else { Stack.Push(ch); } } // No duplicates found return false;} // Driver codepublic static void Main(String[] args){ // input balanced expression String str = "(((a+(b))+(c+d)))"; if (findDuplicateparenthesis(str)) { Console.WriteLine("Duplicate Found "); } else { Console.WriteLine("No Duplicates Found "); }}} // This code is contributed by 29AjayKumar
<script> // Javascript program to find duplicate// parenthesis in a balanced expression // Function to find duplicate parenthesis// in a balanced expressionfunction findDuplicateparenthesis(s){ // Create a stack of characters let Stack = []; // Iterate through the given expression let str = s.split(""); for(let ch = 0; ch < str.length;ch++) { // If current character is close // parenthesis ')' if (str[ch] == ')') { // pop character from the stack let top = Stack.pop(); // Stores the number of characters between a // closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not let elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.pop(); } if (elementsInside < 1) { return true; } } // push open parenthesis '(', operators // and operands to stack else { Stack.push(str[ch]); } } // No duplicates found return false;} // Driver codelet str = "(((a+(b))+(c+d)))"; // Input balanced expressionif (findDuplicateparenthesis(str)){ document.write("Duplicate Found ");}else{ document.write("No Duplicates Found ");} // This code is contributed by rag2127 </script>
Output:
Duplicate Found
Time complexity of above solution is O(n).
Auxiliary space used by the program is O(n).
This article is contributed by Aditya Goel. 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.
sirjan13
rituraj_jain
Rajput-Ji
mr.garg
29AjayKumar
rag2127
sangamchoudhary7
Stack
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Tower of Hanoi
Inorder Tree Traversal without Recursion
Queue using Stacks
Implement a stack using singly linked list
Stack | Set 4 (Evaluation of Postfix Expression)
Next Greater Element
Implement Stack using Queues
Merge Overlapping Intervals
Iterative Depth First Traversal of Graph
Largest Rectangular Area in a Histogram | Set 2 | [
{
"code": null,
"e": 25136,
"s": 25108,
"text": "\n25 Jul, 2021"
},
{
"code": null,
"e": 25316,
"s": 25136,
"text": "Given a balanced expression, find if it contains duplicate parenthesis or not. A set of parenthesis are duplicate if the same subexpression is surrounded by multiple parenthesis. "
},
{
"code": null,
"e": 25327,
"s": 25316,
"text": "Examples: "
},
{
"code": null,
"e": 25822,
"s": 25327,
"text": "Below expressions have duplicate parenthesis - \n((a+b)+((c+d)))\nThe subexpression \"c+d\" is surrounded by two\npairs of brackets.\n\n(((a+(b)))+(c+d))\nThe subexpression \"a+(b)\" is surrounded by two \npairs of brackets.\n\n(((a+(b))+c+d))\nThe whole expression is surrounded by two \npairs of brackets.\n\n((a+(b))+(c+d))\n(b) and ((a+(b)) is surrounded by two\npairs of brackets.\n\nBelow expressions don't have any duplicate parenthesis -\n((a+b)+(c+d)) \nNo subsexpression is surrounded by duplicate\nbrackets."
},
{
"code": null,
"e": 25920,
"s": 25822,
"text": "It may be assumed that the given expression is valid and there are not any white spaces present. "
},
{
"code": null,
"e": 26874,
"s": 25920,
"text": "The idea is to use stack. Iterate through the given expression and for each character in the expression, if the character is a open parenthesis ‘(‘ or any of the operators or operands, push it to the top of the stack. If the character is close parenthesis ‘)’, then pop characters from the stack till matching open parenthesis ‘(‘ is found and a counter is used, whose value is incremented for every character encountered till the opening parenthesis ‘(‘ is found. If the number of characters encountered between the opening and closing parenthesis pair, which is equal to the value of the counter, is less than 1, then a pair of duplicate parenthesis is found else there is no occurrence of redundant parenthesis pairs. For example, (((a+b))+c) has duplicate brackets around “a+b”. When the second “)” after a+b is encountered, the stack contains “((“. Since the top of stack is a opening bracket, it can be concluded that there are duplicate brackets."
},
{
"code": null,
"e": 26919,
"s": 26874,
"text": "Below is the implementation of above idea : "
},
{
"code": null,
"e": 26923,
"s": 26919,
"text": "C++"
},
{
"code": null,
"e": 26928,
"s": 26923,
"text": "Java"
},
{
"code": null,
"e": 26936,
"s": 26928,
"text": "Python3"
},
{
"code": null,
"e": 26939,
"s": 26936,
"text": "C#"
},
{
"code": null,
"e": 26950,
"s": 26939,
"text": "Javascript"
},
{
"code": "// C++ program to find duplicate parenthesis in a// balanced expression#include <bits/stdc++.h>using namespace std; // Function to find duplicate parenthesis in a// balanced expressionbool findDuplicateparenthesis(string str){ // create a stack of characters stack<char> Stack; // Iterate through the given expression for (char ch : str) { // if current character is close parenthesis ')' if (ch == ')') { // pop character from the stack char top = Stack.top(); Stack.pop(); // stores the number of characters between a // closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not int elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.top(); Stack.pop(); } if(elementsInside < 1) { return 1; } } // push open parenthesis '(', operators and // operands to stack else Stack.push(ch); } // No duplicates found return false;} // Driver codeint main(){ // input balanced expression string str = \"(((a+(b))+(c+d)))\"; if (findDuplicateparenthesis(str)) cout << \"Duplicate Found \"; else cout << \"No Duplicates Found \"; return 0;}",
"e": 28378,
"s": 26950,
"text": null
},
{
"code": "import java.util.Stack; // Java program to find duplicate parenthesis in a// balanced expressionpublic class GFG { // Function to find duplicate parenthesis in a// balanced expression static boolean findDuplicateparenthesis(String s) { // create a stack of characters Stack<Character> Stack = new Stack<>(); // Iterate through the given expression char[] str = s.toCharArray(); for (char ch : str) { // if current character is close parenthesis ')' if (ch == ')') { // pop character from the stack char top = Stack.peek(); Stack.pop(); // stores the number of characters between a // closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not int elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.peek(); Stack.pop(); } if (elementsInside < 1) { return true; } } // push open parenthesis '(', operators and // operands to stack else { Stack.push(ch); } } // No duplicates found return false; } // Driver codepublic static void main(String[] args) { // input balanced expression String str = \"(((a+(b))+(c+d)))\"; if (findDuplicateparenthesis(str)) { System.out.println(\"Duplicate Found \"); } else { System.out.println(\"No Duplicates Found \"); } }}",
"e": 30072,
"s": 28378,
"text": null
},
{
"code": "# Python3 program to find duplicate# parenthesis in a balanced expression # Function to find duplicate parenthesis# in a balanced expressiondef findDuplicateparenthesis(string): # create a stack of characters Stack = [] # Iterate through the given expression for ch in string: # if current character is # close parenthesis ')' if ch == ')': # pop character from the stack top = Stack.pop() # stores the number of characters between # a closing and opening parenthesis # if this count is less than or equal to 1 # then the brackets are redundant else not elementsInside = 0 while top != '(': elementsInside += 1 top = Stack.pop() if elementsInside < 1: return True # push open parenthesis '(', operators # and operands to stack else: Stack.append(ch) # No duplicates found return False # Driver Codeif __name__ == \"__main__\": # input balanced expression string = \"(((a+(b))+(c+d)))\" if findDuplicateparenthesis(string) == True: print(\"Duplicate Found\") else: print(\"No Duplicates Found\") # This code is contributed by Rituraj Jain",
"e": 31394,
"s": 30072,
"text": null
},
{
"code": "// C# program to find duplicate parenthesis// in a balanced expressionusing System;using System.Collections.Generic; class GFG{ // Function to find duplicate parenthesis // in a balanced expressionstatic Boolean findDuplicateparenthesis(String s){ // create a stack of characters Stack<char> Stack = new Stack<char>(); // Iterate through the given expression char[] str = s.ToCharArray(); foreach (char ch in str) { // if current character is // close parenthesis ')' if (ch == ')') { // pop character from the stack char top = Stack.Peek(); Stack.Pop(); // stores the number of characters between // a closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not int elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.Peek(); Stack.Pop(); } if (elementsInside < 1) { return true; } } // push open parenthesis '(', // operators and operands to stack else { Stack.Push(ch); } } // No duplicates found return false;} // Driver codepublic static void Main(String[] args){ // input balanced expression String str = \"(((a+(b))+(c+d)))\"; if (findDuplicateparenthesis(str)) { Console.WriteLine(\"Duplicate Found \"); } else { Console.WriteLine(\"No Duplicates Found \"); }}} // This code is contributed by 29AjayKumar",
"e": 33055,
"s": 31394,
"text": null
},
{
"code": "<script> // Javascript program to find duplicate// parenthesis in a balanced expression // Function to find duplicate parenthesis// in a balanced expressionfunction findDuplicateparenthesis(s){ // Create a stack of characters let Stack = []; // Iterate through the given expression let str = s.split(\"\"); for(let ch = 0; ch < str.length;ch++) { // If current character is close // parenthesis ')' if (str[ch] == ')') { // pop character from the stack let top = Stack.pop(); // Stores the number of characters between a // closing and opening parenthesis // if this count is less than or equal to 1 // then the brackets are redundant else not let elementsInside = 0; while (top != '(') { elementsInside++; top = Stack.pop(); } if (elementsInside < 1) { return true; } } // push open parenthesis '(', operators // and operands to stack else { Stack.push(str[ch]); } } // No duplicates found return false;} // Driver codelet str = \"(((a+(b))+(c+d)))\"; // Input balanced expressionif (findDuplicateparenthesis(str)){ document.write(\"Duplicate Found \");}else{ document.write(\"No Duplicates Found \");} // This code is contributed by rag2127 </script>",
"e": 34553,
"s": 33055,
"text": null
},
{
"code": null,
"e": 34562,
"s": 34553,
"text": "Output: "
},
{
"code": null,
"e": 34578,
"s": 34562,
"text": "Duplicate Found"
},
{
"code": null,
"e": 34622,
"s": 34578,
"text": "Time complexity of above solution is O(n). "
},
{
"code": null,
"e": 34667,
"s": 34622,
"text": "Auxiliary space used by the program is O(n)."
},
{
"code": null,
"e": 35087,
"s": 34667,
"text": "This article is contributed by Aditya Goel. 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": 35096,
"s": 35087,
"text": "sirjan13"
},
{
"code": null,
"e": 35109,
"s": 35096,
"text": "rituraj_jain"
},
{
"code": null,
"e": 35119,
"s": 35109,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 35127,
"s": 35119,
"text": "mr.garg"
},
{
"code": null,
"e": 35139,
"s": 35127,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35147,
"s": 35139,
"text": "rag2127"
},
{
"code": null,
"e": 35164,
"s": 35147,
"text": "sangamchoudhary7"
},
{
"code": null,
"e": 35170,
"s": 35164,
"text": "Stack"
},
{
"code": null,
"e": 35176,
"s": 35170,
"text": "Stack"
},
{
"code": null,
"e": 35274,
"s": 35176,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35301,
"s": 35274,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 35342,
"s": 35301,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 35361,
"s": 35342,
"text": "Queue using Stacks"
},
{
"code": null,
"e": 35404,
"s": 35361,
"text": "Implement a stack using singly linked list"
},
{
"code": null,
"e": 35453,
"s": 35404,
"text": "Stack | Set 4 (Evaluation of Postfix Expression)"
},
{
"code": null,
"e": 35474,
"s": 35453,
"text": "Next Greater Element"
},
{
"code": null,
"e": 35503,
"s": 35474,
"text": "Implement Stack using Queues"
},
{
"code": null,
"e": 35531,
"s": 35503,
"text": "Merge Overlapping Intervals"
},
{
"code": null,
"e": 35572,
"s": 35531,
"text": "Iterative Depth First Traversal of Graph"
}
] |
Average - GeeksforGeeks | 24 Feb, 2022
Average a number expressing the central or typical value in a set of data, in particular the mode, median, or (most commonly) the mean, which is calculated by dividing the sum of the values in the set by their number.
The basic formula for the average of n numbers x1,x2,......xn is
A = (x1 + x2 ........xn)/ n
Important points:
1. Sum of first n natural number = n(n + 1)/2
Average of first n natural number = (n + 1)/2
2. Sum of square of first n natural number = n(n+1)(2n+1)/6
Avg. of square of first n natural number = (n+1)(2n+1)/6
3. Sum of cube of first n natural number = [n(n+1)/2]2
Avg. of cube of first n natural number = (n(n+1)2
4. Sum of first n natural odd number = n2
Avg. of first n natural odd number = n
5. Sum of first n natural even number = n(n+1)
Avg. of first n natural even number = n+1
Sample problems
Question :1 Find the average of the square of first 16 natural number is: Solution : We know that Sum of square of first n natural number = n(n+1)(2n+1)/6 Avg. of square of first n natural number = (n+1)(2n+1)/6 So, Avg. of square of first 16 natural number = (16+1)(2×16+1)/6 = 17 x 33 /6 = 187/2
Question 2: The average of 9 observations is 87. If the average of the first five observations is 79 and the average of the next three is 92. Find the 9th observation. Solution : Average of 9 observations = 87 So, Sum of 9 observations = 87 x 9 = 783 Average of first 5 observations = 79 The sum of first 5 observations = 79 x 5 = 395 The sum of 6th,7th and 8th = 92 x 3 = 276 9th number = 783 – 395 – 276 = 112
Question 3: Five years ago the average of the Husband and wife was 25 years, today the average age of the Husband, wife, and child is 21 years. How old is the child? Solution : H + W = 25 Sum of ages of both 5 years before = 25×2 = 50 Today, sum of there ages is = 50 + 5 + 5 = 60 Today avg. of H + W + C = 21 Sum of ages of H , W and C = 21×3 = 63 Age of child = 63 – 60 = 3 years
Question 4: The average of mother, father and son was 44 years at the time of marriage of the son. After 1 year an infant was born and after 5 years of marriage, the average age of the family becomes 37 years. Find the age of the bride at the time of the marriage. Solution : Sum of ages of F + M + S = 44 x 3 = 132 years Sum of ages of M + F + S + D + C = 37 x 5 = 185 years Sum of ages of (M + F + S) = 132 + 3×5 = 147 years Sum of ages of D + C after 5 years = 185 – 147 = 38 years D + C = 38 The child was born after 1 year of marriage so present age of the child is 4 year then D + 4 = 38 D = 34 years at present So,at the time of marriage bride age was= 34 – 5 = 29 years
Question 5: The average temp. of Monday, Tuesday, Wednesday and Thursday are 31o, and the average temp. of Tuesday, Wednesday, Thursday, and Friday are 29.5o. If the temp of Friday is 4/5 times of Monday. Find the temp of Monday. Solution :Find Sum Sum of temp. of M + T + W + Th = 31 x 4 = 124..........(1) Sum of temp. of T + W + Th + F = 29.5 x 4 = 118.........(2) Subtract (2) for (1) M – F = 6 Given F = (4/5)M M/F = 5/4 then 5x – 4x = 6 x = 6 Temp. of Monday = 5 x 6 = 30o
Question 6: There are 42 students in a hostel. If the number of students increased by 14. The expense of mess increased by Rs 28 per day. While the average expenditure per head decreased by Rs 2. Find the original expenditure. Solution : Total students after increment = 42 + 14 = 56 Let the expenditure of students is A Rs/day. Increase in expenditure Rs 28/day. Acc. to question 42A + 28 = 56(A – 2) 42A + 28 = 56A – 112 14A = 140 A = 10 Hence, the original expenditure of the student was Rs 10/day.
Question 7: The average of 200 numbers is 96 but it was found that 2 numbers 16 and 43 are mistakenly calculated as 61 and 34. Find his correct average it was also found that the total number is only 190. Solution : Average of 200 numbers = 96 Sum of 200 numbers = 96 x 200 = 19200 Two numbers mistakenly calculated as 61 and 34 instead of 16 and 43. So, 61 + 34 = 95 16 + 43 = 59 Diff = 95 – 59 = 36 So,Actual sum of 200 numbers = 19200 – 36 = 19164 total numbers are also 190 instead of 200. So, correct average = 19164/190 = 100.86
Question 8: The average age of boys in school is 13 years and of girls is 12 years. If the total number of boys is 240, then find the number of girls if the average of school is 12 years 8 months. Solution: Average age of 240 boys = 13 years Sum of the age of 240 boys = 240 x 13 Let a be the number of girls in school. than Sum of the age of girls = 12a Total number of boys and girls in school = (240 + a) Total sum of age of boys and girls = (240 + a)12 year 8 month Acc. to question 240x13y + 12a = (240 + a)12y8m change years into month 240x13x12 + (12×12)a = (240 + a)(12×12 + 8) 37440 + 144a = 36480 + 152a 8a = 960 a = 120 Hence, the number of girls in school is 120. Alternate solution:
Question 9: A batsman scored 120 runs in his 16th innings due to this his average increased by 5 runs. Find his current average. Solution: Let the average of 15 innings is A. Acc. to question 15A + 120 = 16(A + 5) =>15A + 120 = 16A + 80 =>A = 40 Hence, current average of the batsman is (40 + 5) = 45
Question 10: There are three natural numbers if the average of any two numbers is added with the third number 48,40 and 36 will be obtained. Find all the natural numbers. Solution: Let a,b and c are the numbers. Given (a+b)/2 + c = 48 => a + b + 2c = 96 .........(1) (b+c)/2 + a = 40 => 2a + b + c = 80 ..........(2) (c+a)/2 + b = 36 => a + 2b + c = 72 ..........(3) Add (1)(2)(3), we get 4(a + b + c) = 248 a + b + c = 62 Put value of (a+b+c) in (1)(2) and (3)to get individual values 1)(a+b+c) + c = 96 62 + c = 96 c = 34 2)a + (a+b+c) = 80 a + 62 = 80 a = 18 3) b + (a+b+c) = 72 b + 62 = 72 b = 10
Question 11: A biker travels at speed of 60 km/hr from A to B and returns with a speed of 40 km/hr. What is the average speed of the total journey? Solution: Let a is the distance between A and B. Total distance travel in journey = 2a Time to travel from A to B = Distance/speed = a/60 Time to travel from B to A = Distance/speed = a/40 Total time of journey = a/60 + a/40 Average speed = Total distance/total time =2a / (a/60 + a/40) =240 x 2a /10a = 240/5 = 48 Hence, the average speed is 48 km/hr.
Question 12: The average age of 15 boys is increased by 4 years when two new girls replace two girls of age 16 years and 18 years. Find the average age of the two new girls?
Solution: The total age increase is 15×4 year= 60 years
The total age of new girls added is 16+18+60= 94 years
The average age of two new girls added is 94/2= 47 years
pujasingg43
pippallasiddu
singh_teekam
Aptitude
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Puzzle | How much money did the man have before entering the bank?
Aptitude | Arithmetic Aptitude 6 | Question 1
Maximum GCD of all subarrays of length at least 2
Aptitude | Arithmetic Aptitude 2 | Question 3
Aptitude | GATE CS 1998 | Question 49
Puzzle | Splitting a Cake with a Missing Piece in two equal portion
Order and Ranking Questions & Answers
Length of race track based on the final distance between participants
Aptitude | Arithmetic Aptitude | Question 4
10 Tips and Tricks to Crack Internships and Placements | [
{
"code": null,
"e": 24644,
"s": 24616,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 24863,
"s": 24644,
"text": "Average a number expressing the central or typical value in a set of data, in particular the mode, median, or (most commonly) the mean, which is calculated by dividing the sum of the values in the set by their number. "
},
{
"code": null,
"e": 24930,
"s": 24863,
"text": "The basic formula for the average of n numbers x1,x2,......xn is "
},
{
"code": null,
"e": 24968,
"s": 24930,
"text": " A = (x1 + x2 ........xn)/ n"
},
{
"code": null,
"e": 24988,
"s": 24968,
"text": "Important points: "
},
{
"code": null,
"e": 25492,
"s": 24988,
"text": "1. Sum of first n natural number = n(n + 1)/2\n Average of first n natural number = (n + 1)/2\n\n2. Sum of square of first n natural number = n(n+1)(2n+1)/6\n Avg. of square of first n natural number = (n+1)(2n+1)/6\n\n3. Sum of cube of first n natural number = [n(n+1)/2]2\n Avg. of cube of first n natural number = (n(n+1)2\n\n4. Sum of first n natural odd number = n2\n Avg. of first n natural odd number = n\n\n5. Sum of first n natural even number = n(n+1)\n Avg. of first n natural even number = n+1"
},
{
"code": null,
"e": 25509,
"s": 25492,
"text": "Sample problems "
},
{
"code": null,
"e": 25808,
"s": 25509,
"text": "Question :1 Find the average of the square of first 16 natural number is: Solution : We know that Sum of square of first n natural number = n(n+1)(2n+1)/6 Avg. of square of first n natural number = (n+1)(2n+1)/6 So, Avg. of square of first 16 natural number = (16+1)(2×16+1)/6 = 17 x 33 /6 = 187/2 "
},
{
"code": null,
"e": 26221,
"s": 25808,
"text": "Question 2: The average of 9 observations is 87. If the average of the first five observations is 79 and the average of the next three is 92. Find the 9th observation. Solution : Average of 9 observations = 87 So, Sum of 9 observations = 87 x 9 = 783 Average of first 5 observations = 79 The sum of first 5 observations = 79 x 5 = 395 The sum of 6th,7th and 8th = 92 x 3 = 276 9th number = 783 – 395 – 276 = 112 "
},
{
"code": null,
"e": 26604,
"s": 26221,
"text": "Question 3: Five years ago the average of the Husband and wife was 25 years, today the average age of the Husband, wife, and child is 21 years. How old is the child? Solution : H + W = 25 Sum of ages of both 5 years before = 25×2 = 50 Today, sum of there ages is = 50 + 5 + 5 = 60 Today avg. of H + W + C = 21 Sum of ages of H , W and C = 21×3 = 63 Age of child = 63 – 60 = 3 years "
},
{
"code": null,
"e": 27283,
"s": 26604,
"text": "Question 4: The average of mother, father and son was 44 years at the time of marriage of the son. After 1 year an infant was born and after 5 years of marriage, the average age of the family becomes 37 years. Find the age of the bride at the time of the marriage. Solution : Sum of ages of F + M + S = 44 x 3 = 132 years Sum of ages of M + F + S + D + C = 37 x 5 = 185 years Sum of ages of (M + F + S) = 132 + 3×5 = 147 years Sum of ages of D + C after 5 years = 185 – 147 = 38 years D + C = 38 The child was born after 1 year of marriage so present age of the child is 4 year then D + 4 = 38 D = 34 years at present So,at the time of marriage bride age was= 34 – 5 = 29 years "
},
{
"code": null,
"e": 27763,
"s": 27283,
"text": "Question 5: The average temp. of Monday, Tuesday, Wednesday and Thursday are 31o, and the average temp. of Tuesday, Wednesday, Thursday, and Friday are 29.5o. If the temp of Friday is 4/5 times of Monday. Find the temp of Monday. Solution :Find Sum Sum of temp. of M + T + W + Th = 31 x 4 = 124..........(1) Sum of temp. of T + W + Th + F = 29.5 x 4 = 118.........(2) Subtract (2) for (1) M – F = 6 Given F = (4/5)M M/F = 5/4 then 5x – 4x = 6 x = 6 Temp. of Monday = 5 x 6 = 30o "
},
{
"code": null,
"e": 28266,
"s": 27763,
"text": "Question 6: There are 42 students in a hostel. If the number of students increased by 14. The expense of mess increased by Rs 28 per day. While the average expenditure per head decreased by Rs 2. Find the original expenditure. Solution : Total students after increment = 42 + 14 = 56 Let the expenditure of students is A Rs/day. Increase in expenditure Rs 28/day. Acc. to question 42A + 28 = 56(A – 2) 42A + 28 = 56A – 112 14A = 140 A = 10 Hence, the original expenditure of the student was Rs 10/day. "
},
{
"code": null,
"e": 28802,
"s": 28266,
"text": "Question 7: The average of 200 numbers is 96 but it was found that 2 numbers 16 and 43 are mistakenly calculated as 61 and 34. Find his correct average it was also found that the total number is only 190. Solution : Average of 200 numbers = 96 Sum of 200 numbers = 96 x 200 = 19200 Two numbers mistakenly calculated as 61 and 34 instead of 16 and 43. So, 61 + 34 = 95 16 + 43 = 59 Diff = 95 – 59 = 36 So,Actual sum of 200 numbers = 19200 – 36 = 19164 total numbers are also 190 instead of 200. So, correct average = 19164/190 = 100.86 "
},
{
"code": null,
"e": 29500,
"s": 28802,
"text": "Question 8: The average age of boys in school is 13 years and of girls is 12 years. If the total number of boys is 240, then find the number of girls if the average of school is 12 years 8 months. Solution: Average age of 240 boys = 13 years Sum of the age of 240 boys = 240 x 13 Let a be the number of girls in school. than Sum of the age of girls = 12a Total number of boys and girls in school = (240 + a) Total sum of age of boys and girls = (240 + a)12 year 8 month Acc. to question 240x13y + 12a = (240 + a)12y8m change years into month 240x13x12 + (12×12)a = (240 + a)(12×12 + 8) 37440 + 144a = 36480 + 152a 8a = 960 a = 120 Hence, the number of girls in school is 120. Alternate solution: "
},
{
"code": null,
"e": 29802,
"s": 29500,
"text": "Question 9: A batsman scored 120 runs in his 16th innings due to this his average increased by 5 runs. Find his current average. Solution: Let the average of 15 innings is A. Acc. to question 15A + 120 = 16(A + 5) =>15A + 120 = 16A + 80 =>A = 40 Hence, current average of the batsman is (40 + 5) = 45 "
},
{
"code": null,
"e": 30404,
"s": 29802,
"text": "Question 10: There are three natural numbers if the average of any two numbers is added with the third number 48,40 and 36 will be obtained. Find all the natural numbers. Solution: Let a,b and c are the numbers. Given (a+b)/2 + c = 48 => a + b + 2c = 96 .........(1) (b+c)/2 + a = 40 => 2a + b + c = 80 ..........(2) (c+a)/2 + b = 36 => a + 2b + c = 72 ..........(3) Add (1)(2)(3), we get 4(a + b + c) = 248 a + b + c = 62 Put value of (a+b+c) in (1)(2) and (3)to get individual values 1)(a+b+c) + c = 96 62 + c = 96 c = 34 2)a + (a+b+c) = 80 a + 62 = 80 a = 18 3) b + (a+b+c) = 72 b + 62 = 72 b = 10 "
},
{
"code": null,
"e": 30906,
"s": 30404,
"text": "Question 11: A biker travels at speed of 60 km/hr from A to B and returns with a speed of 40 km/hr. What is the average speed of the total journey? Solution: Let a is the distance between A and B. Total distance travel in journey = 2a Time to travel from A to B = Distance/speed = a/60 Time to travel from B to A = Distance/speed = a/40 Total time of journey = a/60 + a/40 Average speed = Total distance/total time =2a / (a/60 + a/40) =240 x 2a /10a = 240/5 = 48 Hence, the average speed is 48 km/hr. "
},
{
"code": null,
"e": 31081,
"s": 30906,
"text": " Question 12: The average age of 15 boys is increased by 4 years when two new girls replace two girls of age 16 years and 18 years. Find the average age of the two new girls?"
},
{
"code": null,
"e": 31137,
"s": 31081,
"text": "Solution: The total age increase is 15×4 year= 60 years"
},
{
"code": null,
"e": 31192,
"s": 31137,
"text": "The total age of new girls added is 16+18+60= 94 years"
},
{
"code": null,
"e": 31249,
"s": 31192,
"text": "The average age of two new girls added is 94/2= 47 years"
},
{
"code": null,
"e": 31261,
"s": 31249,
"text": "pujasingg43"
},
{
"code": null,
"e": 31275,
"s": 31261,
"text": "pippallasiddu"
},
{
"code": null,
"e": 31288,
"s": 31275,
"text": "singh_teekam"
},
{
"code": null,
"e": 31297,
"s": 31288,
"text": "Aptitude"
},
{
"code": null,
"e": 31395,
"s": 31297,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31462,
"s": 31395,
"text": "Puzzle | How much money did the man have before entering the bank?"
},
{
"code": null,
"e": 31508,
"s": 31462,
"text": "Aptitude | Arithmetic Aptitude 6 | Question 1"
},
{
"code": null,
"e": 31558,
"s": 31508,
"text": "Maximum GCD of all subarrays of length at least 2"
},
{
"code": null,
"e": 31604,
"s": 31558,
"text": "Aptitude | Arithmetic Aptitude 2 | Question 3"
},
{
"code": null,
"e": 31642,
"s": 31604,
"text": "Aptitude | GATE CS 1998 | Question 49"
},
{
"code": null,
"e": 31710,
"s": 31642,
"text": "Puzzle | Splitting a Cake with a Missing Piece in two equal portion"
},
{
"code": null,
"e": 31748,
"s": 31710,
"text": "Order and Ranking Questions & Answers"
},
{
"code": null,
"e": 31818,
"s": 31748,
"text": "Length of race track based on the final distance between participants"
},
{
"code": null,
"e": 31862,
"s": 31818,
"text": "Aptitude | Arithmetic Aptitude | Question 4"
}
] |
Detect Cycle in a Directed Graph - GeeksforGeeks | 22 Apr, 2022
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false.Example,
Input: n = 4, e = 6
0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3
Output: Yes
Explanation:
Diagram:
The diagram clearly shows a cycle 0 -> 2 -> 0
Input:n = 4, e = 4
0 -> 1, 0 -> 2, 1 -> 2, 2 -> 3
Output:No
Explanation:
Diagram:
The diagram clearly shows no cycle
Solution using Depth First Search or DFS
Approach: Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (self-loop) or one of its ancestors in the tree produced by DFS. In the following graph, there are 3 back edges, marked with a cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph.
For a disconnected graph, Get the DFS forest as output. To detect cycle, check for a cycle in individual trees by checking back edges.To detect a back edge, keep track of vertices currently in the recursion stack of function for DFS traversal. If a vertex is reached that is already in the recursion stack, then there is a cycle in the tree. The edge that connects the current vertex to the vertex in the recursion stack is a back edge. Use recStack[] array to keep track of vertices in the recursion stack.Dry run of the above approach:
In the above image there is a mistake node 1 is making a directed edge to 2 not with 0 please make a note.
Algorithm: Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false.
Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false.
Create the graph using the given number of edges and vertices.
Create a recursive function that initializes the current index or vertex, visited, and recursion stack.
Mark the current node as visited and also mark the index in recursion stack.
Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.
If the adjacent vertices are already marked in the recursion stack then return true.
Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false.
Implementation:
C++
Java
Python
C#
Javascript
// A C++ Program to detect cycle in a graph#include<bits/stdc++.h> using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency lists bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic()public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isCyclic(); // returns true if there is a cycle in this graph}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // This function is a variation of DFSUtil() in https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack){ if(visited[v] == false) { // Mark the current node as visited and part of recursion stack visited[v] = true; recStack[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) return true; else if (recStack[*i]) return true; } } recStack[v] = false; // remove the vertex from recursion stack return false;} // Returns true if the graph contains a cycle, else false.// This function is a variation of DFS() in https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclic(){ // Mark all the vertices as not visited and not part of recursion // stack bool *visited = new bool[V]; bool *recStack = new bool[V]; for(int i = 0; i < V; i++) { visited[i] = false; recStack[i] = false; } // Call the recursive helper function to detect cycle in different // DFS trees for(int i = 0; i < V; i++) if ( !visited[i] && isCyclicUtil(i, visited, recStack)) return true; return false;} int main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); if(g.isCyclic()) cout << "Graph contains cycle"; else cout << "Graph doesn't contain cycle"; return 0;}
// A Java Program to detect cycle in a graphimport java.util.ArrayList;import java.util.LinkedList;import java.util.List; class Graph { private final int V; private final List<List<Integer>> adj; public Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) adj.add(new LinkedList<>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj.get(i); for (Integer c: children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int source, int dest) { adj.get(source).add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[V]; boolean[] recStack = new boolean[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) System.out.println("Graph contains cycle"); else System.out.println("Graph doesn't " + "contain cycle"); }} // This code is contributed by Sagar Shah.
# Python program to detect cycle# in a graph from collections import defaultdict class Graph(): def __init__(self,vertices): self.graph = defaultdict(list) self.V = vertices def addEdge(self,u,v): self.graph[u].append(v) def isCyclicUtil(self, v, visited, recStack): # Mark current node as visited and # adds to recursion stack visited[v] = True recStack[v] = True # Recur for all neighbours # if any neighbour is visited and in # recStack then graph is cyclic for neighbour in self.graph[v]: if visited[neighbour] == False: if self.isCyclicUtil(neighbour, visited, recStack) == True: return True elif recStack[neighbour] == True: return True # The node needs to be popped from # recursion stack before function ends recStack[v] = False return False # Returns true if graph is cyclic else false def isCyclic(self): visited = [False] * (self.V + 1) recStack = [False] * (self.V + 1) for node in range(self.V): if visited[node] == False: if self.isCyclicUtil(node,visited,recStack) == True: return True return False g = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)if g.isCyclic() == 1: print "Graph has a cycle"else: print "Graph has no cycle" # Thanks to Divyanshu Mehta for contributing this code
// A C# Program to detect cycle in a graphusing System;using System.Collections.Generic; public class Graph { private readonly int V; private readonly List<List<int>> adj; public Graph(int V) { this.V = V; adj = new List<List<int>>(V); for (int i = 0; i < V; i++) adj.Add(new List<int>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclicUtil(int i, bool[] visited, bool[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<int> children = adj[i]; foreach (int c in children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int sou, int dest) { adj[sou].Add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack bool[] visited = new bool[V]; bool[] recStack = new bool[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void Main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) Console.WriteLine("Graph contains cycle"); else Console.WriteLine("Graph doesn't " + "contain cycle"); }} // This code contributed by Rajput-Ji
<script> // A JavaScript Program to detect cycle in a graph let V;let adj=[];function Graph(v){ V=v; for (let i = 0; i < V; i++) adj.push([]);} // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212function isCyclicUtil(i,visited,recStack){ // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; let children = adj[i]; for (let c=0;c< children.length;c++) if (isCyclicUtil(children, visited, recStack)) return true; recStack[i] = false; return false;} function addEdge(source,dest){ adj.push(dest);} // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212function isCyclic(){ // Mark all the vertices as not visited and // not part of recursion stack let visited = new Array(V); let recStack = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; recStack[i]=false; } // Call the recursive helper function to // detect cycle in different DFS trees for (let i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false;} // Driver codeGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(1, 2);addEdge(2, 0);addEdge(2, 3);addEdge(3, 3); if(isCyclic()) document.write("Graph contains cycle");else document.write("Graph doesn't " + "contain cycle"); // This code is contributed by patel2127 </script>
Output:
Graph contains cycle
Complexity Analysis: Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E).Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed.
Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E).
Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed.
YouTubeGeeksforGeeks500K subscribersDetect Cycle in a Directed Graph | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:14•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=joqmqvHC_Bo" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
In the below article, another O(V + E) method is discussed : Detect Cycle in a direct graph using colorsPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SagarShah1
AmanjotKaur3
kyungsut
Rajput-Ji
andrew1234
nailwalhimanshu
muhammedazeem
nikhilis18
avanitrachhadiya2155
rishi2024csit1073
codingbeastsaysyadav
Adobe
Amazon
BankBazaar
DFS
Flipkart
graph-cycle
MakeMyTrip
Microsoft
Oracle
Rockstand
Samsung
Graph
Flipkart
Amazon
Microsoft
Samsung
MakeMyTrip
Oracle
Adobe
BankBazaar
Rockstand
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
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
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Traveling Salesman Problem (TSP) Implementation
Strongly Connected Components | [
{
"code": null,
"e": 37369,
"s": 37341,
"text": "\n22 Apr, 2022"
},
{
"code": null,
"e": 37552,
"s": 37369,
"text": "Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false.Example, "
},
{
"code": null,
"e": 37653,
"s": 37552,
"text": "Input: n = 4, e = 6\n0 -> 1, 0 -> 2, 1 -> 2, 2 -> 0, 2 -> 3, 3 -> 3\nOutput: Yes\nExplanation:\nDiagram:"
},
{
"code": null,
"e": 37783,
"s": 37653,
"text": "The diagram clearly shows a cycle 0 -> 2 -> 0\n\n\nInput:n = 4, e = 4\n0 -> 1, 0 -> 2, 1 -> 2, 2 -> 3\nOutput:No\nExplanation:\nDiagram:"
},
{
"code": null,
"e": 37818,
"s": 37783,
"text": "The diagram clearly shows no cycle"
},
{
"code": null,
"e": 37860,
"s": 37818,
"text": "Solution using Depth First Search or DFS "
},
{
"code": null,
"e": 38328,
"s": 37860,
"text": "Approach: Depth First Traversal can be used to detect a cycle in a Graph. DFS for a connected graph produces a tree. There is a cycle in a graph only if there is a back edge present in the graph. A back edge is an edge that is from a node to itself (self-loop) or one of its ancestors in the tree produced by DFS. In the following graph, there are 3 back edges, marked with a cross sign. We can observe that these 3 back edges indicate 3 cycles present in the graph. "
},
{
"code": null,
"e": 38868,
"s": 38328,
"text": "For a disconnected graph, Get the DFS forest as output. To detect cycle, check for a cycle in individual trees by checking back edges.To detect a back edge, keep track of vertices currently in the recursion stack of function for DFS traversal. If a vertex is reached that is already in the recursion stack, then there is a cycle in the tree. The edge that connects the current vertex to the vertex in the recursion stack is a back edge. Use recStack[] array to keep track of vertices in the recursion stack.Dry run of the above approach: "
},
{
"code": null,
"e": 38975,
"s": 38868,
"text": "In the above image there is a mistake node 1 is making a directed edge to 2 not with 0 please make a note."
},
{
"code": null,
"e": 39686,
"s": 38975,
"text": "Algorithm: Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false."
},
{
"code": null,
"e": 40386,
"s": 39686,
"text": "Create the graph using the given number of edges and vertices.Create a recursive function that initializes the current index or vertex, visited, and recursion stack.Mark the current node as visited and also mark the index in recursion stack.Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true.If the adjacent vertices are already marked in the recursion stack then return true.Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false."
},
{
"code": null,
"e": 40449,
"s": 40386,
"text": "Create the graph using the given number of edges and vertices."
},
{
"code": null,
"e": 40553,
"s": 40449,
"text": "Create a recursive function that initializes the current index or vertex, visited, and recursion stack."
},
{
"code": null,
"e": 40630,
"s": 40553,
"text": "Mark the current node as visited and also mark the index in recursion stack."
},
{
"code": null,
"e": 40815,
"s": 40630,
"text": "Find all the vertices which are not visited and are adjacent to the current node. Recursively call the function for those vertices, If the recursive function returns true, return true."
},
{
"code": null,
"e": 40900,
"s": 40815,
"text": "If the adjacent vertices are already marked in the recursion stack then return true."
},
{
"code": null,
"e": 41091,
"s": 40900,
"text": "Create a wrapper class, that calls the recursive function for all the vertices and if any function returns true return true. Else if for all vertices the function returns false return false."
},
{
"code": null,
"e": 41109,
"s": 41091,
"text": "Implementation: "
},
{
"code": null,
"e": 41115,
"s": 41111,
"text": "C++"
},
{
"code": null,
"e": 41120,
"s": 41115,
"text": "Java"
},
{
"code": null,
"e": 41127,
"s": 41120,
"text": "Python"
},
{
"code": null,
"e": 41130,
"s": 41127,
"text": "C#"
},
{
"code": null,
"e": 41141,
"s": 41130,
"text": "Javascript"
},
{
"code": "// A C++ Program to detect cycle in a graph#include<bits/stdc++.h> using namespace std; class Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency lists bool isCyclicUtil(int v, bool visited[], bool *rs); // used by isCyclic()public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isCyclic(); // returns true if there is a cycle in this graph}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list.} // This function is a variation of DFSUtil() in https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclicUtil(int v, bool visited[], bool *recStack){ if(visited[v] == false) { // Mark the current node as visited and part of recursion stack visited[v] = true; recStack[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for(i = adj[v].begin(); i != adj[v].end(); ++i) { if ( !visited[*i] && isCyclicUtil(*i, visited, recStack) ) return true; else if (recStack[*i]) return true; } } recStack[v] = false; // remove the vertex from recursion stack return false;} // Returns true if the graph contains a cycle, else false.// This function is a variation of DFS() in https://www.geeksforgeeks.org/archives/18212bool Graph::isCyclic(){ // Mark all the vertices as not visited and not part of recursion // stack bool *visited = new bool[V]; bool *recStack = new bool[V]; for(int i = 0; i < V; i++) { visited[i] = false; recStack[i] = false; } // Call the recursive helper function to detect cycle in different // DFS trees for(int i = 0; i < V; i++) if ( !visited[i] && isCyclicUtil(i, visited, recStack)) return true; return false;} int main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); if(g.isCyclic()) cout << \"Graph contains cycle\"; else cout << \"Graph doesn't contain cycle\"; return 0;}",
"e": 43433,
"s": 41141,
"text": null
},
{
"code": "// A Java Program to detect cycle in a graphimport java.util.ArrayList;import java.util.LinkedList;import java.util.List; class Graph { private final int V; private final List<List<Integer>> adj; public Graph(int V) { this.V = V; adj = new ArrayList<>(V); for (int i = 0; i < V; i++) adj.add(new LinkedList<>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclicUtil(int i, boolean[] visited, boolean[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<Integer> children = adj.get(i); for (Integer c: children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int source, int dest) { adj.get(source).add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private boolean isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack boolean[] visited = new boolean[V]; boolean[] recStack = new boolean[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) System.out.println(\"Graph contains cycle\"); else System.out.println(\"Graph doesn't \" + \"contain cycle\"); }} // This code is contributed by Sagar Shah.",
"e": 45780,
"s": 43433,
"text": null
},
{
"code": "# Python program to detect cycle# in a graph from collections import defaultdict class Graph(): def __init__(self,vertices): self.graph = defaultdict(list) self.V = vertices def addEdge(self,u,v): self.graph[u].append(v) def isCyclicUtil(self, v, visited, recStack): # Mark current node as visited and # adds to recursion stack visited[v] = True recStack[v] = True # Recur for all neighbours # if any neighbour is visited and in # recStack then graph is cyclic for neighbour in self.graph[v]: if visited[neighbour] == False: if self.isCyclicUtil(neighbour, visited, recStack) == True: return True elif recStack[neighbour] == True: return True # The node needs to be popped from # recursion stack before function ends recStack[v] = False return False # Returns true if graph is cyclic else false def isCyclic(self): visited = [False] * (self.V + 1) recStack = [False] * (self.V + 1) for node in range(self.V): if visited[node] == False: if self.isCyclicUtil(node,visited,recStack) == True: return True return False g = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3)if g.isCyclic() == 1: print \"Graph has a cycle\"else: print \"Graph has no cycle\" # Thanks to Divyanshu Mehta for contributing this code",
"e": 47307,
"s": 45780,
"text": null
},
{
"code": "// A C# Program to detect cycle in a graphusing System;using System.Collections.Generic; public class Graph { private readonly int V; private readonly List<List<int>> adj; public Graph(int V) { this.V = V; adj = new List<List<int>>(V); for (int i = 0; i < V; i++) adj.Add(new List<int>()); } // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclicUtil(int i, bool[] visited, bool[] recStack) { // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; List<int> children = adj[i]; foreach (int c in children) if (isCyclicUtil(c, visited, recStack)) return true; recStack[i] = false; return false; } private void addEdge(int sou, int dest) { adj[sou].Add(dest); } // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212 private bool isCyclic() { // Mark all the vertices as not visited and // not part of recursion stack bool[] visited = new bool[V]; bool[] recStack = new bool[V]; // Call the recursive helper function to // detect cycle in different DFS trees for (int i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false; } // Driver code public static void Main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 2); graph.addEdge(2, 0); graph.addEdge(2, 3); graph.addEdge(3, 3); if(graph.isCyclic()) Console.WriteLine(\"Graph contains cycle\"); else Console.WriteLine(\"Graph doesn't \" + \"contain cycle\"); }} // This code contributed by Rajput-Ji",
"e": 49582,
"s": 47307,
"text": null
},
{
"code": "<script> // A JavaScript Program to detect cycle in a graph let V;let adj=[];function Graph(v){ V=v; for (let i = 0; i < V; i++) adj.push([]);} // This function is a variation of DFSUtil() in // https://www.geeksforgeeks.org/archives/18212function isCyclicUtil(i,visited,recStack){ // Mark the current node as visited and // part of recursion stack if (recStack[i]) return true; if (visited[i]) return false; visited[i] = true; recStack[i] = true; let children = adj[i]; for (let c=0;c< children.length;c++) if (isCyclicUtil(children, visited, recStack)) return true; recStack[i] = false; return false;} function addEdge(source,dest){ adj.push(dest);} // Returns true if the graph contains a // cycle, else false. // This function is a variation of DFS() in // https://www.geeksforgeeks.org/archives/18212function isCyclic(){ // Mark all the vertices as not visited and // not part of recursion stack let visited = new Array(V); let recStack = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; recStack[i]=false; } // Call the recursive helper function to // detect cycle in different DFS trees for (let i = 0; i < V; i++) if (isCyclicUtil(i, visited, recStack)) return true; return false;} // Driver codeGraph(4);addEdge(0, 1);addEdge(0, 2);addEdge(1, 2);addEdge(2, 0);addEdge(2, 3);addEdge(3, 3); if(isCyclic()) document.write(\"Graph contains cycle\");else document.write(\"Graph doesn't \" + \"contain cycle\"); // This code is contributed by patel2127 </script>",
"e": 51405,
"s": 49582,
"text": null
},
{
"code": null,
"e": 51414,
"s": 51405,
"text": "Output: "
},
{
"code": null,
"e": 51435,
"s": 51414,
"text": "Graph contains cycle"
},
{
"code": null,
"e": 51659,
"s": 51435,
"text": "Complexity Analysis: Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E).Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed."
},
{
"code": null,
"e": 51776,
"s": 51659,
"text": "Time Complexity: O(V+E). Time Complexity of this method is same as time complexity of DFS traversal which is O(V+E)."
},
{
"code": null,
"e": 51863,
"s": 51776,
"text": "Space Complexity: O(V). To store the visited and recursion stack O(V) space is needed."
},
{
"code": null,
"e": 52696,
"s": 51865,
"text": "YouTubeGeeksforGeeks500K subscribersDetect Cycle in a Directed Graph | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 7:14•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=joqmqvHC_Bo\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 52926,
"s": 52696,
"text": "In the below article, another O(V + E) method is discussed : Detect Cycle in a direct graph using colorsPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 52937,
"s": 52926,
"text": "SagarShah1"
},
{
"code": null,
"e": 52950,
"s": 52937,
"text": "AmanjotKaur3"
},
{
"code": null,
"e": 52959,
"s": 52950,
"text": "kyungsut"
},
{
"code": null,
"e": 52969,
"s": 52959,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 52980,
"s": 52969,
"text": "andrew1234"
},
{
"code": null,
"e": 52996,
"s": 52980,
"text": "nailwalhimanshu"
},
{
"code": null,
"e": 53010,
"s": 52996,
"text": "muhammedazeem"
},
{
"code": null,
"e": 53021,
"s": 53010,
"text": "nikhilis18"
},
{
"code": null,
"e": 53042,
"s": 53021,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 53060,
"s": 53042,
"text": "rishi2024csit1073"
},
{
"code": null,
"e": 53081,
"s": 53060,
"text": "codingbeastsaysyadav"
},
{
"code": null,
"e": 53087,
"s": 53081,
"text": "Adobe"
},
{
"code": null,
"e": 53094,
"s": 53087,
"text": "Amazon"
},
{
"code": null,
"e": 53105,
"s": 53094,
"text": "BankBazaar"
},
{
"code": null,
"e": 53109,
"s": 53105,
"text": "DFS"
},
{
"code": null,
"e": 53118,
"s": 53109,
"text": "Flipkart"
},
{
"code": null,
"e": 53130,
"s": 53118,
"text": "graph-cycle"
},
{
"code": null,
"e": 53141,
"s": 53130,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 53151,
"s": 53141,
"text": "Microsoft"
},
{
"code": null,
"e": 53158,
"s": 53151,
"text": "Oracle"
},
{
"code": null,
"e": 53168,
"s": 53158,
"text": "Rockstand"
},
{
"code": null,
"e": 53176,
"s": 53168,
"text": "Samsung"
},
{
"code": null,
"e": 53182,
"s": 53176,
"text": "Graph"
},
{
"code": null,
"e": 53191,
"s": 53182,
"text": "Flipkart"
},
{
"code": null,
"e": 53198,
"s": 53191,
"text": "Amazon"
},
{
"code": null,
"e": 53208,
"s": 53198,
"text": "Microsoft"
},
{
"code": null,
"e": 53216,
"s": 53208,
"text": "Samsung"
},
{
"code": null,
"e": 53227,
"s": 53216,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 53234,
"s": 53227,
"text": "Oracle"
},
{
"code": null,
"e": 53240,
"s": 53234,
"text": "Adobe"
},
{
"code": null,
"e": 53251,
"s": 53240,
"text": "BankBazaar"
},
{
"code": null,
"e": 53261,
"s": 53251,
"text": "Rockstand"
},
{
"code": null,
"e": 53265,
"s": 53261,
"text": "DFS"
},
{
"code": null,
"e": 53271,
"s": 53265,
"text": "Graph"
},
{
"code": null,
"e": 53369,
"s": 53271,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 53378,
"s": 53369,
"text": "Comments"
},
{
"code": null,
"e": 53391,
"s": 53378,
"text": "Old Comments"
},
{
"code": null,
"e": 53442,
"s": 53391,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 53493,
"s": 53442,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 53551,
"s": 53493,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 53582,
"s": 53551,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 53615,
"s": 53582,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 53683,
"s": 53615,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 53758,
"s": 53683,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 53808,
"s": 53758,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 53856,
"s": 53808,
"text": "Traveling Salesman Problem (TSP) Implementation"
}
] |
Complete guide to Python’s cross-validation with examples | by Vaclav Dekanovsky | Towards Data Science | Examples and use cases of sklearn’s cross-validation explaining KFold, shuffling, stratification, and the data ratio of the train and test sets.
Cross-validation is an important concept in machine learning which helps the data scientists in two major ways: it can reduce the size of data and ensures that the artificial intelligence model is robust enough. Cross validation does that at the cost of resource consumption, so it’s important to understand how it works before you decide to use it.
In this article, we will briefly review the benefits of cross-validation and afterward I’ll show you detailed application using a broad variety of methods in the popular python Sklearn library. We will learn:
What is KFold, ShuffledKfold and StratifiedKfold and see how they differ
How to cross validate your model without KFold using cross_validate and cross_val_score methods
What are the other split options — RepeatedKFold, LeaveOneOut and LeavePOut and an usecase for GroupKFold
How important it is to consider target and feature distribution
Normally you split the data into 3 sets.
Training: used to train the model and optimize the model’s hyperparameters
Testing: used to check that the optimized model works on unknown data to test that the model generalizes well
Validation: during optimizing some information about test set leaks into the model by your choice of the parameters so you perform a final check on completely unknown data
Introducing cross-validation into the process helps you to reduce the need for the validation set because you’re able to train and test on the same data.
In most common cross-validation approach you use part of the training set for testing. You do it several times so that each data point appears once in the test set.
Even though sklearn’s train_test_split method is using a stratified split, which means that the train and test set have the same distribution of the target variable, it’s possible that you accidentally train on a subset which doesn’t reflect the real world.
Imagine that you try to predict whether a person is a male or a female by his or her height and weight. One would assume that taller and heavier people would rather be males; though if you’re very unlucky your train data would only contain dwarf men and tall Amazon women. Thanks to cross validation you perform multiple train_test split and while one fold can achieve extraordinary good results the other might underperform. Anytime one of the splits shows unusual results it means that there’s an anomaly in your data.
If your cross-validation split doesn’t achieve similar score, you have missed something important about the data.
You can always write your own function to split the data, but scikit-learn already contains cover 10 methods for splitting the data which allows you to tackle almost any problem.
Let’s start coding though. You download the complete example on github.
As a first step let’s create a simple range of numbers from 1,2,3 ... 24,25.
# create the range 1 to 25rn = range(1,26)
Then let’s initiate sklearn’s Kfold method without shuffling, which is the simplest option for how to split the data. I’ll create two Kfolds, one splitting data 3-times and other doing 5 folds.
from sklearn.model_selection import KFoldkf5 = KFold(n_splits=5, shuffle=False)kf3 = KFold(n_splits=3, shuffle=False)
If I pass my range to the KFold it will return two lists containing indices of the data points which would fall into train and test set.
# the Kfold function retunrs the indices of the data. Our range goes from 1-25 so the index is 0-24for train_index, test_index in kf3.split(rn): print(train_index, test_index)
KFold returns indices not the real datapoints.
Since KFold returns the index, if you want to see the real data we must use np.take in NumPy array or .iloc in pandas.
# to get the values from our data, we use np.take() to access a value at particular indexfor train_index, test_index in kf3.split(rn): print(np.take(rn,train_index), np.take(rn,test_index))
# Import scikit-learn libraries
from sklearn.model_selection import KFold
import numpy as np
# create the range 1 to 25
rn = range(1,26)
# to demonstrate how the data are split, we will create 3 and 5 folds.
# KFold function has to be applied on the data and it returns an location (index) of the train and test samples.
kf5 = KFold(n_splits=5, shuffle=False)
kf3 = KFold(n_splits=3, shuffle=False)
# the Kfold function retunrs the indices of the data. Our range goes from 1-25 so the index is 0-24
for train_index, test_index in kf3.split(rn):
print(train_index, test_index)
[ 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24] [0 1 2 3 4 5 6 7 8]
[ 0 1 2 3 4 5 6 7 8 17 18 19 20 21 22 23 24] [ 9 10 11 12 13 14 15 16]
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] [17 18 19 20 21 22 23 24]
# to get the values from our data, we use np.take() to access a value at particular index
for train_index, test_index in kf3.split(rn):
print(np.take(rn,train_index), np.take(rn,test_index))
[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25] [1 2 3 4 5 6 7 8 9]
[ 1 2 3 4 5 6 7 8 9 18 19 20 21 22 23 24 25] [10 11 12 13 14 15 16 17]
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17] [18 19 20 21 22 23 24 25]
To better understand how the KFold method divides the data, let’s display it on a chart. Because we have used shuffled=False the first data point belongs to the test set in the first fold, the next one as well. The test and train data points are nicely arranged.
It’s important to say that the number of fold influences that size of your test set. 3 folds tests on 33% of the data while 5 folds on 1/5 which equals to 20% of the data.
Each data points appears once in the test set and k-times in the train set
# Import scikit-learn libraries
from sklearn.model_selection import KFold
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# create the range 1 to 25
rn = range(1,26)
# to demonstrate how the data are split, we will create 3 and 5 folds.
# KFold function has to be applied on the data and it returns an location (index) of the train and test samples.
kf5 = KFold(n_splits=5, shuffle=False)
kf3 = KFold(n_splits=3, shuffle=False)
# Let's split our test range into 5 and3 folds and display the splits on the chart.
# In order to clearly show which data belongs to each set, we will shift the values by -.1 and +.1
# the first fold will contain values 0.9 in train and 1.1 in the test set, second 1.9 and 2.1, etc.
# we will also give each sets the different color
# because we will repeat this exercise for the shuffled version, let's create a function
def kfoldize(kf, rn, shift=.1):
train = pd.DataFrame()
test = pd.DataFrame()
i = 1
for train_index, test_index in kf.split(rn):
train_df = pd.DataFrame(np.take(rn, train_index), columns=["x"])
train_df["val"] = i - shift
train = train.append(train_df)
test_df = pd.DataFrame(np.take(rn, test_index), columns=["x"])
test_df["val"] = i + shift
test = test.append(test_df)
i += 1
return train, test
train5, test5 = kfoldize(kf5,rn)
train3, test3 = kfoldize(kf3,rn)
fig,ax = plt.subplots(1,2, figsize=(15,5))
ax[0].scatter(x="x",y="val",c="b",label="train",s=15,data=train5)
ax[0].scatter(x="x",y="val",c="r",label="test",s=15,data=test5)
ax[1].scatter(x="x",y="val",c="b",label="train",s=15,data=train3)
ax[1].scatter(x="x",y="val",c="r",label="test",s=15,data=test3)
ax[0].set_ylabel("Kfold")
ax[0].set_xlabel("feature")
ax[1].set_xlabel("feature")
ax[0].set_title("5 Folds")
ax[1].set_title("3 Folds")
plt.suptitle("Kfold split between train and test features")
plt.legend(bbox_to_anchor=(1.05, 1))
plt.show()
Your data might follow a specific order and it might be risky to select the data in order of appearance. That can be solved by setting KFold’s shuffle parameter to True. In that case KFold will randomly pick the datapoints which would become part of the train and test set. Or to be precise not completely randomly, random_state influences which points appear each set and the same random_state always results in the same split.
Working on the real problem you will rarely have a small array as an input so let’s have a look at the real example using a well-known Iris dataset.
Iris dataset contain 150 measurements of petal and sepal sizes of 3 varieties of the iris flower —50 Iris setosas, 50 Iris virginicas and 50 Iris versicolors
In the github notebook I run a test using only a single fold which achieves 95% accuracy on the training set and 100% on the test set. What was my surprise when 3-fold split results into exactly 0% accuracy. You read it well, my model did not pick a single flower correctly.
i = 1for train_index, test_index in kf3.split(iris_df): X_train = iris_df.iloc[train_index].loc[:, features] X_test = iris_df.iloc[test_index][features] y_train = iris_df.iloc[train_index].loc[:,'target'] y_test = iris_df.loc[test_index]['target'] #Train the model model.fit(X_train, y_train) #Training the model print(f"Accuracy for the fold no. {i} on the test set: {accuracy_score(y_test, model.predict(X_test))}") i += 1
Do you remember that unshuffled KFold picks the data in order? Our set contains 150 observations, the first 50 belongs to one specie, 51–100 to the other, and the remaining to the third one. Our 3-fold model was very unlucky to always pick measurement of two of the Irises while the test set contained only the flowers which the model has never seen.
To address this problem we can change the shuffled=True parameter and choose the samples randomly. But that also runs into problems.
The groups are still not balanced. You are often training on a much higher number of samples of one type while testing on different types. Let’s see if we can do something about that.
In many scenarios it is important to preserve the same distribution of samples in the train and test set. That is achieved by StratifiedKFold which can again be shuffled or unshuffled.
You can see that the KFold divides the data into the groups which have the kept the ratios. StratifiedKFold reflects the distribution of the target variable even in case some of the values appear more often in the dataset. It doesn’t however evaluate the distribution of the input measurements. We will talk more about that at the end.
To enjoy the benefits of cross-validation you don’t have to split the data manually. Sklearn offers two methods for quick evaluation using cross-validation. cross-val-score returns a list of model scores and cross-validate also reports training times.
# cross_validate also allows to specify metrics which you want to seefor i, score in enumerate(cross_validate(model, X,y, cv=3)["test_score"]): print(f"Accuracy for the fold no. {i} on the test set: {score}")
Besides the functions mentioned above sklearn is endowed with a whole bunch of other methods to help you address specific needs.
Repeated Kfold would create multiple combinations of train-test split.
While regular cross-validation makes sure that you see each data point once in the test set, ShuffleSplit allows you to specify how many features are picked to test in each fold.
LeaveOneOut and LeavePOut solve the need in other special cases. The first one always leaves only one sample to be in the test set.
As a general rule, most authors, and empirical evidence, suggest that 5- or 10- fold cross validation should be preferred to LOO. — sklearn documentation
Group Kfolds
GroupKFold has its place in scenarios when you have multiple data samples taken from the same subject. For example more than one measurement from the same person. It’s likely that data from the same group will behave similarly and if you will train on one of the measurements and test on the other you will get a good score, but it won’t prove that your model generalizes well. GroupKFold assures that the whole group goes either to the train or to the test set. Read more in sklearn documentation about groups.
Problems involving time series are also sensitive to the order of data points. It’s usually much easier to guess past based on current knowledge than to predict the future. For this reason it makes sense to always feed the time series models with older data while predicting the newer ones. Sklearn’s TimeSeriesSplit does exactly that.
There is one last matter which is crucial to highlight. You might think that the stratified split would solve all your machine learning problems, but it’s not true. StratifiedKFold ensures that there remains the same ratio of the targets in both train and test set. In our case 33% of each type of Iris.
To demonstrate that on an unbalanced dataset we will look at popular Kaggle Titanic competition. Your goal would be to train an AI model that would predict whether a passenger on Titanic survived or died when the ship sank. Let’s look at how StratiffiedKFold would divide the survivors and victims in the dataset in each fold.
It looks good, isn’t it? However, your data might still be improperly split. If you look at the distribution of the key features (I purposefully choose this distribution to demonstrate my point, because often it’s enough to shuffle the data to get much more balanced distribution) you will see that you often try to predict the results based on training data which are different from the test set. For example if you look at the distribution of the genders in the train and test sets.
Cross-validation at least helps you to realize this problem in case the score of the model differs significantly for each fold. Imagine you would be so unlucky, using only a single split which would perfectly suit your test data, but catastrophically fail on real-world scenarios.
It a very complex task to balance your data so that you train and test on ideal distribution. Many argue that it’s not necessary, because the model should generalize good enough to work on the unknown data.
I would nevertheless encourage you to think about the distribution of features. Imagine that you would have a shop where customers are mostly men and you would try to predict sales using data from a marketing campaign targeted to women. It wouldn’t be the best model for your shop.
Conclusion
Train-test split is a basic concept in many machine learning assignments, but if you have enough resources consider applying cross-validation to your problem. It will not only help you use less data, but an inconsistent score on the different folds would suggest that you have missed some important relation inside your data.
Sklearn library contains a bunch of methods to split the data to fit your AI exercise. You can create basic KFold, shuffle the data, or stratify them according to the target variable. You can use additional methods or just test your model with cross-validate or cross-val-score without bothering with manual data split. In any case your resulting score should show a stable pattern, because you don’t want your model to depend on ‘lucky’ data split to perform well.
All data, charts, and python processing was summarized in the notebook available on github.
towardsdatascience.com
# did you like the tutorial, check also* Pandas alternatives - Vaex, Dash, PySpark and Julia - and when to use them* Persist pandas in other formats than CSV* Read CSV in Julia, an alternative to python* How to turn list of addresses or regions into a map* Various application of anomaly detection* How to deal with extra whitespaces in CSV using Pandas | [
{
"code": null,
"e": 317,
"s": 172,
"text": "Examples and use cases of sklearn’s cross-validation explaining KFold, shuffling, stratification, and the data ratio of the train and test sets."
},
{
"code": null,
"e": 667,
"s": 317,
"text": "Cross-validation is an important concept in machine learning which helps the data scientists in two major ways: it can reduce the size of data and ensures that the artificial intelligence model is robust enough. Cross validation does that at the cost of resource consumption, so it’s important to understand how it works before you decide to use it."
},
{
"code": null,
"e": 876,
"s": 667,
"text": "In this article, we will briefly review the benefits of cross-validation and afterward I’ll show you detailed application using a broad variety of methods in the popular python Sklearn library. We will learn:"
},
{
"code": null,
"e": 949,
"s": 876,
"text": "What is KFold, ShuffledKfold and StratifiedKfold and see how they differ"
},
{
"code": null,
"e": 1045,
"s": 949,
"text": "How to cross validate your model without KFold using cross_validate and cross_val_score methods"
},
{
"code": null,
"e": 1151,
"s": 1045,
"text": "What are the other split options — RepeatedKFold, LeaveOneOut and LeavePOut and an usecase for GroupKFold"
},
{
"code": null,
"e": 1215,
"s": 1151,
"text": "How important it is to consider target and feature distribution"
},
{
"code": null,
"e": 1256,
"s": 1215,
"text": "Normally you split the data into 3 sets."
},
{
"code": null,
"e": 1331,
"s": 1256,
"text": "Training: used to train the model and optimize the model’s hyperparameters"
},
{
"code": null,
"e": 1441,
"s": 1331,
"text": "Testing: used to check that the optimized model works on unknown data to test that the model generalizes well"
},
{
"code": null,
"e": 1613,
"s": 1441,
"text": "Validation: during optimizing some information about test set leaks into the model by your choice of the parameters so you perform a final check on completely unknown data"
},
{
"code": null,
"e": 1767,
"s": 1613,
"text": "Introducing cross-validation into the process helps you to reduce the need for the validation set because you’re able to train and test on the same data."
},
{
"code": null,
"e": 1932,
"s": 1767,
"text": "In most common cross-validation approach you use part of the training set for testing. You do it several times so that each data point appears once in the test set."
},
{
"code": null,
"e": 2190,
"s": 1932,
"text": "Even though sklearn’s train_test_split method is using a stratified split, which means that the train and test set have the same distribution of the target variable, it’s possible that you accidentally train on a subset which doesn’t reflect the real world."
},
{
"code": null,
"e": 2711,
"s": 2190,
"text": "Imagine that you try to predict whether a person is a male or a female by his or her height and weight. One would assume that taller and heavier people would rather be males; though if you’re very unlucky your train data would only contain dwarf men and tall Amazon women. Thanks to cross validation you perform multiple train_test split and while one fold can achieve extraordinary good results the other might underperform. Anytime one of the splits shows unusual results it means that there’s an anomaly in your data."
},
{
"code": null,
"e": 2825,
"s": 2711,
"text": "If your cross-validation split doesn’t achieve similar score, you have missed something important about the data."
},
{
"code": null,
"e": 3004,
"s": 2825,
"text": "You can always write your own function to split the data, but scikit-learn already contains cover 10 methods for splitting the data which allows you to tackle almost any problem."
},
{
"code": null,
"e": 3076,
"s": 3004,
"text": "Let’s start coding though. You download the complete example on github."
},
{
"code": null,
"e": 3153,
"s": 3076,
"text": "As a first step let’s create a simple range of numbers from 1,2,3 ... 24,25."
},
{
"code": null,
"e": 3196,
"s": 3153,
"text": "# create the range 1 to 25rn = range(1,26)"
},
{
"code": null,
"e": 3390,
"s": 3196,
"text": "Then let’s initiate sklearn’s Kfold method without shuffling, which is the simplest option for how to split the data. I’ll create two Kfolds, one splitting data 3-times and other doing 5 folds."
},
{
"code": null,
"e": 3508,
"s": 3390,
"text": "from sklearn.model_selection import KFoldkf5 = KFold(n_splits=5, shuffle=False)kf3 = KFold(n_splits=3, shuffle=False)"
},
{
"code": null,
"e": 3645,
"s": 3508,
"text": "If I pass my range to the KFold it will return two lists containing indices of the data points which would fall into train and test set."
},
{
"code": null,
"e": 3824,
"s": 3645,
"text": "# the Kfold function retunrs the indices of the data. Our range goes from 1-25 so the index is 0-24for train_index, test_index in kf3.split(rn): print(train_index, test_index)"
},
{
"code": null,
"e": 3871,
"s": 3824,
"text": "KFold returns indices not the real datapoints."
},
{
"code": null,
"e": 3990,
"s": 3871,
"text": "Since KFold returns the index, if you want to see the real data we must use np.take in NumPy array or .iloc in pandas."
},
{
"code": null,
"e": 4183,
"s": 3990,
"text": "# to get the values from our data, we use np.take() to access a value at particular indexfor train_index, test_index in kf3.split(rn): print(np.take(rn,train_index), np.take(rn,test_index))"
},
{
"code": null,
"e": 4277,
"s": 4183,
"text": "# Import scikit-learn libraries\nfrom sklearn.model_selection import KFold\nimport numpy as np\n"
},
{
"code": null,
"e": 4322,
"s": 4277,
"text": "# create the range 1 to 25\nrn = range(1,26)\n"
},
{
"code": null,
"e": 4586,
"s": 4322,
"text": "# to demonstrate how the data are split, we will create 3 and 5 folds. \n# KFold function has to be applied on the data and it returns an location (index) of the train and test samples.\nkf5 = KFold(n_splits=5, shuffle=False)\nkf3 = KFold(n_splits=3, shuffle=False)\n"
},
{
"code": null,
"e": 4768,
"s": 4586,
"text": "# the Kfold function retunrs the indices of the data. Our range goes from 1-25 so the index is 0-24\nfor train_index, test_index in kf3.split(rn):\n print(train_index, test_index)\n"
},
{
"code": null,
"e": 4997,
"s": 4768,
"text": "[ 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24] [0 1 2 3 4 5 6 7 8]\n[ 0 1 2 3 4 5 6 7 8 17 18 19 20 21 22 23 24] [ 9 10 11 12 13 14 15 16]\n[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] [17 18 19 20 21 22 23 24]\n"
},
{
"code": null,
"e": 5193,
"s": 4997,
"text": "# to get the values from our data, we use np.take() to access a value at particular index\nfor train_index, test_index in kf3.split(rn):\n print(np.take(rn,train_index), np.take(rn,test_index))\n"
},
{
"code": null,
"e": 5422,
"s": 5193,
"text": "[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25] [1 2 3 4 5 6 7 8 9]\n[ 1 2 3 4 5 6 7 8 9 18 19 20 21 22 23 24 25] [10 11 12 13 14 15 16 17]\n[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17] [18 19 20 21 22 23 24 25]\n"
},
{
"code": null,
"e": 5685,
"s": 5422,
"text": "To better understand how the KFold method divides the data, let’s display it on a chart. Because we have used shuffled=False the first data point belongs to the test set in the first fold, the next one as well. The test and train data points are nicely arranged."
},
{
"code": null,
"e": 5857,
"s": 5685,
"text": "It’s important to say that the number of fold influences that size of your test set. 3 folds tests on 33% of the data while 5 folds on 1/5 which equals to 20% of the data."
},
{
"code": null,
"e": 5932,
"s": 5857,
"text": "Each data points appears once in the test set and k-times in the train set"
},
{
"code": null,
"e": 6078,
"s": 5932,
"text": "# Import scikit-learn libraries\nfrom sklearn.model_selection import KFold\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n"
},
{
"code": null,
"e": 6123,
"s": 6078,
"text": "# create the range 1 to 25\nrn = range(1,26)\n"
},
{
"code": null,
"e": 6387,
"s": 6123,
"text": "# to demonstrate how the data are split, we will create 3 and 5 folds. \n# KFold function has to be applied on the data and it returns an location (index) of the train and test samples.\nkf5 = KFold(n_splits=5, shuffle=False)\nkf3 = KFold(n_splits=3, shuffle=False)\n"
},
{
"code": null,
"e": 7286,
"s": 6387,
"text": "# Let's split our test range into 5 and3 folds and display the splits on the chart.\n# In order to clearly show which data belongs to each set, we will shift the values by -.1 and +.1\n# the first fold will contain values 0.9 in train and 1.1 in the test set, second 1.9 and 2.1, etc.\n# we will also give each sets the different color\n# because we will repeat this exercise for the shuffled version, let's create a function \n\ndef kfoldize(kf, rn, shift=.1):\n train = pd.DataFrame()\n test = pd.DataFrame()\n i = 1\n for train_index, test_index in kf.split(rn):\n train_df = pd.DataFrame(np.take(rn, train_index), columns=[\"x\"])\n train_df[\"val\"] = i - shift\n train = train.append(train_df)\n\n test_df = pd.DataFrame(np.take(rn, test_index), columns=[\"x\"])\n test_df[\"val\"] = i + shift\n test = test.append(test_df)\n i += 1\n return train, test\n"
},
{
"code": null,
"e": 7901,
"s": 7286,
"text": "train5, test5 = kfoldize(kf5,rn)\ntrain3, test3 = kfoldize(kf3,rn)\n\nfig,ax = plt.subplots(1,2, figsize=(15,5))\nax[0].scatter(x=\"x\",y=\"val\",c=\"b\",label=\"train\",s=15,data=train5)\nax[0].scatter(x=\"x\",y=\"val\",c=\"r\",label=\"test\",s=15,data=test5)\nax[1].scatter(x=\"x\",y=\"val\",c=\"b\",label=\"train\",s=15,data=train3)\nax[1].scatter(x=\"x\",y=\"val\",c=\"r\",label=\"test\",s=15,data=test3)\nax[0].set_ylabel(\"Kfold\")\nax[0].set_xlabel(\"feature\")\nax[1].set_xlabel(\"feature\")\nax[0].set_title(\"5 Folds\")\nax[1].set_title(\"3 Folds\")\nplt.suptitle(\"Kfold split between train and test features\")\nplt.legend(bbox_to_anchor=(1.05, 1))\nplt.show()\n"
},
{
"code": null,
"e": 8330,
"s": 7901,
"text": "Your data might follow a specific order and it might be risky to select the data in order of appearance. That can be solved by setting KFold’s shuffle parameter to True. In that case KFold will randomly pick the datapoints which would become part of the train and test set. Or to be precise not completely randomly, random_state influences which points appear each set and the same random_state always results in the same split."
},
{
"code": null,
"e": 8479,
"s": 8330,
"text": "Working on the real problem you will rarely have a small array as an input so let’s have a look at the real example using a well-known Iris dataset."
},
{
"code": null,
"e": 8637,
"s": 8479,
"text": "Iris dataset contain 150 measurements of petal and sepal sizes of 3 varieties of the iris flower —50 Iris setosas, 50 Iris virginicas and 50 Iris versicolors"
},
{
"code": null,
"e": 8912,
"s": 8637,
"text": "In the github notebook I run a test using only a single fold which achieves 95% accuracy on the training set and 100% on the test set. What was my surprise when 3-fold split results into exactly 0% accuracy. You read it well, my model did not pick a single flower correctly."
},
{
"code": null,
"e": 9369,
"s": 8912,
"text": "i = 1for train_index, test_index in kf3.split(iris_df): X_train = iris_df.iloc[train_index].loc[:, features] X_test = iris_df.iloc[test_index][features] y_train = iris_df.iloc[train_index].loc[:,'target'] y_test = iris_df.loc[test_index]['target'] #Train the model model.fit(X_train, y_train) #Training the model print(f\"Accuracy for the fold no. {i} on the test set: {accuracy_score(y_test, model.predict(X_test))}\") i += 1"
},
{
"code": null,
"e": 9720,
"s": 9369,
"text": "Do you remember that unshuffled KFold picks the data in order? Our set contains 150 observations, the first 50 belongs to one specie, 51–100 to the other, and the remaining to the third one. Our 3-fold model was very unlucky to always pick measurement of two of the Irises while the test set contained only the flowers which the model has never seen."
},
{
"code": null,
"e": 9853,
"s": 9720,
"text": "To address this problem we can change the shuffled=True parameter and choose the samples randomly. But that also runs into problems."
},
{
"code": null,
"e": 10037,
"s": 9853,
"text": "The groups are still not balanced. You are often training on a much higher number of samples of one type while testing on different types. Let’s see if we can do something about that."
},
{
"code": null,
"e": 10222,
"s": 10037,
"text": "In many scenarios it is important to preserve the same distribution of samples in the train and test set. That is achieved by StratifiedKFold which can again be shuffled or unshuffled."
},
{
"code": null,
"e": 10558,
"s": 10222,
"text": "You can see that the KFold divides the data into the groups which have the kept the ratios. StratifiedKFold reflects the distribution of the target variable even in case some of the values appear more often in the dataset. It doesn’t however evaluate the distribution of the input measurements. We will talk more about that at the end."
},
{
"code": null,
"e": 10810,
"s": 10558,
"text": "To enjoy the benefits of cross-validation you don’t have to split the data manually. Sklearn offers two methods for quick evaluation using cross-validation. cross-val-score returns a list of model scores and cross-validate also reports training times."
},
{
"code": null,
"e": 11022,
"s": 10810,
"text": "# cross_validate also allows to specify metrics which you want to seefor i, score in enumerate(cross_validate(model, X,y, cv=3)[\"test_score\"]): print(f\"Accuracy for the fold no. {i} on the test set: {score}\")"
},
{
"code": null,
"e": 11151,
"s": 11022,
"text": "Besides the functions mentioned above sklearn is endowed with a whole bunch of other methods to help you address specific needs."
},
{
"code": null,
"e": 11222,
"s": 11151,
"text": "Repeated Kfold would create multiple combinations of train-test split."
},
{
"code": null,
"e": 11401,
"s": 11222,
"text": "While regular cross-validation makes sure that you see each data point once in the test set, ShuffleSplit allows you to specify how many features are picked to test in each fold."
},
{
"code": null,
"e": 11533,
"s": 11401,
"text": "LeaveOneOut and LeavePOut solve the need in other special cases. The first one always leaves only one sample to be in the test set."
},
{
"code": null,
"e": 11687,
"s": 11533,
"text": "As a general rule, most authors, and empirical evidence, suggest that 5- or 10- fold cross validation should be preferred to LOO. — sklearn documentation"
},
{
"code": null,
"e": 11700,
"s": 11687,
"text": "Group Kfolds"
},
{
"code": null,
"e": 12212,
"s": 11700,
"text": "GroupKFold has its place in scenarios when you have multiple data samples taken from the same subject. For example more than one measurement from the same person. It’s likely that data from the same group will behave similarly and if you will train on one of the measurements and test on the other you will get a good score, but it won’t prove that your model generalizes well. GroupKFold assures that the whole group goes either to the train or to the test set. Read more in sklearn documentation about groups."
},
{
"code": null,
"e": 12548,
"s": 12212,
"text": "Problems involving time series are also sensitive to the order of data points. It’s usually much easier to guess past based on current knowledge than to predict the future. For this reason it makes sense to always feed the time series models with older data while predicting the newer ones. Sklearn’s TimeSeriesSplit does exactly that."
},
{
"code": null,
"e": 12852,
"s": 12548,
"text": "There is one last matter which is crucial to highlight. You might think that the stratified split would solve all your machine learning problems, but it’s not true. StratifiedKFold ensures that there remains the same ratio of the targets in both train and test set. In our case 33% of each type of Iris."
},
{
"code": null,
"e": 13179,
"s": 12852,
"text": "To demonstrate that on an unbalanced dataset we will look at popular Kaggle Titanic competition. Your goal would be to train an AI model that would predict whether a passenger on Titanic survived or died when the ship sank. Let’s look at how StratiffiedKFold would divide the survivors and victims in the dataset in each fold."
},
{
"code": null,
"e": 13664,
"s": 13179,
"text": "It looks good, isn’t it? However, your data might still be improperly split. If you look at the distribution of the key features (I purposefully choose this distribution to demonstrate my point, because often it’s enough to shuffle the data to get much more balanced distribution) you will see that you often try to predict the results based on training data which are different from the test set. For example if you look at the distribution of the genders in the train and test sets."
},
{
"code": null,
"e": 13945,
"s": 13664,
"text": "Cross-validation at least helps you to realize this problem in case the score of the model differs significantly for each fold. Imagine you would be so unlucky, using only a single split which would perfectly suit your test data, but catastrophically fail on real-world scenarios."
},
{
"code": null,
"e": 14152,
"s": 13945,
"text": "It a very complex task to balance your data so that you train and test on ideal distribution. Many argue that it’s not necessary, because the model should generalize good enough to work on the unknown data."
},
{
"code": null,
"e": 14434,
"s": 14152,
"text": "I would nevertheless encourage you to think about the distribution of features. Imagine that you would have a shop where customers are mostly men and you would try to predict sales using data from a marketing campaign targeted to women. It wouldn’t be the best model for your shop."
},
{
"code": null,
"e": 14445,
"s": 14434,
"text": "Conclusion"
},
{
"code": null,
"e": 14771,
"s": 14445,
"text": "Train-test split is a basic concept in many machine learning assignments, but if you have enough resources consider applying cross-validation to your problem. It will not only help you use less data, but an inconsistent score on the different folds would suggest that you have missed some important relation inside your data."
},
{
"code": null,
"e": 15237,
"s": 14771,
"text": "Sklearn library contains a bunch of methods to split the data to fit your AI exercise. You can create basic KFold, shuffle the data, or stratify them according to the target variable. You can use additional methods or just test your model with cross-validate or cross-val-score without bothering with manual data split. In any case your resulting score should show a stable pattern, because you don’t want your model to depend on ‘lucky’ data split to perform well."
},
{
"code": null,
"e": 15329,
"s": 15237,
"text": "All data, charts, and python processing was summarized in the notebook available on github."
},
{
"code": null,
"e": 15352,
"s": 15329,
"text": "towardsdatascience.com"
}
] |
SymPy: Symbolic Computation in Python | by Khuyen Tran | Towards Data Science | Have you ever wished to solve a math equation in Python? Wouldn’t it be nice if we could solve an algebraic equation like below in one line of code
[-1/2, 0]
...or simply work with math symbols instead of boring Python code?
That is when SymPy comes in handy.
SymPy is a Python library that allows you to compute mathematical objects symbolically.
To install SymPy, type:
pip install sympy
Now let’s go over some of the amazing things that SymPy can do!
Start with importing all methods provided by SymPy
from sympy import *
Normally, when computing a square root, we get a decimal:
But with SymPy, we can get a simplified version of the square root instead:
It is because SymPy tries to represent mathematical objects exactly instead of approximately.
Thus, we will get a fraction instead of a decimal when dividing 2 numbers using SymPy.
The real power of SymPy is its ability to work with symbols. To create symbols, use the method symbols() :
Cool! We can create an expression in terms of x and y. What happens if we add a number to this expression?
Aha! + 2 is added to the expression and the expression remains unevaluated.
Why would working with symbols be useful? Because we can now use all kinds of math tricks we learn in school such as expanding, factoring and simplifying an equation to make our life easier.
We know that the expansion of the expression on the left is equal to the expression on the right.
Can this be done with SymPy? Yes! SymPy allows us to expand an equation using expand :
Cool! We can also factor our expression by using factor :
Another cool thing we can do with SymPy is to simplify an equation using simplify :
Pretty nice, isn’t it?
One of the most common questions we see when dealing with mathematical symbols is to solve an equation. Luckily, this can also be done with SymPy.
To solve an equation, use solve :
If we substitute the equation below by 2, what do we get?
We can figure that out using eq.subs(x, 2) :
We can also substitute x with another variable to get an expression like below:
Nice!
Remember all the fun trigonometric identities we learn in high school?
Instead of looking up these identities, wouldn’t it be nice if we can use SymPy to figure this out for us?
To simplify expressions using trigonometric identities, use trigsimp()
With SymPy, you can also do calculus! What is the derivative of the expression below?
If you cannot figure it out, don’t worry. We can use SymPy to figure it out.
Now let’s try to get back to the original expression by taking the integral of the derivate.
We can also take the limit as x approaches infinity.
or 2:
SymPy also provides special functions to:
Find the factorial of a number
Rewrite the expression in terms of another
If you like the output and want to get the LaTex form of an expression, use latex :
You could paste this LaTex form to your notebook’s markdown and get a nice mathematical expression like below!
Congratulation! You have just learned how to compute mathematical objects symbolically in Python using SymPy. The next time you solve math, try using SymPy to make your life easier.
There are so many other useful methods SymPy provides that I could not cover here. I encourage you to check out this documentation for more inspiration.
Feel free to fork and play with the code for this article in this Github repo:
github.com
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these: | [
{
"code": null,
"e": 319,
"s": 171,
"text": "Have you ever wished to solve a math equation in Python? Wouldn’t it be nice if we could solve an algebraic equation like below in one line of code"
},
{
"code": null,
"e": 329,
"s": 319,
"text": "[-1/2, 0]"
},
{
"code": null,
"e": 396,
"s": 329,
"text": "...or simply work with math symbols instead of boring Python code?"
},
{
"code": null,
"e": 431,
"s": 396,
"text": "That is when SymPy comes in handy."
},
{
"code": null,
"e": 519,
"s": 431,
"text": "SymPy is a Python library that allows you to compute mathematical objects symbolically."
},
{
"code": null,
"e": 543,
"s": 519,
"text": "To install SymPy, type:"
},
{
"code": null,
"e": 561,
"s": 543,
"text": "pip install sympy"
},
{
"code": null,
"e": 625,
"s": 561,
"text": "Now let’s go over some of the amazing things that SymPy can do!"
},
{
"code": null,
"e": 676,
"s": 625,
"text": "Start with importing all methods provided by SymPy"
},
{
"code": null,
"e": 696,
"s": 676,
"text": "from sympy import *"
},
{
"code": null,
"e": 754,
"s": 696,
"text": "Normally, when computing a square root, we get a decimal:"
},
{
"code": null,
"e": 830,
"s": 754,
"text": "But with SymPy, we can get a simplified version of the square root instead:"
},
{
"code": null,
"e": 924,
"s": 830,
"text": "It is because SymPy tries to represent mathematical objects exactly instead of approximately."
},
{
"code": null,
"e": 1011,
"s": 924,
"text": "Thus, we will get a fraction instead of a decimal when dividing 2 numbers using SymPy."
},
{
"code": null,
"e": 1118,
"s": 1011,
"text": "The real power of SymPy is its ability to work with symbols. To create symbols, use the method symbols() :"
},
{
"code": null,
"e": 1225,
"s": 1118,
"text": "Cool! We can create an expression in terms of x and y. What happens if we add a number to this expression?"
},
{
"code": null,
"e": 1301,
"s": 1225,
"text": "Aha! + 2 is added to the expression and the expression remains unevaluated."
},
{
"code": null,
"e": 1492,
"s": 1301,
"text": "Why would working with symbols be useful? Because we can now use all kinds of math tricks we learn in school such as expanding, factoring and simplifying an equation to make our life easier."
},
{
"code": null,
"e": 1590,
"s": 1492,
"text": "We know that the expansion of the expression on the left is equal to the expression on the right."
},
{
"code": null,
"e": 1677,
"s": 1590,
"text": "Can this be done with SymPy? Yes! SymPy allows us to expand an equation using expand :"
},
{
"code": null,
"e": 1735,
"s": 1677,
"text": "Cool! We can also factor our expression by using factor :"
},
{
"code": null,
"e": 1819,
"s": 1735,
"text": "Another cool thing we can do with SymPy is to simplify an equation using simplify :"
},
{
"code": null,
"e": 1842,
"s": 1819,
"text": "Pretty nice, isn’t it?"
},
{
"code": null,
"e": 1989,
"s": 1842,
"text": "One of the most common questions we see when dealing with mathematical symbols is to solve an equation. Luckily, this can also be done with SymPy."
},
{
"code": null,
"e": 2023,
"s": 1989,
"text": "To solve an equation, use solve :"
},
{
"code": null,
"e": 2081,
"s": 2023,
"text": "If we substitute the equation below by 2, what do we get?"
},
{
"code": null,
"e": 2126,
"s": 2081,
"text": "We can figure that out using eq.subs(x, 2) :"
},
{
"code": null,
"e": 2206,
"s": 2126,
"text": "We can also substitute x with another variable to get an expression like below:"
},
{
"code": null,
"e": 2212,
"s": 2206,
"text": "Nice!"
},
{
"code": null,
"e": 2283,
"s": 2212,
"text": "Remember all the fun trigonometric identities we learn in high school?"
},
{
"code": null,
"e": 2390,
"s": 2283,
"text": "Instead of looking up these identities, wouldn’t it be nice if we can use SymPy to figure this out for us?"
},
{
"code": null,
"e": 2461,
"s": 2390,
"text": "To simplify expressions using trigonometric identities, use trigsimp()"
},
{
"code": null,
"e": 2547,
"s": 2461,
"text": "With SymPy, you can also do calculus! What is the derivative of the expression below?"
},
{
"code": null,
"e": 2624,
"s": 2547,
"text": "If you cannot figure it out, don’t worry. We can use SymPy to figure it out."
},
{
"code": null,
"e": 2717,
"s": 2624,
"text": "Now let’s try to get back to the original expression by taking the integral of the derivate."
},
{
"code": null,
"e": 2770,
"s": 2717,
"text": "We can also take the limit as x approaches infinity."
},
{
"code": null,
"e": 2776,
"s": 2770,
"text": "or 2:"
},
{
"code": null,
"e": 2818,
"s": 2776,
"text": "SymPy also provides special functions to:"
},
{
"code": null,
"e": 2849,
"s": 2818,
"text": "Find the factorial of a number"
},
{
"code": null,
"e": 2892,
"s": 2849,
"text": "Rewrite the expression in terms of another"
},
{
"code": null,
"e": 2976,
"s": 2892,
"text": "If you like the output and want to get the LaTex form of an expression, use latex :"
},
{
"code": null,
"e": 3087,
"s": 2976,
"text": "You could paste this LaTex form to your notebook’s markdown and get a nice mathematical expression like below!"
},
{
"code": null,
"e": 3269,
"s": 3087,
"text": "Congratulation! You have just learned how to compute mathematical objects symbolically in Python using SymPy. The next time you solve math, try using SymPy to make your life easier."
},
{
"code": null,
"e": 3422,
"s": 3269,
"text": "There are so many other useful methods SymPy provides that I could not cover here. I encourage you to check out this documentation for more inspiration."
},
{
"code": null,
"e": 3501,
"s": 3422,
"text": "Feel free to fork and play with the code for this article in this Github repo:"
},
{
"code": null,
"e": 3512,
"s": 3501,
"text": "github.com"
},
{
"code": null,
"e": 3672,
"s": 3512,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
Check if a binary tree is sorted level-wise or not - GeeksforGeeks | 23 Jun, 2021
Given a binary tree. The task is to check if the binary tree is sorted level-wise or not. A binary tree is level sorted if max( i-1th level) is less than min( ith level ). Examples:
Input : 1
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
Output : Sorted
Input: 1
/
4
/ \
6 5
\
2
Output: Not sorted
Simple Solution: A simple solution is to compare minimum and maximum value of each adjacent level i and i+1. Traverse to ith and i+1th level, compare the minimum value of i+1th level with maximum value of ith level and return the result. Time complexity: O(n2).Efficient Solution: An efficient solution is to do level order traversal and keep track of the minimum and maximum values of current level. Use a variable prevMax to store the maximum value of the previous level. Then compare the minimum value of current level with the maximum value of the previous level, pevMax. If minimum value is greater than the prevMax, then the given tree is sorted level-wise up to current level. For next level, prevMax is the equal to maximum value of current level. So update the prevMax with maximum value of current level. Repeat this until all levels of given tree are not traversed. Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// CPP program to determine whether// binary tree is level sorted or not. #include <bits/stdc++.h>using namespace std; // Structure of a tree node.struct Node { int key; Node *left, *right;}; // Function to create new tree node.Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Function to determine if// given binary tree is level sorted// or not.int isSorted(Node* root){ // to store maximum value of previous // level. int prevMax = INT_MIN; // to store minimum value of current // level. int minval; // to store maximum value of current // level. int maxval; // to store number of nodes in current // level. int levelSize; // queue to perform level order traversal. queue<Node*> q; q.push(root); while (!q.empty()) { // find number of nodes in current // level. levelSize = q.size(); minval = INT_MAX; maxval = INT_MIN; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q.front(); q.pop(); levelSize--; minval = min(minval, root->key); maxval = max(maxval, root->key); if (root->left) q.push(root->left); if (root->right) q.push(root->right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver programint main(){ /* 1 / 4 \ 6 / \ 8 9 / \ 12 10 */ Node* root = newNode(1); root->left = newNode(4); root->left->right = newNode(6); root->left->right->left = newNode(8); root->left->right->right = newNode(9); root->left->right->left->left = newNode(12); root->left->right->right->right = newNode(10); if (isSorted(root)) cout << "Sorted"; else cout << "Not sorted"; return 0;}
// Java program to determine whether// binary tree is level sorted or not.import java.util.*; class GfG { // Structure of a tree node.static class Node { int key; Node left, right;} // Function to create new tree node.static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = null; temp.right = null; return temp;} // Function to determine if// given binary tree is level sorted// or not.static int isSorted(Node root){ // to store maximum value of previous // level. int prevMax = Integer.MIN_VALUE; // to store minimum value of current // level. int minval; // to store maximum value of current // level. int maxval; // to store number of nodes in current // level. int levelSize; // queue to perform level order traversal. Queue<Node> q = new LinkedList<Node> (); q.add(root); while (!q.isEmpty()) { // find number of nodes in current // level. levelSize = q.size(); minval = Integer.MAX_VALUE; maxval = Integer.MIN_VALUE; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q.peek(); q.remove(); levelSize--; minval = Math.min(minval, root.key); maxval = Math.max(maxval, root.key); if (root.left != null) q.add(root.left); if (root.right != null) q.add(root.right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver programpublic static void main(String[] args){ /* 1 / 4 \ 6 / \ 8 9 / \ 12 10 */ Node root = newNode(1); root.left = newNode(4); root.left.right = newNode(6); root.left.right.left = newNode(8); root.left.right.right = newNode(9); root.left.right.left.left = newNode(12); root.left.right.right.right = newNode(10); if (isSorted(root) == 1) System.out.println("Sorted"); else System.out.println("Not sorted");}}
# Python3 program to determine whether# binary tree is level sorted or not.from queue import Queue # Function to create new tree node.class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Function to determine if given binary# tree is level sorted or not.def isSorted(root): # to store maximum value of previous # level. prevMax = -999999999999 # to store minimum value of current # level. minval = None # to store maximum value of current # level. maxval = None # to store number of nodes in current # level. levelSize = None # queue to perform level order traversal. q = Queue() q.put(root) while (not q.empty()): # find number of nodes in current # level. levelSize = q.qsize() minval = 999999999999 maxval = -999999999999 # traverse current level and find # minimum and maximum value of # this level. while (levelSize > 0): root = q.queue[0] q.get() levelSize -= 1 minval = min(minval, root.key) maxval = max(maxval, root.key) if (root.left): q.put(root.left) if (root.right): q.put(root.right) # if minimum value of this level # is not greater than maximum # value of previous level then # given tree is not level sorted. if (minval <= prevMax): return 0 # maximum value of this level is # previous maximum value for # next level. prevMax = maxval return 1 # Driver Codeif __name__ == '__main__': # # 1 # / # 4 # \ # 6 # / \ # 8 9 # / \ # 12 10 root = newNode(1) root.left = newNode(4) root.left.right = newNode(6) root.left.right.left = newNode(8) root.left.right.right = newNode(9) root.left.right.left.left = newNode(12) root.left.right.right.right = newNode(10) if (isSorted(root)): print("Sorted") else: print("Not sorted") # This code is contributed by PranchalK
// C# program to determine whether// binary tree is level sorted or not.using System;using System.Collections.Generic; class GFG{ // Structure of a tree node.public class Node{ public int key; public Node left, right;} // Function to create new tree node.static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = null; temp.right = null; return temp;} // Function to determine if// given binary tree is level sorted// or not.static int isSorted(Node root){ // to store maximum value of previous // level. int prevMax = int.MinValue; // to store minimum value of current // level. int minval; // to store maximum value of current // level. int maxval; // to store number of nodes in current // level. int levelSize; // queue to perform level order traversal. Queue<Node> q = new Queue<Node> (); q.Enqueue(root); while (q.Count != 0) { // find number of nodes in current // level. levelSize = q.Count; minval = int.MaxValue; maxval = int.MinValue; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q.Peek(); q.Dequeue(); levelSize--; minval = Math.Min(minval, root.key); maxval = Math.Max(maxval, root.key); if (root.left != null) q.Enqueue(root.left); if (root.right != null) q.Enqueue(root.right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver Codepublic static void Main(String[] args){ /* 1 / 4 \ 6 / \ 8 9 / \ 12 10 */ Node root = newNode(1); root.left = newNode(4); root.left.right = newNode(6); root.left.right.left = newNode(8); root.left.right.right = newNode(9); root.left.right.left.left = newNode(12); root.left.right.right.right = newNode(10); if (isSorted(root) == 1) Console.WriteLine("Sorted"); else Console.WriteLine("Not sorted");}} // This code is contributed by PrinciRaj1992
<script> // JavaScript program to determine whether// binary tree is level sorted or not. // Structure of a tree node.class Node{ constructor() { this.key = null; this.left = null; this.right = null; }} // Function to create new tree node.function newNode(key){ var temp = new Node(); temp.key = key; temp.left = null; temp.right = null; return temp;} // Function to determine if// given binary tree is level sorted// or not.function isSorted(root){ // to store maximum value of previous // level. var prevMax = -1000000000; // to store minimum value of current // level. var minval; // to store maximum value of current // level. var maxval; // to store number of nodes in current // level. var levelSize; // queue to perform level order traversal. var q = []; q.push(root); while (q.length != 0) { // find number of nodes in current // level. levelSize = q.length; minval = 1000000000; maxval = -1000000000; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q[0]; q.shift(); levelSize--; minval = Math.min(minval, root.key); maxval = Math.max(maxval, root.key); if (root.left != null) q.push(root.left); if (root.right != null) q.push(root.right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver Code/* 1 / 4 \ 6 / \ 8 9 / \ 12 10*/var root = newNode(1);root.left = newNode(4);root.left.right = newNode(6);root.left.right.left = newNode(8);root.left.right.right = newNode(9);root.left.right.left.left = newNode(12);root.left.right.right.right = newNode(10);if (isSorted(root) == 1) document.write("Sorted");else document.write("Not Sorted"); </script>
Sorted
Time Complexity: O(n) Auxiliary Space: O(n)
prerna saini
PranchalKatiyar
princiraj1992
rutvik_56
Binary Tree
tree-level-order
Trees
Data Structures
Tree
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Introduction to Tree Data Structure
Insertion and Deletion in Heaps
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion | [
{
"code": null,
"e": 25280,
"s": 25252,
"text": "\n23 Jun, 2021"
},
{
"code": null,
"e": 25464,
"s": 25280,
"text": "Given a binary tree. The task is to check if the binary tree is sorted level-wise or not. A binary tree is level sorted if max( i-1th level) is less than min( ith level ). Examples: "
},
{
"code": null,
"e": 25762,
"s": 25464,
"text": "Input : 1 \n / \\\n / \\\n 2 3\n / \\ / \\\n / \\ / \\\n 4 5 6 7\nOutput : Sorted\n\nInput: 1 \n / \n 4 \n / \\\n 6 5\n \\\n 2\nOutput: Not sorted"
},
{
"code": null,
"e": 26690,
"s": 25764,
"text": "Simple Solution: A simple solution is to compare minimum and maximum value of each adjacent level i and i+1. Traverse to ith and i+1th level, compare the minimum value of i+1th level with maximum value of ith level and return the result. Time complexity: O(n2).Efficient Solution: An efficient solution is to do level order traversal and keep track of the minimum and maximum values of current level. Use a variable prevMax to store the maximum value of the previous level. Then compare the minimum value of current level with the maximum value of the previous level, pevMax. If minimum value is greater than the prevMax, then the given tree is sorted level-wise up to current level. For next level, prevMax is the equal to maximum value of current level. So update the prevMax with maximum value of current level. Repeat this until all levels of given tree are not traversed. Below is the implementation of above approach: "
},
{
"code": null,
"e": 26694,
"s": 26690,
"text": "C++"
},
{
"code": null,
"e": 26699,
"s": 26694,
"text": "Java"
},
{
"code": null,
"e": 26707,
"s": 26699,
"text": "Python3"
},
{
"code": null,
"e": 26710,
"s": 26707,
"text": "C#"
},
{
"code": null,
"e": 26721,
"s": 26710,
"text": "Javascript"
},
{
"code": "// CPP program to determine whether// binary tree is level sorted or not. #include <bits/stdc++.h>using namespace std; // Structure of a tree node.struct Node { int key; Node *left, *right;}; // Function to create new tree node.Node* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return temp;} // Function to determine if// given binary tree is level sorted// or not.int isSorted(Node* root){ // to store maximum value of previous // level. int prevMax = INT_MIN; // to store minimum value of current // level. int minval; // to store maximum value of current // level. int maxval; // to store number of nodes in current // level. int levelSize; // queue to perform level order traversal. queue<Node*> q; q.push(root); while (!q.empty()) { // find number of nodes in current // level. levelSize = q.size(); minval = INT_MAX; maxval = INT_MIN; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q.front(); q.pop(); levelSize--; minval = min(minval, root->key); maxval = max(maxval, root->key); if (root->left) q.push(root->left); if (root->right) q.push(root->right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver programint main(){ /* 1 / 4 \\ 6 / \\ 8 9 / \\ 12 10 */ Node* root = newNode(1); root->left = newNode(4); root->left->right = newNode(6); root->left->right->left = newNode(8); root->left->right->right = newNode(9); root->left->right->left->left = newNode(12); root->left->right->right->right = newNode(10); if (isSorted(root)) cout << \"Sorted\"; else cout << \"Not sorted\"; return 0;}",
"e": 29050,
"s": 26721,
"text": null
},
{
"code": "// Java program to determine whether// binary tree is level sorted or not.import java.util.*; class GfG { // Structure of a tree node.static class Node { int key; Node left, right;} // Function to create new tree node.static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = null; temp.right = null; return temp;} // Function to determine if// given binary tree is level sorted// or not.static int isSorted(Node root){ // to store maximum value of previous // level. int prevMax = Integer.MIN_VALUE; // to store minimum value of current // level. int minval; // to store maximum value of current // level. int maxval; // to store number of nodes in current // level. int levelSize; // queue to perform level order traversal. Queue<Node> q = new LinkedList<Node> (); q.add(root); while (!q.isEmpty()) { // find number of nodes in current // level. levelSize = q.size(); minval = Integer.MAX_VALUE; maxval = Integer.MIN_VALUE; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q.peek(); q.remove(); levelSize--; minval = Math.min(minval, root.key); maxval = Math.max(maxval, root.key); if (root.left != null) q.add(root.left); if (root.right != null) q.add(root.right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver programpublic static void main(String[] args){ /* 1 / 4 \\ 6 / \\ 8 9 / \\ 12 10 */ Node root = newNode(1); root.left = newNode(4); root.left.right = newNode(6); root.left.right.left = newNode(8); root.left.right.right = newNode(9); root.left.right.left.left = newNode(12); root.left.right.right.right = newNode(10); if (isSorted(root) == 1) System.out.println(\"Sorted\"); else System.out.println(\"Not sorted\");}}",
"e": 31473,
"s": 29050,
"text": null
},
{
"code": "# Python3 program to determine whether# binary tree is level sorted or not.from queue import Queue # Function to create new tree node.class newNode: def __init__(self, key): self.key = key self.left = self.right = None # Function to determine if given binary# tree is level sorted or not.def isSorted(root): # to store maximum value of previous # level. prevMax = -999999999999 # to store minimum value of current # level. minval = None # to store maximum value of current # level. maxval = None # to store number of nodes in current # level. levelSize = None # queue to perform level order traversal. q = Queue() q.put(root) while (not q.empty()): # find number of nodes in current # level. levelSize = q.qsize() minval = 999999999999 maxval = -999999999999 # traverse current level and find # minimum and maximum value of # this level. while (levelSize > 0): root = q.queue[0] q.get() levelSize -= 1 minval = min(minval, root.key) maxval = max(maxval, root.key) if (root.left): q.put(root.left) if (root.right): q.put(root.right) # if minimum value of this level # is not greater than maximum # value of previous level then # given tree is not level sorted. if (minval <= prevMax): return 0 # maximum value of this level is # previous maximum value for # next level. prevMax = maxval return 1 # Driver Codeif __name__ == '__main__': # # 1 # / # 4 # \\ # 6 # / \\ # 8 9 # / \\ # 12 10 root = newNode(1) root.left = newNode(4) root.left.right = newNode(6) root.left.right.left = newNode(8) root.left.right.right = newNode(9) root.left.right.left.left = newNode(12) root.left.right.right.right = newNode(10) if (isSorted(root)): print(\"Sorted\") else: print(\"Not sorted\") # This code is contributed by PranchalK",
"e": 33624,
"s": 31473,
"text": null
},
{
"code": "// C# program to determine whether// binary tree is level sorted or not.using System;using System.Collections.Generic; class GFG{ // Structure of a tree node.public class Node{ public int key; public Node left, right;} // Function to create new tree node.static Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = null; temp.right = null; return temp;} // Function to determine if// given binary tree is level sorted// or not.static int isSorted(Node root){ // to store maximum value of previous // level. int prevMax = int.MinValue; // to store minimum value of current // level. int minval; // to store maximum value of current // level. int maxval; // to store number of nodes in current // level. int levelSize; // queue to perform level order traversal. Queue<Node> q = new Queue<Node> (); q.Enqueue(root); while (q.Count != 0) { // find number of nodes in current // level. levelSize = q.Count; minval = int.MaxValue; maxval = int.MinValue; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q.Peek(); q.Dequeue(); levelSize--; minval = Math.Min(minval, root.key); maxval = Math.Max(maxval, root.key); if (root.left != null) q.Enqueue(root.left); if (root.right != null) q.Enqueue(root.right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver Codepublic static void Main(String[] args){ /* 1 / 4 \\ 6 / \\ 8 9 / \\ 12 10 */ Node root = newNode(1); root.left = newNode(4); root.left.right = newNode(6); root.left.right.left = newNode(8); root.left.right.right = newNode(9); root.left.right.left.left = newNode(12); root.left.right.right.right = newNode(10); if (isSorted(root) == 1) Console.WriteLine(\"Sorted\"); else Console.WriteLine(\"Not sorted\");}} // This code is contributed by PrinciRaj1992",
"e": 36129,
"s": 33624,
"text": null
},
{
"code": "<script> // JavaScript program to determine whether// binary tree is level sorted or not. // Structure of a tree node.class Node{ constructor() { this.key = null; this.left = null; this.right = null; }} // Function to create new tree node.function newNode(key){ var temp = new Node(); temp.key = key; temp.left = null; temp.right = null; return temp;} // Function to determine if// given binary tree is level sorted// or not.function isSorted(root){ // to store maximum value of previous // level. var prevMax = -1000000000; // to store minimum value of current // level. var minval; // to store maximum value of current // level. var maxval; // to store number of nodes in current // level. var levelSize; // queue to perform level order traversal. var q = []; q.push(root); while (q.length != 0) { // find number of nodes in current // level. levelSize = q.length; minval = 1000000000; maxval = -1000000000; // traverse current level and find // minimum and maximum value of // this level. while (levelSize > 0) { root = q[0]; q.shift(); levelSize--; minval = Math.min(minval, root.key); maxval = Math.max(maxval, root.key); if (root.left != null) q.push(root.left); if (root.right != null) q.push(root.right); } // if minimum value of this level // is not greater than maximum // value of previous level then // given tree is not level sorted. if (minval <= prevMax) return 0; // maximum value of this level is // previous maximum value for // next level. prevMax = maxval; } return 1;} // Driver Code/* 1 / 4 \\ 6 / \\ 8 9 / \\ 12 10*/var root = newNode(1);root.left = newNode(4);root.left.right = newNode(6);root.left.right.left = newNode(8);root.left.right.right = newNode(9);root.left.right.left.left = newNode(12);root.left.right.right.right = newNode(10);if (isSorted(root) == 1) document.write(\"Sorted\");else document.write(\"Not Sorted\"); </script>",
"e": 38411,
"s": 36129,
"text": null
},
{
"code": null,
"e": 38418,
"s": 38411,
"text": "Sorted"
},
{
"code": null,
"e": 38465,
"s": 38420,
"text": "Time Complexity: O(n) Auxiliary Space: O(n) "
},
{
"code": null,
"e": 38478,
"s": 38465,
"text": "prerna saini"
},
{
"code": null,
"e": 38494,
"s": 38478,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 38508,
"s": 38494,
"text": "princiraj1992"
},
{
"code": null,
"e": 38518,
"s": 38508,
"text": "rutvik_56"
},
{
"code": null,
"e": 38530,
"s": 38518,
"text": "Binary Tree"
},
{
"code": null,
"e": 38547,
"s": 38530,
"text": "tree-level-order"
},
{
"code": null,
"e": 38553,
"s": 38547,
"text": "Trees"
},
{
"code": null,
"e": 38569,
"s": 38553,
"text": "Data Structures"
},
{
"code": null,
"e": 38574,
"s": 38569,
"text": "Tree"
},
{
"code": null,
"e": 38590,
"s": 38574,
"text": "Data Structures"
},
{
"code": null,
"e": 38595,
"s": 38590,
"text": "Tree"
},
{
"code": null,
"e": 38693,
"s": 38595,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38742,
"s": 38693,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 38767,
"s": 38742,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 38794,
"s": 38767,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 38830,
"s": 38794,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 38862,
"s": 38830,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 38912,
"s": 38862,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 38947,
"s": 38912,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 38981,
"s": 38947,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 39010,
"s": 38981,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
Tryit Editor v3.7 | CSS Image Reflection
Tryit: Image reflection below | [
{
"code": null,
"e": 30,
"s": 9,
"text": "CSS Image Reflection"
}
] |
JavaScript Date getUTCDate() Method - GeeksforGeeks | 19 Oct, 2021
Below is the example of Date getUTCDate() method.
Example:
javascript
<script> // If nothing is in parameter it takes // the current date while creating Date object var date = new Date(); // Date of the month from above date object // is being extracted using getUTCDate(). var getUTC = date.getUTCDate(); //Printing on console document.write(getUTC);</script>
Output:
29
The date.getUTCDate() method is used to fetch the date of a month according to universal time from a given Date object.Syntax:
DateObj.getUTCDate();
Parameter: This method does not accept any parameter. It is just used along with a Date Object from which we want to fetch the date of the month according to universal time.Return Values: It returns the date of the month for the given date object according to universal time. The date of the month is an integer value ranging from 1 to 31.More codes for the above method are as follows:Program 1: The date of the month should lie in between 1 to 31 because none of the months have a date greater than 31 that is why it returns NaN i.e, not a number because the date for the month does not exist.
javascript
<script> // Here a date has been assigned according // to universal time while creating a Date object var dateobj = new Date('October 33, 1996 05:35:32 GMT-11:00'); // date of the month from above date object // is being extracted using getUTCDate(). var B = dateobj.getUTCDate(); // Printing date of the month. document.write(B);</script>
Output:
NaN
Program 2: If date of the month is not given then by default getUTCDate() function returns 1 according to universal time.It is an exception case.
javascript
<script> // Here a date has been assigned according to // universal time while creating Date object var dateobj = new Date('October 1996 05:35:32 GMT-11:00'); // date of the month from above date object is // extracted using getUTCDate(). var B = dateobj.getUTCDate(); // Printing date of the month. document.write(B);</script>
Output:
1
Supported Browsers: The browsers supported by JavaScript Date getUTCDate() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 4 and above
Safari 1 and above
ysachin2314
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript | [
{
"code": null,
"e": 30060,
"s": 30032,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 30112,
"s": 30060,
"text": "Below is the example of Date getUTCDate() method. "
},
{
"code": null,
"e": 30123,
"s": 30112,
"text": "Example: "
},
{
"code": null,
"e": 30134,
"s": 30123,
"text": "javascript"
},
{
"code": "<script> // If nothing is in parameter it takes // the current date while creating Date object var date = new Date(); // Date of the month from above date object // is being extracted using getUTCDate(). var getUTC = date.getUTCDate(); //Printing on console document.write(getUTC);</script>",
"e": 30459,
"s": 30134,
"text": null
},
{
"code": null,
"e": 30469,
"s": 30459,
"text": "Output: "
},
{
"code": null,
"e": 30472,
"s": 30469,
"text": "29"
},
{
"code": null,
"e": 30601,
"s": 30472,
"text": "The date.getUTCDate() method is used to fetch the date of a month according to universal time from a given Date object.Syntax: "
},
{
"code": null,
"e": 30623,
"s": 30601,
"text": "DateObj.getUTCDate();"
},
{
"code": null,
"e": 31221,
"s": 30623,
"text": "Parameter: This method does not accept any parameter. It is just used along with a Date Object from which we want to fetch the date of the month according to universal time.Return Values: It returns the date of the month for the given date object according to universal time. The date of the month is an integer value ranging from 1 to 31.More codes for the above method are as follows:Program 1: The date of the month should lie in between 1 to 31 because none of the months have a date greater than 31 that is why it returns NaN i.e, not a number because the date for the month does not exist. "
},
{
"code": null,
"e": 31232,
"s": 31221,
"text": "javascript"
},
{
"code": "<script> // Here a date has been assigned according // to universal time while creating a Date object var dateobj = new Date('October 33, 1996 05:35:32 GMT-11:00'); // date of the month from above date object // is being extracted using getUTCDate(). var B = dateobj.getUTCDate(); // Printing date of the month. document.write(B);</script>",
"e": 31592,
"s": 31232,
"text": null
},
{
"code": null,
"e": 31602,
"s": 31592,
"text": "Output: "
},
{
"code": null,
"e": 31606,
"s": 31602,
"text": "NaN"
},
{
"code": null,
"e": 31754,
"s": 31606,
"text": "Program 2: If date of the month is not given then by default getUTCDate() function returns 1 according to universal time.It is an exception case. "
},
{
"code": null,
"e": 31765,
"s": 31754,
"text": "javascript"
},
{
"code": "<script> // Here a date has been assigned according to // universal time while creating Date object var dateobj = new Date('October 1996 05:35:32 GMT-11:00'); // date of the month from above date object is // extracted using getUTCDate(). var B = dateobj.getUTCDate(); // Printing date of the month. document.write(B);</script>",
"e": 32113,
"s": 31765,
"text": null
},
{
"code": null,
"e": 32123,
"s": 32113,
"text": "Output: "
},
{
"code": null,
"e": 32125,
"s": 32123,
"text": "1"
},
{
"code": null,
"e": 32227,
"s": 32125,
"text": "Supported Browsers: The browsers supported by JavaScript Date getUTCDate() method are listed below: "
},
{
"code": null,
"e": 32253,
"s": 32227,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 32271,
"s": 32253,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 32291,
"s": 32271,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 32321,
"s": 32291,
"text": "Internet Explorer 4 and above"
},
{
"code": null,
"e": 32339,
"s": 32321,
"text": "Opera 4 and above"
},
{
"code": null,
"e": 32358,
"s": 32339,
"text": "Safari 1 and above"
},
{
"code": null,
"e": 32372,
"s": 32360,
"text": "ysachin2314"
},
{
"code": null,
"e": 32388,
"s": 32372,
"text": "javascript-date"
},
{
"code": null,
"e": 32407,
"s": 32388,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 32418,
"s": 32407,
"text": "JavaScript"
},
{
"code": null,
"e": 32435,
"s": 32418,
"text": "Web Technologies"
},
{
"code": null,
"e": 32533,
"s": 32435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32578,
"s": 32533,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32639,
"s": 32578,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32708,
"s": 32639,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 32780,
"s": 32708,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 32832,
"s": 32780,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 32874,
"s": 32832,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 32907,
"s": 32874,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32950,
"s": 32907,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 33012,
"s": 32950,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
C# Access Modifiers | By now, you are quite familiar with the public keyword that appears
in many of our examples:
public string color;
The public keyword is an access modifier,
which is used to set the access level/visibility for classes, fields, methods and properties.
C# has the following access modifiers:
There's also two combinations: protected internal and private protected.
For now, lets focus on public and private modifiers.
If you declare a field with a private access modifier, it can only be
accessed within the same class:
class Car
{
private string model = "Mustang";
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
The output will be:
Try it Yourself »
If you try to access it outside the class, an error will occur:
class Car
{
private string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
The output will be:
Try it Yourself »
If you declare a field with a public access modifier, it is accessible for
all classes:
class Car
{
public string model = "Mustang";
}
class Program
{
static void Main(string[] args)
{
Car myObj = new Car();
Console.WriteLine(myObj.model);
}
}
The output will be:
Try it Yourself »
To control the visibility of class members (the security level of
each individual class and class member).
To achieve "Encapsulation" - which is the process of making sure that "sensitive" data is hidden from users.
This is done by declaring fields as private. You will learn more about this in the next chapter.
Note: By default, all members of a class are private if you don't specify an access modifier:
class Car
{
string model; // private
string year; // private
}
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": 94,
"s": 0,
"text": "By now, you are quite familiar with the public keyword that appears \nin many of our examples:"
},
{
"code": null,
"e": 116,
"s": 94,
"text": "public string color;\n"
},
{
"code": null,
"e": 253,
"s": 116,
"text": "The public keyword is an access modifier, \nwhich is used to set the access level/visibility for classes, fields, methods and properties."
},
{
"code": null,
"e": 292,
"s": 253,
"text": "C# has the following access modifiers:"
},
{
"code": null,
"e": 365,
"s": 292,
"text": "There's also two combinations: protected internal and private protected."
},
{
"code": null,
"e": 418,
"s": 365,
"text": "For now, lets focus on public and private modifiers."
},
{
"code": null,
"e": 521,
"s": 418,
"text": "If you declare a field with a private access modifier, it can only be \naccessed within the same class:"
},
{
"code": null,
"e": 679,
"s": 521,
"text": "class Car\n \n{\n private string model = \"Mustang\";\n\n static void Main(string[] args)\n {\n Car myObj = new Car();\n Console.WriteLine(myObj.model);\n }\n}"
},
{
"code": null,
"e": 699,
"s": 679,
"text": "The output will be:"
},
{
"code": null,
"e": 719,
"s": 699,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 783,
"s": 719,
"text": "If you try to access it outside the class, an error will occur:"
},
{
"code": null,
"e": 960,
"s": 783,
"text": "class Car\n{\n private string model = \"Mustang\";\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Car myObj = new Car();\n Console.WriteLine(myObj.model);\n }\n}\n \n"
},
{
"code": null,
"e": 980,
"s": 960,
"text": "The output will be:"
},
{
"code": null,
"e": 1000,
"s": 980,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1089,
"s": 1000,
"text": "If you declare a field with a public access modifier, it is accessible for \nall classes:"
},
{
"code": null,
"e": 1265,
"s": 1089,
"text": "class Car\n{\n public string model = \"Mustang\";\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Car myObj = new Car();\n Console.WriteLine(myObj.model);\n }\n}\n \n"
},
{
"code": null,
"e": 1285,
"s": 1265,
"text": "The output will be:"
},
{
"code": null,
"e": 1305,
"s": 1285,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1413,
"s": 1305,
"text": "To control the visibility of class members (the security level of \neach individual class and class member)."
},
{
"code": null,
"e": 1620,
"s": 1413,
"text": "To achieve \"Encapsulation\" - which is the process of making sure that \"sensitive\" data is hidden from users. \nThis is done by declaring fields as private. You will learn more about this in the next chapter."
},
{
"code": null,
"e": 1714,
"s": 1620,
"text": "Note: By default, all members of a class are private if you don't specify an access modifier:"
},
{
"code": null,
"e": 1787,
"s": 1714,
"text": "class Car\n{\n string model; // private\n string year; // private\n}\n \n"
},
{
"code": null,
"e": 1820,
"s": 1787,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1862,
"s": 1820,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1969,
"s": 1862,
"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": 1988,
"s": 1969,
"text": "[email protected]"
}
] |
How to open PIL Image in Tkinter on Canvas? | Pillow package (or PIL) helps a lot to process and load images in Python projects. It is a free open-source library available in Python that adds support to load, process, and manipulate the images of different formats.
In order to open the Image in Tkinter canvas, we have to first import the library using from PIL import Image, ImageTk command. To display the image in our Tkinter application, we can use the Canvas widget by specifying the image file in the create_image(x,y,image) method.
#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x270")
#Create a canvas
canvas= Canvas(win, width= 600, height= 400)
canvas.pack()
#Load an image in the script
img= ImageTk.PhotoImage(Image.open("download.png"))
#Add image to the Canvas Items
canvas.create_image(10,10,anchor=NW,image=img)
win.mainloop()
Running the above code will display a window with an image inside the canvas widget. | [
{
"code": null,
"e": 1282,
"s": 1062,
"text": "Pillow package (or PIL) helps a lot to process and load images in Python projects. It is a free open-source library available in Python that adds support to load, process, and manipulate the images of different formats."
},
{
"code": null,
"e": 1556,
"s": 1282,
"text": "In order to open the Image in Tkinter canvas, we have to first import the library using from PIL import Image, ImageTk command. To display the image in our Tkinter application, we can use the Canvas widget by specifying the image file in the create_image(x,y,image) method."
},
{
"code": null,
"e": 2002,
"s": 1556,
"text": "#Import the required Libraries\nfrom tkinter import *\nfrom PIL import Image,ImageTk\n\n#Create an instance of tkinter frame\nwin = Tk()\n\n#Set the geometry of tkinter frame\nwin.geometry(\"750x270\")\n\n#Create a canvas\ncanvas= Canvas(win, width= 600, height= 400)\ncanvas.pack()\n\n#Load an image in the script\nimg= ImageTk.PhotoImage(Image.open(\"download.png\"))\n\n#Add image to the Canvas Items\ncanvas.create_image(10,10,anchor=NW,image=img)\n\nwin.mainloop()"
},
{
"code": null,
"e": 2087,
"s": 2002,
"text": "Running the above code will display a window with an image inside the canvas widget."
}
] |
NHibernate - Fluent Hibernate | In this chapter, we will be covering fluent NHibernate. Fluent NHibernate is another way of mapping or you can say it is an alternative to NHibernate's standard XML mapping files. Instead of writing XML (.hbm.xml files) documents. With the help of Fluent NHibernate, you can write mappings in strongly typed C# code.
In Fluent NHibernate mappings are compiled along with the rest of your application.
In Fluent NHibernate mappings are compiled along with the rest of your application.
You can easily change your mappings just like your application code and the compiler will fail on any typos.
You can easily change your mappings just like your application code and the compiler will fail on any typos.
It has a conventional configuration system, where you can specify patterns for overriding naming conventions and many other things.
It has a conventional configuration system, where you can specify patterns for overriding naming conventions and many other things.
You can also set how things should be named once, then Fluent NHibernate does the rest.
You can also set how things should be named once, then Fluent NHibernate does the rest.
Let’s have a look into a simple example by creating a new console project. In this chapter, we will use a simple database in which we have a simple Customer table as shown in the following image.
The first step is to start Fluent NHibernate is to install Fluent NHibernate package. So open the NuGet Package Manager Console and enter the following command.
PM> install-package FluentNHibernate
Once it is installed successfully, you will see the following message.
Let’s add a simple model class of Customer and the following program shows the Customer class implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FluentNHibernateDemo {
class Customer {
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
}
Now we need to create Mappings using fluent NHibernate, so add one more class CustomerMap in your project. Here is the implementation of the CustomerMap class.
using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
using System.Threading.Tasks;
namespace FluentNHibernateDemo {
class CustomerMap : ClassMap<Customer> {
public CustomerMap() {
Id(x => x.Id);
Map(x => x.FirstName);
Map(x => x.LastName);
Table("Customer");
}
}
}
Let’s add another class NHibernateHelper in which we will set different configuration settings.
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
namespace FluentNHibernateDemo {
public class NHibernateHelper {
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory {
get {
if (_sessionFactory == null)
InitializeSessionFactory(); return _sessionFactory;
}
}
private static void InitializeSessionFactory() {
_sessionFactory = Fluently.Configure()
String Data Source = asia13797\\sqlexpress;
String Initial Catalog = NHibernateDemoDB;
String Integrated Security = True;
String Connect Timeout = 15;
String Encrypt = False;
String TrustServerCertificate = False;
String ApplicationIntent = ReadWrite;
String MultiSubnetFailover = False;
.Database(MsSqlConfiguration.MsSql2008 .ConnectionString(
@"Data Source + Initial Catalog + Integrated Security + Connect Timeout
+ Encrypt + TrustServerCertificate + ApplicationIntent +
MultiSubnetFailover") .ShowSql() )
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<Program>())
.ExposeConfiguration(cfg => new SchemaExport(cfg)
.Create(true, true))
.BuildSessionFactory();
}
public static ISession OpenSession() {
return SessionFactory.OpenSession();
}
}
}
Now let’s move to the Program.cs file in which we will start a session and then create a new customer and save that customer to the database as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FluentNHibernateDemo {
class Program {
static void Main(string[] args) {
using (var session = NHibernateHelper.OpenSession()) {
using (var transaction = session.BeginTransaction()) {
var customer = new Customer {
FirstName = "Allan",
LastName = "Bomer"
};
session.Save(customer);
transaction.Commit();
Console.WriteLine("Customer Created: " + customer.FirstName + "\t" +
customer.LastName);
}
Console.ReadKey();
}
}
}
}
Let’s run your application and you will see the following output.
if exists (select * from dbo.sysobjects where id = object_id(N'Customer') and
OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table Customer
create table Customer (
Id INT IDENTITY NOT NULL,
FirstName NVARCHAR(255) null,
LastName NVARCHAR(255) null,
primary key (Id)
)
NHibernate: INSERT INTO Customer (FirstName, LastName) VALUES (@p0, @p1);
select SCOPE_IDENTITY();@p0 = 'Allan' [Type: String (4000)],
@p1 = 'Bomer' [Type: String (4000)]
Customer Created: Allan Bomer
As you can see the new customer is created. To see the customer record, let’s go to the database and see the View Data and you will see that 1 Customer is added.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2650,
"s": 2333,
"text": "In this chapter, we will be covering fluent NHibernate. Fluent NHibernate is another way of mapping or you can say it is an alternative to NHibernate's standard XML mapping files. Instead of writing XML (.hbm.xml files) documents. With the help of Fluent NHibernate, you can write mappings in strongly typed C# code."
},
{
"code": null,
"e": 2734,
"s": 2650,
"text": "In Fluent NHibernate mappings are compiled along with the rest of your application."
},
{
"code": null,
"e": 2818,
"s": 2734,
"text": "In Fluent NHibernate mappings are compiled along with the rest of your application."
},
{
"code": null,
"e": 2927,
"s": 2818,
"text": "You can easily change your mappings just like your application code and the compiler will fail on any typos."
},
{
"code": null,
"e": 3036,
"s": 2927,
"text": "You can easily change your mappings just like your application code and the compiler will fail on any typos."
},
{
"code": null,
"e": 3168,
"s": 3036,
"text": "It has a conventional configuration system, where you can specify patterns for overriding naming conventions and many other things."
},
{
"code": null,
"e": 3300,
"s": 3168,
"text": "It has a conventional configuration system, where you can specify patterns for overriding naming conventions and many other things."
},
{
"code": null,
"e": 3388,
"s": 3300,
"text": "You can also set how things should be named once, then Fluent NHibernate does the rest."
},
{
"code": null,
"e": 3476,
"s": 3388,
"text": "You can also set how things should be named once, then Fluent NHibernate does the rest."
},
{
"code": null,
"e": 3672,
"s": 3476,
"text": "Let’s have a look into a simple example by creating a new console project. In this chapter, we will use a simple database in which we have a simple Customer table as shown in the following image."
},
{
"code": null,
"e": 3833,
"s": 3672,
"text": "The first step is to start Fluent NHibernate is to install Fluent NHibernate package. So open the NuGet Package Manager Console and enter the following command."
},
{
"code": null,
"e": 3871,
"s": 3833,
"text": "PM> install-package FluentNHibernate\n"
},
{
"code": null,
"e": 3942,
"s": 3871,
"text": "Once it is installed successfully, you will see the following message."
},
{
"code": null,
"e": 4052,
"s": 3942,
"text": "Let’s add a simple model class of Customer and the following program shows the Customer class implementation."
},
{
"code": null,
"e": 4383,
"s": 4052,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq;\nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace FluentNHibernateDemo { \n class Customer { \n public virtual int Id { get; set; } \n public virtual string FirstName { get; set; } \n public virtual string LastName { get; set; } \n } \n}"
},
{
"code": null,
"e": 4543,
"s": 4383,
"text": "Now we need to create Mappings using fluent NHibernate, so add one more class CustomerMap in your project. Here is the implementation of the CustomerMap class."
},
{
"code": null,
"e": 4940,
"s": 4543,
"text": "using FluentNHibernate.Mapping; \nusing System; \nusing System.Collections.Generic; \nusing System.Linq; using System.Text; \nusing System.Threading.Tasks;\n\nnamespace FluentNHibernateDemo { \n class CustomerMap : ClassMap<Customer> { \n public CustomerMap() { \n Id(x => x.Id); \n Map(x => x.FirstName); \n Map(x => x.LastName); \n Table(\"Customer\"); \n } \n }\n}"
},
{
"code": null,
"e": 5036,
"s": 4940,
"text": "Let’s add another class NHibernateHelper in which we will set different configuration settings."
},
{
"code": null,
"e": 6554,
"s": 5036,
"text": "using FluentNHibernate.Cfg; \nusing FluentNHibernate.Cfg.Db; \nusing NHibernate; \nusing NHibernate.Tool.hbm2ddl;\n\nnamespace FluentNHibernateDemo { \n\n public class NHibernateHelper { \n\t\n private static ISessionFactory _sessionFactory;\n\t\t\n private static ISessionFactory SessionFactory { \n get { \n if (_sessionFactory == null)\n InitializeSessionFactory(); return _sessionFactory; \n } \n }\n \n private static void InitializeSessionFactory() { \n _sessionFactory = Fluently.Configure() \n\t\t\t\n String Data Source = asia13797\\\\sqlexpress;\n String Initial Catalog = NHibernateDemoDB;\n String Integrated Security = True;\n String Connect Timeout = 15;\n String Encrypt = False;\n String TrustServerCertificate = False;\n String ApplicationIntent = ReadWrite;\n String MultiSubnetFailover = False;\n\t\t\t\n .Database(MsSqlConfiguration.MsSql2008 .ConnectionString( \n @\"Data Source + Initial Catalog + Integrated Security + Connect Timeout\n + Encrypt + TrustServerCertificate + ApplicationIntent + \n MultiSubnetFailover\") .ShowSql() ) \n\t\t\t\t\n .Mappings(m => m.FluentMappings\n .AddFromAssemblyOf<Program>()) \n .ExposeConfiguration(cfg => new SchemaExport(cfg) \n .Create(true, true)) \n .BuildSessionFactory(); \n }\n\t\t\n public static ISession OpenSession() { \n return SessionFactory.OpenSession(); \n } \n }\n}"
},
{
"code": null,
"e": 6711,
"s": 6554,
"text": "Now let’s move to the Program.cs file in which we will start a session and then create a new customer and save that customer to the database as shown below."
},
{
"code": null,
"e": 7499,
"s": 6711,
"text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks;\n\nnamespace FluentNHibernateDemo { \n class Program { \n\t\n static void Main(string[] args) { \n\t\t\n using (var session = NHibernateHelper.OpenSession()) { \n\t\t\t\n using (var transaction = session.BeginTransaction()) { \n var customer = new Customer { \n FirstName = \"Allan\", \n LastName = \"Bomer\" \n }; \n\t\t\t\t\t\n session.Save(customer); \n transaction.Commit();\n Console.WriteLine(\"Customer Created: \" + customer.FirstName + \"\\t\" +\n customer.LastName); \n } \n\t\t\t\t\n Console.ReadKey(); \n } \n } \n } \n}"
},
{
"code": null,
"e": 7565,
"s": 7499,
"text": "Let’s run your application and you will see the following output."
},
{
"code": null,
"e": 8061,
"s": 7565,
"text": "if exists (select * from dbo.sysobjects where id = object_id(N'Customer') and\n OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table Customer\n\ncreate table Customer (\n Id INT IDENTITY NOT NULL,\n FirstName NVARCHAR(255) null,\n LastName NVARCHAR(255) null,\n primary key (Id)\n)\n\nNHibernate: INSERT INTO Customer (FirstName, LastName) VALUES (@p0, @p1); \n select SCOPE_IDENTITY();@p0 = 'Allan' [Type: String (4000)], \n @p1 = 'Bomer' [Type: String (4000)]\n Customer Created: Allan Bomer\n"
},
{
"code": null,
"e": 8223,
"s": 8061,
"text": "As you can see the new customer is created. To see the customer record, let’s go to the database and see the View Data and you will see that 1 Customer is added."
},
{
"code": null,
"e": 8230,
"s": 8223,
"text": " Print"
},
{
"code": null,
"e": 8241,
"s": 8230,
"text": " Add Notes"
}
] |
Converting Odd and Even-indexed characters in a string to uppercase/lowercase in JavaScript? | We need to write a function that reads a string and converts the odd indexed characters in the
string to upperCase and the even ones to lowerCase and returns a new string.
Full code for doing the same will be −
const text = 'Hello world, it is so nice to be alive.';
const changeCase = (str) => {
const newStr = str
.split("")
.map((word, index) => {
if(index % 2 === 0){
return word.toLowerCase();
}else{
return word.toUpperCase();
}
})
.join("");
return newStr;
};
console.log(changeCase(text));
The code converts the string into an array, maps through each of its word and converts them to
uppercase or lowercase based on their index.
Lastly, it converts the array back into a string and returns it. The output in console will be −
hElLo wOrLd, It iS So nIcE To bE AlIvE. | [
{
"code": null,
"e": 1234,
"s": 1062,
"text": "We need to write a function that reads a string and converts the odd indexed characters in the\nstring to upperCase and the even ones to lowerCase and returns a new string."
},
{
"code": null,
"e": 1273,
"s": 1234,
"text": "Full code for doing the same will be −"
},
{
"code": null,
"e": 1614,
"s": 1273,
"text": "const text = 'Hello world, it is so nice to be alive.';\nconst changeCase = (str) => {\n const newStr = str\n .split(\"\")\n .map((word, index) => {\n if(index % 2 === 0){\n return word.toLowerCase();\n }else{\n return word.toUpperCase();\n }\n })\n .join(\"\");\n return newStr;\n};\nconsole.log(changeCase(text));"
},
{
"code": null,
"e": 1754,
"s": 1614,
"text": "The code converts the string into an array, maps through each of its word and converts them to\nuppercase or lowercase based on their index."
},
{
"code": null,
"e": 1851,
"s": 1754,
"text": "Lastly, it converts the array back into a string and returns it. The output in console will be −"
},
{
"code": null,
"e": 1891,
"s": 1851,
"text": "hElLo wOrLd, It iS So nIcE To bE AlIvE."
}
] |
Learning Decision Trees. In the context of supervised learning... | by Arun Jagota | Towards Data Science | In the context of supervised learning, a decision tree is a tree for predicting the output for a given input. We start from the root of the tree and ask a particular question about the input. Depending on the answer, we go down to one or another of its children. The child we visit is the root of another tree. So we repeat the process, i.e. ask another question here. Eventually, we reach a leaf, i.e. a node with no children. This node contains the final answer which we output and stop.
This process is depicted below.
Let’s see an example.
In machine learning, decision trees are of interest because they can be learned automatically from labeled data. A labeled data set is a set of pairs (x, y). Here x is the input vector and y the target output.
Below is a labeled data set for our example.
Weather Temperature ActionSunny Warm Go to parkSunny Cold Stay at homeSunny Hot Stay at homeRainy Warm Stay at homeRainy Cold Stay at home
Why Decision Trees?
Learned decision trees often produce good predictors. Because they operate in a tree structure, they can capture interactions among the predictor variables. (This will register as we see more examples.)
The added benefit is that the learned models are transparent. That is, we can inspect them and deduce how they predict. By contrast, neural networks are opaque. Deep ones even more so.
Of course, when prediction accuracy is paramount, opaqueness can be tolerated. Decision trees cover this too. Ensembles of decision trees (specifically Random Forest) have state-of-the-art accuracy.
So either way, it’s good to learn about decision tree learning.
Learning Decision Trees
Okay, let’s get to it. We’ll focus on binary classification as this suffices to bring out the key ideas in learning. For completeness, we will also discuss how to morph a binary classifier to a multi-class classifier or to a regressor.
The pedagogical approach we take below mirrors the process of induction. We’ll start with learning base cases, then build out to more elaborate ones.
Learning Base Case 1: Single Numeric Predictor
Consider the following problem. The input is a temperature. The output is a subjective assessment by an individual or a collective of whether the temperature is HOT or NOT.
Let’s depict our labeled data as follows, with - denoting NOT and + denoting HOT. The temperatures are implicit in the order in the horizontal line.
- - - - - + + + + +
This data is linearly separable. All the -s come before the +s.
In general, it need not be, as depicted below.
- - - - - + - + - - - + - + + - + + - + + + + + + + +
Perhaps the labels are aggregated from the opinions of multiple people. There might be some disagreement, especially near the boundary separating most of the -s from most of the +s.
Our job is to learn a threshold that yields the best decision rule. What do we mean by “decision rule”. For any threshold T, we define this as
IF temperature < T return NOTELSE return HOT
The accuracy of this decision rule on the training set depends on T.
The objective of learning is to find the T that gives us the most accurate decision rule. Such a T is called an optimal split.
In fact, we have just seen our first example of learning a decision tree. The decision tree is depicted below.
Learning Base Case 2: Single Categorical Predictor
Consider season as a predictor and sunny or rainy as the binary outcome. Say we have a training set of daily recordings. For each day, whether the day was sunny or rainy is recorded as the outcome to predict. The season the day was in is recorded as the predictor.
This problem is simpler than Learning Base Case 1. The predictor has only a few values. The four seasons. No optimal split to be learned. It’s as if all we need to do is to fill in the ‘predict’ portions of the case statement.
case seasonwhen summer: Predict sunnywhen winter: Predict rainywhen fall: ??when spring: ??
That said, we do have the issue of “noisy labels”. This just means that the outcome cannot be determined with certainty. Summer can have rainy days.
This issue is easy to take care of. At a leaf of the tree, we store the distribution over the counts of the two outcomes we observed in the training set. This is depicted below.
Say the season was summer. The relevant leaf shows 80: sunny and 5: rainy. So we would predict sunny with a confidence 80/85.
Learning General Case 1: Multiple Numeric Predictors
Not surprisingly, this is more involved.
We start by imposing the simplifying constraint that the decision rule at any node of the tree tests only for a single dimension of the input.
Call our predictor variables X1, ..., Xn. This means that at the tree’s root we can test for exactly one of these. The question is, which one?
We answer this as follows. For each of the n predictor variables, we consider the problem of predicting the outcome solely from that predictor variable. This gives us n one-dimensional predictor problems to solve. We compute the optimal splits T1, ..., Tn for these, in the manner described in the first base case. While doing so we also record the accuracies on the training set that each of these splits delivers.
At the root of the tree, we test for that Xi whose optimal split Ti yields the most accurate (one-dimensional) predictor. This is depicted below.
So now we need to repeat this process for the two children A and B of this root. Towards this, first, we derive training sets for A and B as follows. The training set for A (B) is the restriction of the parent’s training set to those instances in which Xi is less than T (>= T). Let’s also delete the Xi dimension from each of the training sets.
Now we have two instances of exactly the same learning problem. So we recurse.
And so it goes until our training set has no predictors. Only binary outcomes. The node to which such a training set is attached is a leaf. Nothing to test. The data on the leaf are the proportions of the two outcomes in the training set. This suffices to predict both the best outcome at the leaf and the confidence in it.
Learning General Case 2: Multiple Categorical Predictors
Here we have n categorical predictor variables X1, ..., Xn. As we did for multiple numeric predictors, we derive n univariate prediction problems from this, solve each of them, and compute their accuracies to determine the most accurate univariate classifier. The predictor variable of this classifier is the one we place at the decision tree’s root.
Next, we set up the training sets for this root’s children.
There is one child for each value v of the root’s predictor variable Xi. The training set at this child is the restriction of the root’s training set to those instances in which Xi equals v. We also delete attribute Xi from this training set.
Now we recurse as we did with multiple numeric predictors.
Example
Let’s illustrate this learning on a slightly enhanced version of our first example, below. We’ve named the two outcomes O and I, to denote outdoors and indoors respectively. We’ve also attached counts to these two outcomes. A row with a count of o for O and i for I denotes o instances labeled O and i instances labeled I.
Weather Temperature ActionSunny Warm O (50), I (10)Sunny Cold O (10), I (40)Sunny Hot O (5), I (30)Rainy Warm O (10), I (25)Rainy Cold O (1), I (35)Rainy Hot O (2), I(7)
So what predictor variable should we test at the tree’s root? Well, weather being rainy predicts I. (That is, we stay indoors.) Weather being sunny is not predictive on its own. Now consider Temperature. Not surprisingly, the temperature is hot or cold also predicts I.
Which variable is the winner? Not clear. Let’s give the nod to Temperature since two of its three values predict the outcome. (This is a subjective preference. Don’t take it too literally.)
Now we recurse.
The final tree that results is below.
Mixed Predictor Variables
What if we have both numeric and categorical predictor variables? A reasonable approach is to ignore the difference. To figure out which variable to test for at a node, just determine, as before, which of the available predictor variables predicts the outcome the best. For a numeric predictor, this will involve finding an optimal split first.
The Learning Algorithm: Abstracting Out The Key Operations
Let’s abstract out the key operations in our learning algorithm. These abstractions will help us in describing its extension to the multi-class case and to the regression case.
The key operations are
Evaluate how accurately any one variable predicts the response.Derive child training sets from those of the parent.
Evaluate how accurately any one variable predicts the response.
Derive child training sets from those of the parent.
Multi-class Case
What if our response variable has more than two outcomes? As an example, say on the problem of deciding what to do based on the weather and the temperature we add one more option: go to the Mall.
Fundamentally nothing changes. Adding more outcomes to the response variable does not affect our ability to do operation 1. (The evaluation metric might differ though.) Operation 2 is not affected either, as it doesn’t even look at the response.
Regression
What if our response variable is numeric? Here is one example. Predict the day’s high temperature from the month of the year and the latitude.
Can we still evaluate the accuracy with which any single predictor variable predicts the response? This raises a question. How do we even predict a numeric response if any of the predictor variables are categorical?
Let’s start by discussing this. First, we look at
Base Case 1: Single Categorical Predictor Variable
For each value of this predictor, we can record the values of the response variable we see in the training set. A sensible prediction is the mean of these responses.
Let’s write this out formally. Let X denote our categorical predictor and y the numeric response. Our prediction of y when X equals v is an estimate of the value we expect in this situation, i.e. E[y|X=v].
Let’s see a numeric example. Consider the training set
X A A B By 1 2 4 5
Our predicted ys for X = A and X = B are 1.5 and 4.5 respectively.
Base Case 2: Single Numeric Predictor Variable
For any particular split T, a numeric predictor operates as a boolean categorical variable. So the previous section covers this case as well.
Except that we need an extra loop to evaluate various candidate T’s and pick the one which works the best. Speaking of “works the best”, we haven’t covered this yet. We do this below.
Evaluation Metric
Both the response and its predictions are numeric. We just need a metric that quantifies how close to the target response the predicted one is. A sensible metric may be derived from the sum of squares of the discrepancies between the target response and the predicted response.
General Case
We have covered operation 1, i.e. evaluating the quality of a predictor variable towards a numeric response. Operation 2, deriving child training sets from a parent’s, needs no change. As noted earlier, this derivation process does not use the response at all.
The Response Predicted At A Leaf
As in the classification case, the training set attached at a leaf has no predictor variables, only a collection of outcomes. As noted earlier, a sensible prediction at the leaf would be the mean of these outcomes. So this is what we should do when we arrive at a leaf.
Modeling Tradeoffs
Consider our regression example: predict the day’s high temperature from the month of the year and the latitude.
Consider the month of the year. We could treat it as a categorical predictor with values January, February, March, ... Or as a numeric predictor with values 1, 2, 3, ...
What are the tradeoffs? Treating it as a numeric predictor lets us leverage the order in the months. February is near January and far away from August. That said, how do we capture that December and January are neighboring months? 12 and 1 as numbers are far apart.
Perhaps more importantly, decision tree learning with a numeric predictor operates only via splits. That would mean that a node on a tree that tests for this variable can only make binary decisions. By contrast, using the categorical predictor gives us 12 children. In principle, this is capable of making finer-grained decisions.
Now consider latitude. We can treat it as a numeric predictor. Or as a categorical one induced by a certain binning, e.g. in units of + or - 10 degrees. The latter enables finer-grained decisions in a decision tree.
Summary
In this post, we have described learning decision trees with intuition, examples, and pictures. We have covered both decision trees for both classification and regression problems. We have also covered both numeric and categorical predictor variables.
Further Reading
Decision tree learning
Decision tree learning | [
{
"code": null,
"e": 662,
"s": 172,
"text": "In the context of supervised learning, a decision tree is a tree for predicting the output for a given input. We start from the root of the tree and ask a particular question about the input. Depending on the answer, we go down to one or another of its children. The child we visit is the root of another tree. So we repeat the process, i.e. ask another question here. Eventually, we reach a leaf, i.e. a node with no children. This node contains the final answer which we output and stop."
},
{
"code": null,
"e": 694,
"s": 662,
"text": "This process is depicted below."
},
{
"code": null,
"e": 716,
"s": 694,
"text": "Let’s see an example."
},
{
"code": null,
"e": 926,
"s": 716,
"text": "In machine learning, decision trees are of interest because they can be learned automatically from labeled data. A labeled data set is a set of pairs (x, y). Here x is the input vector and y the target output."
},
{
"code": null,
"e": 971,
"s": 926,
"text": "Below is a labeled data set for our example."
},
{
"code": null,
"e": 1156,
"s": 971,
"text": "Weather Temperature ActionSunny Warm Go to parkSunny Cold Stay at homeSunny Hot Stay at homeRainy Warm Stay at homeRainy Cold Stay at home"
},
{
"code": null,
"e": 1176,
"s": 1156,
"text": "Why Decision Trees?"
},
{
"code": null,
"e": 1379,
"s": 1176,
"text": "Learned decision trees often produce good predictors. Because they operate in a tree structure, they can capture interactions among the predictor variables. (This will register as we see more examples.)"
},
{
"code": null,
"e": 1564,
"s": 1379,
"text": "The added benefit is that the learned models are transparent. That is, we can inspect them and deduce how they predict. By contrast, neural networks are opaque. Deep ones even more so."
},
{
"code": null,
"e": 1763,
"s": 1564,
"text": "Of course, when prediction accuracy is paramount, opaqueness can be tolerated. Decision trees cover this too. Ensembles of decision trees (specifically Random Forest) have state-of-the-art accuracy."
},
{
"code": null,
"e": 1827,
"s": 1763,
"text": "So either way, it’s good to learn about decision tree learning."
},
{
"code": null,
"e": 1851,
"s": 1827,
"text": "Learning Decision Trees"
},
{
"code": null,
"e": 2087,
"s": 1851,
"text": "Okay, let’s get to it. We’ll focus on binary classification as this suffices to bring out the key ideas in learning. For completeness, we will also discuss how to morph a binary classifier to a multi-class classifier or to a regressor."
},
{
"code": null,
"e": 2237,
"s": 2087,
"text": "The pedagogical approach we take below mirrors the process of induction. We’ll start with learning base cases, then build out to more elaborate ones."
},
{
"code": null,
"e": 2284,
"s": 2237,
"text": "Learning Base Case 1: Single Numeric Predictor"
},
{
"code": null,
"e": 2457,
"s": 2284,
"text": "Consider the following problem. The input is a temperature. The output is a subjective assessment by an individual or a collective of whether the temperature is HOT or NOT."
},
{
"code": null,
"e": 2606,
"s": 2457,
"text": "Let’s depict our labeled data as follows, with - denoting NOT and + denoting HOT. The temperatures are implicit in the order in the horizontal line."
},
{
"code": null,
"e": 2626,
"s": 2606,
"text": "- - - - - + + + + +"
},
{
"code": null,
"e": 2690,
"s": 2626,
"text": "This data is linearly separable. All the -s come before the +s."
},
{
"code": null,
"e": 2737,
"s": 2690,
"text": "In general, it need not be, as depicted below."
},
{
"code": null,
"e": 2791,
"s": 2737,
"text": "- - - - - + - + - - - + - + + - + + - + + + + + + + +"
},
{
"code": null,
"e": 2973,
"s": 2791,
"text": "Perhaps the labels are aggregated from the opinions of multiple people. There might be some disagreement, especially near the boundary separating most of the -s from most of the +s."
},
{
"code": null,
"e": 3116,
"s": 2973,
"text": "Our job is to learn a threshold that yields the best decision rule. What do we mean by “decision rule”. For any threshold T, we define this as"
},
{
"code": null,
"e": 3163,
"s": 3116,
"text": "IF temperature < T return NOTELSE return HOT"
},
{
"code": null,
"e": 3232,
"s": 3163,
"text": "The accuracy of this decision rule on the training set depends on T."
},
{
"code": null,
"e": 3359,
"s": 3232,
"text": "The objective of learning is to find the T that gives us the most accurate decision rule. Such a T is called an optimal split."
},
{
"code": null,
"e": 3470,
"s": 3359,
"text": "In fact, we have just seen our first example of learning a decision tree. The decision tree is depicted below."
},
{
"code": null,
"e": 3521,
"s": 3470,
"text": "Learning Base Case 2: Single Categorical Predictor"
},
{
"code": null,
"e": 3786,
"s": 3521,
"text": "Consider season as a predictor and sunny or rainy as the binary outcome. Say we have a training set of daily recordings. For each day, whether the day was sunny or rainy is recorded as the outcome to predict. The season the day was in is recorded as the predictor."
},
{
"code": null,
"e": 4013,
"s": 3786,
"text": "This problem is simpler than Learning Base Case 1. The predictor has only a few values. The four seasons. No optimal split to be learned. It’s as if all we need to do is to fill in the ‘predict’ portions of the case statement."
},
{
"code": null,
"e": 4105,
"s": 4013,
"text": "case seasonwhen summer: Predict sunnywhen winter: Predict rainywhen fall: ??when spring: ??"
},
{
"code": null,
"e": 4254,
"s": 4105,
"text": "That said, we do have the issue of “noisy labels”. This just means that the outcome cannot be determined with certainty. Summer can have rainy days."
},
{
"code": null,
"e": 4432,
"s": 4254,
"text": "This issue is easy to take care of. At a leaf of the tree, we store the distribution over the counts of the two outcomes we observed in the training set. This is depicted below."
},
{
"code": null,
"e": 4558,
"s": 4432,
"text": "Say the season was summer. The relevant leaf shows 80: sunny and 5: rainy. So we would predict sunny with a confidence 80/85."
},
{
"code": null,
"e": 4611,
"s": 4558,
"text": "Learning General Case 1: Multiple Numeric Predictors"
},
{
"code": null,
"e": 4652,
"s": 4611,
"text": "Not surprisingly, this is more involved."
},
{
"code": null,
"e": 4795,
"s": 4652,
"text": "We start by imposing the simplifying constraint that the decision rule at any node of the tree tests only for a single dimension of the input."
},
{
"code": null,
"e": 4938,
"s": 4795,
"text": "Call our predictor variables X1, ..., Xn. This means that at the tree’s root we can test for exactly one of these. The question is, which one?"
},
{
"code": null,
"e": 5354,
"s": 4938,
"text": "We answer this as follows. For each of the n predictor variables, we consider the problem of predicting the outcome solely from that predictor variable. This gives us n one-dimensional predictor problems to solve. We compute the optimal splits T1, ..., Tn for these, in the manner described in the first base case. While doing so we also record the accuracies on the training set that each of these splits delivers."
},
{
"code": null,
"e": 5500,
"s": 5354,
"text": "At the root of the tree, we test for that Xi whose optimal split Ti yields the most accurate (one-dimensional) predictor. This is depicted below."
},
{
"code": null,
"e": 5846,
"s": 5500,
"text": "So now we need to repeat this process for the two children A and B of this root. Towards this, first, we derive training sets for A and B as follows. The training set for A (B) is the restriction of the parent’s training set to those instances in which Xi is less than T (>= T). Let’s also delete the Xi dimension from each of the training sets."
},
{
"code": null,
"e": 5925,
"s": 5846,
"text": "Now we have two instances of exactly the same learning problem. So we recurse."
},
{
"code": null,
"e": 6249,
"s": 5925,
"text": "And so it goes until our training set has no predictors. Only binary outcomes. The node to which such a training set is attached is a leaf. Nothing to test. The data on the leaf are the proportions of the two outcomes in the training set. This suffices to predict both the best outcome at the leaf and the confidence in it."
},
{
"code": null,
"e": 6306,
"s": 6249,
"text": "Learning General Case 2: Multiple Categorical Predictors"
},
{
"code": null,
"e": 6657,
"s": 6306,
"text": "Here we have n categorical predictor variables X1, ..., Xn. As we did for multiple numeric predictors, we derive n univariate prediction problems from this, solve each of them, and compute their accuracies to determine the most accurate univariate classifier. The predictor variable of this classifier is the one we place at the decision tree’s root."
},
{
"code": null,
"e": 6717,
"s": 6657,
"text": "Next, we set up the training sets for this root’s children."
},
{
"code": null,
"e": 6960,
"s": 6717,
"text": "There is one child for each value v of the root’s predictor variable Xi. The training set at this child is the restriction of the root’s training set to those instances in which Xi equals v. We also delete attribute Xi from this training set."
},
{
"code": null,
"e": 7019,
"s": 6960,
"text": "Now we recurse as we did with multiple numeric predictors."
},
{
"code": null,
"e": 7027,
"s": 7019,
"text": "Example"
},
{
"code": null,
"e": 7350,
"s": 7027,
"text": "Let’s illustrate this learning on a slightly enhanced version of our first example, below. We’ve named the two outcomes O and I, to denote outdoors and indoors respectively. We’ve also attached counts to these two outcomes. A row with a count of o for O and i for I denotes o instances labeled O and i instances labeled I."
},
{
"code": null,
"e": 7576,
"s": 7350,
"text": "Weather Temperature ActionSunny Warm O (50), I (10)Sunny Cold O (10), I (40)Sunny Hot O (5), I (30)Rainy Warm O (10), I (25)Rainy Cold O (1), I (35)Rainy Hot O (2), I(7)"
},
{
"code": null,
"e": 7846,
"s": 7576,
"text": "So what predictor variable should we test at the tree’s root? Well, weather being rainy predicts I. (That is, we stay indoors.) Weather being sunny is not predictive on its own. Now consider Temperature. Not surprisingly, the temperature is hot or cold also predicts I."
},
{
"code": null,
"e": 8036,
"s": 7846,
"text": "Which variable is the winner? Not clear. Let’s give the nod to Temperature since two of its three values predict the outcome. (This is a subjective preference. Don’t take it too literally.)"
},
{
"code": null,
"e": 8052,
"s": 8036,
"text": "Now we recurse."
},
{
"code": null,
"e": 8090,
"s": 8052,
"text": "The final tree that results is below."
},
{
"code": null,
"e": 8116,
"s": 8090,
"text": "Mixed Predictor Variables"
},
{
"code": null,
"e": 8461,
"s": 8116,
"text": "What if we have both numeric and categorical predictor variables? A reasonable approach is to ignore the difference. To figure out which variable to test for at a node, just determine, as before, which of the available predictor variables predicts the outcome the best. For a numeric predictor, this will involve finding an optimal split first."
},
{
"code": null,
"e": 8520,
"s": 8461,
"text": "The Learning Algorithm: Abstracting Out The Key Operations"
},
{
"code": null,
"e": 8697,
"s": 8520,
"text": "Let’s abstract out the key operations in our learning algorithm. These abstractions will help us in describing its extension to the multi-class case and to the regression case."
},
{
"code": null,
"e": 8720,
"s": 8697,
"text": "The key operations are"
},
{
"code": null,
"e": 8836,
"s": 8720,
"text": "Evaluate how accurately any one variable predicts the response.Derive child training sets from those of the parent."
},
{
"code": null,
"e": 8900,
"s": 8836,
"text": "Evaluate how accurately any one variable predicts the response."
},
{
"code": null,
"e": 8953,
"s": 8900,
"text": "Derive child training sets from those of the parent."
},
{
"code": null,
"e": 8970,
"s": 8953,
"text": "Multi-class Case"
},
{
"code": null,
"e": 9166,
"s": 8970,
"text": "What if our response variable has more than two outcomes? As an example, say on the problem of deciding what to do based on the weather and the temperature we add one more option: go to the Mall."
},
{
"code": null,
"e": 9412,
"s": 9166,
"text": "Fundamentally nothing changes. Adding more outcomes to the response variable does not affect our ability to do operation 1. (The evaluation metric might differ though.) Operation 2 is not affected either, as it doesn’t even look at the response."
},
{
"code": null,
"e": 9423,
"s": 9412,
"text": "Regression"
},
{
"code": null,
"e": 9566,
"s": 9423,
"text": "What if our response variable is numeric? Here is one example. Predict the day’s high temperature from the month of the year and the latitude."
},
{
"code": null,
"e": 9782,
"s": 9566,
"text": "Can we still evaluate the accuracy with which any single predictor variable predicts the response? This raises a question. How do we even predict a numeric response if any of the predictor variables are categorical?"
},
{
"code": null,
"e": 9832,
"s": 9782,
"text": "Let’s start by discussing this. First, we look at"
},
{
"code": null,
"e": 9883,
"s": 9832,
"text": "Base Case 1: Single Categorical Predictor Variable"
},
{
"code": null,
"e": 10049,
"s": 9883,
"text": "For each value of this predictor, we can record the values of the response variable we see in the training set. A sensible prediction is the mean of these responses."
},
{
"code": null,
"e": 10255,
"s": 10049,
"text": "Let’s write this out formally. Let X denote our categorical predictor and y the numeric response. Our prediction of y when X equals v is an estimate of the value we expect in this situation, i.e. E[y|X=v]."
},
{
"code": null,
"e": 10310,
"s": 10255,
"text": "Let’s see a numeric example. Consider the training set"
},
{
"code": null,
"e": 10329,
"s": 10310,
"text": "X A A B By 1 2 4 5"
},
{
"code": null,
"e": 10396,
"s": 10329,
"text": "Our predicted ys for X = A and X = B are 1.5 and 4.5 respectively."
},
{
"code": null,
"e": 10443,
"s": 10396,
"text": "Base Case 2: Single Numeric Predictor Variable"
},
{
"code": null,
"e": 10585,
"s": 10443,
"text": "For any particular split T, a numeric predictor operates as a boolean categorical variable. So the previous section covers this case as well."
},
{
"code": null,
"e": 10769,
"s": 10585,
"text": "Except that we need an extra loop to evaluate various candidate T’s and pick the one which works the best. Speaking of “works the best”, we haven’t covered this yet. We do this below."
},
{
"code": null,
"e": 10787,
"s": 10769,
"text": "Evaluation Metric"
},
{
"code": null,
"e": 11065,
"s": 10787,
"text": "Both the response and its predictions are numeric. We just need a metric that quantifies how close to the target response the predicted one is. A sensible metric may be derived from the sum of squares of the discrepancies between the target response and the predicted response."
},
{
"code": null,
"e": 11078,
"s": 11065,
"text": "General Case"
},
{
"code": null,
"e": 11339,
"s": 11078,
"text": "We have covered operation 1, i.e. evaluating the quality of a predictor variable towards a numeric response. Operation 2, deriving child training sets from a parent’s, needs no change. As noted earlier, this derivation process does not use the response at all."
},
{
"code": null,
"e": 11372,
"s": 11339,
"text": "The Response Predicted At A Leaf"
},
{
"code": null,
"e": 11642,
"s": 11372,
"text": "As in the classification case, the training set attached at a leaf has no predictor variables, only a collection of outcomes. As noted earlier, a sensible prediction at the leaf would be the mean of these outcomes. So this is what we should do when we arrive at a leaf."
},
{
"code": null,
"e": 11661,
"s": 11642,
"text": "Modeling Tradeoffs"
},
{
"code": null,
"e": 11774,
"s": 11661,
"text": "Consider our regression example: predict the day’s high temperature from the month of the year and the latitude."
},
{
"code": null,
"e": 11944,
"s": 11774,
"text": "Consider the month of the year. We could treat it as a categorical predictor with values January, February, March, ... Or as a numeric predictor with values 1, 2, 3, ..."
},
{
"code": null,
"e": 12210,
"s": 11944,
"text": "What are the tradeoffs? Treating it as a numeric predictor lets us leverage the order in the months. February is near January and far away from August. That said, how do we capture that December and January are neighboring months? 12 and 1 as numbers are far apart."
},
{
"code": null,
"e": 12541,
"s": 12210,
"text": "Perhaps more importantly, decision tree learning with a numeric predictor operates only via splits. That would mean that a node on a tree that tests for this variable can only make binary decisions. By contrast, using the categorical predictor gives us 12 children. In principle, this is capable of making finer-grained decisions."
},
{
"code": null,
"e": 12757,
"s": 12541,
"text": "Now consider latitude. We can treat it as a numeric predictor. Or as a categorical one induced by a certain binning, e.g. in units of + or - 10 degrees. The latter enables finer-grained decisions in a decision tree."
},
{
"code": null,
"e": 12765,
"s": 12757,
"text": "Summary"
},
{
"code": null,
"e": 13017,
"s": 12765,
"text": "In this post, we have described learning decision trees with intuition, examples, and pictures. We have covered both decision trees for both classification and regression problems. We have also covered both numeric and categorical predictor variables."
},
{
"code": null,
"e": 13033,
"s": 13017,
"text": "Further Reading"
},
{
"code": null,
"e": 13056,
"s": 13033,
"text": "Decision tree learning"
}
] |
Introduction to the C99 Programming Language : Part I - GeeksforGeeks | 14 Feb, 2020
C99 is another name of ISO/IEC 9899:1999 standards specification for C that was adopted in 1999. This article mainly concentrates on the new features added in C99 by comparing with the C89 standard. In the development stage of the C99 standard, every element of the C language was re-examined, usage patterns were analyzed, and future demands were anticipated. C’s relationship with C++ provided a backdrop for the entire development process. The resulting C99 standard is a testimonial to the strengths of the original.
Keywords added in C99:inline: C99 adds the keyword inline which is applicable to functions. If we write inline datatype function_name (param) to any function it means that we are specifying the compiler to optimize calls to that function i.e. the function’s code will be expanded inline rather than called.Example:// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, maximum(x, y)); return 0;}Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword.The above program is equivalent to the following#include <stdio.h> int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, (x > y ? x : y)); return 0;}Output:Maximum of 5 and 10 is 10
Output:Maximum of 5 and 10 is 10
Inline functions help us to create efficient code by maintaining a structured, function-based approach.restrict: restrict is a type qualifier applicable only for pointers. A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Access to the object by another pointer can occur only if the second pointer is based on the first.We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program._Bool Datatype: _Bool datatype was added in C99 standard which stores 0 and 1 values. _Bool is an integer type.Note: bool keyword in C++ and _Bool in C are different._Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false._Complex: C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex:float _Complexdouble _Complexlong double _Complex_Imaginary: As said above, C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex and _Imaginary:float _Imaginarydouble _Imaginarylong double _ImaginaryIn the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros.Addition of Type Qualifiers: Another important aspect added in C99 is the introduction of long long and unsigned long long type modifiers. A long long int has a range of –(2^63 – 1) to +(2^63 –1). An Unsigned long long int has a minimal range starting from 0 to +(2^64 –1). This long long type allows 64-bit integers to support as a built-in type.Changes in Arrays: C99 added two important features to arrays:Variable Length Arrays: In C89 standard, the array size has to be specified using integer constants at the array declaration and array size is fixed at compile time. In C99 standard, we can declare an array whose dimensions are specified by any integer expressions whose values known at run-time. This is called Variable Length Arrays(VLA).Inclusion of Type Qualifiers: In C99, we can use the keyword static inside the square brackets during array declaration. This is only applied when array is declared in function parameters i.eExample:int fun1(char arr[static 80]){ // code}In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning.Example:#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf("%d ", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}Output:2 3 4 5 5 5 5 5 6 6
Single Line Comments: Single Line comments aren’t accepted in C89 standard. C99 standard introduces Single Line Comments which are used only when brief remarks are needed. These comments begin with // and runs to the end of the line.Eg:// First Commentint a; // another commentDeclaration of Identifiers:According to the C89 standard, all Identifiers should be declared at the start of the code block. If we need any other identifier at the middle, we can’t declare for that instance or time. We need to declare that at the start. C99 has changed this rule as we can declare identifiers whenever we need in a code.In simple, we can see this as:#include <stdio.h>int main(){ int i; i = 1; int j; // this declaration is invalid in C89 standard, but valid in C99 and C++ j = 3;}Output:
Keywords added in C99:inline: C99 adds the keyword inline which is applicable to functions. If we write inline datatype function_name (param) to any function it means that we are specifying the compiler to optimize calls to that function i.e. the function’s code will be expanded inline rather than called.Example:// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, maximum(x, y)); return 0;}Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword.The above program is equivalent to the following#include <stdio.h> int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, (x > y ? x : y)); return 0;}Output:Maximum of 5 and 10 is 10
Output:Maximum of 5 and 10 is 10
Inline functions help us to create efficient code by maintaining a structured, function-based approach.restrict: restrict is a type qualifier applicable only for pointers. A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Access to the object by another pointer can occur only if the second pointer is based on the first.We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program._Bool Datatype: _Bool datatype was added in C99 standard which stores 0 and 1 values. _Bool is an integer type.Note: bool keyword in C++ and _Bool in C are different._Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false._Complex: C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex:float _Complexdouble _Complexlong double _Complex_Imaginary: As said above, C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex and _Imaginary:float _Imaginarydouble _Imaginarylong double _ImaginaryIn the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros.
inline: C99 adds the keyword inline which is applicable to functions. If we write inline datatype function_name (param) to any function it means that we are specifying the compiler to optimize calls to that function i.e. the function’s code will be expanded inline rather than called.Example:// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, maximum(x, y)); return 0;}Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword.The above program is equivalent to the following#include <stdio.h> int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, (x > y ? x : y)); return 0;}Output:Maximum of 5 and 10 is 10
Output:Maximum of 5 and 10 is 10
Inline functions help us to create efficient code by maintaining a structured, function-based approach.
Example:
// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, maximum(x, y)); return 0;}
Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword.
The above program is equivalent to the following
#include <stdio.h> int main(){ int x = 5, y = 10; printf("Maximum of %d and %d is %d", x, y, (x > y ? x : y)); return 0;}
Maximum of 5 and 10 is 10
Maximum of 5 and 10 is 10
Inline functions help us to create efficient code by maintaining a structured, function-based approach.
restrict: restrict is a type qualifier applicable only for pointers. A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Access to the object by another pointer can occur only if the second pointer is based on the first.We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program.
We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program.
_Bool Datatype: _Bool datatype was added in C99 standard which stores 0 and 1 values. _Bool is an integer type.Note: bool keyword in C++ and _Bool in C are different._Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false.
Note: bool keyword in C++ and _Bool in C are different.
_Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false.
_Complex: C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex:float _Complexdouble _Complexlong double _Complex
Types defined in _Complex:
float _Complex
double _Complex
long double _Complex
_Imaginary: As said above, C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex and _Imaginary:float _Imaginarydouble _Imaginarylong double _ImaginaryIn the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros.
Types defined in _Complex and _Imaginary:
float _Imaginary
double _Imaginary
long double _Imaginary
In the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros.
Addition of Type Qualifiers: Another important aspect added in C99 is the introduction of long long and unsigned long long type modifiers. A long long int has a range of –(2^63 – 1) to +(2^63 –1). An Unsigned long long int has a minimal range starting from 0 to +(2^64 –1). This long long type allows 64-bit integers to support as a built-in type.
Changes in Arrays: C99 added two important features to arrays:Variable Length Arrays: In C89 standard, the array size has to be specified using integer constants at the array declaration and array size is fixed at compile time. In C99 standard, we can declare an array whose dimensions are specified by any integer expressions whose values known at run-time. This is called Variable Length Arrays(VLA).Inclusion of Type Qualifiers: In C99, we can use the keyword static inside the square brackets during array declaration. This is only applied when array is declared in function parameters i.eExample:int fun1(char arr[static 80]){ // code}In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning.Example:#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf("%d ", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}Output:2 3 4 5 5 5 5 5 6 6
Variable Length Arrays: In C89 standard, the array size has to be specified using integer constants at the array declaration and array size is fixed at compile time. In C99 standard, we can declare an array whose dimensions are specified by any integer expressions whose values known at run-time. This is called Variable Length Arrays(VLA).
Inclusion of Type Qualifiers: In C99, we can use the keyword static inside the square brackets during array declaration. This is only applied when array is declared in function parameters i.eExample:int fun1(char arr[static 80]){ // code}In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning.Example:#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf("%d ", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}Output:2 3 4 5 5 5 5 5 6 6
Example:
int fun1(char arr[static 80]){ // code}
In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning.
Example:
#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf("%d ", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}
2 3 4 5 5 5 5 5 6 6
Single Line Comments: Single Line comments aren’t accepted in C89 standard. C99 standard introduces Single Line Comments which are used only when brief remarks are needed. These comments begin with // and runs to the end of the line.Eg:// First Commentint a; // another comment
Eg:
// First Commentint a; // another comment
Declaration of Identifiers:According to the C89 standard, all Identifiers should be declared at the start of the code block. If we need any other identifier at the middle, we can’t declare for that instance or time. We need to declare that at the start. C99 has changed this rule as we can declare identifiers whenever we need in a code.In simple, we can see this as:#include <stdio.h>int main(){ int i; i = 1; int j; // this declaration is invalid in C89 standard, but valid in C99 and C++ j = 3;}Output:
In simple, we can see this as:
#include <stdio.h>int main(){ int i; i = 1; int j; // this declaration is invalid in C89 standard, but valid in C99 and C++ j = 3;}
C Language
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Arrow operator -> in C/C++ with Examples
Structures in C++
Differences between Procedural and Object Oriented Programming
Top 10 Programming Languages to Learn in 2022
Decorators with parameters in Python | [
{
"code": null,
"e": 24208,
"s": 24180,
"text": "\n14 Feb, 2020"
},
{
"code": null,
"e": 24729,
"s": 24208,
"text": "C99 is another name of ISO/IEC 9899:1999 standards specification for C that was adopted in 1999. This article mainly concentrates on the new features added in C99 by comparing with the C89 standard. In the development stage of the C99 standard, every element of the C language was re-examined, usage patterns were analyzed, and future demands were anticipated. C’s relationship with C++ provided a backdrop for the entire development process. The resulting C99 standard is a testimonial to the strengths of the original."
},
{
"code": null,
"e": 29847,
"s": 24729,
"text": "Keywords added in C99:inline: C99 adds the keyword inline which is applicable to functions. If we write inline datatype function_name (param) to any function it means that we are specifying the compiler to optimize calls to that function i.e. the function’s code will be expanded inline rather than called.Example:// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, maximum(x, y)); return 0;}Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword.The above program is equivalent to the following#include <stdio.h> int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, (x > y ? x : y)); return 0;}Output:Maximum of 5 and 10 is 10\nOutput:Maximum of 5 and 10 is 10\nInline functions help us to create efficient code by maintaining a structured, function-based approach.restrict: restrict is a type qualifier applicable only for pointers. A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Access to the object by another pointer can occur only if the second pointer is based on the first.We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program._Bool Datatype: _Bool datatype was added in C99 standard which stores 0 and 1 values. _Bool is an integer type.Note: bool keyword in C++ and _Bool in C are different._Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false._Complex: C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex:float _Complexdouble _Complexlong double _Complex_Imaginary: As said above, C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex and _Imaginary:float _Imaginarydouble _Imaginarylong double _ImaginaryIn the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros.Addition of Type Qualifiers: Another important aspect added in C99 is the introduction of long long and unsigned long long type modifiers. A long long int has a range of –(2^63 – 1) to +(2^63 –1). An Unsigned long long int has a minimal range starting from 0 to +(2^64 –1). This long long type allows 64-bit integers to support as a built-in type.Changes in Arrays: C99 added two important features to arrays:Variable Length Arrays: In C89 standard, the array size has to be specified using integer constants at the array declaration and array size is fixed at compile time. In C99 standard, we can declare an array whose dimensions are specified by any integer expressions whose values known at run-time. This is called Variable Length Arrays(VLA).Inclusion of Type Qualifiers: In C99, we can use the keyword static inside the square brackets during array declaration. This is only applied when array is declared in function parameters i.eExample:int fun1(char arr[static 80]){ // code}In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning.Example:#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf(\"%d \", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}Output:2 3 4 5 5 5 5 5 6 6\nSingle Line Comments: Single Line comments aren’t accepted in C89 standard. C99 standard introduces Single Line Comments which are used only when brief remarks are needed. These comments begin with // and runs to the end of the line.Eg:// First Commentint a; // another commentDeclaration of Identifiers:According to the C89 standard, all Identifiers should be declared at the start of the code block. If we need any other identifier at the middle, we can’t declare for that instance or time. We need to declare that at the start. C99 has changed this rule as we can declare identifiers whenever we need in a code.In simple, we can see this as:#include <stdio.h>int main(){ int i; i = 1; int j; // this declaration is invalid in C89 standard, but valid in C99 and C++ j = 3;}Output:\n"
},
{
"code": null,
"e": 32361,
"s": 29847,
"text": "Keywords added in C99:inline: C99 adds the keyword inline which is applicable to functions. If we write inline datatype function_name (param) to any function it means that we are specifying the compiler to optimize calls to that function i.e. the function’s code will be expanded inline rather than called.Example:// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, maximum(x, y)); return 0;}Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword.The above program is equivalent to the following#include <stdio.h> int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, (x > y ? x : y)); return 0;}Output:Maximum of 5 and 10 is 10\nOutput:Maximum of 5 and 10 is 10\nInline functions help us to create efficient code by maintaining a structured, function-based approach.restrict: restrict is a type qualifier applicable only for pointers. A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Access to the object by another pointer can occur only if the second pointer is based on the first.We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program._Bool Datatype: _Bool datatype was added in C99 standard which stores 0 and 1 values. _Bool is an integer type.Note: bool keyword in C++ and _Bool in C are different._Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false._Complex: C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex:float _Complexdouble _Complexlong double _Complex_Imaginary: As said above, C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex and _Imaginary:float _Imaginarydouble _Imaginarylong double _ImaginaryIn the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros."
},
{
"code": null,
"e": 33364,
"s": 32361,
"text": "inline: C99 adds the keyword inline which is applicable to functions. If we write inline datatype function_name (param) to any function it means that we are specifying the compiler to optimize calls to that function i.e. the function’s code will be expanded inline rather than called.Example:// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, maximum(x, y)); return 0;}Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword.The above program is equivalent to the following#include <stdio.h> int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, (x > y ? x : y)); return 0;}Output:Maximum of 5 and 10 is 10\nOutput:Maximum of 5 and 10 is 10\nInline functions help us to create efficient code by maintaining a structured, function-based approach."
},
{
"code": null,
"e": 33373,
"s": 33364,
"text": "Example:"
},
{
"code": "// C program to demonstrate inline keyword #include <stdio.h> inline int maximum(int a, int b){ return a > b ? a : b;} int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, maximum(x, y)); return 0;}",
"e": 33618,
"s": 33373,
"text": null
},
{
"code": null,
"e": 33727,
"s": 33618,
"text": "Note: Some Compilers show undefined reference to maximum(). This inline feature is used rarely as a keyword."
},
{
"code": null,
"e": 33776,
"s": 33727,
"text": "The above program is equivalent to the following"
},
{
"code": "#include <stdio.h> int main(){ int x = 5, y = 10; printf(\"Maximum of %d and %d is %d\", x, y, (x > y ? x : y)); return 0;}",
"e": 33918,
"s": 33776,
"text": null
},
{
"code": null,
"e": 33945,
"s": 33918,
"text": "Maximum of 5 and 10 is 10\n"
},
{
"code": null,
"e": 33972,
"s": 33945,
"text": "Maximum of 5 and 10 is 10\n"
},
{
"code": null,
"e": 34076,
"s": 33972,
"text": "Inline functions help us to create efficient code by maintaining a structured, function-based approach."
},
{
"code": null,
"e": 34545,
"s": 34076,
"text": "restrict: restrict is a type qualifier applicable only for pointers. A pointer qualified by restrict is initially the only means by which the object it points to can be accessed. Access to the object by another pointer can occur only if the second pointer is based on the first.We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program."
},
{
"code": null,
"e": 34736,
"s": 34545,
"text": "We use restrict qualifier to restrict access to the object. These are primarily used as function parameters or in malloc(). The restrict qualifier never changes the semantics of the program."
},
{
"code": null,
"e": 35020,
"s": 34736,
"text": "_Bool Datatype: _Bool datatype was added in C99 standard which stores 0 and 1 values. _Bool is an integer type.Note: bool keyword in C++ and _Bool in C are different._Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false."
},
{
"code": null,
"e": 35076,
"s": 35020,
"text": "Note: bool keyword in C++ and _Bool in C are different."
},
{
"code": null,
"e": 35194,
"s": 35076,
"text": "_Bool is used rarely instead C99 defines a new header file stdbool.h which defines three macros bool, true and false."
},
{
"code": null,
"e": 35448,
"s": 35194,
"text": "_Complex: C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex:float _Complexdouble _Complexlong double _Complex"
},
{
"code": null,
"e": 35475,
"s": 35448,
"text": "Types defined in _Complex:"
},
{
"code": null,
"e": 35490,
"s": 35475,
"text": "float _Complex"
},
{
"code": null,
"e": 35506,
"s": 35490,
"text": "double _Complex"
},
{
"code": null,
"e": 35527,
"s": 35506,
"text": "long double _Complex"
},
{
"code": null,
"e": 36013,
"s": 35527,
"text": "_Imaginary: As said above, C99 adds support for performing operations on complex numbers through _Complex and _Imaginary keywords. These keywords provide better support for numerical programming.Types defined in _Complex and _Imaginary:float _Imaginarydouble _Imaginarylong double _ImaginaryIn the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros."
},
{
"code": null,
"e": 36055,
"s": 36013,
"text": "Types defined in _Complex and _Imaginary:"
},
{
"code": null,
"e": 36072,
"s": 36055,
"text": "float _Imaginary"
},
{
"code": null,
"e": 36090,
"s": 36072,
"text": "double _Imaginary"
},
{
"code": null,
"e": 36113,
"s": 36090,
"text": "long double _Imaginary"
},
{
"code": null,
"e": 36308,
"s": 36113,
"text": "In the same way discussed in _Bool datatype, these _Complex and _Imaginary aren’t used frequently. Instead, we use the header-file which consists of in-built macros complex and imaginary macros."
},
{
"code": null,
"e": 36656,
"s": 36308,
"text": "Addition of Type Qualifiers: Another important aspect added in C99 is the introduction of long long and unsigned long long type modifiers. A long long int has a range of –(2^63 – 1) to +(2^63 –1). An Unsigned long long int has a minimal range starting from 0 to +(2^64 –1). This long long type allows 64-bit integers to support as a built-in type."
},
{
"code": null,
"e": 38119,
"s": 36656,
"text": "Changes in Arrays: C99 added two important features to arrays:Variable Length Arrays: In C89 standard, the array size has to be specified using integer constants at the array declaration and array size is fixed at compile time. In C99 standard, we can declare an array whose dimensions are specified by any integer expressions whose values known at run-time. This is called Variable Length Arrays(VLA).Inclusion of Type Qualifiers: In C99, we can use the keyword static inside the square brackets during array declaration. This is only applied when array is declared in function parameters i.eExample:int fun1(char arr[static 80]){ // code}In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning.Example:#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf(\"%d \", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}Output:2 3 4 5 5 5 5 5 6 6\n"
},
{
"code": null,
"e": 38460,
"s": 38119,
"text": "Variable Length Arrays: In C89 standard, the array size has to be specified using integer constants at the array declaration and array size is fixed at compile time. In C99 standard, we can declare an array whose dimensions are specified by any integer expressions whose values known at run-time. This is called Variable Length Arrays(VLA)."
},
{
"code": null,
"e": 39521,
"s": 38460,
"text": "Inclusion of Type Qualifiers: In C99, we can use the keyword static inside the square brackets during array declaration. This is only applied when array is declared in function parameters i.eExample:int fun1(char arr[static 80]){ // code}In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning.Example:#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf(\"%d \", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}Output:2 3 4 5 5 5 5 5 6 6\n"
},
{
"code": null,
"e": 39530,
"s": 39521,
"text": "Example:"
},
{
"code": "int fun1(char arr[static 80]){ // code}",
"e": 39573,
"s": 39530,
"text": null
},
{
"code": null,
"e": 40094,
"s": 39573,
"text": "In the above example arr is always a pointer to an 80-element array i.e arr is guaranteed to point the starting element of the array of chars that contains atleast 80 elements. We can also use the keywords restrict, volatile and const inside the square brackets if that array is declared inside a function parameters. Keyword restrict specifies that the pointer is the sole initial means of access to the object. const states that the pointer always points to the same object. volatile is allowed, but it has no meaning."
},
{
"code": null,
"e": 40103,
"s": 40094,
"text": "Example:"
},
{
"code": "#include <stdio.h>void fun(int a[static 10]){ for (int i = 0; i < 10; i++) { a[i] += 1; printf(\"%d \", a[i]); }} int main(){ int a[] = { 1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 6, 7, 8, 9, 10 }; fun(a);}",
"e": 40368,
"s": 40103,
"text": null
},
{
"code": null,
"e": 40389,
"s": 40368,
"text": "2 3 4 5 5 5 5 5 6 6\n"
},
{
"code": null,
"e": 40667,
"s": 40389,
"text": "Single Line Comments: Single Line comments aren’t accepted in C89 standard. C99 standard introduces Single Line Comments which are used only when brief remarks are needed. These comments begin with // and runs to the end of the line.Eg:// First Commentint a; // another comment"
},
{
"code": null,
"e": 40671,
"s": 40667,
"text": "Eg:"
},
{
"code": "// First Commentint a; // another comment",
"e": 40713,
"s": 40671,
"text": null
},
{
"code": null,
"e": 41232,
"s": 40713,
"text": "Declaration of Identifiers:According to the C89 standard, all Identifiers should be declared at the start of the code block. If we need any other identifier at the middle, we can’t declare for that instance or time. We need to declare that at the start. C99 has changed this rule as we can declare identifiers whenever we need in a code.In simple, we can see this as:#include <stdio.h>int main(){ int i; i = 1; int j; // this declaration is invalid in C89 standard, but valid in C99 and C++ j = 3;}Output:\n"
},
{
"code": null,
"e": 41263,
"s": 41232,
"text": "In simple, we can see this as:"
},
{
"code": "#include <stdio.h>int main(){ int i; i = 1; int j; // this declaration is invalid in C89 standard, but valid in C99 and C++ j = 3;}",
"e": 41407,
"s": 41263,
"text": null
},
{
"code": null,
"e": 41420,
"s": 41409,
"text": "C Language"
},
{
"code": null,
"e": 41441,
"s": 41420,
"text": "Programming Language"
},
{
"code": null,
"e": 41539,
"s": 41441,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41577,
"s": 41539,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 41597,
"s": 41577,
"text": "Multithreading in C"
},
{
"code": null,
"e": 41623,
"s": 41597,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 41645,
"s": 41623,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 41686,
"s": 41645,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 41727,
"s": 41686,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 41745,
"s": 41727,
"text": "Structures in C++"
},
{
"code": null,
"e": 41808,
"s": 41745,
"text": "Differences between Procedural and Object Oriented Programming"
},
{
"code": null,
"e": 41854,
"s": 41808,
"text": "Top 10 Programming Languages to Learn in 2022"
}
] |
java.time.Clock.tick() Method Example | The java.time.Clock.tick() method obtains a clock that returns instants from the specified clock truncated to the nearest occurrence of the specified duration.
Following is the declaration for java.time.Clock.tick() method.
public static Clock tick(Clock baseClock, Duration tickDuration)
baseClock − the base clock to add the duration to, not null.
baseClock − the base clock to add the duration to, not null.
tickDuration − the duration of each visible tick, not negative, not null.
tickDuration − the duration of each visible tick, not negative, not null.
a clock that ticks in whole units of the duration, not null.
IllegalArgumentException − if the duration is negative, or has a part smaller than a whole millisecond such that the whole duration is not divisible into one second.
IllegalArgumentException − if the duration is negative, or has a part smaller than a whole millisecond such that the whole duration is not divisible into one second.
ArithmeticException − if the duration is too large to be represented as nanos.
ArithmeticException − if the duration is too large to be represented as nanos.
The following example shows the usage of java.time.Clock.tick() method.
package com.tutorialspoint;
import java.time.Clock;
import java.time.Duration;
public class ClockDemo {
public static void main(String[] args) {
Clock clock = Clock.systemUTC();
Duration tickDuration = Duration.ofNanos(250000);
Clock clock1 = Clock.tick(clock, tickDuration);
System.out.println("Clock : " + clock.instant());
System.out.println("Clock1 : " + clock1.instant());
}
}
Let us compile and run the above program, this will produce the following result −
Clock : 2017-03-07T06:53:24.870Z
Clock1 : 2017-03-07T06:53:24.951Z
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2075,
"s": 1915,
"text": "The java.time.Clock.tick() method obtains a clock that returns instants from the specified clock truncated to the nearest occurrence of the specified duration."
},
{
"code": null,
"e": 2139,
"s": 2075,
"text": "Following is the declaration for java.time.Clock.tick() method."
},
{
"code": null,
"e": 2205,
"s": 2139,
"text": "public static Clock tick(Clock baseClock, Duration tickDuration)\n"
},
{
"code": null,
"e": 2266,
"s": 2205,
"text": "baseClock − the base clock to add the duration to, not null."
},
{
"code": null,
"e": 2327,
"s": 2266,
"text": "baseClock − the base clock to add the duration to, not null."
},
{
"code": null,
"e": 2401,
"s": 2327,
"text": "tickDuration − the duration of each visible tick, not negative, not null."
},
{
"code": null,
"e": 2475,
"s": 2401,
"text": "tickDuration − the duration of each visible tick, not negative, not null."
},
{
"code": null,
"e": 2536,
"s": 2475,
"text": "a clock that ticks in whole units of the duration, not null."
},
{
"code": null,
"e": 2702,
"s": 2536,
"text": "IllegalArgumentException − if the duration is negative, or has a part smaller than a whole millisecond such that the whole duration is not divisible into one second."
},
{
"code": null,
"e": 2868,
"s": 2702,
"text": "IllegalArgumentException − if the duration is negative, or has a part smaller than a whole millisecond such that the whole duration is not divisible into one second."
},
{
"code": null,
"e": 2947,
"s": 2868,
"text": "ArithmeticException − if the duration is too large to be represented as nanos."
},
{
"code": null,
"e": 3026,
"s": 2947,
"text": "ArithmeticException − if the duration is too large to be represented as nanos."
},
{
"code": null,
"e": 3098,
"s": 3026,
"text": "The following example shows the usage of java.time.Clock.tick() method."
},
{
"code": null,
"e": 3522,
"s": 3098,
"text": "package com.tutorialspoint;\n\nimport java.time.Clock;\nimport java.time.Duration;\n\npublic class ClockDemo {\n public static void main(String[] args) {\n\n Clock clock = Clock.systemUTC(); \n\n Duration tickDuration = Duration.ofNanos(250000);\n Clock clock1 = Clock.tick(clock, tickDuration);\n System.out.println(\"Clock : \" + clock.instant());\n System.out.println(\"Clock1 : \" + clock1.instant());\n }\n}"
},
{
"code": null,
"e": 3605,
"s": 3522,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3673,
"s": 3605,
"text": "Clock : 2017-03-07T06:53:24.870Z\nClock1 : 2017-03-07T06:53:24.951Z\n"
},
{
"code": null,
"e": 3680,
"s": 3673,
"text": " Print"
},
{
"code": null,
"e": 3691,
"s": 3680,
"text": " Add Notes"
}
] |
Bootstrap 4 .justify-content-*-end class | To justify the flex items on the end, use the justify-content-end class.
To justify the flex items on the end, on different screen sizes, use the justify-content-*-end class. The flex items justified at the end would be visible like the following on different screen sizes −
Small Screen Size
<div class="d-flex justify-content-sm-end bg-danger mb-5">
<div class="p-2 bg-primary">Alabama</div>
<div class="p-2 bg-info">New York</div>
<div class="p-2 bg-secondary">Texas</div>
</div>
Medium Screen Size
<div class="d-flex justify-content-md-end bg-danger mb-5">
<div class="p-2 bg-primary">Alabama</div>
<div class="p-2 bg-info">New York</div>
<div class="p-2 bg-secondary">Texas</div>
</div>
Let us see the complete code and learn how to work with justify-content-*-end class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container mt-3">
<h3>US</h3>
<div class="d-flex justify-content-sm-end bg-danger mb-5">
<div class="p-2 bg-primary">Alabama</div>
<div class="p-2 bg-info">New York</div>
<div class="p-2 bg-secondary">Texas</div>
</div>
<div class="d-flex justify-content-md-end bg-danger mb-5">
<div class="p-2 bg-primary">Alabama</div>
<div class="p-2 bg-info">New York</div>
<div class="p-2 bg-secondary">Texas</div>
</div>
<div class="d-flex justify-content-lg-end bg-danger mb-5">
<div class="p-2 bg-primary">Alabama</div>
<div class="p-2 bg-info">New York</div>
<div class="p-2 bg-secondary">Texas</div>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To justify the flex items on the end, use the justify-content-end class."
},
{
"code": null,
"e": 1337,
"s": 1135,
"text": "To justify the flex items on the end, on different screen sizes, use the justify-content-*-end class. The flex items justified at the end would be visible like the following on different screen sizes −"
},
{
"code": null,
"e": 1355,
"s": 1337,
"text": "Small Screen Size"
},
{
"code": null,
"e": 1551,
"s": 1355,
"text": "<div class=\"d-flex justify-content-sm-end bg-danger mb-5\">\n <div class=\"p-2 bg-primary\">Alabama</div>\n <div class=\"p-2 bg-info\">New York</div>\n <div class=\"p-2 bg-secondary\">Texas</div>\n</div>"
},
{
"code": null,
"e": 1570,
"s": 1551,
"text": "Medium Screen Size"
},
{
"code": null,
"e": 1766,
"s": 1570,
"text": "<div class=\"d-flex justify-content-md-end bg-danger mb-5\">\n <div class=\"p-2 bg-primary\">Alabama</div>\n <div class=\"p-2 bg-info\">New York</div>\n <div class=\"p-2 bg-secondary\">Texas</div>\n</div>"
},
{
"code": null,
"e": 1852,
"s": 1766,
"text": "Let us see the complete code and learn how to work with justify-content-*-end class −"
},
{
"code": null,
"e": 1862,
"s": 1852,
"text": "Live Demo"
},
{
"code": null,
"e": 3105,
"s": 1862,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n <div class=\"container mt-3\">\n <h3>US</h3>\n <div class=\"d-flex justify-content-sm-end bg-danger mb-5\">\n <div class=\"p-2 bg-primary\">Alabama</div>\n <div class=\"p-2 bg-info\">New York</div>\n <div class=\"p-2 bg-secondary\">Texas</div>\n </div>\n <div class=\"d-flex justify-content-md-end bg-danger mb-5\">\n <div class=\"p-2 bg-primary\">Alabama</div>\n <div class=\"p-2 bg-info\">New York</div>\n <div class=\"p-2 bg-secondary\">Texas</div>\n </div>\n <div class=\"d-flex justify-content-lg-end bg-danger mb-5\">\n <div class=\"p-2 bg-primary\">Alabama</div>\n <div class=\"p-2 bg-info\">New York</div>\n <div class=\"p-2 bg-secondary\">Texas</div>\n </div>\n </div>\n</body>\n</html>"
}
] |
Get Day Number of Week in Java | To get the day of the week, use Calendar.DAY_OF_WEEK.
Firstly, declare a calendar object and get the current date and time.
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime().toString());
Now, fetch the day of the week in an integer variable.
int day = calendar.get(Calendar.DAY_OF_WEEK);
The following is the final example.
Live Demo
import java.util.Calendar;
public class Demo {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime().toString());
int day = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println("Day: " + day);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
System.out.println("Hour: " + hour);
int minute = calendar.get(Calendar.MINUTE);
System.out.println("Minute: " + minute);
}
}
Mon Nov 19 10:11:41 UTC 2018
Day: 2
Hour: 10
Minute: 11 | [
{
"code": null,
"e": 1116,
"s": 1062,
"text": "To get the day of the week, use Calendar.DAY_OF_WEEK."
},
{
"code": null,
"e": 1186,
"s": 1116,
"text": "Firstly, declare a calendar object and get the current date and time."
},
{
"code": null,
"e": 1281,
"s": 1186,
"text": "Calendar calendar = Calendar.getInstance();\nSystem.out.println(calendar.getTime().toString());"
},
{
"code": null,
"e": 1336,
"s": 1281,
"text": "Now, fetch the day of the week in an integer variable."
},
{
"code": null,
"e": 1382,
"s": 1336,
"text": "int day = calendar.get(Calendar.DAY_OF_WEEK);"
},
{
"code": null,
"e": 1418,
"s": 1382,
"text": "The following is the final example."
},
{
"code": null,
"e": 1429,
"s": 1418,
"text": " Live Demo"
},
{
"code": null,
"e": 1920,
"s": 1429,
"text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n System.out.println(calendar.getTime().toString());\n int day = calendar.get(Calendar.DAY_OF_WEEK);\n System.out.println(\"Day: \" + day);\n int hour = calendar.get(Calendar.HOUR_OF_DAY);\n System.out.println(\"Hour: \" + hour);\n int minute = calendar.get(Calendar.MINUTE);\n System.out.println(\"Minute: \" + minute);\n }\n}"
},
{
"code": null,
"e": 1976,
"s": 1920,
"text": "Mon Nov 19 10:11:41 UTC 2018\nDay: 2\nHour: 10\nMinute: 11"
}
] |
Bridge edge in a graph | Practice | GeeksforGeeks | Given a Graph of V vertices and E edges and another edge(c - d), the task is to find if the given edge is a Bridge. i.e., removing the edge disconnects the graph.
Example 1:
Input:
c = 1, d = 2
Output:
1
Explanation:
From the graph, we can clearly see that
blocking the edge 1-2 will result in
disconnection of the graph. So, it is
a Bridge and thus the Output 1.
Example 2:
Input:
c = 0, d = 2
Output:
0
Explanation:
blocking the edge between nodes 0 and 2
won't affect the connectivity of the graph.
So, it's not a Bridge Edge. All the Bridge
Edges in the graph are marked with a blue
line in the above image.
Your Task:
You don't need to read input or print anything. Your task is to complete the function isBridge() which takes number of vertices V, the number of edges E, an adjacency lsit adj and two integers c and d denoting the edge as input parameters and returns 1 if the given edge c-d is a Bridge. Else, it returns 0.
Expected Time Complexity: O(V + E).
Expected Auxiliary Space: O(V).
Constraints:
1 ≤ V,E ≤ 105
0 ≤ c, d ≤ V-1
0
amishasahu3286 days ago
void dfs(int node, vector<int> adj[], int c, int d, vector<int> &visited){
visited[node] = 1;
for(auto it: adj[node]){
if(!visited[it] && (node != c || it != d))
dfs(it, adj, c, d, visited);
}
}
int isBridge(int V, vector<int> adj[], int c, int d)
{
// Code here
vector<int> visited(V, 0);
dfs(c, adj, c, d, visited);
// if d visited i.e it can be reached with some other path as well apart from throught c
// hence, it can't be bridges
return !visited[d];
}
0
sharadyaduvanshi2 weeks ago
void dfs(vector<int>adj[],int v,int index,vector<bool>&visited) { if(visited[index] == true) return ; visited[index] = true; for(int i = 0; i < adj[index].size(); i ++) { if(visited[adj[index][i]] != true) dfs(adj,v,adj[index][i],visited); } } int isBridge(int v, vector<int> adj[], int c, int d) { vector<int>::iterator position1 = find(adj[c].begin(), adj[c].end(), d);if (position1 != adj[c].end()) // == adj[c].end() means the element was not found adj[c].erase(position1); vector<int>::iterator position2 = find(adj[d].begin(), adj[d].end(), c);if (position2 != adj[d].end()) // == adj[d.end() means the element was not found adj[d].erase(position2); vector<bool>visited(v+1,false); dfs(adj,v,c,visited); if(visited[d] == true) return 0; return 1; }
+2
madhukartemba1 month ago
JAVA SOLUTION USING PLAIN DFS:
class Solution
{
private static void dfs(int node, boolean visited[], ArrayList<ArrayList<Integer>> adj)
{
visited[node] = true;
for(int x : adj.get(node))
{
if(visited[x]==false)
{
dfs(x, visited, adj);
}
}
}
//Function to find if the given edge is a bridge in graph.
static int isBridge(int V, ArrayList<ArrayList<Integer>> adj, int c, int d)
{
boolean visited[] = new boolean[V];
adj.get(c).remove(new Integer(d));
adj.get(d).remove(new Integer(c));
dfs(c, visited, adj);
if(visited[d]==true) return 0;
return 1;
}
}
0
shivkatoch5632 months ago
c++ BFS easy
dfs(int x,vector<int>adj[],int c,int d,vector<int>&vis){
vis[x]=1;
for(auto it:adj[x]){
if(!vis[it] && (x!=c || it!=d))dfs(it,adj,c,d,vis);
}
return 0;
}
int isBridge(int v, vector<int> adj[], int c, int d)
{
vector<int>vis(v,0);
dfs(c,adj,c,d,vis);
return !vis[d];
}
Read Less
+2
kronizerdeltac2 months ago
JAVA SOLUTION:
static void dfs(ArrayList<ArrayList<Integer>> graph, int src, boolean[] vis) {
vis[src] = true;
for(int e : graph.get(src)) {
if(!vis[e])
dfs(graph, e, vis);
}
}
static int findEdge(ArrayList<ArrayList<Integer>> graph, int u, int v) {
for(int i = 0; i < graph.get(u).size(); i++) {
int e = graph.get(u).get(i);
if (e == v)
return i;
}
return -1;
}
static int isBridge(int V, ArrayList<ArrayList<Integer>> graph,int c,int d)
{
int initialComponent = 0;
boolean[] vis = new boolean[V];
for(int i = 0; i < V; i++) {
if(!vis[i]) {
initialComponent++;
dfs(graph, i, vis);
}
}
//removeEdge(graph, u, v);
int idx1 = findEdge(graph, c, d);
graph.get(c).remove(idx1);
int idx2 = findEdge(graph, d, c);
graph.get(d).remove(idx2);
int finalComponent = 0;
vis = new boolean[V];
for(int i = 0; i < V; i++) {
if(!vis[i]) {
finalComponent++;
dfs(graph, i, vis);
}
}
return initialComponent != finalComponent ? 1 : 0;
}
0
avenvy2 months ago
PYTHON SOLUTION
def isBridge(self, V, adj, c, d):
# code here
def dfs(node,adj,vis):
vis[node]=1
for j in adj[node]:
if vis[j]==0:
dfs(j,adj,vis)
vis1=[0]*V
initial=0
for i in range(V):
if vis1[i]==0:
initial+=1
dfs(i,adj,vis1)
vis2=[0]*V
if d in adj[c]:
adj[c].remove(d)
if c in adj[d]:
adj[d].remove(c)
final=0
for i in range(V):
if vis2[i]==0:
final+=1
dfs(i,adj,vis2)
if initial==final:
return 0
else:
return 1
0
ac_7
This comment was deleted.
0
soumo2k153 months ago
DFS
int dfs(int x,vector<int>adj[],int c,int d,vector<int>&vis){ vis[x]=1; for(auto it:adj[x]){ if(!vis[it] && (x!=c || it!=d))dfs(it,adj,c,d,vis); } return 0; } int isBridge(int v, vector<int> adj[], int c, int d) { vector<int>vis(v,0); dfs(c,adj,c,d,vis); return !vis[d]; }
0
mufaddalshakir553 months ago
C++ Beast BFS
int isBridge(int V, vector<int> adj[], int c, int d)
{
vector<int> vis(V,-1);
queue<int> q;
q.push(c);
vis[c] = 1;
int count = 0;
while(!q.empty()){
int u = q.front();
q.pop();
for(auto elem : adj[u]){
if(elem == d){
count++;
if(count>1) return 0;
continue;
}
else if(vis[elem] == -1){
q.push(elem);
vis[elem] = 1;
}
}
}
return 1;
}
0
sagittarius3 months ago
void bfs(vector<int> adj[],bool visited[],int V,int src){ visited[src]=true; queue<int> q; q.push(src); while(!q.empty()){ int node = q.front(); q.pop(); for(int i=0;i<adj[node].size();i++){ if(visited[adj[node][i]]==false){ visited[adj[node][i]]=true; q.push(adj[node][i]); } } } } int isBridge(int V, vector<int> adj[], int c, int d) { // Code here bool visited[V]; memset(visited,false,sizeof(visited)); int count1 = 0; int count2 = 0; for(int i=0;i<V;i++){ if(visited[i]==false){ count1++; bfs(adj,visited,V,i); } } vector<int>::iterator it = find(adj[c].begin(),adj[c].end(),d); adj[c].erase(it); it = find(adj[d].begin(),adj[d].end(),c); adj[d].erase(it); memset(visited,false,sizeof(visited)); for(int i=0;i<V;i++){ if(visited[i]==false){ count2++; bfs(adj,visited,V,i); } } if(count1==count2)return 0; return 1; }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 389,
"s": 226,
"text": "Given a Graph of V vertices and E edges and another edge(c - d), the task is to find if the given edge is a Bridge. i.e., removing the edge disconnects the graph."
},
{
"code": null,
"e": 402,
"s": 391,
"text": "Example 1:"
},
{
"code": null,
"e": 597,
"s": 402,
"text": "Input:\n\nc = 1, d = 2\nOutput:\n1\nExplanation:\nFrom the graph, we can clearly see that\nblocking the edge 1-2 will result in \ndisconnection of the graph. So, it is \na Bridge and thus the Output 1.\n\n"
},
{
"code": null,
"e": 608,
"s": 597,
"text": "Example 2:"
},
{
"code": null,
"e": 848,
"s": 608,
"text": "Input:\n\nc = 0, d = 2\nOutput:\n0\nExplanation:\n\nblocking the edge between nodes 0 and 2\nwon't affect the connectivity of the graph.\nSo, it's not a Bridge Edge. All the Bridge\nEdges in the graph are marked with a blue\nline in the above image.\n"
},
{
"code": null,
"e": 1170,
"s": 850,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function isBridge() which takes number of vertices V, the number of edges E, an adjacency lsit adj and two integers c and d denoting the edge as input parameters and returns 1 if the given edge c-d is a Bridge. Else, it returns 0."
},
{
"code": null,
"e": 1240,
"s": 1172,
"text": "Expected Time Complexity: O(V + E).\nExpected Auxiliary Space: O(V)."
},
{
"code": null,
"e": 1292,
"s": 1242,
"text": "Constraints:\n1 ≤ V,E ≤ 105\n0 ≤ c, d ≤ V-1"
},
{
"code": null,
"e": 1294,
"s": 1292,
"text": "0"
},
{
"code": null,
"e": 1318,
"s": 1294,
"text": "amishasahu3286 days ago"
},
{
"code": null,
"e": 1895,
"s": 1318,
"text": "void dfs(int node, vector<int> adj[], int c, int d, vector<int> &visited){\n visited[node] = 1;\n for(auto it: adj[node]){\n if(!visited[it] && (node != c || it != d))\n dfs(it, adj, c, d, visited);\n }\n }\n int isBridge(int V, vector<int> adj[], int c, int d) \n {\n // Code here\n vector<int> visited(V, 0);\n dfs(c, adj, c, d, visited);\n // if d visited i.e it can be reached with some other path as well apart from throught c\n // hence, it can't be bridges\n return !visited[d];\n }"
},
{
"code": null,
"e": 1897,
"s": 1895,
"text": "0"
},
{
"code": null,
"e": 1925,
"s": 1897,
"text": "sharadyaduvanshi2 weeks ago"
},
{
"code": null,
"e": 2830,
"s": 1925,
"text": " void dfs(vector<int>adj[],int v,int index,vector<bool>&visited) { if(visited[index] == true) return ; visited[index] = true; for(int i = 0; i < adj[index].size(); i ++) { if(visited[adj[index][i]] != true) dfs(adj,v,adj[index][i],visited); } } int isBridge(int v, vector<int> adj[], int c, int d) { vector<int>::iterator position1 = find(adj[c].begin(), adj[c].end(), d);if (position1 != adj[c].end()) // == adj[c].end() means the element was not found adj[c].erase(position1); vector<int>::iterator position2 = find(adj[d].begin(), adj[d].end(), c);if (position2 != adj[d].end()) // == adj[d.end() means the element was not found adj[d].erase(position2); vector<bool>visited(v+1,false); dfs(adj,v,c,visited); if(visited[d] == true) return 0; return 1; }"
},
{
"code": null,
"e": 2833,
"s": 2830,
"text": "+2"
},
{
"code": null,
"e": 2858,
"s": 2833,
"text": "madhukartemba1 month ago"
},
{
"code": null,
"e": 2889,
"s": 2858,
"text": "JAVA SOLUTION USING PLAIN DFS:"
},
{
"code": null,
"e": 3675,
"s": 2889,
"text": "class Solution\n{\n \n private static void dfs(int node, boolean visited[], ArrayList<ArrayList<Integer>> adj)\n {\n visited[node] = true;\n for(int x : adj.get(node))\n {\n if(visited[x]==false)\n {\n dfs(x, visited, adj);\n }\n }\n }\n \n \n \n \n //Function to find if the given edge is a bridge in graph.\n static int isBridge(int V, ArrayList<ArrayList<Integer>> adj, int c, int d)\n {\n \n boolean visited[] = new boolean[V];\n \n \n adj.get(c).remove(new Integer(d));\n adj.get(d).remove(new Integer(c));\n \n dfs(c, visited, adj);\n \n \n if(visited[d]==true) return 0;\n \n return 1;\n \n \n }\n}"
},
{
"code": null,
"e": 3677,
"s": 3675,
"text": "0"
},
{
"code": null,
"e": 3703,
"s": 3677,
"text": "shivkatoch5632 months ago"
},
{
"code": null,
"e": 3716,
"s": 3703,
"text": "c++ BFS easy"
},
{
"code": null,
"e": 4059,
"s": 3718,
"text": "dfs(int x,vector<int>adj[],int c,int d,vector<int>&vis){\n vis[x]=1;\n for(auto it:adj[x]){\n if(!vis[it] && (x!=c || it!=d))dfs(it,adj,c,d,vis);\n }\n return 0;\n }\n int isBridge(int v, vector<int> adj[], int c, int d) \n {\n vector<int>vis(v,0);\n dfs(c,adj,c,d,vis);\n return !vis[d];\n }"
},
{
"code": null,
"e": 4069,
"s": 4059,
"text": "Read Less"
},
{
"code": null,
"e": 4074,
"s": 4071,
"text": "+2"
},
{
"code": null,
"e": 4101,
"s": 4074,
"text": "kronizerdeltac2 months ago"
},
{
"code": null,
"e": 4116,
"s": 4101,
"text": "JAVA SOLUTION:"
},
{
"code": null,
"e": 5440,
"s": 4118,
"text": "static void dfs(ArrayList<ArrayList<Integer>> graph, int src, boolean[] vis) {\n vis[src] = true;\n for(int e : graph.get(src)) {\n if(!vis[e])\n dfs(graph, e, vis);\n }\n }\n static int findEdge(ArrayList<ArrayList<Integer>> graph, int u, int v) {\n for(int i = 0; i < graph.get(u).size(); i++) {\n int e = graph.get(u).get(i);\n if (e == v)\n return i;\n }\n return -1;\n }\n static int isBridge(int V, ArrayList<ArrayList<Integer>> graph,int c,int d)\n {\n int initialComponent = 0;\n boolean[] vis = new boolean[V];\n \n for(int i = 0; i < V; i++) {\n if(!vis[i]) {\n initialComponent++;\n dfs(graph, i, vis);\n }\n }\n \n //removeEdge(graph, u, v);\n int idx1 = findEdge(graph, c, d);\n graph.get(c).remove(idx1);\n int idx2 = findEdge(graph, d, c);\n graph.get(d).remove(idx2);\n \n int finalComponent = 0;\n \n vis = new boolean[V];\n \n for(int i = 0; i < V; i++) {\n if(!vis[i]) {\n finalComponent++;\n dfs(graph, i, vis);\n }\n }\n \n return initialComponent != finalComponent ? 1 : 0;\n }"
},
{
"code": null,
"e": 5442,
"s": 5440,
"text": "0"
},
{
"code": null,
"e": 5461,
"s": 5442,
"text": "avenvy2 months ago"
},
{
"code": null,
"e": 5477,
"s": 5461,
"text": "PYTHON SOLUTION"
},
{
"code": null,
"e": 6180,
"s": 5477,
"text": "def isBridge(self, V, adj, c, d):\n # code here\n def dfs(node,adj,vis):\n vis[node]=1\n for j in adj[node]:\n if vis[j]==0:\n dfs(j,adj,vis)\n vis1=[0]*V \n initial=0\n for i in range(V):\n if vis1[i]==0:\n initial+=1\n dfs(i,adj,vis1)\n \n vis2=[0]*V\n if d in adj[c]:\n adj[c].remove(d)\n if c in adj[d]:\n adj[d].remove(c)\n final=0\n for i in range(V):\n if vis2[i]==0:\n final+=1\n dfs(i,adj,vis2)\n if initial==final:\n return 0\n else:\n return 1"
},
{
"code": null,
"e": 6182,
"s": 6180,
"text": "0"
},
{
"code": null,
"e": 6187,
"s": 6182,
"text": "ac_7"
},
{
"code": null,
"e": 6213,
"s": 6187,
"text": "This comment was deleted."
},
{
"code": null,
"e": 6215,
"s": 6213,
"text": "0"
},
{
"code": null,
"e": 6237,
"s": 6215,
"text": "soumo2k153 months ago"
},
{
"code": null,
"e": 6241,
"s": 6237,
"text": "DFS"
},
{
"code": null,
"e": 6574,
"s": 6241,
"text": "int dfs(int x,vector<int>adj[],int c,int d,vector<int>&vis){ vis[x]=1; for(auto it:adj[x]){ if(!vis[it] && (x!=c || it!=d))dfs(it,adj,c,d,vis); } return 0; } int isBridge(int v, vector<int> adj[], int c, int d) { vector<int>vis(v,0); dfs(c,adj,c,d,vis); return !vis[d]; }"
},
{
"code": null,
"e": 6576,
"s": 6574,
"text": "0"
},
{
"code": null,
"e": 6605,
"s": 6576,
"text": "mufaddalshakir553 months ago"
},
{
"code": null,
"e": 6619,
"s": 6605,
"text": "C++ Beast BFS"
},
{
"code": null,
"e": 7250,
"s": 6619,
"text": " int isBridge(int V, vector<int> adj[], int c, int d) \n {\n vector<int> vis(V,-1);\n queue<int> q;\n q.push(c);\n vis[c] = 1;\n int count = 0;\n while(!q.empty()){\n int u = q.front();\n q.pop();\n for(auto elem : adj[u]){\n if(elem == d){\n count++;\n if(count>1) return 0;\n continue;\n }\n else if(vis[elem] == -1){\n q.push(elem);\n vis[elem] = 1;\n }\n }\n }\n \n return 1;\n }"
},
{
"code": null,
"e": 7252,
"s": 7250,
"text": "0"
},
{
"code": null,
"e": 7276,
"s": 7252,
"text": "sagittarius3 months ago"
},
{
"code": null,
"e": 8488,
"s": 7276,
"text": "void bfs(vector<int> adj[],bool visited[],int V,int src){ visited[src]=true; queue<int> q; q.push(src); while(!q.empty()){ int node = q.front(); q.pop(); for(int i=0;i<adj[node].size();i++){ if(visited[adj[node][i]]==false){ visited[adj[node][i]]=true; q.push(adj[node][i]); } } } } int isBridge(int V, vector<int> adj[], int c, int d) { // Code here bool visited[V]; memset(visited,false,sizeof(visited)); int count1 = 0; int count2 = 0; for(int i=0;i<V;i++){ if(visited[i]==false){ count1++; bfs(adj,visited,V,i); } } vector<int>::iterator it = find(adj[c].begin(),adj[c].end(),d); adj[c].erase(it); it = find(adj[d].begin(),adj[d].end(),c); adj[d].erase(it); memset(visited,false,sizeof(visited)); for(int i=0;i<V;i++){ if(visited[i]==false){ count2++; bfs(adj,visited,V,i); } } if(count1==count2)return 0; return 1; }"
},
{
"code": null,
"e": 8634,
"s": 8488,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 8670,
"s": 8634,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8680,
"s": 8670,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8690,
"s": 8680,
"text": "\nContest\n"
},
{
"code": null,
"e": 8753,
"s": 8690,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8901,
"s": 8753,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9109,
"s": 8901,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 9215,
"s": 9109,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Functional Programming with Java - Functions | A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again.
Functional Programming revolves around first class functions, pure functions and high order functions.
A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.
A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable.
A High Order Function is the one which can take a function as an argument and/or can return a function.
A High Order Function is the one which can take a function as an argument and/or can return a function.
A Pure Function is the one which has no side effect while its execution.
A Pure Function is the one which has no side effect while its execution.
A first class function can be treated as a variable. That means it can be passed as a parameter to a function, it can be returned by a function or can be assigned to a variable as well. Java supports first class function using lambda expression. A lambda expression is analogous to an anonymous function. See the example below −
public class FunctionTester {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
SquareMaker squareMaker = item -> item * item;
for(int i = 0; i < array.length; i++){
System.out.println(squareMaker.square(array[i]));
}
}
}
interface SquareMaker {
int square(int item);
}
1
4
9
16
25
Here we have created the implementation of square function using a lambda expression and assigned it to variable squareMaker.
A high order function either takes a function as a parameter or returns a function. In Java, we can pass or return a lambda expression to achieve such functionality.
import java.util.function.Function;
public class FunctionTester {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
Function<Integer, Integer> square = t -> t * t;
Function<Integer, Integer> cube = t -> t * t * t;
for(int i = 0; i < array.length; i++){
print(square, array[i]);
}
for(int i = 0; i < array.length; i++){
print(cube, array[i]);
}
}
private static <T, R> void print(Function<T, R> function, T t ) {
System.out.println(function.apply(t));
}
}
1
4
9
16
25
1
8
27
64
125
A pure function does not modify any global variable or modify any reference passed as a parameter to it. So it has no side-effect. It always returns the same value when invoked with same parameters. Such functions are very useful and are thread safe. In example below, sum is a pure function.
public class FunctionTester {
public static void main(String[] args) {
int a, b;
a = 1;
b = 2;
System.out.println(sum(a, b));
}
private static int sum(int a, int b){
return a + b;
}
}
3
32 Lectures
3.5 hours
Pavan Lalwani
11 Lectures
1 hours
Prof. Paul Cline, Ed.D
72 Lectures
10.5 hours
Arun Ammasai
51 Lectures
2 hours
Skillbakerystudios
43 Lectures
4 hours
Mohammad Nauman
8 Lectures
1 hours
Santharam Sivalenka
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2392,
"s": 2089,
"text": "A function is a block of statements that performs a specific task. Functions accept data, process it, and return a result. Functions are written primarily to support the concept of re usability. Once a function is written, it can be called easily, without having to write the same code again and again."
},
{
"code": null,
"e": 2495,
"s": 2392,
"text": "Functional Programming revolves around first class functions, pure functions and high order functions."
},
{
"code": null,
"e": 2658,
"s": 2495,
"text": "A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable."
},
{
"code": null,
"e": 2821,
"s": 2658,
"text": "A First Class Function is the one that uses first class entities like String, numbers which can be passed as arguments, can be returned or assigned to a variable."
},
{
"code": null,
"e": 2925,
"s": 2821,
"text": "A High Order Function is the one which can take a function as an argument and/or can return a function."
},
{
"code": null,
"e": 3029,
"s": 2925,
"text": "A High Order Function is the one which can take a function as an argument and/or can return a function."
},
{
"code": null,
"e": 3102,
"s": 3029,
"text": "A Pure Function is the one which has no side effect while its execution."
},
{
"code": null,
"e": 3175,
"s": 3102,
"text": "A Pure Function is the one which has no side effect while its execution."
},
{
"code": null,
"e": 3504,
"s": 3175,
"text": "A first class function can be treated as a variable. That means it can be passed as a parameter to a function, it can be returned by a function or can be assigned to a variable as well. Java supports first class function using lambda expression. A lambda expression is analogous to an anonymous function. See the example below −"
},
{
"code": null,
"e": 3838,
"s": 3504,
"text": "public class FunctionTester {\n public static void main(String[] args) {\n int[] array = {1, 2, 3, 4, 5};\n SquareMaker squareMaker = item -> item * item;\n for(int i = 0; i < array.length; i++){\n System.out.println(squareMaker.square(array[i]));\n }\n }\n}\ninterface SquareMaker {\n int square(int item);\n}"
},
{
"code": null,
"e": 3851,
"s": 3838,
"text": "1\n4\n9\n16\n25\n"
},
{
"code": null,
"e": 3977,
"s": 3851,
"text": "Here we have created the implementation of square function using a lambda expression and assigned it to variable squareMaker."
},
{
"code": null,
"e": 4143,
"s": 3977,
"text": "A high order function either takes a function as a parameter or returns a function. In Java, we can pass or return a lambda expression to achieve such functionality."
},
{
"code": null,
"e": 4718,
"s": 4143,
"text": "import java.util.function.Function;\n\npublic class FunctionTester {\n public static void main(String[] args) {\n int[] array = {1, 2, 3, 4, 5};\n\n Function<Integer, Integer> square = t -> t * t; \n Function<Integer, Integer> cube = t -> t * t * t;\n\n for(int i = 0; i < array.length; i++){\n print(square, array[i]);\n } \n for(int i = 0; i < array.length; i++){\n print(cube, array[i]);\n }\n }\n\n private static <T, R> void print(Function<T, R> function, T t ) {\n System.out.println(function.apply(t));\n }\n}"
},
{
"code": null,
"e": 4745,
"s": 4718,
"text": "1\n4\n9\n16\n25\n1\n8\n27\n64\n125\n"
},
{
"code": null,
"e": 5038,
"s": 4745,
"text": "A pure function does not modify any global variable or modify any reference passed as a parameter to it. So it has no side-effect. It always returns the same value when invoked with same parameters. Such functions are very useful and are thread safe. In example below, sum is a pure function."
},
{
"code": null,
"e": 5265,
"s": 5038,
"text": "public class FunctionTester {\n public static void main(String[] args) {\n int a, b;\n a = 1;\n b = 2;\n System.out.println(sum(a, b));\n }\n\n private static int sum(int a, int b){\n return a + b;\n }\n}"
},
{
"code": null,
"e": 5268,
"s": 5265,
"text": "3\n"
},
{
"code": null,
"e": 5303,
"s": 5268,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5318,
"s": 5303,
"text": " Pavan Lalwani"
},
{
"code": null,
"e": 5351,
"s": 5318,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5375,
"s": 5351,
"text": " Prof. Paul Cline, Ed.D"
},
{
"code": null,
"e": 5411,
"s": 5375,
"text": "\n 72 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 5425,
"s": 5411,
"text": " Arun Ammasai"
},
{
"code": null,
"e": 5458,
"s": 5425,
"text": "\n 51 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5478,
"s": 5458,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5511,
"s": 5478,
"text": "\n 43 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5528,
"s": 5511,
"text": " Mohammad Nauman"
},
{
"code": null,
"e": 5560,
"s": 5528,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5581,
"s": 5560,
"text": " Santharam Sivalenka"
},
{
"code": null,
"e": 5588,
"s": 5581,
"text": " Print"
},
{
"code": null,
"e": 5599,
"s": 5588,
"text": " Add Notes"
}
] |
Understanding data. Musings on information, memory... | by Cassie Kozyrkov | Towards Data Science | 2.9K plays2.9K
Everything our senses perceive is data, though its storage in our cranial wet stuff leaves something to be desired. Writing it down is a bit more reliable, especially when we write it down on a computer. When those notes are well-organized, we call them data... though I’ve seen some awfully messy electronic scribbles get the same name. I’m not sure why some people pronounce the word data like it has a capital D in it.
Why do we pronounce data with a capital D?
We need to learn to be irreverently pragmatic about data, so this is an article to help beginners see behind the curtain and to help practitioners explain the basics to newcomers who show symptoms of data-worship.
If you start your journey by shopping for datasets online, you’re in danger of forgetting where they come form. I’m going to start from absolute scratch to show you that you can make data anytime, anywhere.
Here are some perennial denizens of my larder, arranged on my floor.
This photograph is data — it’s stored as information that your device uses to show you pretty colors. (If you’re curious to know what images look like when you can see the matrix, glance at my intro to supervised learning.)
Let’s make some sense out of what we’re looking at. We have infinite options about what to pay attention to and remember. Here’s something I see when I look at the foodstuffs.
If you close your eyes, do you remember every detail of what you just saw? No? Me neither. That’s pretty much the reason we collect data. If we could remember and process it flawlessly in our heads, there’d be no need. The internet could be one hermit in a cave, recounting all the tweets of humankind and perfectly rendering each of our billions of cat photos.
Because human memory is a leaky bucket, it would be an improvement to jot the information down the way we used to when I went to school for statistics, back in the dark ages. That’s right, my friends, I still have paper around here somewhere! Let’s write down these 27 data points.
What’s great about this version — relative to what’s in my hippocampus or on my floor — is that it’s more durable and reliable.
Human memory is a leaky bucket.
We take the memory revolution for granted since it started millenia ago with merchants needing a reliable record of who sold whom how many bushels of what. Take a moment to realize how glorious it is to have a universal system of writing that stores numbers better than our brains do. When we record data, we produce an unfaithful corruption of our richly perceived realities, but after that we can transfer uncorrupted copies of the result to other members of our species with perfect fidelity. Writing is amazing! Little bits of mind and memory that get to live outside our bodies.
When we analyze data, we’re accessing someone else’s memories.
Worried about machines outperforming our brains? Even paper can do that! These 27 little numbers are a big lift for your brain to store, but durability is guaranteed if you have a writing implement at hand.
While this is a durability win, working with paper is annoying. For example, what if a whim strikes me to rearrange them from biggest to smallest? Abracadabra, paper, show me a better order! No? Darn.
You know what’s awesome about software? The abracadabra actually works! So let’s upgrade from paper to a computer.
Spreadsheets leave me lukewarm. They’re very limited compared with modern data science tools. I prefer to oscillate between R and Python, so let’s give R a whirl this time around. You can follow along in your browser with Jupyter: click on the “with R” box, then hit the scissors icon a few times until everything is deleted. Congrats, it took 5 seconds and you’re all set to paste in my code snippets and run [Shift+Enter] them.
weight <- c(50, 946, 454, 454, 110, 100, 340, 454, 200, 148, 355, 907, 454, 822, 127, 750, 255, 500, 500, 500, 8, 125, 284, 118, 227, 148, 125)weight <- weight[order(weight, decreasing = TRUE)]print(weight)
What you’ll notice is that R’s abracadabra for sorting your data is not obvious if you’re new around here.
Well, that’s true of the word “abracadabra” itself and also true of the menus in spreadsheet software. You only know those things because you were exposed to them, not because they’re universal laws. To get things done with a computer, you need to ask your resident soothsayer for the magic words/gestures and then practice using them. My favorite sage is called The Internet and knows all the things.
To accelerate your wizard training, don’t just paste the magic words — try altering them and see what happens. For example, what changes if you turn TRUE into FALSE in the snippet above?
Isn’t it amazing how quickly you get the answer? One reason I love programming is that it’s a cross between magic spells and LEGO.
If you’ve ever wished you could do magic, just learn to write code.
Here’s programming in a nutshell: ask the internet how to do something, take the magic words you just learned, see what happens when you adjust them, then put them together like LEGO blocks to do your bidding.
The trouble with these 27 numbers is that even if they’re sorted, they don’t mean much to us. As we read them, we forget what we just read a second ago. That’s human brains for you; tell us to read a sorted list of a million numbers and at best we’ll remember the last few. We need a quick way to sort and summarize so we can get a handle on what we’re looking at.
That’s what analytics is for!
median(weight)
With the right incantation, we can instantly know what the median weight is. (Median means “middle thing.”)
Turns out the answer is 284g. Who doesn’t love instant gratification? There are all kinds of summary options: min(), max(), mean(), median(), mode(), variance()... try them all! Or try this single magic word to find out what happens.
summary(weight)
By the way, these things are called statistics. A statistic is any way of mushing up your data. That’s not what the field of statistics is about — here’s an 8min intro to the academic discipline.
This section isn’t about the kind of plotting that involves world domination (stay tuned for that article). It’s about summarizing data with pictures. Turns out a picture can be worth more than a thousand words — one per datapoint and then some. (In this case we’ll make one that’s only worth 27 weights.)
If we want to know how the weights are distributed in our data — for example, are there more items between 0 and 200g or between 600g and 800g? — a histogram is our best friend.
Histograms are one way (among many) of summarizing and displaying our sample data. Their blocks are taller for more popular values of the data.
Think of bar charts and histograms as popularity contests.
To make one in spreadsheet software, the magic spell is a long series of clicking on various menus. In R, it’s faster:
hist(weight)
Here’s what our one-liner got us:
What are we looking at?
On the horizontal axis, we have bins (or tip jars, if you prefer). They’re set to 200g increments by default, but we’ll change that in a moment. On the vertical axis are the counts: how many times did we see a weight between 0g and 200g? The plot says 11. How about between 600g and 800g? Only one (that’s the table salt, if memory serves).
We can choose our bin size — the default we got without fiddling with code is 200g bins, but maybe we want to use 100g bins instead. No problem! Magicians-in-training can tinker with my incantation to discover how it works.
hist(weight, col = "salmon2", breaks = seq(0, 1000, 100))
Here’s the result:
Now we can clearly see that the two most common categories are 100–200 and 400–500. Does anybody care? Probably not. We only did this because we could. A real analyst, on the other hand, excels at the science of looking at data quickly and the art of looking where the interesting nuggets lie. If they’re good their craft, they’re worth their weight in gold.
If these 27 items are the everything we care about, then this sample histogram I’ve just made also happens to be the population distribution.
That’s pretty much what a distribution is: it’s the histogram you’d get if you applied hist() to the whole population (all the information you care about), not just the sample (the data you happen to have on hand). There are a few footnotes, such as the scale on the y-axis, but we’ll leave those for another blog post — please don’t hurt me, mathematicians!
If our population is all packaged foods ever, the distribution would be shaped like the histogram of all their weights. That distribution exists only in our imaginations as a theoretical idea — some packaged food products are lost to the mists of time. We can’t make that dataset even if we wanted to, so the best we can do is make guesses about it using a good sample.
There’s a variety of opinions, but the definition I favor is this one: “Data science is the discipline of making data useful.” Its three subfields involve mining large amounts of information for inspiration (analytics), making decisions wisely based on limited information (statistics), and using patterns in data to automate tasks (ML/AI).
All of data science boils down to this: knowledge is power.
The universe is full of information waiting to be harvested and put to good use. While our brains are amazing at navigating our realities, they’re not so good at storing and processing some types of very useful information.
That’s why humanity turned first to clay tablets, then to paper, and eventually to silicon for help. We developed software for looking at information quickly and these days the people who know how to use it call themselves data scientists or data analysts. The real heroes are those who build the tools that allow these practitioners to get a grip on information better and faster. By the way, even the internet is an analytics tool — we just rarely think of it that way because even children can do that kind of data analysis.
Everything we perceive is stored somewhere, at least temporarily. There’s nothing magical about data except that it’s written down more reliably than brains manage. Some information is useful, some is misleading, the rest is in the middle. The same goes for data.
We’re all data analysts and always have been.
We take our amazing biological capabilities for granted and exaggerate the difference between our innate information processing and the machine-assisted variety. The difference is durability, speed, and scale... but the same rules of common sense apply in both. Why do those rules go out the window at the first sign of an equation?
I’m glad we celebrate information as fuel for progress, but worshipping data as something mystical makes no sense to me. It’s better to speak about data simply, since we’re all data analysts and always have been. Let’s empower everyone to see themselves that way!
If you had fun here and you’re looking for an applied AI course designed to be fun for beginners and experts alike, here’s one I made for your amusement: | [
{
"code": null,
"e": 191,
"s": 172,
"text": "\n\n2.9K plays2.9K\n\n"
},
{
"code": null,
"e": 613,
"s": 191,
"text": "Everything our senses perceive is data, though its storage in our cranial wet stuff leaves something to be desired. Writing it down is a bit more reliable, especially when we write it down on a computer. When those notes are well-organized, we call them data... though I’ve seen some awfully messy electronic scribbles get the same name. I’m not sure why some people pronounce the word data like it has a capital D in it."
},
{
"code": null,
"e": 656,
"s": 613,
"text": "Why do we pronounce data with a capital D?"
},
{
"code": null,
"e": 870,
"s": 656,
"text": "We need to learn to be irreverently pragmatic about data, so this is an article to help beginners see behind the curtain and to help practitioners explain the basics to newcomers who show symptoms of data-worship."
},
{
"code": null,
"e": 1077,
"s": 870,
"text": "If you start your journey by shopping for datasets online, you’re in danger of forgetting where they come form. I’m going to start from absolute scratch to show you that you can make data anytime, anywhere."
},
{
"code": null,
"e": 1146,
"s": 1077,
"text": "Here are some perennial denizens of my larder, arranged on my floor."
},
{
"code": null,
"e": 1370,
"s": 1146,
"text": "This photograph is data — it’s stored as information that your device uses to show you pretty colors. (If you’re curious to know what images look like when you can see the matrix, glance at my intro to supervised learning.)"
},
{
"code": null,
"e": 1546,
"s": 1370,
"text": "Let’s make some sense out of what we’re looking at. We have infinite options about what to pay attention to and remember. Here’s something I see when I look at the foodstuffs."
},
{
"code": null,
"e": 1908,
"s": 1546,
"text": "If you close your eyes, do you remember every detail of what you just saw? No? Me neither. That’s pretty much the reason we collect data. If we could remember and process it flawlessly in our heads, there’d be no need. The internet could be one hermit in a cave, recounting all the tweets of humankind and perfectly rendering each of our billions of cat photos."
},
{
"code": null,
"e": 2190,
"s": 1908,
"text": "Because human memory is a leaky bucket, it would be an improvement to jot the information down the way we used to when I went to school for statistics, back in the dark ages. That’s right, my friends, I still have paper around here somewhere! Let’s write down these 27 data points."
},
{
"code": null,
"e": 2318,
"s": 2190,
"text": "What’s great about this version — relative to what’s in my hippocampus or on my floor — is that it’s more durable and reliable."
},
{
"code": null,
"e": 2350,
"s": 2318,
"text": "Human memory is a leaky bucket."
},
{
"code": null,
"e": 2934,
"s": 2350,
"text": "We take the memory revolution for granted since it started millenia ago with merchants needing a reliable record of who sold whom how many bushels of what. Take a moment to realize how glorious it is to have a universal system of writing that stores numbers better than our brains do. When we record data, we produce an unfaithful corruption of our richly perceived realities, but after that we can transfer uncorrupted copies of the result to other members of our species with perfect fidelity. Writing is amazing! Little bits of mind and memory that get to live outside our bodies."
},
{
"code": null,
"e": 2997,
"s": 2934,
"text": "When we analyze data, we’re accessing someone else’s memories."
},
{
"code": null,
"e": 3204,
"s": 2997,
"text": "Worried about machines outperforming our brains? Even paper can do that! These 27 little numbers are a big lift for your brain to store, but durability is guaranteed if you have a writing implement at hand."
},
{
"code": null,
"e": 3405,
"s": 3204,
"text": "While this is a durability win, working with paper is annoying. For example, what if a whim strikes me to rearrange them from biggest to smallest? Abracadabra, paper, show me a better order! No? Darn."
},
{
"code": null,
"e": 3520,
"s": 3405,
"text": "You know what’s awesome about software? The abracadabra actually works! So let’s upgrade from paper to a computer."
},
{
"code": null,
"e": 3950,
"s": 3520,
"text": "Spreadsheets leave me lukewarm. They’re very limited compared with modern data science tools. I prefer to oscillate between R and Python, so let’s give R a whirl this time around. You can follow along in your browser with Jupyter: click on the “with R” box, then hit the scissors icon a few times until everything is deleted. Congrats, it took 5 seconds and you’re all set to paste in my code snippets and run [Shift+Enter] them."
},
{
"code": null,
"e": 4157,
"s": 3950,
"text": "weight <- c(50, 946, 454, 454, 110, 100, 340, 454, 200, 148, 355, 907, 454, 822, 127, 750, 255, 500, 500, 500, 8, 125, 284, 118, 227, 148, 125)weight <- weight[order(weight, decreasing = TRUE)]print(weight)"
},
{
"code": null,
"e": 4264,
"s": 4157,
"text": "What you’ll notice is that R’s abracadabra for sorting your data is not obvious if you’re new around here."
},
{
"code": null,
"e": 4666,
"s": 4264,
"text": "Well, that’s true of the word “abracadabra” itself and also true of the menus in spreadsheet software. You only know those things because you were exposed to them, not because they’re universal laws. To get things done with a computer, you need to ask your resident soothsayer for the magic words/gestures and then practice using them. My favorite sage is called The Internet and knows all the things."
},
{
"code": null,
"e": 4853,
"s": 4666,
"text": "To accelerate your wizard training, don’t just paste the magic words — try altering them and see what happens. For example, what changes if you turn TRUE into FALSE in the snippet above?"
},
{
"code": null,
"e": 4984,
"s": 4853,
"text": "Isn’t it amazing how quickly you get the answer? One reason I love programming is that it’s a cross between magic spells and LEGO."
},
{
"code": null,
"e": 5052,
"s": 4984,
"text": "If you’ve ever wished you could do magic, just learn to write code."
},
{
"code": null,
"e": 5262,
"s": 5052,
"text": "Here’s programming in a nutshell: ask the internet how to do something, take the magic words you just learned, see what happens when you adjust them, then put them together like LEGO blocks to do your bidding."
},
{
"code": null,
"e": 5627,
"s": 5262,
"text": "The trouble with these 27 numbers is that even if they’re sorted, they don’t mean much to us. As we read them, we forget what we just read a second ago. That’s human brains for you; tell us to read a sorted list of a million numbers and at best we’ll remember the last few. We need a quick way to sort and summarize so we can get a handle on what we’re looking at."
},
{
"code": null,
"e": 5657,
"s": 5627,
"text": "That’s what analytics is for!"
},
{
"code": null,
"e": 5672,
"s": 5657,
"text": "median(weight)"
},
{
"code": null,
"e": 5780,
"s": 5672,
"text": "With the right incantation, we can instantly know what the median weight is. (Median means “middle thing.”)"
},
{
"code": null,
"e": 6014,
"s": 5780,
"text": "Turns out the answer is 284g. Who doesn’t love instant gratification? There are all kinds of summary options: min(), max(), mean(), median(), mode(), variance()... try them all! Or try this single magic word to find out what happens."
},
{
"code": null,
"e": 6030,
"s": 6014,
"text": "summary(weight)"
},
{
"code": null,
"e": 6226,
"s": 6030,
"text": "By the way, these things are called statistics. A statistic is any way of mushing up your data. That’s not what the field of statistics is about — here’s an 8min intro to the academic discipline."
},
{
"code": null,
"e": 6532,
"s": 6226,
"text": "This section isn’t about the kind of plotting that involves world domination (stay tuned for that article). It’s about summarizing data with pictures. Turns out a picture can be worth more than a thousand words — one per datapoint and then some. (In this case we’ll make one that’s only worth 27 weights.)"
},
{
"code": null,
"e": 6710,
"s": 6532,
"text": "If we want to know how the weights are distributed in our data — for example, are there more items between 0 and 200g or between 600g and 800g? — a histogram is our best friend."
},
{
"code": null,
"e": 6854,
"s": 6710,
"text": "Histograms are one way (among many) of summarizing and displaying our sample data. Their blocks are taller for more popular values of the data."
},
{
"code": null,
"e": 6913,
"s": 6854,
"text": "Think of bar charts and histograms as popularity contests."
},
{
"code": null,
"e": 7032,
"s": 6913,
"text": "To make one in spreadsheet software, the magic spell is a long series of clicking on various menus. In R, it’s faster:"
},
{
"code": null,
"e": 7045,
"s": 7032,
"text": "hist(weight)"
},
{
"code": null,
"e": 7079,
"s": 7045,
"text": "Here’s what our one-liner got us:"
},
{
"code": null,
"e": 7103,
"s": 7079,
"text": "What are we looking at?"
},
{
"code": null,
"e": 7444,
"s": 7103,
"text": "On the horizontal axis, we have bins (or tip jars, if you prefer). They’re set to 200g increments by default, but we’ll change that in a moment. On the vertical axis are the counts: how many times did we see a weight between 0g and 200g? The plot says 11. How about between 600g and 800g? Only one (that’s the table salt, if memory serves)."
},
{
"code": null,
"e": 7668,
"s": 7444,
"text": "We can choose our bin size — the default we got without fiddling with code is 200g bins, but maybe we want to use 100g bins instead. No problem! Magicians-in-training can tinker with my incantation to discover how it works."
},
{
"code": null,
"e": 7726,
"s": 7668,
"text": "hist(weight, col = \"salmon2\", breaks = seq(0, 1000, 100))"
},
{
"code": null,
"e": 7745,
"s": 7726,
"text": "Here’s the result:"
},
{
"code": null,
"e": 8104,
"s": 7745,
"text": "Now we can clearly see that the two most common categories are 100–200 and 400–500. Does anybody care? Probably not. We only did this because we could. A real analyst, on the other hand, excels at the science of looking at data quickly and the art of looking where the interesting nuggets lie. If they’re good their craft, they’re worth their weight in gold."
},
{
"code": null,
"e": 8246,
"s": 8104,
"text": "If these 27 items are the everything we care about, then this sample histogram I’ve just made also happens to be the population distribution."
},
{
"code": null,
"e": 8605,
"s": 8246,
"text": "That’s pretty much what a distribution is: it’s the histogram you’d get if you applied hist() to the whole population (all the information you care about), not just the sample (the data you happen to have on hand). There are a few footnotes, such as the scale on the y-axis, but we’ll leave those for another blog post — please don’t hurt me, mathematicians!"
},
{
"code": null,
"e": 8975,
"s": 8605,
"text": "If our population is all packaged foods ever, the distribution would be shaped like the histogram of all their weights. That distribution exists only in our imaginations as a theoretical idea — some packaged food products are lost to the mists of time. We can’t make that dataset even if we wanted to, so the best we can do is make guesses about it using a good sample."
},
{
"code": null,
"e": 9316,
"s": 8975,
"text": "There’s a variety of opinions, but the definition I favor is this one: “Data science is the discipline of making data useful.” Its three subfields involve mining large amounts of information for inspiration (analytics), making decisions wisely based on limited information (statistics), and using patterns in data to automate tasks (ML/AI)."
},
{
"code": null,
"e": 9376,
"s": 9316,
"text": "All of data science boils down to this: knowledge is power."
},
{
"code": null,
"e": 9600,
"s": 9376,
"text": "The universe is full of information waiting to be harvested and put to good use. While our brains are amazing at navigating our realities, they’re not so good at storing and processing some types of very useful information."
},
{
"code": null,
"e": 10128,
"s": 9600,
"text": "That’s why humanity turned first to clay tablets, then to paper, and eventually to silicon for help. We developed software for looking at information quickly and these days the people who know how to use it call themselves data scientists or data analysts. The real heroes are those who build the tools that allow these practitioners to get a grip on information better and faster. By the way, even the internet is an analytics tool — we just rarely think of it that way because even children can do that kind of data analysis."
},
{
"code": null,
"e": 10392,
"s": 10128,
"text": "Everything we perceive is stored somewhere, at least temporarily. There’s nothing magical about data except that it’s written down more reliably than brains manage. Some information is useful, some is misleading, the rest is in the middle. The same goes for data."
},
{
"code": null,
"e": 10438,
"s": 10392,
"text": "We’re all data analysts and always have been."
},
{
"code": null,
"e": 10771,
"s": 10438,
"text": "We take our amazing biological capabilities for granted and exaggerate the difference between our innate information processing and the machine-assisted variety. The difference is durability, speed, and scale... but the same rules of common sense apply in both. Why do those rules go out the window at the first sign of an equation?"
},
{
"code": null,
"e": 11035,
"s": 10771,
"text": "I’m glad we celebrate information as fuel for progress, but worshipping data as something mystical makes no sense to me. It’s better to speak about data simply, since we’re all data analysts and always have been. Let’s empower everyone to see themselves that way!"
}
] |
Tryit Editor v3.7 | Tryit: JavaScript in head | [] |
Jupyter Data Science Stack + Docker in under 15 minutes | by Tanbal تنبل | Towards Data Science | Motivation: Say you want to play around with some cool data science libraries in Python or R but what you don’t want to do is spend hours on installing Python or R, working out what libraries you need, installing each and every one and then messing around with the tedium of getting things to work just right on your version of Linux/Windows/OSX/OS9 — well this is where Docker comes to the rescue! With Docker we can get a Jupyter ‘Data Science’ notebook stack up and running in no time at all. Let’s get started!
Docker is allows us to run a ‘ready to go’ Jupyter data science stack in what’s known as a container:
A container image is a lightweight, stand-alone, executable package of a piece of software that includes everything needed to run it: code, runtime, system tools, system libraries, settings. Available for both Linux and Windows based apps, containerized software will always run the same, regardless of the environment. Containers isolate software from its surroundings, for example differences between development and staging environments and help reduce conflicts between teams running different software on the same infrastructure.
So what’s the difference between a container and a virtual machine?
Containers and virtual machines have similar resource isolation and allocation benefits, but function differently because containers virtualize the operating system instead of hardware, containers are more portable and efficient.
To get started with Docker you’ll need to install Docker Community Edition. Download the appropriate installer for your environment here. Once you’ve installed Docker, restart your machine and we can move on to getting our Jupyter container set up. When running a container you’ll need to tell Docker what the base image for that container is.
So what’s an image and how does it relate to a container?
A Docker image is built up from a series of layers. Each layer represents an instruction in the image’s Dockerfile. Each layer except the very last one is read-only.
A container is simply a running instance of an image. The real time-saver with using Docker is that someone else has already built an image that has everything we need to start using a fully kitted-out Jupyter data science stack! All we need to do is tell Docker to start up a container based on that pre-defined image. To do this we’re going to write a simple recipe in the form of a Docker compose file. Save the file below as docker-compose.yml to your working directory:
After you’ve saved the file, open it with your favourite editor and change the section that says:
/Absolute/Path/To/Where/Your/Notebook/Files/Will/Be/Saved
to the path on your local machine where you want your work to be saved. Make sure that the path actually exists, that is, any directories have already been created. Failing to do so will cause errors when you attempt to start your container and worse yet, you won’t be able to save any work you do in the container!
Great, so we’ve got our Docker compose file ready to go, now we can use the docker-compose command to start up our container. Open a terminal or command prompt and change into your working directory and run the following command:
docker-compose up
You should see something like the following output in your terminal/command prompt (I’ve omitted some of the output for brevity):
$ docker-compose upCreating network “jupyternotebook_default” with the default driverCreating datascience-notebook-container ...Creating datascience-notebook-container ... doneAttaching to datascience-notebook-containerdatascience-notebook-container | Execute the command: jupyter notebook...datascience-notebook-container | [I 11:37:37.993 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/?token=123456789123456789123456789123456789datascience-notebook-container | [I 11:37:37.993 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).datascience-notebook-container | [C 11:37:37.994 NotebookApp]datascience-notebook-container |datascience-notebook-container | Copy/paste this URL into your browser when you connect for the first time,datascience-notebook-container | to login with a token:datascience-notebook-container | http://localhost:8888/?token=123456789123456789123456789123456789
The last line is a URL that we need to copy and paste into our browser to access our new Jupyter stack:
http://localhost:8888/?token=123456789123456789123456789123456789
Once you’ve done that you should be greeted by your very own containerised Jupyter service! You can learn more about what the Jupyter data science stack gives you be visiting this link.
To create your first notebook, drill into the work directory and then click on the ‘New’ button on the right hand side and choose ‘Python 3’ to create a new Python 3 based Notebook. Once you’ve done so, check your the path where you chose to save your work to locally and you should see your new Notebook’s .ipynb file saved!
To shut down the container once you’re done working, simply hit Ctrl-C in the terminal/command prompt. Your work will all be saved on your actual machine in the path we set in our Docker compose file. And there you have it — a quick and easy way to start using Jupyter notebooks with the magic of Docker.
I hope you found this article helpful, please leave any feedback or comments below. Happy hacking! | [
{
"code": null,
"e": 686,
"s": 171,
"text": "Motivation: Say you want to play around with some cool data science libraries in Python or R but what you don’t want to do is spend hours on installing Python or R, working out what libraries you need, installing each and every one and then messing around with the tedium of getting things to work just right on your version of Linux/Windows/OSX/OS9 — well this is where Docker comes to the rescue! With Docker we can get a Jupyter ‘Data Science’ notebook stack up and running in no time at all. Let’s get started!"
},
{
"code": null,
"e": 788,
"s": 686,
"text": "Docker is allows us to run a ‘ready to go’ Jupyter data science stack in what’s known as a container:"
},
{
"code": null,
"e": 1323,
"s": 788,
"text": "A container image is a lightweight, stand-alone, executable package of a piece of software that includes everything needed to run it: code, runtime, system tools, system libraries, settings. Available for both Linux and Windows based apps, containerized software will always run the same, regardless of the environment. Containers isolate software from its surroundings, for example differences between development and staging environments and help reduce conflicts between teams running different software on the same infrastructure."
},
{
"code": null,
"e": 1391,
"s": 1323,
"text": "So what’s the difference between a container and a virtual machine?"
},
{
"code": null,
"e": 1621,
"s": 1391,
"text": "Containers and virtual machines have similar resource isolation and allocation benefits, but function differently because containers virtualize the operating system instead of hardware, containers are more portable and efficient."
},
{
"code": null,
"e": 1965,
"s": 1621,
"text": "To get started with Docker you’ll need to install Docker Community Edition. Download the appropriate installer for your environment here. Once you’ve installed Docker, restart your machine and we can move on to getting our Jupyter container set up. When running a container you’ll need to tell Docker what the base image for that container is."
},
{
"code": null,
"e": 2023,
"s": 1965,
"text": "So what’s an image and how does it relate to a container?"
},
{
"code": null,
"e": 2189,
"s": 2023,
"text": "A Docker image is built up from a series of layers. Each layer represents an instruction in the image’s Dockerfile. Each layer except the very last one is read-only."
},
{
"code": null,
"e": 2664,
"s": 2189,
"text": "A container is simply a running instance of an image. The real time-saver with using Docker is that someone else has already built an image that has everything we need to start using a fully kitted-out Jupyter data science stack! All we need to do is tell Docker to start up a container based on that pre-defined image. To do this we’re going to write a simple recipe in the form of a Docker compose file. Save the file below as docker-compose.yml to your working directory:"
},
{
"code": null,
"e": 2762,
"s": 2664,
"text": "After you’ve saved the file, open it with your favourite editor and change the section that says:"
},
{
"code": null,
"e": 2820,
"s": 2762,
"text": "/Absolute/Path/To/Where/Your/Notebook/Files/Will/Be/Saved"
},
{
"code": null,
"e": 3136,
"s": 2820,
"text": "to the path on your local machine where you want your work to be saved. Make sure that the path actually exists, that is, any directories have already been created. Failing to do so will cause errors when you attempt to start your container and worse yet, you won’t be able to save any work you do in the container!"
},
{
"code": null,
"e": 3366,
"s": 3136,
"text": "Great, so we’ve got our Docker compose file ready to go, now we can use the docker-compose command to start up our container. Open a terminal or command prompt and change into your working directory and run the following command:"
},
{
"code": null,
"e": 3384,
"s": 3366,
"text": "docker-compose up"
},
{
"code": null,
"e": 3514,
"s": 3384,
"text": "You should see something like the following output in your terminal/command prompt (I’ve omitted some of the output for brevity):"
},
{
"code": null,
"e": 4498,
"s": 3514,
"text": "$ docker-compose upCreating network “jupyternotebook_default” with the default driverCreating datascience-notebook-container ...Creating datascience-notebook-container ... doneAttaching to datascience-notebook-containerdatascience-notebook-container | Execute the command: jupyter notebook...datascience-notebook-container | [I 11:37:37.993 NotebookApp] The Jupyter Notebook is running at: http://[all ip addresses on your system]:8888/?token=123456789123456789123456789123456789datascience-notebook-container | [I 11:37:37.993 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).datascience-notebook-container | [C 11:37:37.994 NotebookApp]datascience-notebook-container |datascience-notebook-container | Copy/paste this URL into your browser when you connect for the first time,datascience-notebook-container | to login with a token:datascience-notebook-container | http://localhost:8888/?token=123456789123456789123456789123456789"
},
{
"code": null,
"e": 4602,
"s": 4498,
"text": "The last line is a URL that we need to copy and paste into our browser to access our new Jupyter stack:"
},
{
"code": null,
"e": 4668,
"s": 4602,
"text": "http://localhost:8888/?token=123456789123456789123456789123456789"
},
{
"code": null,
"e": 4854,
"s": 4668,
"text": "Once you’ve done that you should be greeted by your very own containerised Jupyter service! You can learn more about what the Jupyter data science stack gives you be visiting this link."
},
{
"code": null,
"e": 5180,
"s": 4854,
"text": "To create your first notebook, drill into the work directory and then click on the ‘New’ button on the right hand side and choose ‘Python 3’ to create a new Python 3 based Notebook. Once you’ve done so, check your the path where you chose to save your work to locally and you should see your new Notebook’s .ipynb file saved!"
},
{
"code": null,
"e": 5485,
"s": 5180,
"text": "To shut down the container once you’re done working, simply hit Ctrl-C in the terminal/command prompt. Your work will all be saved on your actual machine in the path we set in our Docker compose file. And there you have it — a quick and easy way to start using Jupyter notebooks with the magic of Docker."
}
] |
Count even and odd digits in an Integer - GeeksforGeeks | 28 Feb, 2022
A certain number is given and the task is to count even digits and odd digits of the number and also even digits are present even a number of times and, similarly, for odd numbers.
Print Yes If:
If number contains even digits even number of time
Odd digits odd number of times
Else
Print No
Examples :
Input : 22233
Output : NO
count_even_digits = 3
count_odd_digits = 2
In this number even digits occur odd number of times and odd
digits occur even number of times so its print NO.
Input : 44555
Output : YES
count_even_digits = 2
count_odd_digits = 3
In this number even digits occur even number of times and odd
digits occur odd number of times so its print YES.
Efficient solution for calculating even and odd digits in a number.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count// even and odd digits// in a given number#include <iostream>using namespace std; // Function to count digitsint countEvenOdd(int n){ int even_count = 0; int odd_count = 0; while (n > 0) { int rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = n / 10; } cout << "Even count : " << even_count; cout << "\nOdd count : " << odd_count; if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Codeint main(){ int n; n = 2335453; int t = countEvenOdd(n); if (t == 1) cout << "\nYES" << endl; else cout << "\nNO" << endl; return 0;}
// Java program to count// even and odd digits// in a given number import java.io.*; class GFG{ // Function to count digitsstatic int countEvenOdd(int n){ int even_count = 0; int odd_count = 0; while (n > 0) { int rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = n / 10; } System.out.println ( "Even count : " + even_count); System.out.println ( "Odd count : " + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code public static void main (String[] args) { int n; n = 2335453; int t = countEvenOdd(n); if (t == 1) System.out.println ( "YES" ); else System.out.println( "NO") ; }}
# python program to count even and# odd digits in a given number # Function to count digitsdef countEvenOdd(n): even_count = 0 odd_count = 0 while (n > 0): rem = n % 10 if (rem % 2 == 0): even_count += 1 else: odd_count += 1 n = int(n / 10) print( "Even count : " , even_count) print("\nOdd count : " , odd_count) if (even_count % 2 == 0 and odd_count % 2 != 0): return 1 else: return 0 # Driver coden = 2335453;t = countEvenOdd(n); if (t == 1): print("YES")else: print("NO") # This code is contributed by Sam007.
// C# program to count even and// odd digits in a given numberusing System; class GFG { // Function to count digitsstatic int countEvenOdd(int n){ int even_count = 0; int odd_count = 0; while (n > 0) { int rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = n / 10; } Console.WriteLine("Even count : " + even_count); Console.WriteLine("Odd count : " + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code public static void Main () { int n; n = 2335453; int t = countEvenOdd(n); if (t == 1) Console.WriteLine ("YES"); else Console.WriteLine("NO") ; }} // This code is contributed by vt_m.
<?php// PHP program to count// even and odd digits// in a given number // Function to count digitsfunction countEvenOdd($n){ $even_count = 0; $odd_count = 0; while ($n > 0) { $rem = $n % 10; if ($rem % 2 == 0) $even_count++; else $odd_count++; $n = (int)($n / 10); } echo("Even count : " . $even_count); echo("\nOdd count : " . $odd_count); if ($even_count % 2 == 0 && $odd_count % 2 != 0) return 1; else return 0;} // Driver code$n = 2335453;$t = countEvenOdd($n);if ($t == 1) echo("\nYES");else echo("\nNO"); // This code is contributed by Ajit.?>
<script> /// Javascript program to count// even and odd digits// in a given number // Function to count digitsfunction countEvenOdd(n){ let even_count = 0; let odd_count = 0; while (n > 0) { let rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = Math.floor(n / 10); } document.write("Even count : " + even_count); document.write("<br>" + "Odd count : " + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code let n; n = 2335453; let t = countEvenOdd(n); if (t == 1) document.write("<br>" + "YES" + "<br>"); else document.write("<br>"+"NO" + "<br>"); // This code is contributed by Mayank Tyagi </script>
Even count : 2
Odd count : 5
YES
Another solution to solve this problem is a character array or string.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count// even and odd digits// in a given number// using char array#include <bits/stdc++.h>using namespace std; // Function to count digitsint countEvenOdd(char num[], int n){ int even_count = 0; int odd_count = 0; for (int i = 0; i < n; i++) { int x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } cout << "Even count : " << even_count; cout << "\nOdd count : " << odd_count; if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Codeint main(){ char num[18] = { 1, 2, 3 }; int n = strlen(num); int t = countEvenOdd(num, n); if (t == 1) cout << "\nYES" << endl; else cout << "\nNO" << endl; return 0;}
// Java program to count// even and odd digits// in a given number// using char array import java.io.*; class GFG{ // Function to count digitsstatic int countEvenOdd(char num[], int n){ int even_count = 0; int odd_count = 0; for (int i = 0; i < n; i++) { int x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } System.out.println ("Even count : " + even_count); System.out.println( "Odd count : " + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code public static void main (String[] args) { char num[] = { 1, 2, 3 }; int n = num.length; int t = countEvenOdd(num, n); if (t == 1) System.out.println("YES") ; else System.out.println("NO") ; }} // This code is contributed by vt_m
# Python3 program to count# even and odd digits# in a given number# using char array # Function to count digitsdef countEvenOdd(num, n): even_count = 0; odd_count = 0; num=list(str(num)) for i in num: if i in ('0','2','4','6','8'): even_count+=1 else: odd_count+=1 print("Even count : ", even_count); print("Odd count : ", odd_count); if (even_count % 2 == 0 and odd_count % 2 != 0): return 1; else: return 0; # Driver Codenum = (1, 2, 3);n = len(num);t = countEvenOdd(num, n); if t == 1: print("YES");else: print("NO"); # This code is contributed by mits.
// C# program to count// even and odd digits// in a given number// using char arrayusing System; class GFG{ // Function to count digits static int countEvenOdd(char []num, int n) { int even_count = 0; int odd_count = 0; for (int i = 0; i < n; i++) { int x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } Console.WriteLine("Even count : " + even_count); Console.WriteLine( "Odd count : " + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0; } // Driver code public static void Main () { char [] num = { '1', '2', '3' }; int n = num.Length; int t = countEvenOdd(num, n); if (t == 1) Console.WriteLine("YES") ; else Console.WriteLine("NO") ; }} // This code is contributed by Sam007.
<?php// PHP program to count// even and odd digits// in a given number// using char array // Function to count digitsfunction countEvenOdd($num, $n){ $even_count = 0; $odd_count = 0; for ($i = 0; $i < $n; $i++) { $x = $num[$i] - 48; if ($x % 2 == 0) $even_count++; else $odd_count++; } echo "Even count : " . $even_count; echo "\nOdd count : " . $odd_count; if ($even_count % 2 == 0 && $odd_count % 2 != 0) return 1; else return 0;} // Driver Code $num = array( 1, 2, 3 ); $n = strlen(num); $t = countEvenOdd($num, $n); if ($t == 1) echo "\nYES" ,"\n"; else echo "\nNO" ,"\n"; // This code is contributed by ajit.?>
<script> // Javascript program to count// even and odd digits// in a given number// using char array // Function to count digitsfunction countEvenOdd(num, n){ even_count = 0; odd_count = 0; for(var i = 0; i < n; i++) { x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } document.write("Even count : " + even_count); document.write("<br>Odd count : " + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver codevar num = [ 1, 2, 3 ];n = num.length;t = countEvenOdd(num, n); if (t == 1) document.write("<br>YES <br>");else document.write("<br>NO <br>"); // This code is contributed by akshitsaxenaa09 </script>
Even count : 1
Odd count : 2
NO
We have to convert the given number to a string by taking a new variable.
Traverse the string, convert each element to an integer.
If the character(digit) is even, then the increased count
Else increment the odd count.
If the even count is even and the odd count is odd, then print Yes.
Else print no.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of above approach#include<bits/stdc++.h>using namespace std; string getResult(int n){ // Converting integer to String string st = to_string(n); int even_count = 0; int odd_count = 0; // Looping till length of String for(int i = 0; i < st.length(); i++) { if ((st[i] % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return "Yes"; else return "no";} // Driver Codeint main(){ int n = 77788; // Passing this number to get result function cout<<getResult(n)<<endl; } // This code is contributed by shinjanpatra.
// Java implementation of above approachclass GFG{ static String getResult(int n){ // Converting integer to String String st = String.valueOf(n); int even_count = 0; int odd_count = 0; // Looping till length of String for(int i = 0; i < st.length(); i++) { if ((st.charAt(i) % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return "Yes"; else return "no";} // Driver Codepublic static void main(String[] args){ int n = 77788; // Passing this number to get result function System.out.println(getResult(n)); }} // This code is contributed by 29AjayKumar
# Python implementation of above approachdef getResult(n): # Converting integer to string st = str(n) even_count = 0 odd_count = 0 # Looping till length of string for i in range(len(st)): if((int(st[i]) % 2) == 0): # digit is even so increment even count even_count += 1 else: odd_count += 1 # Checking even count is even and odd count is odd if(even_count % 2 == 0 and odd_count % 2 != 0): return 'Yes' else: return 'no' # Driver Coden = 77788 # passing this number to get result functionprint(getResult(n)) # this code is contributed by vikkycirus
// C# implementation of above approachusing System;using System.Collections.Generic; class GFG{ static String getResult(int n){ // Converting integer to String String st = String.Join("",n); int even_count = 0; int odd_count = 0; // Looping till length of String for(int i = 0; i < st.Length; i++) { if ((st[i] % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return "Yes"; else return "no";} // Driver Codepublic static void Main(String[] args){ int n = 77788; // Passing this number to get result function Console.WriteLine(getResult(n)); }} // This code is contributed by Princi Singh
<script> // Javascript implementation of above approach function getResult(n){ // Converting integer to String var st = n.toString(); var even_count = 0; var odd_count = 0; // Looping till length of String for(var i = 0; i < st.length; i++) { if ((st.charAt(i) % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return "Yes"; else return "no";} // Driver Code var n = 77788; // Passing this number to get result function document.write(getResult(n)); </script>
Yes
This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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.
vt_m
jit_t
Sam007
Mithun Kumar
geethanjalivilluri
Akanksha_Rai
mayanktyagi1709
vikkycirus
akshitsaxenaa09
29AjayKumar
bunnyram19
princi singh
shinjanpatra
number-digits
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Overriding in Java
Constructors in C++
Operator Overloading in C++
C++ Classes and Objects
Copy Constructor in C++
Types of Operating Systems
Interfaces in Java
Polymorphism in C++
C++ Data Types
Friend class and function in C++ | [
{
"code": null,
"e": 25164,
"s": 25136,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 25346,
"s": 25164,
"text": "A certain number is given and the task is to count even digits and odd digits of the number and also even digits are present even a number of times and, similarly, for odd numbers. "
},
{
"code": null,
"e": 25466,
"s": 25346,
"text": "Print Yes If:\n If number contains even digits even number of time\n Odd digits odd number of times\nElse \n Print No"
},
{
"code": null,
"e": 25477,
"s": 25466,
"text": "Examples :"
},
{
"code": null,
"e": 25912,
"s": 25477,
"text": "Input : 22233\nOutput : NO\n count_even_digits = 3\n count_odd_digits = 2\n In this number even digits occur odd number of times and odd \n digits occur even number of times so its print NO.\n\nInput : 44555\nOutput : YES\n count_even_digits = 2\n count_odd_digits = 3\n In this number even digits occur even number of times and odd \n digits occur odd number of times so its print YES."
},
{
"code": null,
"e": 25982,
"s": 25912,
"text": "Efficient solution for calculating even and odd digits in a number. "
},
{
"code": null,
"e": 25986,
"s": 25982,
"text": "C++"
},
{
"code": null,
"e": 25991,
"s": 25986,
"text": "Java"
},
{
"code": null,
"e": 25999,
"s": 25991,
"text": "Python3"
},
{
"code": null,
"e": 26002,
"s": 25999,
"text": "C#"
},
{
"code": null,
"e": 26006,
"s": 26002,
"text": "PHP"
},
{
"code": null,
"e": 26017,
"s": 26006,
"text": "Javascript"
},
{
"code": "// C++ program to count// even and odd digits// in a given number#include <iostream>using namespace std; // Function to count digitsint countEvenOdd(int n){ int even_count = 0; int odd_count = 0; while (n > 0) { int rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = n / 10; } cout << \"Even count : \" << even_count; cout << \"\\nOdd count : \" << odd_count; if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Codeint main(){ int n; n = 2335453; int t = countEvenOdd(n); if (t == 1) cout << \"\\nYES\" << endl; else cout << \"\\nNO\" << endl; return 0;}",
"e": 26756,
"s": 26017,
"text": null
},
{
"code": "// Java program to count// even and odd digits// in a given number import java.io.*; class GFG{ // Function to count digitsstatic int countEvenOdd(int n){ int even_count = 0; int odd_count = 0; while (n > 0) { int rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = n / 10; } System.out.println ( \"Even count : \" + even_count); System.out.println ( \"Odd count : \" + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code public static void main (String[] args) { int n; n = 2335453; int t = countEvenOdd(n); if (t == 1) System.out.println ( \"YES\" ); else System.out.println( \"NO\") ; }}",
"e": 27620,
"s": 26756,
"text": null
},
{
"code": "# python program to count even and# odd digits in a given number # Function to count digitsdef countEvenOdd(n): even_count = 0 odd_count = 0 while (n > 0): rem = n % 10 if (rem % 2 == 0): even_count += 1 else: odd_count += 1 n = int(n / 10) print( \"Even count : \" , even_count) print(\"\\nOdd count : \" , odd_count) if (even_count % 2 == 0 and odd_count % 2 != 0): return 1 else: return 0 # Driver coden = 2335453;t = countEvenOdd(n); if (t == 1): print(\"YES\")else: print(\"NO\") # This code is contributed by Sam007.",
"e": 28267,
"s": 27620,
"text": null
},
{
"code": "// C# program to count even and// odd digits in a given numberusing System; class GFG { // Function to count digitsstatic int countEvenOdd(int n){ int even_count = 0; int odd_count = 0; while (n > 0) { int rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = n / 10; } Console.WriteLine(\"Even count : \" + even_count); Console.WriteLine(\"Odd count : \" + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code public static void Main () { int n; n = 2335453; int t = countEvenOdd(n); if (t == 1) Console.WriteLine (\"YES\"); else Console.WriteLine(\"NO\") ; }} // This code is contributed by vt_m.",
"e": 29178,
"s": 28267,
"text": null
},
{
"code": "<?php// PHP program to count// even and odd digits// in a given number // Function to count digitsfunction countEvenOdd($n){ $even_count = 0; $odd_count = 0; while ($n > 0) { $rem = $n % 10; if ($rem % 2 == 0) $even_count++; else $odd_count++; $n = (int)($n / 10); } echo(\"Even count : \" . $even_count); echo(\"\\nOdd count : \" . $odd_count); if ($even_count % 2 == 0 && $odd_count % 2 != 0) return 1; else return 0;} // Driver code$n = 2335453;$t = countEvenOdd($n);if ($t == 1) echo(\"\\nYES\");else echo(\"\\nNO\"); // This code is contributed by Ajit.?>",
"e": 29858,
"s": 29178,
"text": null
},
{
"code": "<script> /// Javascript program to count// even and odd digits// in a given number // Function to count digitsfunction countEvenOdd(n){ let even_count = 0; let odd_count = 0; while (n > 0) { let rem = n % 10; if (rem % 2 == 0) even_count++; else odd_count++; n = Math.floor(n / 10); } document.write(\"Even count : \" + even_count); document.write(\"<br>\" + \"Odd count : \" + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code let n; n = 2335453; let t = countEvenOdd(n); if (t == 1) document.write(\"<br>\" + \"YES\" + \"<br>\"); else document.write(\"<br>\"+\"NO\" + \"<br>\"); // This code is contributed by Mayank Tyagi </script>",
"e": 30667,
"s": 29858,
"text": null
},
{
"code": null,
"e": 30700,
"s": 30667,
"text": "Even count : 2\nOdd count : 5\nYES"
},
{
"code": null,
"e": 30771,
"s": 30700,
"text": "Another solution to solve this problem is a character array or string."
},
{
"code": null,
"e": 30775,
"s": 30771,
"text": "C++"
},
{
"code": null,
"e": 30780,
"s": 30775,
"text": "Java"
},
{
"code": null,
"e": 30788,
"s": 30780,
"text": "Python3"
},
{
"code": null,
"e": 30791,
"s": 30788,
"text": "C#"
},
{
"code": null,
"e": 30795,
"s": 30791,
"text": "PHP"
},
{
"code": null,
"e": 30806,
"s": 30795,
"text": "Javascript"
},
{
"code": "// C++ program to count// even and odd digits// in a given number// using char array#include <bits/stdc++.h>using namespace std; // Function to count digitsint countEvenOdd(char num[], int n){ int even_count = 0; int odd_count = 0; for (int i = 0; i < n; i++) { int x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } cout << \"Even count : \" << even_count; cout << \"\\nOdd count : \" << odd_count; if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Codeint main(){ char num[18] = { 1, 2, 3 }; int n = strlen(num); int t = countEvenOdd(num, n); if (t == 1) cout << \"\\nYES\" << endl; else cout << \"\\nNO\" << endl; return 0;}",
"e": 31629,
"s": 30806,
"text": null
},
{
"code": "// Java program to count// even and odd digits// in a given number// using char array import java.io.*; class GFG{ // Function to count digitsstatic int countEvenOdd(char num[], int n){ int even_count = 0; int odd_count = 0; for (int i = 0; i < n; i++) { int x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } System.out.println (\"Even count : \" + even_count); System.out.println( \"Odd count : \" + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver Code public static void main (String[] args) { char num[] = { 1, 2, 3 }; int n = num.length; int t = countEvenOdd(num, n); if (t == 1) System.out.println(\"YES\") ; else System.out.println(\"NO\") ; }} // This code is contributed by vt_m",
"e": 32588,
"s": 31629,
"text": null
},
{
"code": "# Python3 program to count# even and odd digits# in a given number# using char array # Function to count digitsdef countEvenOdd(num, n): even_count = 0; odd_count = 0; num=list(str(num)) for i in num: if i in ('0','2','4','6','8'): even_count+=1 else: odd_count+=1 print(\"Even count : \", even_count); print(\"Odd count : \", odd_count); if (even_count % 2 == 0 and odd_count % 2 != 0): return 1; else: return 0; # Driver Codenum = (1, 2, 3);n = len(num);t = countEvenOdd(num, n); if t == 1: print(\"YES\");else: print(\"NO\"); # This code is contributed by mits.",
"e": 33262,
"s": 32588,
"text": null
},
{
"code": "// C# program to count// even and odd digits// in a given number// using char arrayusing System; class GFG{ // Function to count digits static int countEvenOdd(char []num, int n) { int even_count = 0; int odd_count = 0; for (int i = 0; i < n; i++) { int x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } Console.WriteLine(\"Even count : \" + even_count); Console.WriteLine( \"Odd count : \" + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0; } // Driver code public static void Main () { char [] num = { '1', '2', '3' }; int n = num.Length; int t = countEvenOdd(num, n); if (t == 1) Console.WriteLine(\"YES\") ; else Console.WriteLine(\"NO\") ; }} // This code is contributed by Sam007.",
"e": 34380,
"s": 33262,
"text": null
},
{
"code": "<?php// PHP program to count// even and odd digits// in a given number// using char array // Function to count digitsfunction countEvenOdd($num, $n){ $even_count = 0; $odd_count = 0; for ($i = 0; $i < $n; $i++) { $x = $num[$i] - 48; if ($x % 2 == 0) $even_count++; else $odd_count++; } echo \"Even count : \" . $even_count; echo \"\\nOdd count : \" . $odd_count; if ($even_count % 2 == 0 && $odd_count % 2 != 0) return 1; else return 0;} // Driver Code $num = array( 1, 2, 3 ); $n = strlen(num); $t = countEvenOdd($num, $n); if ($t == 1) echo \"\\nYES\" ,\"\\n\"; else echo \"\\nNO\" ,\"\\n\"; // This code is contributed by ajit.?>",
"e": 35148,
"s": 34380,
"text": null
},
{
"code": "<script> // Javascript program to count// even and odd digits// in a given number// using char array // Function to count digitsfunction countEvenOdd(num, n){ even_count = 0; odd_count = 0; for(var i = 0; i < n; i++) { x = num[i] - 48; if (x % 2 == 0) even_count++; else odd_count++; } document.write(\"Even count : \" + even_count); document.write(\"<br>Odd count : \" + odd_count); if (even_count % 2 == 0 && odd_count % 2 != 0) return 1; else return 0;} // Driver codevar num = [ 1, 2, 3 ];n = num.length;t = countEvenOdd(num, n); if (t == 1) document.write(\"<br>YES <br>\");else document.write(\"<br>NO <br>\"); // This code is contributed by akshitsaxenaa09 </script>",
"e": 35963,
"s": 35148,
"text": null
},
{
"code": null,
"e": 35995,
"s": 35963,
"text": "Even count : 1\nOdd count : 2\nNO"
},
{
"code": null,
"e": 36069,
"s": 35995,
"text": "We have to convert the given number to a string by taking a new variable."
},
{
"code": null,
"e": 36126,
"s": 36069,
"text": "Traverse the string, convert each element to an integer."
},
{
"code": null,
"e": 36184,
"s": 36126,
"text": "If the character(digit) is even, then the increased count"
},
{
"code": null,
"e": 36214,
"s": 36184,
"text": "Else increment the odd count."
},
{
"code": null,
"e": 36282,
"s": 36214,
"text": "If the even count is even and the odd count is odd, then print Yes."
},
{
"code": null,
"e": 36297,
"s": 36282,
"text": "Else print no."
},
{
"code": null,
"e": 36348,
"s": 36297,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 36352,
"s": 36348,
"text": "C++"
},
{
"code": null,
"e": 36357,
"s": 36352,
"text": "Java"
},
{
"code": null,
"e": 36365,
"s": 36357,
"text": "Python3"
},
{
"code": null,
"e": 36368,
"s": 36365,
"text": "C#"
},
{
"code": null,
"e": 36379,
"s": 36368,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include<bits/stdc++.h>using namespace std; string getResult(int n){ // Converting integer to String string st = to_string(n); int even_count = 0; int odd_count = 0; // Looping till length of String for(int i = 0; i < st.length(); i++) { if ((st[i] % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return \"Yes\"; else return \"no\";} // Driver Codeint main(){ int n = 77788; // Passing this number to get result function cout<<getResult(n)<<endl; } // This code is contributed by shinjanpatra.",
"e": 37107,
"s": 36379,
"text": null
},
{
"code": "// Java implementation of above approachclass GFG{ static String getResult(int n){ // Converting integer to String String st = String.valueOf(n); int even_count = 0; int odd_count = 0; // Looping till length of String for(int i = 0; i < st.length(); i++) { if ((st.charAt(i) % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return \"Yes\"; else return \"no\";} // Driver Codepublic static void main(String[] args){ int n = 77788; // Passing this number to get result function System.out.println(getResult(n)); }} // This code is contributed by 29AjayKumar",
"e": 37952,
"s": 37107,
"text": null
},
{
"code": "# Python implementation of above approachdef getResult(n): # Converting integer to string st = str(n) even_count = 0 odd_count = 0 # Looping till length of string for i in range(len(st)): if((int(st[i]) % 2) == 0): # digit is even so increment even count even_count += 1 else: odd_count += 1 # Checking even count is even and odd count is odd if(even_count % 2 == 0 and odd_count % 2 != 0): return 'Yes' else: return 'no' # Driver Coden = 77788 # passing this number to get result functionprint(getResult(n)) # this code is contributed by vikkycirus",
"e": 38621,
"s": 37952,
"text": null
},
{
"code": "// C# implementation of above approachusing System;using System.Collections.Generic; class GFG{ static String getResult(int n){ // Converting integer to String String st = String.Join(\"\",n); int even_count = 0; int odd_count = 0; // Looping till length of String for(int i = 0; i < st.Length; i++) { if ((st[i] % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return \"Yes\"; else return \"no\";} // Driver Codepublic static void Main(String[] args){ int n = 77788; // Passing this number to get result function Console.WriteLine(getResult(n)); }} // This code is contributed by Princi Singh",
"e": 39502,
"s": 38621,
"text": null
},
{
"code": "<script> // Javascript implementation of above approach function getResult(n){ // Converting integer to String var st = n.toString(); var even_count = 0; var odd_count = 0; // Looping till length of String for(var i = 0; i < st.length; i++) { if ((st.charAt(i) % 2) == 0) // Digit is even so increment even count even_count += 1; else odd_count += 1; } // Checking even count is even and // odd count is odd if (even_count % 2 == 0 && odd_count % 2 != 0) return \"Yes\"; else return \"no\";} // Driver Code var n = 77788; // Passing this number to get result function document.write(getResult(n)); </script>",
"e": 40256,
"s": 39502,
"text": null
},
{
"code": null,
"e": 40260,
"s": 40256,
"text": "Yes"
},
{
"code": null,
"e": 40689,
"s": 40260,
"text": "This article is contributed by Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.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": 40694,
"s": 40689,
"text": "vt_m"
},
{
"code": null,
"e": 40700,
"s": 40694,
"text": "jit_t"
},
{
"code": null,
"e": 40707,
"s": 40700,
"text": "Sam007"
},
{
"code": null,
"e": 40720,
"s": 40707,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 40739,
"s": 40720,
"text": "geethanjalivilluri"
},
{
"code": null,
"e": 40752,
"s": 40739,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 40768,
"s": 40752,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 40779,
"s": 40768,
"text": "vikkycirus"
},
{
"code": null,
"e": 40795,
"s": 40779,
"text": "akshitsaxenaa09"
},
{
"code": null,
"e": 40807,
"s": 40795,
"text": "29AjayKumar"
},
{
"code": null,
"e": 40818,
"s": 40807,
"text": "bunnyram19"
},
{
"code": null,
"e": 40831,
"s": 40818,
"text": "princi singh"
},
{
"code": null,
"e": 40844,
"s": 40831,
"text": "shinjanpatra"
},
{
"code": null,
"e": 40858,
"s": 40844,
"text": "number-digits"
},
{
"code": null,
"e": 40877,
"s": 40858,
"text": "School Programming"
},
{
"code": null,
"e": 40975,
"s": 40877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40984,
"s": 40975,
"text": "Comments"
},
{
"code": null,
"e": 40997,
"s": 40984,
"text": "Old Comments"
},
{
"code": null,
"e": 41016,
"s": 40997,
"text": "Overriding in Java"
},
{
"code": null,
"e": 41036,
"s": 41016,
"text": "Constructors in C++"
},
{
"code": null,
"e": 41064,
"s": 41036,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 41088,
"s": 41064,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 41112,
"s": 41088,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 41139,
"s": 41112,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 41158,
"s": 41139,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 41178,
"s": 41158,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 41193,
"s": 41178,
"text": "C++ Data Types"
}
] |
Moneyball — Linear Regression. Using Linear Regression in Python to... | by Harry Bitten | Towards Data Science | In 2011, the film “Moneyball” was released. The film — adapted from the book by Micheal Lewis, is based on a true story, and follows Oakland A’s general manager Billy Beane, who, after losing his star players, must find a way to reach the playoffs whilst faced with a tight budget. Enter Paul DePodesta, an Ivy League graduate, who, using Sabermetrics, is able to identify the ‘bargain’ players in order to build the team that go on the A’s notorious 20 game win streak and see them finishing 1st in the regular season, throwing the art of sabermetrics into the limelight.
In this post, we will attempt to recreate pieces of DePodestas statistical analysis, using linear regression in python to model the 2002 regular season results.
Linear Regression
Linear Regression is one of the simplest forms of supervised machine learning which models a target prediction value (usually denoted by y) based on independent variables (usually denoted by X).
Y — The dependent variable (Target prediction value)
X — Independent variable(s)
β — Regression coefficients: These refer to the relationship between the x variable and the dependent variable y.
ε — Error term: used to denote the a residual variable produced by a statistical or mathematical model, which is created when the model does not fully represent the actual relationship between the independent variables and the dependent variables. As a result of this incomplete relationship, the error term is the amount at which the equation may differ during empirical analysis.
The job of a linear regression model is essentially to find a linear relationship between the input (X) and output (y).
The dataset used can be found at Kaggle and was originally gathered from baseball-reference.com.
The dataset contains many attributes (columns) as can be seen after importing the relevant modules, and opening with pandas (Note: the full raw code can be found at My Github)
df = pd.read_csv('csvs/baseball.csv')df.head()
The main attributes that we need to be concerned with are:
RS — Runs ScoredRA — Runs AllowedW — WinsOBP — On Base PercentageSLG — Slugging PercentageBA — Batting AveragePlayoffs — Whether a team made it to playoffs or notOOBP — Opponent’s On Base PercentageOSLG — Opponents Slugging Percentage
RS — Runs Scored
RA — Runs Allowed
W — Wins
OBP — On Base Percentage
SLG — Slugging Percentage
BA — Batting Average
Playoffs — Whether a team made it to playoffs or not
OOBP — Opponent’s On Base Percentage
OSLG — Opponents Slugging Percentage
Some of these are fairly self explanatory, however there are a few attributes that require some explaining:
OBP — On Base Percentage: This is a statistic measuring how frequently a batter reaches base, it does not take into account how far the batter runs i.e. third base.SLG — Slugging Percentage: A measure of the batting ‘Productivity’, in simple terms, it measures how far a batter makes it when they hit the ball.BA — Batting Average: Defined by the number of hits divided by at bats, measures how likely a batter is to hit a ball when pitched. Again, does not take into account how far the batter runs.
OBP — On Base Percentage: This is a statistic measuring how frequently a batter reaches base, it does not take into account how far the batter runs i.e. third base.
SLG — Slugging Percentage: A measure of the batting ‘Productivity’, in simple terms, it measures how far a batter makes it when they hit the ball.
BA — Batting Average: Defined by the number of hits divided by at bats, measures how likely a batter is to hit a ball when pitched. Again, does not take into account how far the batter runs.
Now, all three of these statistics are extremely important in this analysis. Pre-’Moneyball’, scouts mainly used Batting Average as a gauge of a good batter, and often a players BA would have a huge impact on their value/salary. However, DePodesta saw this as a mistake, claiming that scouts overvalued BA as a statistic, and massively undervalued OBP and SLG as a measure of a good batter. Billy Beane and the A’s were then able to obtain players with high OBP and SLG at bargain prices, because the scouts overlooked these attributes.
Data Wrangling
Let us add a new column; RD, which shows the difference between RS(Runs Scored), and RA(Runs Allowed). df['RD'] = df['RS'] - df['RA']
Let’s also make sure we only have pre-’Moneyball’ data, this can be done by only including data from before the 2002 regular season. df = df[df.Year < 2002]
Exploratory Data Analysis (EDA)
According to DePodesta, the A’s needed 99 wins in the regular season in order to make playoffs. We can create a plot to visualise this using Seaborn, which is a data visualisation library based on matplotlib.
Let’s start by defining a nice colour palette for our plots.
flatui = ["#6cdae7", "#fd3a4a", "#ffaa1d", "#ff23e5", "#34495e", "#2ecc71"]sns.set_palette(flatui)sns.palplot(sns.color_palette())
Now we can plot the Run Difference vs Wins to visualise DePodestas theory.
sns.lmplot(x = "W", y = "RS", fit_reg = False, hue = "Playoffs", data=df,height=7, aspect=1.25)plt.xlabel("Wins", fontsize = 20)plt.ylabel("Runs Scored", fontsize = 20)plt.axvline(99, 0, 1, color = "Black", ls = '--')plt.show()
As we can see, DePodestas theory seems accurate, as there has only ever been 3 instances where a team has not made playoffs with ≥ 99 wins (seen in the blue dots past the dashed black 99 wins ‘threshold’ line).
DePodesta also calculated that in order to win 99 games and make it to the playoffs, the A’s would have to score 814 runs, whilst allowing just 645, a run differential of 169. We can use many different methods to visualise the relationship between Run Difference and Wins, and we will use two of them.
Firstly, a simple scatterplot:
x = np.array(df.RD)y = np.array(df.W)slope, intercept = np.polyfit(x, y, 1)abline_values = [slope * i + intercept for i in x]plt.figure(figsize=(10,8))plt.scatter(x, y)plt.plot(x, abline_values, 'r')plt.title("Slope = %s" % (slope), fontsize = 12)plt.xlabel("Run Difference", fontsize =20)plt.ylabel("Wins", fontsize = 20)plt.axhline(99, 0, 1, color = "k", ls = '--')plt.show()
Secondly: We can use the Seaborn pairplot:
corrcheck = df[['RD', 'W', 'Playoffs']].copy()g = sns.pairplot(corrcheck, hue = 'Playoffs',vars=["RD", "W"])g.fig.set_size_inches(14,10)
We can already see that there is a clear linear relationship between the two, however, we can further verify this by using Pandas .corr(), which computes the pairwise correlation between columns.
corrcheck.corr(method='pearson')
We can see a correlation of 0.938515 between Wins and Run Difference, indicating an extremely strong relationship.
Now we know that Run Difference correlates so strongly with Wins, what attributes correlate strongly with Run Difference? As we previously mentioned, Scouts at the time relied heavily on Batting Average, and, according to DePodesta, undervalued On Base Percentage and Slugging Percentage. Again we can use the .corr() Pandas function, to compute the pairwise correlation between columns.
podesta = df[['OBP','SLG','BA','RS']]
podesta.corr(method='pearson')
Note the right hand column here, which shows RS’s relationship with OBP, SLG, and BA. We can see that Batting Average is actually the least correlated attribute in respect to Runs Scored, with a correlation of 0.83. Slugging Percentage and On Base Percentage are actually correlated more highly, with 0.93 and 0.90, respectively. This confirms DePodestas idea of the undervalue placed on SLG and OBP and the relative overvaluing of BA.
We can actually apply a bit of machine learning to further verify these claims. Firstly, by using univariate selection, to select those features that have the strongest relationship with the output variable(RD in this case). The scikit-learn library provides the SelectKBest class that allows us to pick a specific number of features. We will use the chi-squared statistical test for non-negative features to select the best features from our dataset. Firstly we need to use moneyball = df.dropna() to remove any null values from our dataset that would interfere with machine learning methods.
Then:
from sklearn.feature_selection import SelectKBestfrom sklearn.feature_selection import chi2 #we use RD as the target columnX = moneyball.iloc[:,6:9]y = moneyball.iloc[:,-1]#apply SelectKBest class to get best featuresbestfeatures = SelectKBest(score_func=chi2, k=3)fit = bestfeatures.fit(X,y)dfscores = pd.DataFrame(fit.scores_)dfcolumns = pd.DataFrame(X.columns)#concat two dataframes for better visualizationfeatureScores = pd.concat([dfcolumns,dfscores],axis=1)featureScores.columns = ['Feature','Score']print(featureScores.nlargest(3,'Score'))
Another method is to use feature importance that comes inbuilt with Tree Based Classifiers. Feature importance will give a score for each feature of the data, the higher the score, the more important or relevant the feature is towards the output variable.
X = moneyball.iloc[:,6:9] #independent columnsy = moneyball.iloc[:,-1] #target columnfrom sklearn.ensemble import ExtraTreesClassifier model = ExtraTreesClassifier()model.fit(X,y)print(model.feature_importances_)feat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(3).plot(kind='barh', figsize = (12,8))plt.xlabel("Importance", fontsize = 20)plt.ylabel("Statistic", fontsize = 20)
Model Building
Scikit-learn provides the functionality for us to build our linear regression models. First of all, we build a model for Runs Scored, predicted using On Base Percentage and Slugging Percentage.
x = df[['OBP','SLG']].valuesy = df[['RS']].values Runs = linear_model.LinearRegression() Runs.fit(x,y)print(Runs.intercept_) print(Runs.coef_)
We can then say that our Runs Scored model takes the form:
RS = -804.627 + (2737.768×(OBP)) + (1584.909×(SLG))
Next, we do the same but for modelling Runs Allowed, using Opponents On Base Percentage and Opponents Slugging Percentage.
x = moneyball[['OOBP','OSLG']].valuesy = moneyball[['RA']].valuesRunsAllowed = linear_model.LinearRegression()RunsAllowed.fit(x,y) print(RunsAllowed.intercept_)print(RunsAllowed.coef_)
We can then say that our Runs Allowed model takes the form:
RA = -775.162 + (3225.004 ×(OOBP)) + (1106.504 ×(OSLG))*
We then need to build a model to predict the number of Wins when given Run Difference.
x = moneyball[['RD']].valuesy = moneyball[['W']].valuesWins = linear_model.LinearRegression()Wins.fit(x,y) print(Wins.intercept_)print(Wins.coef_)
We can say that our Wins model takes the form:
W = 84.092 + (0.085 ×(RD))
Now all we have left to do is get OBP, SLG, OOBP, OSLG, and simply plug them into the models!
We know which players were transferred in and out after the 2001 season, so we can take 2001 player statistics to build the A’s new 2002 team.
The A’s 2002 team pre-season statistics taken from 2001:
OBP: 0.339
SLG: 0.430
OOBP: 0.307
OSLG: 0.373
Now lets create our predictions:
Runs.predict([[0.339,0.430]])
RunsAllowed.predict([[0.307,0.373]])
Meaning we get a RD of 177 (805–628), which we can then plug into our Wins model.
Wins.predict([[177]])
So, in the end, our model predicted 805 Runs Scored, 628 Runs Allowed, and 99 games won, meaning that our model predicted that the A’s would make the playoffs given their team statistics, which they did!
Lets compare our model to DePodestas predictions:
Limitations:
There are, of course, some limitations involved in this short project. For example: As we use a players previous years statistics, there is no guarantee they will be at the same level. For example, older players abilities may regress while younger players may grow. It is also important to note that we assume no injuries.
Limitations aside, the model performance is quite remarkable and really backs up DePodestas theory and explains why the techniques he used were so heavily adopted across the entirity of baseball soon after the Oakland A’s ‘Moneyball’ season.
Thank you so much for reading my first post! I intend to keep making posts like these, mainly using data analysis and machine learning. Any feedback is welcome. | [
{
"code": null,
"e": 744,
"s": 171,
"text": "In 2011, the film “Moneyball” was released. The film — adapted from the book by Micheal Lewis, is based on a true story, and follows Oakland A’s general manager Billy Beane, who, after losing his star players, must find a way to reach the playoffs whilst faced with a tight budget. Enter Paul DePodesta, an Ivy League graduate, who, using Sabermetrics, is able to identify the ‘bargain’ players in order to build the team that go on the A’s notorious 20 game win streak and see them finishing 1st in the regular season, throwing the art of sabermetrics into the limelight."
},
{
"code": null,
"e": 905,
"s": 744,
"text": "In this post, we will attempt to recreate pieces of DePodestas statistical analysis, using linear regression in python to model the 2002 regular season results."
},
{
"code": null,
"e": 923,
"s": 905,
"text": "Linear Regression"
},
{
"code": null,
"e": 1118,
"s": 923,
"text": "Linear Regression is one of the simplest forms of supervised machine learning which models a target prediction value (usually denoted by y) based on independent variables (usually denoted by X)."
},
{
"code": null,
"e": 1171,
"s": 1118,
"text": "Y — The dependent variable (Target prediction value)"
},
{
"code": null,
"e": 1199,
"s": 1171,
"text": "X — Independent variable(s)"
},
{
"code": null,
"e": 1313,
"s": 1199,
"text": "β — Regression coefficients: These refer to the relationship between the x variable and the dependent variable y."
},
{
"code": null,
"e": 1695,
"s": 1313,
"text": "ε — Error term: used to denote the a residual variable produced by a statistical or mathematical model, which is created when the model does not fully represent the actual relationship between the independent variables and the dependent variables. As a result of this incomplete relationship, the error term is the amount at which the equation may differ during empirical analysis."
},
{
"code": null,
"e": 1815,
"s": 1695,
"text": "The job of a linear regression model is essentially to find a linear relationship between the input (X) and output (y)."
},
{
"code": null,
"e": 1912,
"s": 1815,
"text": "The dataset used can be found at Kaggle and was originally gathered from baseball-reference.com."
},
{
"code": null,
"e": 2088,
"s": 1912,
"text": "The dataset contains many attributes (columns) as can be seen after importing the relevant modules, and opening with pandas (Note: the full raw code can be found at My Github)"
},
{
"code": null,
"e": 2135,
"s": 2088,
"text": "df = pd.read_csv('csvs/baseball.csv')df.head()"
},
{
"code": null,
"e": 2194,
"s": 2135,
"text": "The main attributes that we need to be concerned with are:"
},
{
"code": null,
"e": 2429,
"s": 2194,
"text": "RS — Runs ScoredRA — Runs AllowedW — WinsOBP — On Base PercentageSLG — Slugging PercentageBA — Batting AveragePlayoffs — Whether a team made it to playoffs or notOOBP — Opponent’s On Base PercentageOSLG — Opponents Slugging Percentage"
},
{
"code": null,
"e": 2446,
"s": 2429,
"text": "RS — Runs Scored"
},
{
"code": null,
"e": 2464,
"s": 2446,
"text": "RA — Runs Allowed"
},
{
"code": null,
"e": 2473,
"s": 2464,
"text": "W — Wins"
},
{
"code": null,
"e": 2498,
"s": 2473,
"text": "OBP — On Base Percentage"
},
{
"code": null,
"e": 2524,
"s": 2498,
"text": "SLG — Slugging Percentage"
},
{
"code": null,
"e": 2545,
"s": 2524,
"text": "BA — Batting Average"
},
{
"code": null,
"e": 2598,
"s": 2545,
"text": "Playoffs — Whether a team made it to playoffs or not"
},
{
"code": null,
"e": 2635,
"s": 2598,
"text": "OOBP — Opponent’s On Base Percentage"
},
{
"code": null,
"e": 2672,
"s": 2635,
"text": "OSLG — Opponents Slugging Percentage"
},
{
"code": null,
"e": 2780,
"s": 2672,
"text": "Some of these are fairly self explanatory, however there are a few attributes that require some explaining:"
},
{
"code": null,
"e": 3281,
"s": 2780,
"text": "OBP — On Base Percentage: This is a statistic measuring how frequently a batter reaches base, it does not take into account how far the batter runs i.e. third base.SLG — Slugging Percentage: A measure of the batting ‘Productivity’, in simple terms, it measures how far a batter makes it when they hit the ball.BA — Batting Average: Defined by the number of hits divided by at bats, measures how likely a batter is to hit a ball when pitched. Again, does not take into account how far the batter runs."
},
{
"code": null,
"e": 3446,
"s": 3281,
"text": "OBP — On Base Percentage: This is a statistic measuring how frequently a batter reaches base, it does not take into account how far the batter runs i.e. third base."
},
{
"code": null,
"e": 3593,
"s": 3446,
"text": "SLG — Slugging Percentage: A measure of the batting ‘Productivity’, in simple terms, it measures how far a batter makes it when they hit the ball."
},
{
"code": null,
"e": 3784,
"s": 3593,
"text": "BA — Batting Average: Defined by the number of hits divided by at bats, measures how likely a batter is to hit a ball when pitched. Again, does not take into account how far the batter runs."
},
{
"code": null,
"e": 4321,
"s": 3784,
"text": "Now, all three of these statistics are extremely important in this analysis. Pre-’Moneyball’, scouts mainly used Batting Average as a gauge of a good batter, and often a players BA would have a huge impact on their value/salary. However, DePodesta saw this as a mistake, claiming that scouts overvalued BA as a statistic, and massively undervalued OBP and SLG as a measure of a good batter. Billy Beane and the A’s were then able to obtain players with high OBP and SLG at bargain prices, because the scouts overlooked these attributes."
},
{
"code": null,
"e": 4336,
"s": 4321,
"text": "Data Wrangling"
},
{
"code": null,
"e": 4470,
"s": 4336,
"text": "Let us add a new column; RD, which shows the difference between RS(Runs Scored), and RA(Runs Allowed). df['RD'] = df['RS'] - df['RA']"
},
{
"code": null,
"e": 4627,
"s": 4470,
"text": "Let’s also make sure we only have pre-’Moneyball’ data, this can be done by only including data from before the 2002 regular season. df = df[df.Year < 2002]"
},
{
"code": null,
"e": 4659,
"s": 4627,
"text": "Exploratory Data Analysis (EDA)"
},
{
"code": null,
"e": 4868,
"s": 4659,
"text": "According to DePodesta, the A’s needed 99 wins in the regular season in order to make playoffs. We can create a plot to visualise this using Seaborn, which is a data visualisation library based on matplotlib."
},
{
"code": null,
"e": 4929,
"s": 4868,
"text": "Let’s start by defining a nice colour palette for our plots."
},
{
"code": null,
"e": 5060,
"s": 4929,
"text": "flatui = [\"#6cdae7\", \"#fd3a4a\", \"#ffaa1d\", \"#ff23e5\", \"#34495e\", \"#2ecc71\"]sns.set_palette(flatui)sns.palplot(sns.color_palette())"
},
{
"code": null,
"e": 5135,
"s": 5060,
"text": "Now we can plot the Run Difference vs Wins to visualise DePodestas theory."
},
{
"code": null,
"e": 5363,
"s": 5135,
"text": "sns.lmplot(x = \"W\", y = \"RS\", fit_reg = False, hue = \"Playoffs\", data=df,height=7, aspect=1.25)plt.xlabel(\"Wins\", fontsize = 20)plt.ylabel(\"Runs Scored\", fontsize = 20)plt.axvline(99, 0, 1, color = \"Black\", ls = '--')plt.show()"
},
{
"code": null,
"e": 5574,
"s": 5363,
"text": "As we can see, DePodestas theory seems accurate, as there has only ever been 3 instances where a team has not made playoffs with ≥ 99 wins (seen in the blue dots past the dashed black 99 wins ‘threshold’ line)."
},
{
"code": null,
"e": 5876,
"s": 5574,
"text": "DePodesta also calculated that in order to win 99 games and make it to the playoffs, the A’s would have to score 814 runs, whilst allowing just 645, a run differential of 169. We can use many different methods to visualise the relationship between Run Difference and Wins, and we will use two of them."
},
{
"code": null,
"e": 5907,
"s": 5876,
"text": "Firstly, a simple scatterplot:"
},
{
"code": null,
"e": 6285,
"s": 5907,
"text": "x = np.array(df.RD)y = np.array(df.W)slope, intercept = np.polyfit(x, y, 1)abline_values = [slope * i + intercept for i in x]plt.figure(figsize=(10,8))plt.scatter(x, y)plt.plot(x, abline_values, 'r')plt.title(\"Slope = %s\" % (slope), fontsize = 12)plt.xlabel(\"Run Difference\", fontsize =20)plt.ylabel(\"Wins\", fontsize = 20)plt.axhline(99, 0, 1, color = \"k\", ls = '--')plt.show()"
},
{
"code": null,
"e": 6328,
"s": 6285,
"text": "Secondly: We can use the Seaborn pairplot:"
},
{
"code": null,
"e": 6465,
"s": 6328,
"text": "corrcheck = df[['RD', 'W', 'Playoffs']].copy()g = sns.pairplot(corrcheck, hue = 'Playoffs',vars=[\"RD\", \"W\"])g.fig.set_size_inches(14,10)"
},
{
"code": null,
"e": 6661,
"s": 6465,
"text": "We can already see that there is a clear linear relationship between the two, however, we can further verify this by using Pandas .corr(), which computes the pairwise correlation between columns."
},
{
"code": null,
"e": 6694,
"s": 6661,
"text": "corrcheck.corr(method='pearson')"
},
{
"code": null,
"e": 6809,
"s": 6694,
"text": "We can see a correlation of 0.938515 between Wins and Run Difference, indicating an extremely strong relationship."
},
{
"code": null,
"e": 7197,
"s": 6809,
"text": "Now we know that Run Difference correlates so strongly with Wins, what attributes correlate strongly with Run Difference? As we previously mentioned, Scouts at the time relied heavily on Batting Average, and, according to DePodesta, undervalued On Base Percentage and Slugging Percentage. Again we can use the .corr() Pandas function, to compute the pairwise correlation between columns."
},
{
"code": null,
"e": 7235,
"s": 7197,
"text": "podesta = df[['OBP','SLG','BA','RS']]"
},
{
"code": null,
"e": 7266,
"s": 7235,
"text": "podesta.corr(method='pearson')"
},
{
"code": null,
"e": 7702,
"s": 7266,
"text": "Note the right hand column here, which shows RS’s relationship with OBP, SLG, and BA. We can see that Batting Average is actually the least correlated attribute in respect to Runs Scored, with a correlation of 0.83. Slugging Percentage and On Base Percentage are actually correlated more highly, with 0.93 and 0.90, respectively. This confirms DePodestas idea of the undervalue placed on SLG and OBP and the relative overvaluing of BA."
},
{
"code": null,
"e": 8296,
"s": 7702,
"text": "We can actually apply a bit of machine learning to further verify these claims. Firstly, by using univariate selection, to select those features that have the strongest relationship with the output variable(RD in this case). The scikit-learn library provides the SelectKBest class that allows us to pick a specific number of features. We will use the chi-squared statistical test for non-negative features to select the best features from our dataset. Firstly we need to use moneyball = df.dropna() to remove any null values from our dataset that would interfere with machine learning methods."
},
{
"code": null,
"e": 8302,
"s": 8296,
"text": "Then:"
},
{
"code": null,
"e": 8850,
"s": 8302,
"text": "from sklearn.feature_selection import SelectKBestfrom sklearn.feature_selection import chi2 #we use RD as the target columnX = moneyball.iloc[:,6:9]y = moneyball.iloc[:,-1]#apply SelectKBest class to get best featuresbestfeatures = SelectKBest(score_func=chi2, k=3)fit = bestfeatures.fit(X,y)dfscores = pd.DataFrame(fit.scores_)dfcolumns = pd.DataFrame(X.columns)#concat two dataframes for better visualizationfeatureScores = pd.concat([dfcolumns,dfscores],axis=1)featureScores.columns = ['Feature','Score']print(featureScores.nlargest(3,'Score'))"
},
{
"code": null,
"e": 9106,
"s": 8850,
"text": "Another method is to use feature importance that comes inbuilt with Tree Based Classifiers. Feature importance will give a score for each feature of the data, the higher the score, the more important or relevant the feature is towards the output variable."
},
{
"code": null,
"e": 9537,
"s": 9106,
"text": "X = moneyball.iloc[:,6:9] #independent columnsy = moneyball.iloc[:,-1] #target columnfrom sklearn.ensemble import ExtraTreesClassifier model = ExtraTreesClassifier()model.fit(X,y)print(model.feature_importances_)feat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(3).plot(kind='barh', figsize = (12,8))plt.xlabel(\"Importance\", fontsize = 20)plt.ylabel(\"Statistic\", fontsize = 20)"
},
{
"code": null,
"e": 9552,
"s": 9537,
"text": "Model Building"
},
{
"code": null,
"e": 9746,
"s": 9552,
"text": "Scikit-learn provides the functionality for us to build our linear regression models. First of all, we build a model for Runs Scored, predicted using On Base Percentage and Slugging Percentage."
},
{
"code": null,
"e": 9889,
"s": 9746,
"text": "x = df[['OBP','SLG']].valuesy = df[['RS']].values Runs = linear_model.LinearRegression() Runs.fit(x,y)print(Runs.intercept_) print(Runs.coef_)"
},
{
"code": null,
"e": 9948,
"s": 9889,
"text": "We can then say that our Runs Scored model takes the form:"
},
{
"code": null,
"e": 10000,
"s": 9948,
"text": "RS = -804.627 + (2737.768×(OBP)) + (1584.909×(SLG))"
},
{
"code": null,
"e": 10123,
"s": 10000,
"text": "Next, we do the same but for modelling Runs Allowed, using Opponents On Base Percentage and Opponents Slugging Percentage."
},
{
"code": null,
"e": 10308,
"s": 10123,
"text": "x = moneyball[['OOBP','OSLG']].valuesy = moneyball[['RA']].valuesRunsAllowed = linear_model.LinearRegression()RunsAllowed.fit(x,y) print(RunsAllowed.intercept_)print(RunsAllowed.coef_)"
},
{
"code": null,
"e": 10368,
"s": 10308,
"text": "We can then say that our Runs Allowed model takes the form:"
},
{
"code": null,
"e": 10425,
"s": 10368,
"text": "RA = -775.162 + (3225.004 ×(OOBP)) + (1106.504 ×(OSLG))*"
},
{
"code": null,
"e": 10512,
"s": 10425,
"text": "We then need to build a model to predict the number of Wins when given Run Difference."
},
{
"code": null,
"e": 10659,
"s": 10512,
"text": "x = moneyball[['RD']].valuesy = moneyball[['W']].valuesWins = linear_model.LinearRegression()Wins.fit(x,y) print(Wins.intercept_)print(Wins.coef_)"
},
{
"code": null,
"e": 10706,
"s": 10659,
"text": "We can say that our Wins model takes the form:"
},
{
"code": null,
"e": 10733,
"s": 10706,
"text": "W = 84.092 + (0.085 ×(RD))"
},
{
"code": null,
"e": 10827,
"s": 10733,
"text": "Now all we have left to do is get OBP, SLG, OOBP, OSLG, and simply plug them into the models!"
},
{
"code": null,
"e": 10970,
"s": 10827,
"text": "We know which players were transferred in and out after the 2001 season, so we can take 2001 player statistics to build the A’s new 2002 team."
},
{
"code": null,
"e": 11027,
"s": 10970,
"text": "The A’s 2002 team pre-season statistics taken from 2001:"
},
{
"code": null,
"e": 11038,
"s": 11027,
"text": "OBP: 0.339"
},
{
"code": null,
"e": 11049,
"s": 11038,
"text": "SLG: 0.430"
},
{
"code": null,
"e": 11061,
"s": 11049,
"text": "OOBP: 0.307"
},
{
"code": null,
"e": 11073,
"s": 11061,
"text": "OSLG: 0.373"
},
{
"code": null,
"e": 11106,
"s": 11073,
"text": "Now lets create our predictions:"
},
{
"code": null,
"e": 11136,
"s": 11106,
"text": "Runs.predict([[0.339,0.430]])"
},
{
"code": null,
"e": 11173,
"s": 11136,
"text": "RunsAllowed.predict([[0.307,0.373]])"
},
{
"code": null,
"e": 11255,
"s": 11173,
"text": "Meaning we get a RD of 177 (805–628), which we can then plug into our Wins model."
},
{
"code": null,
"e": 11277,
"s": 11255,
"text": "Wins.predict([[177]])"
},
{
"code": null,
"e": 11481,
"s": 11277,
"text": "So, in the end, our model predicted 805 Runs Scored, 628 Runs Allowed, and 99 games won, meaning that our model predicted that the A’s would make the playoffs given their team statistics, which they did!"
},
{
"code": null,
"e": 11531,
"s": 11481,
"text": "Lets compare our model to DePodestas predictions:"
},
{
"code": null,
"e": 11544,
"s": 11531,
"text": "Limitations:"
},
{
"code": null,
"e": 11867,
"s": 11544,
"text": "There are, of course, some limitations involved in this short project. For example: As we use a players previous years statistics, there is no guarantee they will be at the same level. For example, older players abilities may regress while younger players may grow. It is also important to note that we assume no injuries."
},
{
"code": null,
"e": 12109,
"s": 11867,
"text": "Limitations aside, the model performance is quite remarkable and really backs up DePodestas theory and explains why the techniques he used were so heavily adopted across the entirity of baseball soon after the Oakland A’s ‘Moneyball’ season."
}
] |
Dual Boot is Dead: Windows and Linux are now One | by Dimitris Poulopoulos | Towards Data Science | I used to have an Apple laptop as my daily driver. I could do almost everything there; development, proposal writing, music composition etc. But the fear of vendor lock-in, the concern that I am depended on Apple’s whims and vices — which are arguably very expensive — led me to seek a new solution.
See Part II here:
towardsdatascience.com
I started building a machine learning workstation; a great CPU, lots of RAM and a competent GPU, among others. My OS of choice for almost anything was Ubuntu, except I needed Microsoft Office for proposal writing. Office online is just not there yet and, let’s face it, LibreOffice is a disaster. So, the solution was to dual boot Ubuntu and Windows 10. The freedom you experience moving from Apple to Ubuntu is unparalleled, and the options you have building your own PC are almost infinite.
Dual boot was the answer for a long time. One million of context switches later, WSL came. Thus, I started moving a portion of my workflow to Windows. But still, there were many things missing. However, WSL 2 seems to be a game-changer. In this story, I will show you how to move your development workflow to Windows 10 and WSL 2, its new features and what to expect in the near future.
Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!
WSL 2 is the new version of the architecture in WSL. This version comes with several changes that dictate how Linux distributions interact with Windows.
With this release, you get increased file system performance and a full system call compatibility. Of course, you can choose to run your Linux distribution as either WSL 1 or WSL 2, and, moreover, you can switch between those versions at any time. WSL 2 is a major overhaul of the underlying architecture and uses virtualization technology and a Linux kernel to enable its new features. But Microsoft handles the nitty-gritty details so you can focus on what matters.
Microsoft promises a smooth installation experience in the near future for WSL 2 and the ability to update the Linux kernel via Windows updates. For now, the installation process is a bit more involved but nothing scary.
In this example, we will install Ubuntu 20.04 on Windows 10. But the process is the same for any distribution available in Microsoft store. First, you should enable the Windows Subsystem for Linux optional feature. Open PowerShell as Administrator and run the following command:
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
On the next step, we will update our system to WSL 2. For this, Windows 10 must be updated to version 2004 and Intel’s virtualization technology must be enabled in BIOS settings. Launch PowerShell as Administrator and run the following command:
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
Restart your machine to complete the WSL install and update to WSL 2. Then, you need to set WSL 2 as our default version when installing a new distribution. For this, open PowerShell as Administrator and run the following command:
wsl --set-default-version 2
You might see this message after running that command: WSL 2 requires an update to its kernel component. For information please visit https://aka.ms/wsl2kernel. Follow the link and install the MSI from that page to install a Linux kernel on your machine for WSL 2 to use. Once you have the kernel installed, run the command again and it should complete successfully without showing the message.
Last but not least, we should install a Linux distribution. Open the Microsoft store and search for Ubuntu 20.04 LTS. After installing it, you should be able to find a new Ubuntu app on our start menu. Launch it and follow the instructions (mainly create a new UNIX user) to finalize the installation.
To check whether your Linux distribution is installed on WSL 2 run wsl --list --verbose. If the result indicates that it uses WSL 1 you can change it by running wsl --set-version <distribution name> <versionNumber>.
And that’s it. You now have a complete Ubuntu distribution running inside Windows 10!
Having Ubuntu up and ready, you can now install whatever you need. For example, you can install the latest Anaconda distribution if you are a data scientist, angular and npm if you are a front-end engineer and many more. But there are two tools I would like to focus on: Visual Studio Code and Docker + Kubernetes.
Visual Studio Code is the IDE of choice for many developers. Now that we have WSL 2 enabled, the absolutely necessary extension for VS Code is Remote Development.
This plug-in enables remote development against source code that exists on WSL 2, a container image or even a remote VM via SSH. Thus, we can now create our project folders inside our Linux distribution running on WSL 2 and use the Visual Studio Code editor installed on Windows 10 as our IDE.
All the features are there: full language support with IntelliSense, git integration, Visual Studio Code extensions we know and love, the debugger and the terminal. So, get your hands dirty and start coding!
Docker for Windows is good but not great. That was the thing that I was missing the most, the thing that was making me switch between Windows and Ubuntu whenever I needed to build a docker image for my code. But WSL 2 comes with full docker support which, in my opinion, is even better than the pure Linux experience.
To enable it, navigate to your Docker Desktop settings and enable the Use the WSL 2 based engine option.
Moreover, you can run a local Kubernetes cluster, by navigating to the Kubernetes section of the settings and ticking the box.
You can now return to Ubuntu on WSL 2, run docker version or kubectl version and see that the two are up and running.
For an added bonus, you can install the new Windows Terminal. The store description defines the new Windows Terminal as a modern, fast, efficient, powerful, and productive terminal application for users of command-line tools and shells like Command Prompt, PowerShell, and WSL. Its main features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and custom themes, styles, and configurations.
Moreover, it is very beautiful and you can style it however you want, through its accessible settings that are just a JSON file. Look here for inspiration! More on the new Windows Terminal here:
towardsdatascience.com
There are still some features missing, but WSL 2 is on the right path. In the upcoming months, you will be able to install WSL with a single command. Just open a Windows Terminal and enter wsl.exe --install. Also, WSL 2 will be the new default when installing for the first time.
But there are two features that developers expect the most: GPU support and GUI app support.
Adding CUDA and/or GPU Compute support to WSL is the most requested feature since the release of WSL 1. Over the last years, the WSL, Virtualization, DirectX, Windows Driver teams, and other partners have been working hard on this engineering feature. So stay tuned!
Furthermore, support for Linux GUI apps is coming as well. For example, you will be able to run your preferred Linux GUI text editor or IDE in the Linux environment you have installed. You will be able to even develop Linux GUI apps, all in your Windows machine!
In this story, we saw how WSL 2 can turn your Windows PC into a developer workstation running a Linux distribution. The speed is there, the features are there, more are coming up, thus, I would argue that dual boot is dead!
Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!
My name is Dimitris Poulopoulos and I’m a machine learning researcher working for BigDataStack. I am also a PhD student at the University of Piraeus, Greece. I have worked on designing and implementing AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA.
If you are interested in reading more posts about Machine Learning, Deep Learning, Data Science and DataOps follow me on Medium, LinkedIn or @james2pl on twitter. | [
{
"code": null,
"e": 472,
"s": 172,
"text": "I used to have an Apple laptop as my daily driver. I could do almost everything there; development, proposal writing, music composition etc. But the fear of vendor lock-in, the concern that I am depended on Apple’s whims and vices — which are arguably very expensive — led me to seek a new solution."
},
{
"code": null,
"e": 490,
"s": 472,
"text": "See Part II here:"
},
{
"code": null,
"e": 513,
"s": 490,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1006,
"s": 513,
"text": "I started building a machine learning workstation; a great CPU, lots of RAM and a competent GPU, among others. My OS of choice for almost anything was Ubuntu, except I needed Microsoft Office for proposal writing. Office online is just not there yet and, let’s face it, LibreOffice is a disaster. So, the solution was to dual boot Ubuntu and Windows 10. The freedom you experience moving from Apple to Ubuntu is unparalleled, and the options you have building your own PC are almost infinite."
},
{
"code": null,
"e": 1393,
"s": 1006,
"text": "Dual boot was the answer for a long time. One million of context switches later, WSL came. Thus, I started moving a portion of my workflow to Windows. But still, there were many things missing. However, WSL 2 seems to be a game-changer. In this story, I will show you how to move your development workflow to Windows 10 and WSL 2, its new features and what to expect in the near future."
},
{
"code": null,
"e": 1615,
"s": 1393,
"text": "Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!"
},
{
"code": null,
"e": 1768,
"s": 1615,
"text": "WSL 2 is the new version of the architecture in WSL. This version comes with several changes that dictate how Linux distributions interact with Windows."
},
{
"code": null,
"e": 2236,
"s": 1768,
"text": "With this release, you get increased file system performance and a full system call compatibility. Of course, you can choose to run your Linux distribution as either WSL 1 or WSL 2, and, moreover, you can switch between those versions at any time. WSL 2 is a major overhaul of the underlying architecture and uses virtualization technology and a Linux kernel to enable its new features. But Microsoft handles the nitty-gritty details so you can focus on what matters."
},
{
"code": null,
"e": 2457,
"s": 2236,
"text": "Microsoft promises a smooth installation experience in the near future for WSL 2 and the ability to update the Linux kernel via Windows updates. For now, the installation process is a bit more involved but nothing scary."
},
{
"code": null,
"e": 2736,
"s": 2457,
"text": "In this example, we will install Ubuntu 20.04 on Windows 10. But the process is the same for any distribution available in Microsoft store. First, you should enable the Windows Subsystem for Linux optional feature. Open PowerShell as Administrator and run the following command:"
},
{
"code": null,
"e": 2832,
"s": 2736,
"text": "dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart"
},
{
"code": null,
"e": 3077,
"s": 2832,
"text": "On the next step, we will update our system to WSL 2. For this, Windows 10 must be updated to version 2004 and Intel’s virtualization technology must be enabled in BIOS settings. Launch PowerShell as Administrator and run the following command:"
},
{
"code": null,
"e": 3162,
"s": 3077,
"text": "dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart"
},
{
"code": null,
"e": 3393,
"s": 3162,
"text": "Restart your machine to complete the WSL install and update to WSL 2. Then, you need to set WSL 2 as our default version when installing a new distribution. For this, open PowerShell as Administrator and run the following command:"
},
{
"code": null,
"e": 3421,
"s": 3393,
"text": "wsl --set-default-version 2"
},
{
"code": null,
"e": 3816,
"s": 3421,
"text": "You might see this message after running that command: WSL 2 requires an update to its kernel component. For information please visit https://aka.ms/wsl2kernel. Follow the link and install the MSI from that page to install a Linux kernel on your machine for WSL 2 to use. Once you have the kernel installed, run the command again and it should complete successfully without showing the message."
},
{
"code": null,
"e": 4118,
"s": 3816,
"text": "Last but not least, we should install a Linux distribution. Open the Microsoft store and search for Ubuntu 20.04 LTS. After installing it, you should be able to find a new Ubuntu app on our start menu. Launch it and follow the instructions (mainly create a new UNIX user) to finalize the installation."
},
{
"code": null,
"e": 4334,
"s": 4118,
"text": "To check whether your Linux distribution is installed on WSL 2 run wsl --list --verbose. If the result indicates that it uses WSL 1 you can change it by running wsl --set-version <distribution name> <versionNumber>."
},
{
"code": null,
"e": 4420,
"s": 4334,
"text": "And that’s it. You now have a complete Ubuntu distribution running inside Windows 10!"
},
{
"code": null,
"e": 4735,
"s": 4420,
"text": "Having Ubuntu up and ready, you can now install whatever you need. For example, you can install the latest Anaconda distribution if you are a data scientist, angular and npm if you are a front-end engineer and many more. But there are two tools I would like to focus on: Visual Studio Code and Docker + Kubernetes."
},
{
"code": null,
"e": 4898,
"s": 4735,
"text": "Visual Studio Code is the IDE of choice for many developers. Now that we have WSL 2 enabled, the absolutely necessary extension for VS Code is Remote Development."
},
{
"code": null,
"e": 5192,
"s": 4898,
"text": "This plug-in enables remote development against source code that exists on WSL 2, a container image or even a remote VM via SSH. Thus, we can now create our project folders inside our Linux distribution running on WSL 2 and use the Visual Studio Code editor installed on Windows 10 as our IDE."
},
{
"code": null,
"e": 5400,
"s": 5192,
"text": "All the features are there: full language support with IntelliSense, git integration, Visual Studio Code extensions we know and love, the debugger and the terminal. So, get your hands dirty and start coding!"
},
{
"code": null,
"e": 5718,
"s": 5400,
"text": "Docker for Windows is good but not great. That was the thing that I was missing the most, the thing that was making me switch between Windows and Ubuntu whenever I needed to build a docker image for my code. But WSL 2 comes with full docker support which, in my opinion, is even better than the pure Linux experience."
},
{
"code": null,
"e": 5823,
"s": 5718,
"text": "To enable it, navigate to your Docker Desktop settings and enable the Use the WSL 2 based engine option."
},
{
"code": null,
"e": 5950,
"s": 5823,
"text": "Moreover, you can run a local Kubernetes cluster, by navigating to the Kubernetes section of the settings and ticking the box."
},
{
"code": null,
"e": 6068,
"s": 5950,
"text": "You can now return to Ubuntu on WSL 2, run docker version or kubectl version and see that the two are up and running."
},
{
"code": null,
"e": 6519,
"s": 6068,
"text": "For an added bonus, you can install the new Windows Terminal. The store description defines the new Windows Terminal as a modern, fast, efficient, powerful, and productive terminal application for users of command-line tools and shells like Command Prompt, PowerShell, and WSL. Its main features include multiple tabs, panes, Unicode and UTF-8 character support, a GPU accelerated text rendering engine, and custom themes, styles, and configurations."
},
{
"code": null,
"e": 6714,
"s": 6519,
"text": "Moreover, it is very beautiful and you can style it however you want, through its accessible settings that are just a JSON file. Look here for inspiration! More on the new Windows Terminal here:"
},
{
"code": null,
"e": 6737,
"s": 6714,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7017,
"s": 6737,
"text": "There are still some features missing, but WSL 2 is on the right path. In the upcoming months, you will be able to install WSL with a single command. Just open a Windows Terminal and enter wsl.exe --install. Also, WSL 2 will be the new default when installing for the first time."
},
{
"code": null,
"e": 7110,
"s": 7017,
"text": "But there are two features that developers expect the most: GPU support and GUI app support."
},
{
"code": null,
"e": 7377,
"s": 7110,
"text": "Adding CUDA and/or GPU Compute support to WSL is the most requested feature since the release of WSL 1. Over the last years, the WSL, Virtualization, DirectX, Windows Driver teams, and other partners have been working hard on this engineering feature. So stay tuned!"
},
{
"code": null,
"e": 7640,
"s": 7377,
"text": "Furthermore, support for Linux GUI apps is coming as well. For example, you will be able to run your preferred Linux GUI text editor or IDE in the Linux environment you have installed. You will be able to even develop Linux GUI apps, all in your Windows machine!"
},
{
"code": null,
"e": 7864,
"s": 7640,
"text": "In this story, we saw how WSL 2 can turn your Windows PC into a developer workstation running a Linux distribution. The speed is there, the features are there, more are coming up, thus, I would argue that dual boot is dead!"
},
{
"code": null,
"e": 8086,
"s": 7864,
"text": "Learning Rate is my weekly newsletter for those who are curious about the world of AI and MLOps. You’ll hear from me every Friday with updates and thoughts on the latest AI news, research, repos and books. Subscribe here!"
},
{
"code": null,
"e": 8423,
"s": 8086,
"text": "My name is Dimitris Poulopoulos and I’m a machine learning researcher working for BigDataStack. I am also a PhD student at the University of Piraeus, Greece. I have worked on designing and implementing AI and software solutions for major clients such as the European Commission, Eurostat, IMF, the European Central Bank, OECD, and IKEA."
}
] |
MariaDB - Drop Tables | In this chapter, we will learn to delete tables.
Table deletion is very easy, but remember all deleted tables are irrecoverable. The general syntax for table deletion is as follows −
DROP TABLE table_name ;
Two options exist for performing a table drop: use the command prompt or a PHP script.
At the command prompt, simply use the DROP TABLE SQL command −
root@host# mysql -u root -p
Enter password:*******
mysql> use PRODUCTS;
Database changed
mysql> DROP TABLE products_tbl
mysql> SELECT * from products_tbl
ERROR 1146 (42S02): Table 'products_tbl' doesn't exist
PHP provides mysql_query() for dropping tables. Simply pass its second argument the appropriate SQL command −
<html>
<head>
<title>Create a MariaDB Table</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "DROP TABLE products_tbl";
mysql_select_db( 'PRODUCTS' );
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not delete table: ' . mysql_error());
}
echo "Table deleted successfully\n";
mysql_close($conn);
?>
</body>
</html>
On successful table deletion, you will see the following output −
mysql> Table deleted successfully
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2411,
"s": 2362,
"text": "In this chapter, we will learn to delete tables."
},
{
"code": null,
"e": 2545,
"s": 2411,
"text": "Table deletion is very easy, but remember all deleted tables are irrecoverable. The general syntax for table deletion is as follows −"
},
{
"code": null,
"e": 2570,
"s": 2545,
"text": "DROP TABLE table_name ;\n"
},
{
"code": null,
"e": 2657,
"s": 2570,
"text": "Two options exist for performing a table drop: use the command prompt or a PHP script."
},
{
"code": null,
"e": 2720,
"s": 2657,
"text": "At the command prompt, simply use the DROP TABLE SQL command −"
},
{
"code": null,
"e": 2931,
"s": 2720,
"text": "root@host# mysql -u root -p\nEnter password:*******\nmysql> use PRODUCTS;\nDatabase changed\nmysql> DROP TABLE products_tbl\n\nmysql> SELECT * from products_tbl\nERROR 1146 (42S02): Table 'products_tbl' doesn't exist\n"
},
{
"code": null,
"e": 3041,
"s": 2931,
"text": "PHP provides mysql_query() for dropping tables. Simply pass its second argument the appropriate SQL command −"
},
{
"code": null,
"e": 3799,
"s": 3041,
"text": "<html>\n <head>\n <title>Create a MariaDB Table</title>\n </head>\n\n <body>\n <?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n echo 'Connected successfully<br />';\n \n $sql = \"DROP TABLE products_tbl\";\n mysql_select_db( 'PRODUCTS' );\n $retval = mysql_query( $sql, $conn );\n \n if(! $retval ) {\n die('Could not delete table: ' . mysql_error());\n }\n echo \"Table deleted successfully\\n\";\n \n mysql_close($conn);\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 3865,
"s": 3799,
"text": "On successful table deletion, you will see the following output −"
},
{
"code": null,
"e": 3900,
"s": 3865,
"text": "mysql> Table deleted successfully\n"
},
{
"code": null,
"e": 3907,
"s": 3900,
"text": " Print"
},
{
"code": null,
"e": 3918,
"s": 3907,
"text": " Add Notes"
}
] |
Accessing nested JavaScript objects with string key | You can use lodash's get method to get properties at any level safely. Getting first-level properties is pretty straightforward. Nested property access is tricky and you should use a tested library like lodash for it.
You can access a deeply nested object in the following way −
let _ = require("lodash");
let obj = {
a: {
b: {
foo: "test"
},
c: 2
}
};
console.log(_.get(obj, "a.b.foo"));
console.log(_.get(obj, "a.c"));
console.log(_.get(obj, "a.test"));
console.log(_.get(obj, "a.test.x"));
This will give the output −
test
2
undefined
undefined
You can also write your own getProp function in the following way −
const getProp = (object, path) => {
if (path.length === 1) return object[path[0]];
else if (path.length === 0) throw error;
else {
if (object[path[0]]) return getProp(object[path[0]], path.slice(1));
else {
object[path[0]] = {};
return getProp(object[path[0]], path.slice(1));
}
}
};
You can use it by passing an array to access the props.
var obj = {
level1:{
level2:{
level3:{
name: "Foo"
}
},
anotherLevel2: "bar"
}
};
console.log(getProp(obj, ["level1", "level2"]));
This will give the output −
{level3: {name: "Foo"}} | [
{
"code": null,
"e": 1280,
"s": 1062,
"text": "You can use lodash's get method to get properties at any level safely. Getting first-level properties is pretty straightforward. Nested property access is tricky and you should use a tested library like lodash for it."
},
{
"code": null,
"e": 1341,
"s": 1280,
"text": "You can access a deeply nested object in the following way −"
},
{
"code": null,
"e": 1588,
"s": 1341,
"text": "let _ = require(\"lodash\");\nlet obj = {\n a: {\n b: {\n foo: \"test\"\n },\n c: 2\n }\n};\nconsole.log(_.get(obj, \"a.b.foo\"));\nconsole.log(_.get(obj, \"a.c\"));\nconsole.log(_.get(obj, \"a.test\"));\nconsole.log(_.get(obj, \"a.test.x\"));"
},
{
"code": null,
"e": 1616,
"s": 1588,
"text": "This will give the output −"
},
{
"code": null,
"e": 1643,
"s": 1616,
"text": "test\n2\nundefined\nundefined"
},
{
"code": null,
"e": 1711,
"s": 1643,
"text": "You can also write your own getProp function in the following way −"
},
{
"code": null,
"e": 2046,
"s": 1711,
"text": "const getProp = (object, path) => {\n if (path.length === 1) return object[path[0]];\n else if (path.length === 0) throw error;\n else {\n if (object[path[0]]) return getProp(object[path[0]], path.slice(1));\n else {\n object[path[0]] = {};\n return getProp(object[path[0]], path.slice(1));\n }\n }\n};"
},
{
"code": null,
"e": 2102,
"s": 2046,
"text": "You can use it by passing an array to access the props."
},
{
"code": null,
"e": 2287,
"s": 2102,
"text": "var obj = {\n level1:{\n level2:{\n level3:{\n name: \"Foo\"\n }\n },\n anotherLevel2: \"bar\"\n }\n};\nconsole.log(getProp(obj, [\"level1\", \"level2\"]));"
},
{
"code": null,
"e": 2315,
"s": 2287,
"text": "This will give the output −"
},
{
"code": null,
"e": 2339,
"s": 2315,
"text": "{level3: {name: \"Foo\"}}"
}
] |
Spring AOP - XML Based PointCut | A JoinPoint represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. Consider the following examples −
All methods classes contained in a package(s).
All methods classes contained in a package(s).
A particular methods of a class.
A particular methods of a class.
PointCut is a set of one or more JoinPoints where an advice should be executed. You can specify PointCuts using expressions or patterns as we will see in our AOP examples. In Spring, PointCut helps to use specific JoinPoints to apply the advice. Consider the following examples −
expression = "execution(* com.tutorialspoint.*.*(..))"
expression = "execution(* com.tutorialspoint.*.*(..))"
expression = "execution(* com.tutorialspoint.Student.getName(..))"
expression = "execution(* com.tutorialspoint.Student.getName(..))"
<aop:config>
<aop:aspect id = "log" ref = "adviceClass">
<aop:pointcut id = "PointCut-id" expression = "execution( expression )"/>
</aop:aspect>
</aop:config>
Where,
adviceClass − ref of the class containing advice methods
adviceClass − ref of the class containing advice methods
PointCut-id − id of the PointCut
PointCut-id − id of the PointCut
execution( expression ) − Expression covering methods on which advice is to be applied.
execution( expression ) − Expression covering methods on which advice is to be applied.
To understand the above-mentioned concepts related to JoinPoint and PointCut, let us write an example which will implement few of the PointCuts. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application.
Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points.
package com.tutorialspoint;
public class Logging {
/**
* This is the method which I would like to execute
* before a selected method execution.
*/
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
}
Following is the content of the Student.java file.
package com.tutorialspoint;
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name );
return name;
}
public void printThrowException(){
System.out.println("Exception raised");
throw new IllegalArgumentException();
}
}
Following is the content of the MainApp.java file.
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
Student student = (Student) context.getBean("student");
student.getName();
student.getAge();
}
}
Following is the configuration file Beans.xml.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:config>
<aop:aspect id = "log" ref = "logging">
<aop:pointcut id = "selectAll"
expression = "execution(* com.tutorialspoint.*.*(..))"/>
<aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
</aop:aspect>
</aop:config>
<!-- Definition for student bean -->
<bean id = "student" class = "com.tutorialspoint.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id = "logging" class = "com.tutorialspoint.Logging"/>
</beans>
Once you are done with creating the source and bean configuration files, run the application. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Going to setup student profile.
Age : 11
The above-defined <aop:pointcut> selects all the methods defined under the package com.tutorialspoint. Let us suppose, you want to execute your advice before or after a particular method, you can define your PointCut to narrow down your execution by replacing stars (*) in PointCut definition with actual class and method names. Following is a modified XML configuration file to show the concept.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop = "http://www.springframework.org/schema/aop"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">
<aop:config>
<aop:aspect id = "log" ref = "logging">
<aop:pointcut id = "selectAll"
expression = "execution(* com.tutorialspoint.Student.getName(..))"/>
<aop:before pointcut-ref = "selectAll" method = "beforeAdvice"/>
</aop:aspect>
</aop:config>
<!-- Definition for student bean -->
<bean id = "student" class = "com.tutorialspoint.Student">
<property name = "name" value = "Zara" />
<property name = "age" value = "11"/>
</bean>
<!-- Definition for logging aspect -->
<bean id = "logging" class = "com.tutorialspoint.Logging"/>
</beans>
Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message.
Going to setup student profile.
Name : Zara
Age : 11
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2506,
"s": 2269,
"text": "A JoinPoint represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework. Consider the following examples −"
},
{
"code": null,
"e": 2553,
"s": 2506,
"text": "All methods classes contained in a package(s)."
},
{
"code": null,
"e": 2600,
"s": 2553,
"text": "All methods classes contained in a package(s)."
},
{
"code": null,
"e": 2633,
"s": 2600,
"text": "A particular methods of a class."
},
{
"code": null,
"e": 2666,
"s": 2633,
"text": "A particular methods of a class."
},
{
"code": null,
"e": 2946,
"s": 2666,
"text": "PointCut is a set of one or more JoinPoints where an advice should be executed. You can specify PointCuts using expressions or patterns as we will see in our AOP examples. In Spring, PointCut helps to use specific JoinPoints to apply the advice. Consider the following examples −"
},
{
"code": null,
"e": 3001,
"s": 2946,
"text": "expression = \"execution(* com.tutorialspoint.*.*(..))\""
},
{
"code": null,
"e": 3056,
"s": 3001,
"text": "expression = \"execution(* com.tutorialspoint.*.*(..))\""
},
{
"code": null,
"e": 3123,
"s": 3056,
"text": "expression = \"execution(* com.tutorialspoint.Student.getName(..))\""
},
{
"code": null,
"e": 3190,
"s": 3123,
"text": "expression = \"execution(* com.tutorialspoint.Student.getName(..))\""
},
{
"code": null,
"e": 3365,
"s": 3190,
"text": "<aop:config>\n <aop:aspect id = \"log\" ref = \"adviceClass\">\n <aop:pointcut id = \"PointCut-id\" expression = \"execution( expression )\"/> \n </aop:aspect>\n</aop:config>"
},
{
"code": null,
"e": 3372,
"s": 3365,
"text": "Where,"
},
{
"code": null,
"e": 3429,
"s": 3372,
"text": "adviceClass − ref of the class containing advice methods"
},
{
"code": null,
"e": 3486,
"s": 3429,
"text": "adviceClass − ref of the class containing advice methods"
},
{
"code": null,
"e": 3519,
"s": 3486,
"text": "PointCut-id − id of the PointCut"
},
{
"code": null,
"e": 3552,
"s": 3519,
"text": "PointCut-id − id of the PointCut"
},
{
"code": null,
"e": 3640,
"s": 3552,
"text": "execution( expression ) − Expression covering methods on which advice is to be applied."
},
{
"code": null,
"e": 3728,
"s": 3640,
"text": "execution( expression ) − Expression covering methods on which advice is to be applied."
},
{
"code": null,
"e": 4015,
"s": 3728,
"text": "To understand the above-mentioned concepts related to JoinPoint and PointCut, let us write an example which will implement few of the PointCuts. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application."
},
{
"code": null,
"e": 4164,
"s": 4015,
"text": "Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points."
},
{
"code": null,
"e": 4434,
"s": 4164,
"text": "package com.tutorialspoint;\n\npublic class Logging { \n /** \n * This is the method which I would like to execute\n * before a selected method execution.\n */\n public void beforeAdvice(){\n System.out.println(\"Going to setup student profile.\");\n } \n}"
},
{
"code": null,
"e": 4485,
"s": 4434,
"text": "Following is the content of the Student.java file."
},
{
"code": null,
"e": 5045,
"s": 4485,
"text": "package com.tutorialspoint;\n\npublic class Student {\n private Integer age;\n private String name;\n\n public void setAge(Integer age) {\n this.age = age;\n }\n public Integer getAge() {\n System.out.println(\"Age : \" + age );\n return age;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getName() {\n System.out.println(\"Name : \" + name );\n return name;\n }\n public void printThrowException(){\n System.out.println(\"Exception raised\");\n throw new IllegalArgumentException();\n }\n}"
},
{
"code": null,
"e": 5096,
"s": 5045,
"text": "Following is the content of the MainApp.java file."
},
{
"code": null,
"e": 5531,
"s": 5096,
"text": "package com.tutorialspoint;\n\nimport org.springframework.context.ApplicationContext;\nimport org.springframework.context.support.ClassPathXmlApplicationContext;\n\npublic class MainApp {\n public static void main(String[] args) {\n ApplicationContext context = new ClassPathXmlApplicationContext(\"Beans.xml\");\n\n Student student = (Student) context.getBean(\"student\");\n student.getName();\n student.getAge(); \n }\n}"
},
{
"code": null,
"e": 5578,
"s": 5531,
"text": "Following is the configuration file Beans.xml."
},
{
"code": null,
"e": 6679,
"s": 5578,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:aop = \"http://www.springframework.org/schema/aop\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \n http://www.springframework.org/schema/aop \n http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \">\n\n <aop:config>\n <aop:aspect id = \"log\" ref = \"logging\">\n <aop:pointcut id = \"selectAll\" \n expression = \"execution(* com.tutorialspoint.*.*(..))\"/>\n <aop:before pointcut-ref = \"selectAll\" method = \"beforeAdvice\"/> \n </aop:aspect>\n </aop:config>\n\n <!-- Definition for student bean -->\n <bean id = \"student\" class = \"com.tutorialspoint.Student\">\n <property name = \"name\" value = \"Zara\" />\n <property name = \"age\" value = \"11\"/> \n </bean>\n\n <!-- Definition for logging aspect -->\n <bean id = \"logging\" class = \"com.tutorialspoint.Logging\"/> \n \n</beans>"
},
{
"code": null,
"e": 6855,
"s": 6679,
"text": "Once you are done with creating the source and bean configuration files, run the application. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 6941,
"s": 6855,
"text": "Going to setup student profile.\nName : Zara\nGoing to setup student profile.\nAge : 11\n"
},
{
"code": null,
"e": 7338,
"s": 6941,
"text": "The above-defined <aop:pointcut> selects all the methods defined under the package com.tutorialspoint. Let us suppose, you want to execute your advice before or after a particular method, you can define your PointCut to narrow down your execution by replacing stars (*) in PointCut definition with actual class and method names. Following is a modified XML configuration file to show the concept."
},
{
"code": null,
"e": 8451,
"s": 7338,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<beans xmlns = \"http://www.springframework.org/schema/beans\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" \n xmlns:aop = \"http://www.springframework.org/schema/aop\"\n xsi:schemaLocation = \"http://www.springframework.org/schema/beans\n http://www.springframework.org/schema/beans/spring-beans-3.0.xsd \n http://www.springframework.org/schema/aop \n http://www.springframework.org/schema/aop/spring-aop-3.0.xsd \">\n\n <aop:config>\n <aop:aspect id = \"log\" ref = \"logging\">\n <aop:pointcut id = \"selectAll\" \n expression = \"execution(* com.tutorialspoint.Student.getName(..))\"/>\n <aop:before pointcut-ref = \"selectAll\" method = \"beforeAdvice\"/> \n </aop:aspect>\n </aop:config>\n\n <!-- Definition for student bean -->\n <bean id = \"student\" class = \"com.tutorialspoint.Student\">\n <property name = \"name\" value = \"Zara\" />\n <property name = \"age\" value = \"11\"/> \n </bean>\n\n <!-- Definition for logging aspect -->\n <bean id = \"logging\" class = \"com.tutorialspoint.Logging\"/> \n \n</beans>"
},
{
"code": null,
"e": 8706,
"s": 8451,
"text": "Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message."
},
{
"code": null,
"e": 8761,
"s": 8706,
"text": "Going to setup student profile.\nName : Zara\nAge : 11 \n"
},
{
"code": null,
"e": 8768,
"s": 8761,
"text": " Print"
},
{
"code": null,
"e": 8779,
"s": 8768,
"text": " Add Notes"
}
] |
Longest common subarray in the given two arrays - GeeksforGeeks | 23 Dec, 2021
Given two arrays A[] and B[] of N and M integers respectively, the task is to find the maximum length of equal subarray or the longest common subarray between the two given array.
Examples:
Input: A[] = {1, 2, 8, 2, 1}, B[] = {8, 2, 1, 4, 7} Output: 3 Explanation: The subarray that is common to both arrays are {8, 2, 1} and the length of the subarray is 3.Input: A[] = {1, 2, 3, 2, 1}, B[] = {8, 7, 6, 4, 7} Output: 0 Explanation: There is no such subarrays which are equal in the array A[] and B[].
Naive Approach: The idea is to generate all the subarrays of the two given array A[] and B[] and find the longest matching subarray. This solution is exponential in terms of time complexity.Time Complexity: O(2N+M), where N is the length of the array A[] and M is the length of the array B[].
Efficient Approach: The efficient approach is to use Dynamic Programming(DP). This problem is the variation of the Longest Common Subsequence(LCS). Let the input sequences are A[0..n-1] and B[0..m-1] of lengths m & n respectively. Following is the recursive implementation of the equal subarrays:
Since common subarray of A[] and B[] must start at some index i and j such that A[i] is equals to B[j]. Let dp[i][j] be the longest common subarray of A[i...] and B[j...].Therefore, for any index i and j, if A[i] is equals to B[j], then dp[i][j] = dp[i+1][j+1] + 1.The maximum of all the element in the array dp[][] will give the maximum length of equal subarrays.
Since common subarray of A[] and B[] must start at some index i and j such that A[i] is equals to B[j]. Let dp[i][j] be the longest common subarray of A[i...] and B[j...].
Therefore, for any index i and j, if A[i] is equals to B[j], then dp[i][j] = dp[i+1][j+1] + 1.
The maximum of all the element in the array dp[][] will give the maximum length of equal subarrays.
For Example: If the given array A[] = {1, 2, 8, 2, 1} and B[] = {8, 2, 1, 4, 7}. If the characters match at index i and j for the array A[] and B[] respectively, then dp[i][j] will be updated as 1 + dp[i+1][j+1]. Below is the updated dp[][] table for the given array A[] and B[].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to DP approach// to above solution#include <bits/stdc++.h>using namespace std; // Function to find the maximum// length of equal subarrayint FindMaxLength(int A[], int B[], int n, int m){ // Auxiliary dp[][] array int dp[n + 1][m + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) dp[i][j] = 0; // Updating the dp[][] table // in Bottom Up approach for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j][i] = dp[j + 1][i + 1] + 1 if (A[i] == B[j]) dp[j][i] = dp[j + 1][i + 1] + 1; } } int maxm = 0; // Find maximum of all the values // in dp[][] array to get the // maximum length for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Update the length maxm = max(maxm, dp[i][j]); } } // Return the maximum length return maxm;} // Driver Codeint main(){ int A[] = { 1, 2, 8, 2, 1 }; int B[] = { 8, 2, 1, 4, 7 }; int n = sizeof(A) / sizeof(A[0]); int m = sizeof(B) / sizeof(B[0]); // Function call to find // maximum length of subarray cout << (FindMaxLength(A, B, n, m));} // This code is contributed by chitranayal
// Java program to DP approach// to above solutionclass GFG{ // Function to find the maximum // length of equal subarray static int FindMaxLength(int A[], int B[], int n, int m) { // Auxiliary dp[][] array int[][] dp = new int[n + 1][m + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) dp[i][j] = 0; // Updating the dp[][] table // in Bottom Up approach for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j][i] = dp[j + 1][i + 1] + 1 if (A[i] == B[j]) dp[j][i] = dp[j + 1][i + 1] + 1; } } int maxm = 0; // Find maximum of all the values // in dp[][] array to get the // maximum length for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Update the length maxm = Math.max(maxm, dp[i][j]); } } // Return the maximum length return maxm; } // Driver Code public static void main(String[] args) { int A[] = { 1, 2, 8, 2, 1 }; int B[] = { 8, 2, 1, 4, 7 }; int n = A.length; int m = B.length; // Function call to find // maximum length of subarray System.out.print(FindMaxLength(A, B, n, m)); }} // This code is contributed by PrinciRaj1992
# Python program to DP approach# to above solution # Function to find the maximum# length of equal subarray def FindMaxLength(A, B): n = len(A) m = len(B) # Auxiliary dp[][] array dp = [[0 for i in range(n + 1)] for i in range(m + 1)] # Updating the dp[][] table # in Bottom Up approach for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): # If A[i] is equal to B[i] # then dp[j][i] = dp[j + 1][i + 1] + 1 if A[i] == B[j]: dp[j][i] = dp[j + 1][i + 1] + 1 maxm = 0 # Find maximum of all the values # in dp[][] array to get the # maximum length for i in dp: for j in i: # Update the length maxm = max(maxm, j) # Return the maximum length return maxm # Driver Codeif __name__ == '__main__': A = [1, 2, 8, 2, 1] B = [8, 2, 1, 4, 7] # Function call to find # maximum length of subarray print(FindMaxLength(A, B))
// C# program to DP approach// to above solutionusing System; class GFG{ // Function to find the maximum // length of equal subarray static int FindMaxLength(int[] A, int[] B, int n, int m) { // Auxiliary [,]dp array int[, ] dp = new int[n + 1, m + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) dp[i, j] = 0; // Updating the [,]dp table // in Bottom Up approach for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j, i] = dp[j + 1, i + 1] + 1 if (A[i] == B[j]) dp[j, i] = dp[j + 1, i + 1] + 1; } } int maxm = 0; // Find maximum of all the values // in [,]dp array to get the // maximum length for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Update the length maxm = Math.Max(maxm, dp[i, j]); } } // Return the maximum length return maxm; } // Driver Code public static void Main(String[] args) { int[] A = { 1, 2, 8, 2, 1 }; int[] B = { 8, 2, 1, 4, 7 }; int n = A.Length; int m = B.Length; // Function call to find // maximum length of subarray Console.Write(FindMaxLength(A, B, n, m)); }} // This code is contributed by PrinciRaj1992
<script>// Javascript program to DP approach// to above solution // Function to find the maximum // length of equal subarray function FindMaxLength(A,B,n,m) { // Auxiliary dp[][] array let dp = new Array(n + 1); for (let i = 0; i <= n; i++) { dp[i]=new Array(m+1); for (let j = 0; j <= m; j++) dp[i][j] = 0; } // Updating the dp[][] table // in Bottom Up approach for (let i = n - 1; i >= 0; i--) { for (let j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j][i] = dp[j + 1][i + 1] + 1 if (A[i] == B[j]) dp[j][i] = dp[j + 1][i + 1] + 1; } } let maxm = 0; // Find maximum of all the values // in dp[][] array to get the // maximum length for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { // Update the length maxm = Math.max(maxm, dp[i][j]); } } // Return the maximum length return maxm; } // Driver Code let A=[1, 2, 8, 2, 1 ]; let B=[8, 2, 1, 4, 7]; let n = A.length; let m = B.length; // Function call to find // maximum length of subarray document.write(FindMaxLength(A, B, n, m)); // This code is contributed by avanitrachhadiya2155</script>
3
Time Complexity: O(N*M), where N is the length of array A[] and M is the length of array B[].Auxiliary Space: O(N*M)
ukasp
princiraj1992
megha_burnwal
chathurijayaweera
avanitrachhadiya2155
singghakshay
pankajsharmagfg
amartyaghoshgfg
subarray
Algorithms
Arrays
Backtracking
Dynamic Programming
Recursion
Arrays
Dynamic Programming
Recursion
Backtracking
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Introduction to Algorithms
Difference between Informed and Uninformed Search in AI
Cyclomatic Complexity
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray | [
{
"code": null,
"e": 24547,
"s": 24519,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 24727,
"s": 24547,
"text": "Given two arrays A[] and B[] of N and M integers respectively, the task is to find the maximum length of equal subarray or the longest common subarray between the two given array."
},
{
"code": null,
"e": 24738,
"s": 24727,
"text": "Examples: "
},
{
"code": null,
"e": 25051,
"s": 24738,
"text": "Input: A[] = {1, 2, 8, 2, 1}, B[] = {8, 2, 1, 4, 7} Output: 3 Explanation: The subarray that is common to both arrays are {8, 2, 1} and the length of the subarray is 3.Input: A[] = {1, 2, 3, 2, 1}, B[] = {8, 7, 6, 4, 7} Output: 0 Explanation: There is no such subarrays which are equal in the array A[] and B[]. "
},
{
"code": null,
"e": 25344,
"s": 25051,
"text": "Naive Approach: The idea is to generate all the subarrays of the two given array A[] and B[] and find the longest matching subarray. This solution is exponential in terms of time complexity.Time Complexity: O(2N+M), where N is the length of the array A[] and M is the length of the array B[]."
},
{
"code": null,
"e": 25642,
"s": 25344,
"text": "Efficient Approach: The efficient approach is to use Dynamic Programming(DP). This problem is the variation of the Longest Common Subsequence(LCS). Let the input sequences are A[0..n-1] and B[0..m-1] of lengths m & n respectively. Following is the recursive implementation of the equal subarrays: "
},
{
"code": null,
"e": 26007,
"s": 25642,
"text": "Since common subarray of A[] and B[] must start at some index i and j such that A[i] is equals to B[j]. Let dp[i][j] be the longest common subarray of A[i...] and B[j...].Therefore, for any index i and j, if A[i] is equals to B[j], then dp[i][j] = dp[i+1][j+1] + 1.The maximum of all the element in the array dp[][] will give the maximum length of equal subarrays."
},
{
"code": null,
"e": 26179,
"s": 26007,
"text": "Since common subarray of A[] and B[] must start at some index i and j such that A[i] is equals to B[j]. Let dp[i][j] be the longest common subarray of A[i...] and B[j...]."
},
{
"code": null,
"e": 26274,
"s": 26179,
"text": "Therefore, for any index i and j, if A[i] is equals to B[j], then dp[i][j] = dp[i+1][j+1] + 1."
},
{
"code": null,
"e": 26374,
"s": 26274,
"text": "The maximum of all the element in the array dp[][] will give the maximum length of equal subarrays."
},
{
"code": null,
"e": 26655,
"s": 26374,
"text": "For Example: If the given array A[] = {1, 2, 8, 2, 1} and B[] = {8, 2, 1, 4, 7}. If the characters match at index i and j for the array A[] and B[] respectively, then dp[i][j] will be updated as 1 + dp[i+1][j+1]. Below is the updated dp[][] table for the given array A[] and B[]. "
},
{
"code": null,
"e": 26707,
"s": 26655,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26711,
"s": 26707,
"text": "C++"
},
{
"code": null,
"e": 26716,
"s": 26711,
"text": "Java"
},
{
"code": null,
"e": 26724,
"s": 26716,
"text": "Python3"
},
{
"code": null,
"e": 26727,
"s": 26724,
"text": "C#"
},
{
"code": null,
"e": 26738,
"s": 26727,
"text": "Javascript"
},
{
"code": "// C++ program to DP approach// to above solution#include <bits/stdc++.h>using namespace std; // Function to find the maximum// length of equal subarrayint FindMaxLength(int A[], int B[], int n, int m){ // Auxiliary dp[][] array int dp[n + 1][m + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) dp[i][j] = 0; // Updating the dp[][] table // in Bottom Up approach for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j][i] = dp[j + 1][i + 1] + 1 if (A[i] == B[j]) dp[j][i] = dp[j + 1][i + 1] + 1; } } int maxm = 0; // Find maximum of all the values // in dp[][] array to get the // maximum length for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Update the length maxm = max(maxm, dp[i][j]); } } // Return the maximum length return maxm;} // Driver Codeint main(){ int A[] = { 1, 2, 8, 2, 1 }; int B[] = { 8, 2, 1, 4, 7 }; int n = sizeof(A) / sizeof(A[0]); int m = sizeof(B) / sizeof(B[0]); // Function call to find // maximum length of subarray cout << (FindMaxLength(A, B, n, m));} // This code is contributed by chitranayal",
"e": 28056,
"s": 26738,
"text": null
},
{
"code": "// Java program to DP approach// to above solutionclass GFG{ // Function to find the maximum // length of equal subarray static int FindMaxLength(int A[], int B[], int n, int m) { // Auxiliary dp[][] array int[][] dp = new int[n + 1][m + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) dp[i][j] = 0; // Updating the dp[][] table // in Bottom Up approach for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j][i] = dp[j + 1][i + 1] + 1 if (A[i] == B[j]) dp[j][i] = dp[j + 1][i + 1] + 1; } } int maxm = 0; // Find maximum of all the values // in dp[][] array to get the // maximum length for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Update the length maxm = Math.max(maxm, dp[i][j]); } } // Return the maximum length return maxm; } // Driver Code public static void main(String[] args) { int A[] = { 1, 2, 8, 2, 1 }; int B[] = { 8, 2, 1, 4, 7 }; int n = A.length; int m = B.length; // Function call to find // maximum length of subarray System.out.print(FindMaxLength(A, B, n, m)); }} // This code is contributed by PrinciRaj1992",
"e": 29561,
"s": 28056,
"text": null
},
{
"code": "# Python program to DP approach# to above solution # Function to find the maximum# length of equal subarray def FindMaxLength(A, B): n = len(A) m = len(B) # Auxiliary dp[][] array dp = [[0 for i in range(n + 1)] for i in range(m + 1)] # Updating the dp[][] table # in Bottom Up approach for i in range(n - 1, -1, -1): for j in range(m - 1, -1, -1): # If A[i] is equal to B[i] # then dp[j][i] = dp[j + 1][i + 1] + 1 if A[i] == B[j]: dp[j][i] = dp[j + 1][i + 1] + 1 maxm = 0 # Find maximum of all the values # in dp[][] array to get the # maximum length for i in dp: for j in i: # Update the length maxm = max(maxm, j) # Return the maximum length return maxm # Driver Codeif __name__ == '__main__': A = [1, 2, 8, 2, 1] B = [8, 2, 1, 4, 7] # Function call to find # maximum length of subarray print(FindMaxLength(A, B))",
"e": 30528,
"s": 29561,
"text": null
},
{
"code": "// C# program to DP approach// to above solutionusing System; class GFG{ // Function to find the maximum // length of equal subarray static int FindMaxLength(int[] A, int[] B, int n, int m) { // Auxiliary [,]dp array int[, ] dp = new int[n + 1, m + 1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) dp[i, j] = 0; // Updating the [,]dp table // in Bottom Up approach for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j, i] = dp[j + 1, i + 1] + 1 if (A[i] == B[j]) dp[j, i] = dp[j + 1, i + 1] + 1; } } int maxm = 0; // Find maximum of all the values // in [,]dp array to get the // maximum length for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { // Update the length maxm = Math.Max(maxm, dp[i, j]); } } // Return the maximum length return maxm; } // Driver Code public static void Main(String[] args) { int[] A = { 1, 2, 8, 2, 1 }; int[] B = { 8, 2, 1, 4, 7 }; int n = A.Length; int m = B.Length; // Function call to find // maximum length of subarray Console.Write(FindMaxLength(A, B, n, m)); }} // This code is contributed by PrinciRaj1992",
"e": 32022,
"s": 30528,
"text": null
},
{
"code": "<script>// Javascript program to DP approach// to above solution // Function to find the maximum // length of equal subarray function FindMaxLength(A,B,n,m) { // Auxiliary dp[][] array let dp = new Array(n + 1); for (let i = 0; i <= n; i++) { dp[i]=new Array(m+1); for (let j = 0; j <= m; j++) dp[i][j] = 0; } // Updating the dp[][] table // in Bottom Up approach for (let i = n - 1; i >= 0; i--) { for (let j = m - 1; j >= 0; j--) { // If A[i] is equal to B[i] // then dp[j][i] = dp[j + 1][i + 1] + 1 if (A[i] == B[j]) dp[j][i] = dp[j + 1][i + 1] + 1; } } let maxm = 0; // Find maximum of all the values // in dp[][] array to get the // maximum length for (let i = 0; i < n; i++) { for (let j = 0; j < m; j++) { // Update the length maxm = Math.max(maxm, dp[i][j]); } } // Return the maximum length return maxm; } // Driver Code let A=[1, 2, 8, 2, 1 ]; let B=[8, 2, 1, 4, 7]; let n = A.length; let m = B.length; // Function call to find // maximum length of subarray document.write(FindMaxLength(A, B, n, m)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 33501,
"s": 32022,
"text": null
},
{
"code": null,
"e": 33503,
"s": 33501,
"text": "3"
},
{
"code": null,
"e": 33620,
"s": 33503,
"text": "Time Complexity: O(N*M), where N is the length of array A[] and M is the length of array B[].Auxiliary Space: O(N*M)"
},
{
"code": null,
"e": 33626,
"s": 33620,
"text": "ukasp"
},
{
"code": null,
"e": 33640,
"s": 33626,
"text": "princiraj1992"
},
{
"code": null,
"e": 33654,
"s": 33640,
"text": "megha_burnwal"
},
{
"code": null,
"e": 33672,
"s": 33654,
"text": "chathurijayaweera"
},
{
"code": null,
"e": 33693,
"s": 33672,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 33706,
"s": 33693,
"text": "singghakshay"
},
{
"code": null,
"e": 33722,
"s": 33706,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 33738,
"s": 33722,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 33747,
"s": 33738,
"text": "subarray"
},
{
"code": null,
"e": 33758,
"s": 33747,
"text": "Algorithms"
},
{
"code": null,
"e": 33765,
"s": 33758,
"text": "Arrays"
},
{
"code": null,
"e": 33778,
"s": 33765,
"text": "Backtracking"
},
{
"code": null,
"e": 33798,
"s": 33778,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33808,
"s": 33798,
"text": "Recursion"
},
{
"code": null,
"e": 33815,
"s": 33808,
"text": "Arrays"
},
{
"code": null,
"e": 33835,
"s": 33815,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 33845,
"s": 33835,
"text": "Recursion"
},
{
"code": null,
"e": 33858,
"s": 33845,
"text": "Backtracking"
},
{
"code": null,
"e": 33869,
"s": 33858,
"text": "Algorithms"
},
{
"code": null,
"e": 33967,
"s": 33869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33976,
"s": 33967,
"text": "Comments"
},
{
"code": null,
"e": 33989,
"s": 33976,
"text": "Old Comments"
},
{
"code": null,
"e": 34038,
"s": 33989,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 34063,
"s": 34038,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 34090,
"s": 34063,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 34146,
"s": 34090,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 34168,
"s": 34146,
"text": "Cyclomatic Complexity"
},
{
"code": null,
"e": 34183,
"s": 34168,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34199,
"s": 34183,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34226,
"s": 34199,
"text": "Program for array rotation"
},
{
"code": null,
"e": 34274,
"s": 34226,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
SVG - Path | <path> element is used to draw a connected straight lines.
Following is the syntax declaration of <path> element. We've shown main attributes only.
<path
d="data" >
</path>
<path> element is used to define any path. Path element uses Path data which comprises of number of commands. Commands behaves like a nip of pencil or a pointer is moving to draw a path.
As above commands are in Upper case, these represents absolute path. In case their lower case commands are used, then relative path is used.
<html>
<title>SVG Path</title>
<body>
<h1>Sample SVG Path Image</h1>
<svg width="570" height="320">
<g>
<text x="0" y="10" fill="black" >Path #1: Without opacity.</text>
<path d="M 100 100 L 300 100 L 200 300 z"
stroke="black" stroke-width="3" fill="rgb(121,0,121)"> </path>
</g>
</svg>
</body>
</html>
In above example,in first shape, M 100 100 moves drawing pointer to (100,100), L 300 100 draws a line from (100,100) to (300,100), L 200 300 draws a line from (300,100) to (200,300) and z closes the path.
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
<html>
<title>SVG Path</title>
<body>
<h1>Sample SVG Path Image</h1>
<svg width="800" height="800">
<g>
<text x="0" y="15" fill="black" >Path #2: With opacity </text>
<path d="M 100 100 L 300 100 L 200 300 z"
style="fill:rgb(121,0,121);stroke-width:3;
stroke:rgb(0,0,0);stroke-opacity:0.5;"> </path>
</g>
</svg>
</body>
</html>
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering.
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2424,
"s": 2364,
"text": "<path> element is used to draw a connected straight lines."
},
{
"code": null,
"e": 2513,
"s": 2424,
"text": "Following is the syntax declaration of <path> element. We've shown main attributes only."
},
{
"code": null,
"e": 2543,
"s": 2513,
"text": "<path\n d=\"data\" > \n</path>"
},
{
"code": null,
"e": 2730,
"s": 2543,
"text": "<path> element is used to define any path. Path element uses Path data which comprises of number of commands. Commands behaves like a nip of pencil or a pointer is moving to draw a path."
},
{
"code": null,
"e": 2871,
"s": 2730,
"text": "As above commands are in Upper case, these represents absolute path. In case their lower case commands are used, then relative path is used."
},
{
"code": null,
"e": 3285,
"s": 2871,
"text": "<html>\n <title>SVG Path</title>\n <body>\n \n <h1>Sample SVG Path Image</h1>\n \n <svg width=\"570\" height=\"320\">\n <g>\n <text x=\"0\" y=\"10\" fill=\"black\" >Path #1: Without opacity.</text>\n \n <path d=\"M 100 100 L 300 100 L 200 300 z\" \n stroke=\"black\" stroke-width=\"3\" fill=\"rgb(121,0,121)\"> </path>\n </g> \n </svg>\n \n </body>\n</html>"
},
{
"code": null,
"e": 3490,
"s": 3285,
"text": "In above example,in first shape, M 100 100 moves drawing pointer to (100,100), L 300 100 draws a line from (100,100) to (300,100), L 200 300 draws a line from (300,100) to (200,300) and z closes the path."
},
{
"code": null,
"e": 3677,
"s": 3490,
"text": "Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering."
},
{
"code": null,
"e": 4130,
"s": 3677,
"text": "<html>\n <title>SVG Path</title>\n <body>\n \n <h1>Sample SVG Path Image</h1>\n \n <svg width=\"800\" height=\"800\"> \n <g>\n <text x=\"0\" y=\"15\" fill=\"black\" >Path #2: With opacity </text>\n \n <path d=\"M 100 100 L 300 100 L 200 300 z\"\n style=\"fill:rgb(121,0,121);stroke-width:3;\n stroke:rgb(0,0,0);stroke-opacity:0.5;\"> </path>\n </g>\n </svg>\n \n </body>\n</html>"
},
{
"code": null,
"e": 4317,
"s": 4130,
"text": "Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9 and higher also supports SVG image rendering."
},
{
"code": null,
"e": 4352,
"s": 4317,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4383,
"s": 4352,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4390,
"s": 4383,
"text": " Print"
},
{
"code": null,
"e": 4401,
"s": 4390,
"text": " Add Notes"
}
] |
Intro to Agent Based Modeling. An example of how agent based modeling... | by Bassel Karami | Towards Data Science | Table of contents:
1- Intro: why agent based modeling?
2- Our supermarket queueing problem
3- Model design
4- Model execution
5- Conclusion
Agent based modeling (ABM) is a bottom-up simulation technique where we analyze a system by its individual agents that interact with each other.
Suppose we want to predict the number of COVID cases in a particular region, we can create agents representing the people in that region.
We simulate the behavior of several agents (people) where some may be wearing masks while others aren’t, some are vaccinated, some are very social while others aren’t etc. We then simulate their interactions with each other and the associated probabilities of COVID being transmitted...
After running the simulation, we are able to better understand the overall system... we see the number of infections in the population, the number of people recovered, transmission rates, whether we hit herd immunity etc. We can also analyze how the system would look like (infections, recoveries etc.) if we were to impose measures such as forced vaccinations.
The cornerstone of ABM is the ability to understand macro phenomena emerging from micro-scale behavior.
In the above example, the alternative to using ABM is to directly look at macro-level stats such as the number of infections and recoveries and to directly analyze the trends of those stats. Instead, ABM emphasizes the behavior of individual agents which is a more flexible and granular bottom-up approach that can capture aspects a macro-scale model can’t.
ABM has uses in biology, social sciences, traffic management, and supply chain management amongst many other disiplines.
The behavior of those agents should represent reality as closely as possible (we can validate that), so for example, if 75% of people in that region wear masks, then we create agents such that 75% of them are modeled as mask-wearing agents.
Suppose that we are managing staffing costs at a supermarket.
Problem: For a particular hour, we expect 500 customers to show up and we want to determine how many counters should we have open during that hour.
The average customer is worth $10 of gross margin while the average cost to operate a single counter for one hour is $300.
In contrast to standard queueing theory models (M/M/1, M/G/1, M/M/c etc.), agent based modeling can more easily capture behavioral aspects in this multi-waiting-line, multi-server environment.
Common behaviors including queue balking (customer doesn’t join the queue because it is too long), reneging (customer joins the queue but leaves after waiting for too long), and jockeying (customers moving from a longer queue to a shorter one).
We shall attempt to solve this problem using ABM.
We’ll build a simple ABM model with the following assumptions:
1- We are optimizing net profit for this single hour.
2- Exactly 500 customers will be arriving to the Supermarket during this hour.
3- Every customer is worth $10.
4- Every counter costs $300 to operate.
5- Customers arrive at the supermarket queues at different times during the day, based on a beta distribution, such that they are more likely to arrive at the middle of the hour.
6- The average time to process a customer order is 45 seconds, but the processing time differs between customers. It follows a Poisson distribution (for simplicity and to ensure we get discrete non-negative numbers) with an average of 45.
7- Every customer has a balking tolerance which is the number of people in the queue that a customer is willing to join. If there are more people in the queue, the customer won’t join the queue and we lose the sale. The customers’ balking tolerance follows a poisson distribution. The average tolerance is 6 i.e. most customers will balk if there are 6 or more other customers in the queue.
8- Customers choose the counter with the shortest queue.
Note that in real-world applications, we validate the assumptions (or pass them as parameters to be optimized) against available data. Also, in this introductory example, balking is the only behavior we consider.
We run the ABM simulation for 3600 steps (ticks) representing 3600 seconds in the hour. Below is the initial configuration code.
# Configticks = 3600 # 3600 ticks = 3600 seconds = 1 hourno_customers = 500avg_service_time = 45 # ticks/seconds per customergross_margin_per_customer = 10 # dollarscost_per_counter = 300 # dollars
Now, we use the Mesa library in python to code the rest of our model. Let’s start with defining our Customer class and the required attributes. The Customer class is one of two type of agents we will be dealing with, the other is Counter.
from mesa import Agentclass Customer(Agent): def __init__(self, unique_id, model): super().__init__(unique_id, model) # Time required to process the customer's transaction self.service_time = ss.poisson(45).rvs() # Time of arrival at queue self.entry_time = np.int(ss.beta(3, 3).rvs() * ticks) + 1 self.balk_tolerance = ss.poisson(5).rvs() + 1 # Whether or not the customer has arrived at the queue self._arrived = False self._chosen_counter = None self._q_entry = None self._q_exit = None # Start time when customer is being served self._service_entry = None # End time self._service_exit = None
We also need to create a “step” method for our customers which describes what do they do at each step (tick/second) of the simulation.
class Customer(Agent): def __init__(self, unique_id, model): super().__init__(unique_id, model) # Time required to process the customer's transaction self.service_time = ss.poisson(45).rvs() # Time of arrival at queue self.entry_time = np.int(ss.beta(3, 3).rvs() * ticks) + 1 self.balk_tolerance = ss.poisson(5).rvs() + 1 # Whether or not the customer has arrived at the queue self._arrived = False self._chosen_counter = None self._q_entry = None self._q_exit = None # Start time when customer is being served self._service_entry = None # End time self._service_exit = None def select_counter(self): self._arrived = True # Queue at shortest counter self._chosen_counter_idx = np.argmin([ len(counter.queue) for counter in self.model.counters]) self._chosen_counter = self.model.counters[ self._chosen_counter_idx] # Balk if there are too many people at the counter if len(self._chosen_counter.queue) < self.balk_tolerance: self._chosen_counter.queue.append(self) self._q_entry = self.model._current_tick def pay_n_leave(self): self._service_exit = self.model._current_tick self._chosen_counter.active_customer = None def step(self): if (self._arrived == False) & \ (self.model._current_tick >= self.entry_time): self.select_counter() elif isinstance(self._service_entry, int): if self.model._current_tick - self._service_entry \ == self.service_time: self.pay_n_leave()
In the above code, at every simulation step, if we have arrived at the simulation step/time which matches the customer’s entry time (time at which he arrives at the supermarket queue), then we run the select_counter method where he chooses the counter with the shortest queue or he balks if that queue is too long.
If the customer is already being served at the counter, we check if we have already run enough steps to arrive at his service time (time required to process his transaction) then we run the pay_n_leave method.
Similarly, the below code is used for the 2nd type of agents, Counter.
class Counter(Agent): def __init__(self, unique_id, model): super().__init__(unique_id, model) self.queue = [] self.active_customer = None def dequeue(self): try: self.active_customer = self.queue.pop(0) self.active_customer._service_entry = self.model._current_tick self.active_customer._q_exit = self.model._current_tick except: pass def step(self): if self.active_customer is None: self.dequeue()
Finally, we create a QueueModel class which is used to manage the overall simulation/system that the agents belong to.
from mesa import Modelfrom mesa.time import RandomActivationclass QueueModel(Model): """Queueing model with customers and counters as two types of agents that interact with each other """ def __init__(self, no_customers, no_counters, ticks): self.ticks = ticks self._current_tick = 1 self.no_customers = no_customers self.no_counters = no_counters self.schedule = RandomActivation(self) # Create agents self.customers = [] self.counters = [] for i in range(self.no_customers): customer = Customer(i, self) self.schedule.add(customer) self.customers.append(customer) for i in range(self.no_counters): counter = Counter(i + no_customers, self) self.schedule.add(counter) self.counters.append(counter) def step(self): self.schedule.step() self._current_tick += 1
The QueueModel class can be initiated with the number of customers (in our example 500), the number of counters (this is what we are trying to determine), and the ticks (number of simulation steps, 3600 representing 3600 seconds in an hour).
We have a “schedule” attribute where we describe which agents will be activated and when. We use RandomActivation which activates all agents in random order. You can read up the Mesa documentation for different settings.
Upon initialization, there are 2 for loops where we create the Customer and Counter agents. We also add them to the model’s schedule.
There is also a “step” method that orchestrates running one step of the simulation and it also triggers the “step” methods of the agents that are part of the schedule.
We can now run the simulation by running the below code...
model = QueueModel(ticks=ticks, no_customers=no_customers, no_counters=no_counters)for i in range(ticks): model.step()
However, we can also add a “data collector” to our QueueModel class that can help us track metrics of interest. We can track those metrics at every step of our simulation.
Let’s track 8 metrics:
1- Number of customers arrived. At the end of the 3600 simulation steps (representing 1 hour), we should have 500 customers.
2- Number of customers already served.
3- Number of customers who arrived at the queue but balked. We lost those customers.
4- The average queue size across all counters.
5- The average waiting time before a customer is served.
6- Gross margin = number of customers served x $10 per customer
7- Operating costs = number of counters x $300
8- Total profit = Gross margin - Operating costs
In order to add the metrics to our ABM model, we first create them as functions that take our QueueModel as an argument...
def get_customers_arrived(model): customers_arrived = [ customer._arrived for customer in model.customers] no_customers_arrived = np.sum(customers_arrived) return no_customers_arriveddef get_customers_served(model): customers_served = [not(customer._service_exit is None) for customer in model.customers] no_customers_served = np.sum(customers_served) return no_customers_serveddef get_customers_balked(model): customers_arrived = [ customer._arrived for customer in model.customers] # Customers who never joined a queue customers_no_q = np.array([ customer._q_entry is None for customer in model.customers]) no_customers_balked = np.sum(customers_arrived * customers_no_q) return no_customers_balkeddef get_avg_queue_size(model): queue_size = [len(counter.queue) for counter in model.counters] avg_queue_size = np.mean(queue_size) return avg_queue_sizedef get_avg_waiting_time(model): customers_wait = [np.nan if customer._q_exit is None else customer._q_exit - customer._q_entry for customer in model.customers] avg_customer_wait = np.nanmean(customers_wait) return avg_customer_waitdef get_gross_margin(model): return gross_margin_per_customer * get_customers_served(model)def get_operating_costs(model): return cost_per_counter * no_countersdef get_total_profit(model): return get_gross_margin(model) - get_operating_costs(model)
Finally, we update our QueueModel class as follows...
from mesa.datacollection import DataCollectorclass QueueModel(Model): """Queueing model with customers and counters as two types of agents that interact with each other """ def __init__(self, no_customers, no_counters, ticks): self.ticks = ticks self._current_tick = 1 self.no_customers = no_customers self.no_counters = no_counters self.schedule = RandomActivation(self) # Create agents self.customers = [] self.counters = [] for i in range(self.no_customers): customer = Customer(i, self) self.schedule.add(customer) self.customers.append(customer) for i in range(self.no_counters): counter = Counter(i + no_customers, self) self.schedule.add(counter) self.counters.append(counter) self.datacollector = DataCollector( model_reporters={ 'Customers Arrived': get_customers_arrived, 'Customers Served': get_customers_served, 'Customers Balked': get_customers_balked, 'Average Waiting Time': get_avg_waiting_time, 'Average Queue Size': get_avg_queue_size, 'Gross Margin': get_gross_margin, 'Operating Costs': get_operating_costs, 'Total Profit': get_total_profit}) def step(self): self.datacollector.collect(self) self.schedule.step() self._current_tick += 1
We are now ready to run our model...
Let’s try to run our model with 5 counters...
no_counters = 5model = QueueModel(ticks=ticks, no_customers=no_customers, no_counters=no_counters)for i in range(ticks): model.step()
Below are the results and the code used to produce them...
run_stats = model.datacollector.get_model_vars_dataframe()fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1)fig.figure.set_figwidth(12)fig.figure.set_figheight(16)fig.suptitle(f'Simulations stats using {no_counters} counters', fontsize=20)ax1.plot(run_stats[['Customers Arrived', 'Customers Served', 'Customers Balked', ]])ax1.legend(['Customers Arrived', 'Customers Served', 'Customers Balked', ])ax1.set_ylabel('Customers')ax1.set_xlim(0)ax1.set_ylim(0)ax2.plot(run_stats['Average Queue Size'], color='red')ax2.legend(['Average Queue Size'])ax2.set_ylabel('Customers')ax2.set_xlim(0)ax2.set_ylim(0)ax3.plot(run_stats['Average Waiting Time'], color='grey')ax3.legend(['Average Waiting Time (across full hour)'])ax3.set_ylabel('Seconds')ax3.set_xlim(0)ax3.set_ylim(0)ax4.plot(run_stats[['Gross Margin', 'Operating Costs', 'Total Profit' ]])ax4.legend(['Gross Margin', 'Operating Costs', 'Total Profit' ])ax4.set_ylabel('Dollars')ax4.set_xlim(0)fig.show()
The x-axis represents the 3600 ticks/seconds in the 1 hour that we are simulating.
The first chart shows us how after ~1200 seconds (~20 minutes), customers start to balk as too many customer are arriving.
In the 2nd chart, we can see how the queue size starts to increase after roughly ~10 minutes and it peaks at approximately 6 customers per counter at the middle of the hour.
The 3rd chart shows us how average waiting time (cumulative) increases from the beginning of the hour towards the end of the hour as many customers arrive at the middle of the hour and they wait in long queues pushing the average waiting time up.
Finally, the 4th chart shows us our financials, where we accumulate just over $1500 towards the end of the hour.
Based on the above, 5 counters seems to be too low as we can see that just under 200 customers (40%) have balked and they are lost.
Now, let’s try to run the simulations with 5–15 counters to determine what is the ideal number of counters...
full_stats = {}for no_counters in range (5, 16): model = QueueModel(ticks=ticks, no_customers=no_customers, no_counters=no_counters) for i in range(ticks): model.step() run_stats = model.datacollector.get_model_vars_dataframe() full_stats[no_counters] = run_stats.iloc[-1] pd.DataFrame(full_stats).transpose().astype(int)
In the above code, we run simulations with 5–15 counters and we look at the stats at the end of each simulation (not every step of the simulation). The dataframe output shows the results with different numbers of counters...
We can see that total profit is maximized at $2030 with 9 counters.
We can optimize based on any metric of interest... immediate profit is not necessarily the best metric.
Average waiting time per customer using 9 counters is 94 seconds... by just adding one additional counter, we cut the waiting time by 33 seconds to 61 and we only lose $90 (total profit is $1940). Reduced waiting time can likely create a better customer experience leading to more profit in the long-run.
The goal of the above example is to introduce the topic of agent based modeling and its unique benefits, including the ability to easily capture different agent behaviors. Often, it is argued that we take decisions based on bounded rationality.
Furthermore, another major benefit is the ability to see how micro-scale behavior impacts the overall system. We see, for example, how balking tolerance of individuals can dictate different average waiting time in queues and different accumulated profit.
In subsequent articles, we can look at how to select the optimal model assumptions and parameters for a model after validating against available data and stylized facts. | [
{
"code": null,
"e": 191,
"s": 172,
"text": "Table of contents:"
},
{
"code": null,
"e": 227,
"s": 191,
"text": "1- Intro: why agent based modeling?"
},
{
"code": null,
"e": 263,
"s": 227,
"text": "2- Our supermarket queueing problem"
},
{
"code": null,
"e": 279,
"s": 263,
"text": "3- Model design"
},
{
"code": null,
"e": 298,
"s": 279,
"text": "4- Model execution"
},
{
"code": null,
"e": 312,
"s": 298,
"text": "5- Conclusion"
},
{
"code": null,
"e": 457,
"s": 312,
"text": "Agent based modeling (ABM) is a bottom-up simulation technique where we analyze a system by its individual agents that interact with each other."
},
{
"code": null,
"e": 595,
"s": 457,
"text": "Suppose we want to predict the number of COVID cases in a particular region, we can create agents representing the people in that region."
},
{
"code": null,
"e": 882,
"s": 595,
"text": "We simulate the behavior of several agents (people) where some may be wearing masks while others aren’t, some are vaccinated, some are very social while others aren’t etc. We then simulate their interactions with each other and the associated probabilities of COVID being transmitted..."
},
{
"code": null,
"e": 1244,
"s": 882,
"text": "After running the simulation, we are able to better understand the overall system... we see the number of infections in the population, the number of people recovered, transmission rates, whether we hit herd immunity etc. We can also analyze how the system would look like (infections, recoveries etc.) if we were to impose measures such as forced vaccinations."
},
{
"code": null,
"e": 1348,
"s": 1244,
"text": "The cornerstone of ABM is the ability to understand macro phenomena emerging from micro-scale behavior."
},
{
"code": null,
"e": 1706,
"s": 1348,
"text": "In the above example, the alternative to using ABM is to directly look at macro-level stats such as the number of infections and recoveries and to directly analyze the trends of those stats. Instead, ABM emphasizes the behavior of individual agents which is a more flexible and granular bottom-up approach that can capture aspects a macro-scale model can’t."
},
{
"code": null,
"e": 1827,
"s": 1706,
"text": "ABM has uses in biology, social sciences, traffic management, and supply chain management amongst many other disiplines."
},
{
"code": null,
"e": 2068,
"s": 1827,
"text": "The behavior of those agents should represent reality as closely as possible (we can validate that), so for example, if 75% of people in that region wear masks, then we create agents such that 75% of them are modeled as mask-wearing agents."
},
{
"code": null,
"e": 2130,
"s": 2068,
"text": "Suppose that we are managing staffing costs at a supermarket."
},
{
"code": null,
"e": 2278,
"s": 2130,
"text": "Problem: For a particular hour, we expect 500 customers to show up and we want to determine how many counters should we have open during that hour."
},
{
"code": null,
"e": 2401,
"s": 2278,
"text": "The average customer is worth $10 of gross margin while the average cost to operate a single counter for one hour is $300."
},
{
"code": null,
"e": 2594,
"s": 2401,
"text": "In contrast to standard queueing theory models (M/M/1, M/G/1, M/M/c etc.), agent based modeling can more easily capture behavioral aspects in this multi-waiting-line, multi-server environment."
},
{
"code": null,
"e": 2839,
"s": 2594,
"text": "Common behaviors including queue balking (customer doesn’t join the queue because it is too long), reneging (customer joins the queue but leaves after waiting for too long), and jockeying (customers moving from a longer queue to a shorter one)."
},
{
"code": null,
"e": 2889,
"s": 2839,
"text": "We shall attempt to solve this problem using ABM."
},
{
"code": null,
"e": 2952,
"s": 2889,
"text": "We’ll build a simple ABM model with the following assumptions:"
},
{
"code": null,
"e": 3006,
"s": 2952,
"text": "1- We are optimizing net profit for this single hour."
},
{
"code": null,
"e": 3085,
"s": 3006,
"text": "2- Exactly 500 customers will be arriving to the Supermarket during this hour."
},
{
"code": null,
"e": 3117,
"s": 3085,
"text": "3- Every customer is worth $10."
},
{
"code": null,
"e": 3157,
"s": 3117,
"text": "4- Every counter costs $300 to operate."
},
{
"code": null,
"e": 3336,
"s": 3157,
"text": "5- Customers arrive at the supermarket queues at different times during the day, based on a beta distribution, such that they are more likely to arrive at the middle of the hour."
},
{
"code": null,
"e": 3575,
"s": 3336,
"text": "6- The average time to process a customer order is 45 seconds, but the processing time differs between customers. It follows a Poisson distribution (for simplicity and to ensure we get discrete non-negative numbers) with an average of 45."
},
{
"code": null,
"e": 3966,
"s": 3575,
"text": "7- Every customer has a balking tolerance which is the number of people in the queue that a customer is willing to join. If there are more people in the queue, the customer won’t join the queue and we lose the sale. The customers’ balking tolerance follows a poisson distribution. The average tolerance is 6 i.e. most customers will balk if there are 6 or more other customers in the queue."
},
{
"code": null,
"e": 4023,
"s": 3966,
"text": "8- Customers choose the counter with the shortest queue."
},
{
"code": null,
"e": 4236,
"s": 4023,
"text": "Note that in real-world applications, we validate the assumptions (or pass them as parameters to be optimized) against available data. Also, in this introductory example, balking is the only behavior we consider."
},
{
"code": null,
"e": 4365,
"s": 4236,
"text": "We run the ABM simulation for 3600 steps (ticks) representing 3600 seconds in the hour. Below is the initial configuration code."
},
{
"code": null,
"e": 4563,
"s": 4365,
"text": "# Configticks = 3600 # 3600 ticks = 3600 seconds = 1 hourno_customers = 500avg_service_time = 45 # ticks/seconds per customergross_margin_per_customer = 10 # dollarscost_per_counter = 300 # dollars"
},
{
"code": null,
"e": 4802,
"s": 4563,
"text": "Now, we use the Mesa library in python to code the rest of our model. Let’s start with defining our Customer class and the required attributes. The Customer class is one of two type of agents we will be dealing with, the other is Counter."
},
{
"code": null,
"e": 5507,
"s": 4802,
"text": "from mesa import Agentclass Customer(Agent): def __init__(self, unique_id, model): super().__init__(unique_id, model) # Time required to process the customer's transaction self.service_time = ss.poisson(45).rvs() # Time of arrival at queue self.entry_time = np.int(ss.beta(3, 3).rvs() * ticks) + 1 self.balk_tolerance = ss.poisson(5).rvs() + 1 # Whether or not the customer has arrived at the queue self._arrived = False self._chosen_counter = None self._q_entry = None self._q_exit = None # Start time when customer is being served self._service_entry = None # End time self._service_exit = None"
},
{
"code": null,
"e": 5642,
"s": 5507,
"text": "We also need to create a “step” method for our customers which describes what do they do at each step (tick/second) of the simulation."
},
{
"code": null,
"e": 7299,
"s": 5642,
"text": "class Customer(Agent): def __init__(self, unique_id, model): super().__init__(unique_id, model) # Time required to process the customer's transaction self.service_time = ss.poisson(45).rvs() # Time of arrival at queue self.entry_time = np.int(ss.beta(3, 3).rvs() * ticks) + 1 self.balk_tolerance = ss.poisson(5).rvs() + 1 # Whether or not the customer has arrived at the queue self._arrived = False self._chosen_counter = None self._q_entry = None self._q_exit = None # Start time when customer is being served self._service_entry = None # End time self._service_exit = None def select_counter(self): self._arrived = True # Queue at shortest counter self._chosen_counter_idx = np.argmin([ len(counter.queue) for counter in self.model.counters]) self._chosen_counter = self.model.counters[ self._chosen_counter_idx] # Balk if there are too many people at the counter if len(self._chosen_counter.queue) < self.balk_tolerance: self._chosen_counter.queue.append(self) self._q_entry = self.model._current_tick def pay_n_leave(self): self._service_exit = self.model._current_tick self._chosen_counter.active_customer = None def step(self): if (self._arrived == False) & \\ (self.model._current_tick >= self.entry_time): self.select_counter() elif isinstance(self._service_entry, int): if self.model._current_tick - self._service_entry \\ == self.service_time: self.pay_n_leave()"
},
{
"code": null,
"e": 7614,
"s": 7299,
"text": "In the above code, at every simulation step, if we have arrived at the simulation step/time which matches the customer’s entry time (time at which he arrives at the supermarket queue), then we run the select_counter method where he chooses the counter with the shortest queue or he balks if that queue is too long."
},
{
"code": null,
"e": 7824,
"s": 7614,
"text": "If the customer is already being served at the counter, we check if we have already run enough steps to arrive at his service time (time required to process his transaction) then we run the pay_n_leave method."
},
{
"code": null,
"e": 7895,
"s": 7824,
"text": "Similarly, the below code is used for the 2nd type of agents, Counter."
},
{
"code": null,
"e": 8401,
"s": 7895,
"text": "class Counter(Agent): def __init__(self, unique_id, model): super().__init__(unique_id, model) self.queue = [] self.active_customer = None def dequeue(self): try: self.active_customer = self.queue.pop(0) self.active_customer._service_entry = self.model._current_tick self.active_customer._q_exit = self.model._current_tick except: pass def step(self): if self.active_customer is None: self.dequeue()"
},
{
"code": null,
"e": 8520,
"s": 8401,
"text": "Finally, we create a QueueModel class which is used to manage the overall simulation/system that the agents belong to."
},
{
"code": null,
"e": 9445,
"s": 8520,
"text": "from mesa import Modelfrom mesa.time import RandomActivationclass QueueModel(Model): \"\"\"Queueing model with customers and counters as two types of agents that interact with each other \"\"\" def __init__(self, no_customers, no_counters, ticks): self.ticks = ticks self._current_tick = 1 self.no_customers = no_customers self.no_counters = no_counters self.schedule = RandomActivation(self) # Create agents self.customers = [] self.counters = [] for i in range(self.no_customers): customer = Customer(i, self) self.schedule.add(customer) self.customers.append(customer) for i in range(self.no_counters): counter = Counter(i + no_customers, self) self.schedule.add(counter) self.counters.append(counter) def step(self): self.schedule.step() self._current_tick += 1"
},
{
"code": null,
"e": 9687,
"s": 9445,
"text": "The QueueModel class can be initiated with the number of customers (in our example 500), the number of counters (this is what we are trying to determine), and the ticks (number of simulation steps, 3600 representing 3600 seconds in an hour)."
},
{
"code": null,
"e": 9908,
"s": 9687,
"text": "We have a “schedule” attribute where we describe which agents will be activated and when. We use RandomActivation which activates all agents in random order. You can read up the Mesa documentation for different settings."
},
{
"code": null,
"e": 10042,
"s": 9908,
"text": "Upon initialization, there are 2 for loops where we create the Customer and Counter agents. We also add them to the model’s schedule."
},
{
"code": null,
"e": 10210,
"s": 10042,
"text": "There is also a “step” method that orchestrates running one step of the simulation and it also triggers the “step” methods of the agents that are part of the schedule."
},
{
"code": null,
"e": 10269,
"s": 10210,
"text": "We can now run the simulation by running the below code..."
},
{
"code": null,
"e": 10394,
"s": 10269,
"text": "model = QueueModel(ticks=ticks, no_customers=no_customers, no_counters=no_counters)for i in range(ticks): model.step()"
},
{
"code": null,
"e": 10566,
"s": 10394,
"text": "However, we can also add a “data collector” to our QueueModel class that can help us track metrics of interest. We can track those metrics at every step of our simulation."
},
{
"code": null,
"e": 10589,
"s": 10566,
"text": "Let’s track 8 metrics:"
},
{
"code": null,
"e": 10714,
"s": 10589,
"text": "1- Number of customers arrived. At the end of the 3600 simulation steps (representing 1 hour), we should have 500 customers."
},
{
"code": null,
"e": 10753,
"s": 10714,
"text": "2- Number of customers already served."
},
{
"code": null,
"e": 10838,
"s": 10753,
"text": "3- Number of customers who arrived at the queue but balked. We lost those customers."
},
{
"code": null,
"e": 10885,
"s": 10838,
"text": "4- The average queue size across all counters."
},
{
"code": null,
"e": 10942,
"s": 10885,
"text": "5- The average waiting time before a customer is served."
},
{
"code": null,
"e": 11006,
"s": 10942,
"text": "6- Gross margin = number of customers served x $10 per customer"
},
{
"code": null,
"e": 11053,
"s": 11006,
"text": "7- Operating costs = number of counters x $300"
},
{
"code": null,
"e": 11102,
"s": 11053,
"text": "8- Total profit = Gross margin - Operating costs"
},
{
"code": null,
"e": 11225,
"s": 11102,
"text": "In order to add the metrics to our ABM model, we first create them as functions that take our QueueModel as an argument..."
},
{
"code": null,
"e": 12684,
"s": 11225,
"text": "def get_customers_arrived(model): customers_arrived = [ customer._arrived for customer in model.customers] no_customers_arrived = np.sum(customers_arrived) return no_customers_arriveddef get_customers_served(model): customers_served = [not(customer._service_exit is None) for customer in model.customers] no_customers_served = np.sum(customers_served) return no_customers_serveddef get_customers_balked(model): customers_arrived = [ customer._arrived for customer in model.customers] # Customers who never joined a queue customers_no_q = np.array([ customer._q_entry is None for customer in model.customers]) no_customers_balked = np.sum(customers_arrived * customers_no_q) return no_customers_balkeddef get_avg_queue_size(model): queue_size = [len(counter.queue) for counter in model.counters] avg_queue_size = np.mean(queue_size) return avg_queue_sizedef get_avg_waiting_time(model): customers_wait = [np.nan if customer._q_exit is None else customer._q_exit - customer._q_entry for customer in model.customers] avg_customer_wait = np.nanmean(customers_wait) return avg_customer_waitdef get_gross_margin(model): return gross_margin_per_customer * get_customers_served(model)def get_operating_costs(model): return cost_per_counter * no_countersdef get_total_profit(model): return get_gross_margin(model) - get_operating_costs(model)"
},
{
"code": null,
"e": 12738,
"s": 12684,
"text": "Finally, we update our QueueModel class as follows..."
},
{
"code": null,
"e": 14131,
"s": 12738,
"text": "from mesa.datacollection import DataCollectorclass QueueModel(Model): \"\"\"Queueing model with customers and counters as two types of agents that interact with each other \"\"\" def __init__(self, no_customers, no_counters, ticks): self.ticks = ticks self._current_tick = 1 self.no_customers = no_customers self.no_counters = no_counters self.schedule = RandomActivation(self) # Create agents self.customers = [] self.counters = [] for i in range(self.no_customers): customer = Customer(i, self) self.schedule.add(customer) self.customers.append(customer) for i in range(self.no_counters): counter = Counter(i + no_customers, self) self.schedule.add(counter) self.counters.append(counter) self.datacollector = DataCollector( model_reporters={ 'Customers Arrived': get_customers_arrived, 'Customers Served': get_customers_served, 'Customers Balked': get_customers_balked, 'Average Waiting Time': get_avg_waiting_time, 'Average Queue Size': get_avg_queue_size, 'Gross Margin': get_gross_margin, 'Operating Costs': get_operating_costs, 'Total Profit': get_total_profit}) def step(self): self.datacollector.collect(self) self.schedule.step() self._current_tick += 1"
},
{
"code": null,
"e": 14168,
"s": 14131,
"text": "We are now ready to run our model..."
},
{
"code": null,
"e": 14214,
"s": 14168,
"text": "Let’s try to run our model with 5 counters..."
},
{
"code": null,
"e": 14354,
"s": 14214,
"text": "no_counters = 5model = QueueModel(ticks=ticks, no_customers=no_customers, no_counters=no_counters)for i in range(ticks): model.step()"
},
{
"code": null,
"e": 14413,
"s": 14354,
"text": "Below are the results and the code used to produce them..."
},
{
"code": null,
"e": 15518,
"s": 14413,
"text": "run_stats = model.datacollector.get_model_vars_dataframe()fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1)fig.figure.set_figwidth(12)fig.figure.set_figheight(16)fig.suptitle(f'Simulations stats using {no_counters} counters', fontsize=20)ax1.plot(run_stats[['Customers Arrived', 'Customers Served', 'Customers Balked', ]])ax1.legend(['Customers Arrived', 'Customers Served', 'Customers Balked', ])ax1.set_ylabel('Customers')ax1.set_xlim(0)ax1.set_ylim(0)ax2.plot(run_stats['Average Queue Size'], color='red')ax2.legend(['Average Queue Size'])ax2.set_ylabel('Customers')ax2.set_xlim(0)ax2.set_ylim(0)ax3.plot(run_stats['Average Waiting Time'], color='grey')ax3.legend(['Average Waiting Time (across full hour)'])ax3.set_ylabel('Seconds')ax3.set_xlim(0)ax3.set_ylim(0)ax4.plot(run_stats[['Gross Margin', 'Operating Costs', 'Total Profit' ]])ax4.legend(['Gross Margin', 'Operating Costs', 'Total Profit' ])ax4.set_ylabel('Dollars')ax4.set_xlim(0)fig.show()"
},
{
"code": null,
"e": 15601,
"s": 15518,
"text": "The x-axis represents the 3600 ticks/seconds in the 1 hour that we are simulating."
},
{
"code": null,
"e": 15724,
"s": 15601,
"text": "The first chart shows us how after ~1200 seconds (~20 minutes), customers start to balk as too many customer are arriving."
},
{
"code": null,
"e": 15898,
"s": 15724,
"text": "In the 2nd chart, we can see how the queue size starts to increase after roughly ~10 minutes and it peaks at approximately 6 customers per counter at the middle of the hour."
},
{
"code": null,
"e": 16145,
"s": 15898,
"text": "The 3rd chart shows us how average waiting time (cumulative) increases from the beginning of the hour towards the end of the hour as many customers arrive at the middle of the hour and they wait in long queues pushing the average waiting time up."
},
{
"code": null,
"e": 16258,
"s": 16145,
"text": "Finally, the 4th chart shows us our financials, where we accumulate just over $1500 towards the end of the hour."
},
{
"code": null,
"e": 16390,
"s": 16258,
"text": "Based on the above, 5 counters seems to be too low as we can see that just under 200 customers (40%) have balked and they are lost."
},
{
"code": null,
"e": 16500,
"s": 16390,
"text": "Now, let’s try to run the simulations with 5–15 counters to determine what is the ideal number of counters..."
},
{
"code": null,
"e": 16850,
"s": 16500,
"text": "full_stats = {}for no_counters in range (5, 16): model = QueueModel(ticks=ticks, no_customers=no_customers, no_counters=no_counters) for i in range(ticks): model.step() run_stats = model.datacollector.get_model_vars_dataframe() full_stats[no_counters] = run_stats.iloc[-1] pd.DataFrame(full_stats).transpose().astype(int)"
},
{
"code": null,
"e": 17075,
"s": 16850,
"text": "In the above code, we run simulations with 5–15 counters and we look at the stats at the end of each simulation (not every step of the simulation). The dataframe output shows the results with different numbers of counters..."
},
{
"code": null,
"e": 17143,
"s": 17075,
"text": "We can see that total profit is maximized at $2030 with 9 counters."
},
{
"code": null,
"e": 17247,
"s": 17143,
"text": "We can optimize based on any metric of interest... immediate profit is not necessarily the best metric."
},
{
"code": null,
"e": 17552,
"s": 17247,
"text": "Average waiting time per customer using 9 counters is 94 seconds... by just adding one additional counter, we cut the waiting time by 33 seconds to 61 and we only lose $90 (total profit is $1940). Reduced waiting time can likely create a better customer experience leading to more profit in the long-run."
},
{
"code": null,
"e": 17797,
"s": 17552,
"text": "The goal of the above example is to introduce the topic of agent based modeling and its unique benefits, including the ability to easily capture different agent behaviors. Often, it is argued that we take decisions based on bounded rationality."
},
{
"code": null,
"e": 18052,
"s": 17797,
"text": "Furthermore, another major benefit is the ability to see how micro-scale behavior impacts the overall system. We see, for example, how balking tolerance of individuals can dictate different average waiting time in queues and different accumulated profit."
}
] |
From Econometrics to Machine Learning | by Alexandre Wrg | Towards Data Science | As a Data scientist with a master’s degree in econometrics, I took some time to understand the subtleties that make machine learning a different discipline from econometrics. I would like to talk to you about these subtleties that are not obvious at first sight and that made me wonder all along my journey.
Econometrics is the application of statistical methods to economic data in order to give empirical content to economic relationships. More precisely, it is “the quantitative analysis of actual economic phenomena based on the concurrent development of theory and observation, related by appropriate methods of inference”
Machine learning (ML) is the scientific study of algorithms and statistical models that computer systems use to perform a specific task without using explicit instructions, relying on patterns and inference instead. It is seen as a subset of artificial intelligence. Machine learning algorithms build a mathematical model based on sample data, known as training data, in order to make predictions or decisions without being explicitly programmed to perform the task
Very well, so they would seem that both need data, both use statistical models, both make inferences, so according to their definitions the machine learning would seem to deal with broader issues than just the economy. So, why does econometrics still exist ?! This is the question I asked myself when I discovered machine learning at about the same time as the beginning of my econometric studies.
As a futur good econometrist I need to juggle numbers perfectly, have a solid background in Statistics, be a expert of linear algreba and Mathematical optimization and finally have the computer skills to play with data. These skills will be used to understand, demonstrate apply my regression, classification, clustering algorithms or time series prediction. During this year I will learn very deeply some algorithm like Linear Regression , Logistic Regression, Kmeans, ARIMA, VAR ...etc. Wait ? These algorithms are also used for machine learning !
A fundamental difference between machine learning and econometrics lies in their theoretical basis. Econometrics has a solid foundation in mathematical statistics and probability theory. Algorithms are mathematically robust with demonstrable and attractive properties, these algorithms are mainly evaluated on the robustness of their base.
With machine learning, mathematics is of course not absent, but it is present to explain the behaviour of the algorithm and not to demonstrate its reliability and attractive properties. These algorithms are mainly evaluated on their empirical effectiveness. A very revealing example is the success of the Xgboost algorithm which owes its success to its domination over several machine learning competitions rather than its mathematical demonstration.
Another difference is that econometrics has only one solution, given a specified model and a dataset, a parametric regression’s parameters are computed using an algebraic formula. the best linear unbiased estimator (BLUE) of the coefficients is given by the ordinary least squares (OLS) estimator in the case where some assumptions are respected. Here “best” means giving the lowest variance of the estimate, as compared to other unbiased, linear estimators.
While most machine learning algorithms are much too complex to be described by a single mathematical formula. Their solutions have been determined algorithmically by an iterative method called the training phase which has the goal to find the solution that best suits our data, so the solution determined by the machine learning algorithm is approximate and is only most likely optimal.
Econometric models (ie: parametric most of the time) are based on economic theory. Traditional statistical inference tools (such as the maximum likelihood method) are then used to estimate the values of a parameter vector θ, in a parametric model mθ. Asymptotic theory then plays an important role (Taylor’s developments, the law of large numbers and the central limit theorem...etc).
In machine learning, on the other hand, non-parametric models are often constructed, based almost exclusively on data (no underlying distribution assumptions are made), and the meta-parameters used (tree depth, penalty parameter, etc.) are optimized by cross-validation, grid search algorithm or any hyper-parameter optimization algorithm.
You will have understood it, the pattern will be the same as previsouly econometrics rely on robust mathematical test to validate a model, we commonly talk about the goodness of fit of a model. It is evaluated by hypothesis testing, evaluation of the normality of residuals, comparisons of sample distributions. We also talk about R2 which is the proportion of the variance in the dependent variable that is predictable from the independent variable(s),the AIC|BIC which evalue the quality of each model, relative to each of the other models or variable evaluations through p-value .
The evaluation of machine learning models will depend on its prediction, the underlying idea is that if the model is able to predict well then it has successfully learned the hidden patterns in the data. To ensure that the model has not overfitted, the dataset will be separated into a training set and a test set and then come a cross-validation brick to verify the generalization power of the model and that there is no bias in the separation of data. Finally, we will use KPIs that will give us a measure of the gap with reality likesRMSE, MAE or Accuracy .
Both Econometrics and Machine learning try to define a function that define a set of predictor variable that will model a predicted variable :
ɛ are realizations of random variables i.i.d., of law N (0, σ2) also called residual and come from econometrics, otherwise y = f(x) belong to machine learning.
On paper at this stage the two seem to converge, but it is also in the way and objective that they will diverge. Machine learning purpose is y in most of case meanwhile Econometrics purpose is to estimate β of each predictor.
The main purpose of econometrics is not to predict but to quantify an economic phenomenon
If we look at these differences in practice, we will start with a classic econometric model and one of the most widely used models, linear regression. For this purpose we will observe the results of our modeling through the implementation of the sklearnlibrary which mainly serves machine learning models and the implementation of the statsmodelslibrary which is more econometrically oriented.
#import libraryimport pandas as pdimport numpy as npimport seaborn as snsimport statsmodels.api as smfrom sklearn import linear_model#import data iris = sns.load_dataset("iris")
Let’s compare both implementation
dummies = pd.get_dummies(iris["species"], drop_first=False)iris = pd.concat([iris, dummies], axis=1)iris.head()
Since Species is a categorical variable we need to convert it to a format that a computer can handle, so we turn to a onehot encoding format. Let’s begin with machine learning.
We can extract the model coefficients and the slope parameter beta0 through model object. Let’s give a try with statsmodels.
Statsmodels give us a lot of informations compared to sklearn, we got a very good R2, the AIC, BIC that we talk previously, coefficient of each variable and warnings. Let’s try to predict :
We got the same R2 and very good mae and Rmse ... but we constate that coefficient are not equals between both model. Statsmodels warn us that there’s a possibility our model are Multicollinear ! That refers to a situation in which two or more explanatory variables in a multiple regression model are highly linearly related, that means there’s redondant informations in our dataset. That informations come from the species variable we must drop one category because that obvious if iris is not setosa or verginica is it versicolor.
This means that, although our model has a strong R2 and therefore a strong predictive power, these coefficients are biased and uninterpretable.
This information has not been transmitted to us by sklearn. Let’s correct it by passing drop_first = True.
Statsmodel has removed its warning, we now have the unbiased coefficients. Moreover, the skewness are near from 0 and kurtosis too that mean our residus are likely normal, the probability of Jarque-Bera confirm that this is a good model. Let’s rerun our sklearn model :
Finaly we got the same, let’s do some reading. It can be seen that all other things being equal, a 1% increase in the length of the petals increases the width of the petal by 0.24cm. In the case of the categorical variables we always refer to the absent category we can see that all things being equal, the species verginica has a petal wider of 1.04cm than the absent species setosa. All p-values are significant at 5% thresholds so our coefficients are considered robust and unbiased. We have seen the analysis of a linear regression model, which can also be transposed to classification. Logistic regression offers a very interestingodds ratioreading in model analysis, I would discuss the reading of the odds ratio in a future article.
reading in model analysis, I would discuss the reading of the odds ratio in a future article.
The probabilistic foundations of econometrics are undoubtedly its strength, with not only an interpretability of models, but also a quantification of uncertainty. Nevertheless, the predictive performance of machine learning models is interesting, because they allow us to highlight a poor specification of an econometric model and some of these algorithms are more suitable for unstructured data. Econometrics is intended to be rigorous but becomes a very relevant economic factor analysis tool, if your manager asks you to quantify an effect, it could be relevant in addition to giving you statistical and mathematical legitimacy. | [
{
"code": null,
"e": 479,
"s": 171,
"text": "As a Data scientist with a master’s degree in econometrics, I took some time to understand the subtleties that make machine learning a different discipline from econometrics. I would like to talk to you about these subtleties that are not obvious at first sight and that made me wonder all along my journey."
},
{
"code": null,
"e": 799,
"s": 479,
"text": "Econometrics is the application of statistical methods to economic data in order to give empirical content to economic relationships. More precisely, it is “the quantitative analysis of actual economic phenomena based on the concurrent development of theory and observation, related by appropriate methods of inference”"
},
{
"code": null,
"e": 1265,
"s": 799,
"text": "Machine learning (ML) is the scientific study of algorithms and statistical models that computer systems use to perform a specific task without using explicit instructions, relying on patterns and inference instead. It is seen as a subset of artificial intelligence. Machine learning algorithms build a mathematical model based on sample data, known as training data, in order to make predictions or decisions without being explicitly programmed to perform the task"
},
{
"code": null,
"e": 1663,
"s": 1265,
"text": "Very well, so they would seem that both need data, both use statistical models, both make inferences, so according to their definitions the machine learning would seem to deal with broader issues than just the economy. So, why does econometrics still exist ?! This is the question I asked myself when I discovered machine learning at about the same time as the beginning of my econometric studies."
},
{
"code": null,
"e": 2213,
"s": 1663,
"text": "As a futur good econometrist I need to juggle numbers perfectly, have a solid background in Statistics, be a expert of linear algreba and Mathematical optimization and finally have the computer skills to play with data. These skills will be used to understand, demonstrate apply my regression, classification, clustering algorithms or time series prediction. During this year I will learn very deeply some algorithm like Linear Regression , Logistic Regression, Kmeans, ARIMA, VAR ...etc. Wait ? These algorithms are also used for machine learning !"
},
{
"code": null,
"e": 2553,
"s": 2213,
"text": "A fundamental difference between machine learning and econometrics lies in their theoretical basis. Econometrics has a solid foundation in mathematical statistics and probability theory. Algorithms are mathematically robust with demonstrable and attractive properties, these algorithms are mainly evaluated on the robustness of their base."
},
{
"code": null,
"e": 3004,
"s": 2553,
"text": "With machine learning, mathematics is of course not absent, but it is present to explain the behaviour of the algorithm and not to demonstrate its reliability and attractive properties. These algorithms are mainly evaluated on their empirical effectiveness. A very revealing example is the success of the Xgboost algorithm which owes its success to its domination over several machine learning competitions rather than its mathematical demonstration."
},
{
"code": null,
"e": 3463,
"s": 3004,
"text": "Another difference is that econometrics has only one solution, given a specified model and a dataset, a parametric regression’s parameters are computed using an algebraic formula. the best linear unbiased estimator (BLUE) of the coefficients is given by the ordinary least squares (OLS) estimator in the case where some assumptions are respected. Here “best” means giving the lowest variance of the estimate, as compared to other unbiased, linear estimators."
},
{
"code": null,
"e": 3850,
"s": 3463,
"text": "While most machine learning algorithms are much too complex to be described by a single mathematical formula. Their solutions have been determined algorithmically by an iterative method called the training phase which has the goal to find the solution that best suits our data, so the solution determined by the machine learning algorithm is approximate and is only most likely optimal."
},
{
"code": null,
"e": 4235,
"s": 3850,
"text": "Econometric models (ie: parametric most of the time) are based on economic theory. Traditional statistical inference tools (such as the maximum likelihood method) are then used to estimate the values of a parameter vector θ, in a parametric model mθ. Asymptotic theory then plays an important role (Taylor’s developments, the law of large numbers and the central limit theorem...etc)."
},
{
"code": null,
"e": 4575,
"s": 4235,
"text": "In machine learning, on the other hand, non-parametric models are often constructed, based almost exclusively on data (no underlying distribution assumptions are made), and the meta-parameters used (tree depth, penalty parameter, etc.) are optimized by cross-validation, grid search algorithm or any hyper-parameter optimization algorithm."
},
{
"code": null,
"e": 5159,
"s": 4575,
"text": "You will have understood it, the pattern will be the same as previsouly econometrics rely on robust mathematical test to validate a model, we commonly talk about the goodness of fit of a model. It is evaluated by hypothesis testing, evaluation of the normality of residuals, comparisons of sample distributions. We also talk about R2 which is the proportion of the variance in the dependent variable that is predictable from the independent variable(s),the AIC|BIC which evalue the quality of each model, relative to each of the other models or variable evaluations through p-value ."
},
{
"code": null,
"e": 5720,
"s": 5159,
"text": "The evaluation of machine learning models will depend on its prediction, the underlying idea is that if the model is able to predict well then it has successfully learned the hidden patterns in the data. To ensure that the model has not overfitted, the dataset will be separated into a training set and a test set and then come a cross-validation brick to verify the generalization power of the model and that there is no bias in the separation of data. Finally, we will use KPIs that will give us a measure of the gap with reality likesRMSE, MAE or Accuracy ."
},
{
"code": null,
"e": 5863,
"s": 5720,
"text": "Both Econometrics and Machine learning try to define a function that define a set of predictor variable that will model a predicted variable :"
},
{
"code": null,
"e": 6023,
"s": 5863,
"text": "ɛ are realizations of random variables i.i.d., of law N (0, σ2) also called residual and come from econometrics, otherwise y = f(x) belong to machine learning."
},
{
"code": null,
"e": 6249,
"s": 6023,
"text": "On paper at this stage the two seem to converge, but it is also in the way and objective that they will diverge. Machine learning purpose is y in most of case meanwhile Econometrics purpose is to estimate β of each predictor."
},
{
"code": null,
"e": 6339,
"s": 6249,
"text": "The main purpose of econometrics is not to predict but to quantify an economic phenomenon"
},
{
"code": null,
"e": 6733,
"s": 6339,
"text": "If we look at these differences in practice, we will start with a classic econometric model and one of the most widely used models, linear regression. For this purpose we will observe the results of our modeling through the implementation of the sklearnlibrary which mainly serves machine learning models and the implementation of the statsmodelslibrary which is more econometrically oriented."
},
{
"code": null,
"e": 6911,
"s": 6733,
"text": "#import libraryimport pandas as pdimport numpy as npimport seaborn as snsimport statsmodels.api as smfrom sklearn import linear_model#import data iris = sns.load_dataset(\"iris\")"
},
{
"code": null,
"e": 6945,
"s": 6911,
"text": "Let’s compare both implementation"
},
{
"code": null,
"e": 7057,
"s": 6945,
"text": "dummies = pd.get_dummies(iris[\"species\"], drop_first=False)iris = pd.concat([iris, dummies], axis=1)iris.head()"
},
{
"code": null,
"e": 7234,
"s": 7057,
"text": "Since Species is a categorical variable we need to convert it to a format that a computer can handle, so we turn to a onehot encoding format. Let’s begin with machine learning."
},
{
"code": null,
"e": 7359,
"s": 7234,
"text": "We can extract the model coefficients and the slope parameter beta0 through model object. Let’s give a try with statsmodels."
},
{
"code": null,
"e": 7549,
"s": 7359,
"text": "Statsmodels give us a lot of informations compared to sklearn, we got a very good R2, the AIC, BIC that we talk previously, coefficient of each variable and warnings. Let’s try to predict :"
},
{
"code": null,
"e": 8082,
"s": 7549,
"text": "We got the same R2 and very good mae and Rmse ... but we constate that coefficient are not equals between both model. Statsmodels warn us that there’s a possibility our model are Multicollinear ! That refers to a situation in which two or more explanatory variables in a multiple regression model are highly linearly related, that means there’s redondant informations in our dataset. That informations come from the species variable we must drop one category because that obvious if iris is not setosa or verginica is it versicolor."
},
{
"code": null,
"e": 8226,
"s": 8082,
"text": "This means that, although our model has a strong R2 and therefore a strong predictive power, these coefficients are biased and uninterpretable."
},
{
"code": null,
"e": 8333,
"s": 8226,
"text": "This information has not been transmitted to us by sklearn. Let’s correct it by passing drop_first = True."
},
{
"code": null,
"e": 8603,
"s": 8333,
"text": "Statsmodel has removed its warning, we now have the unbiased coefficients. Moreover, the skewness are near from 0 and kurtosis too that mean our residus are likely normal, the probability of Jarque-Bera confirm that this is a good model. Let’s rerun our sklearn model :"
},
{
"code": null,
"e": 9343,
"s": 8603,
"text": "Finaly we got the same, let’s do some reading. It can be seen that all other things being equal, a 1% increase in the length of the petals increases the width of the petal by 0.24cm. In the case of the categorical variables we always refer to the absent category we can see that all things being equal, the species verginica has a petal wider of 1.04cm than the absent species setosa. All p-values are significant at 5% thresholds so our coefficients are considered robust and unbiased. We have seen the analysis of a linear regression model, which can also be transposed to classification. Logistic regression offers a very interestingodds ratioreading in model analysis, I would discuss the reading of the odds ratio in a future article."
},
{
"code": null,
"e": 9437,
"s": 9343,
"text": "reading in model analysis, I would discuss the reading of the odds ratio in a future article."
}
] |
Visualize Categorical Relationships With Catscatter | by Myriam | Towards Data Science | If you ever needed a way to plot categorial features showing its relationships, I’ve built this resource for you. A catscatter function built over matplotlib.pyplot object and using pandas to visualize relationships between your categorial variables as if it were a scatter plot. (I know, there’re no correlations here, but it looks like it and its built on a scatter plot, right?).
github.com
I work as a Data Analyst using a bit of Data Science and a lot of Data Visualization. Last December a coworker gave me for Christmas the book “Knowledge is Beautiful” which I loved. Its Data Visualizations are amazing and really complex. I like to read it when I want to get inspired.
At the same time, I work for a VC fund, where frameworks and relationships are really important. Showing relationships between categorical variables is not always an easy thing due to their “string” nature.
These two situations motivated me to create and use a catscatter function. This function is based in scatter plots relationships but uses categorical variables in a beautiful and simple way. Actually, the visualization is closer to an “adjacency matrix” than a “scatter plot”: it means that we are not interested in where the markers are to find correlations but on which categories are connected to each other, or which ones are more connected to something than to something else. They can be seen as a kind of “graph” relationships. For that purpose it was important to not only plot the markers in the intersections between features but to draw horizontal and vertical lines in the background to follow easily the connections.
The function is built for Python over Matplotlib and Pandas. It has the following inputs:
df: pandas DataFrame, required. It needs at least two columns with the categorical variables you want to relate, and the value of both (if it’s just an adjacent matrix write a column with )
colx: string, required. The name of the column to display horizontally.
coly: string, required. The name of the column to display vertically.
cols: string, required. The name of the column with the value between the two variables.
color: list, optional. Colors to display in the visualization, the length can be two or three. The two first are the colors for the lines in the matrix, the last one the font color and markers color. default [‘grey’,’black’]
ratio: int or float, optional. A ratio for controlling the relative size of the markers. default 10
font: string, optional. The font for the ticks on the matrix. default ‘Helvetica’
save: bool, optional. True for saving as an image in the same path as the code. default False
save_name: string, optional. The name used for saving the image (then the code ads .png) default: “Default”
There’s no output. The object is not closed so it can be initiated or changed by the user before and after.
Imagine you invite some of your friends to have dinner at home. You can build a catscatter to see everyone favorite food and buy what’s more suitable for all of them. You need a DataFrame containing the relationships between your friends and food. For example, you know that Ignacio loves Hamburguers but also likes Pizza, so you built a relationship between “Ignacio” and “Hamburguer” with a grade “5” and a relationship between “Ignacio” and “Pizza” of grade “3”. You do the same for everything you know about your friends and plot a catscatter.
import pandas as pdimport matplotlib as pltfrom catscatter import catscatter# example data framedata=pd.DataFrame({‘friend’:[‘Peter’,’Marc’,’Ignacio’,’Marta’,’Marta’,’Ignacio’,’Maria’,’Pedro’,’Bea’,’Pedro’], ‘favorite_food’:[‘Salmon’,’Chocolate’,’Hamburguer’,’Pizza’,’Apples’,’Pizza’,’Pizza’,’Hamburguer’,’Salmon’,’Banana’], ‘favorite_grade’:[1,5,5,3,2,3,4,4,3,1]})#plot itcatscatter(data,’friend’,’favorite_food’,’favorite_grade’)plt.show()
Output:
Here you can see that Pizza is the most liked food, but if you are inviting Bea and Peter maybe ordering Salmon Tataki is the best option. Don’t waste your time buying fruit. For Marc, I’m sure you’ve only had desserts with him, you should invite him to a dinner to gather more data!
This example is the same than the one before but bigger and more colorful.
import pandas as pdimport matplotlib as pltfrom catscatter import catscatter# example dataframedata=pd.DataFrame({‘friend’:[‘Peter’,’Marc’,’Ignacio’,’Marta’,’Marta’,’Ignacio’,’Maria’,’Pedro’,’Bea’,’Pedro’], ‘favorite_food’:[‘Salmon’,’Chocolate’,’Hamburguer’,’Pizza’,’Apples’,’Pizza’,’Pizza’,’Hamburguer’,’Salmon’,’Banana’], ‘favorite_grade’:[1,5,5,3,2,3,4,4,3,1]})colors=[‘green’,’grey’,’orange’]# create the plotplt.figure(figsize=(8,8))catscatter(data,’friend’,’favorite_food’,’favorite_grade’,color=colors,ratio=100)plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()
Output:
At my office we wanted to know which EU Seed Investors are more active in which Industries. I gather information about all the seed rounds between 2015 and 2019 in Europe and prepare a dataset with the number of deals each Investor made by Industry (if no deals there’s no row). The number of deals is how strong or weak is the relationship between the Industry and the Investor.
import pandas as pdimport matplotlib.pyplot as pltfrom catscatter import catscatter# read the dataframedf=pd.read_csv(“top-european-investors-seed-rounds-15–19.csv”)df
Output:
kcolors=[‘#F73972’,’#F2B3C6',’#144962']# create the plotplt.figure(figsize=(50,20))catscatter(df,’Investor’,’Company Industry’,’Announced Date’,color=kcolors, ratio=20)plt.xticks(fontsize=20)plt.yticks(fontsize=20)plt.show()
Output:
We had 700 Investors and 600 Industries, but for this visualization I only leave the top 100 Investors and top 50 Industries more active. At my office we created two posters that you can find here and here.
In the one displayed here, you can see that “High-Tech Grunderfonds” made deals in almost all of the top sectors, but with more focus on “Information Technology” and “Software”. Also “Innogest Capital” and “Inbox Capital” have made nearly the same number of deals, but “Inbox Capital” is generalist and “Innogest Capital” focused only on “Ecommerce” and “Fashion”. We can see also that “Advertising” is not really common but “Software” is, and there’re Investors that focus on “Medical” but not on “Travel”
I can’t share the df used for the last one, but I hope it helps seeing the potential of my little piece of code at a bigger scale.
If you want to try catscatter here’s the code for you! 👇
github.com
What do you think? Do you find it useful? What other ways do you have to plot relations between categorical features? Let me know in the comments section!
If you use it I would love to know it too 🤗 | [
{
"code": null,
"e": 554,
"s": 171,
"text": "If you ever needed a way to plot categorial features showing its relationships, I’ve built this resource for you. A catscatter function built over matplotlib.pyplot object and using pandas to visualize relationships between your categorial variables as if it were a scatter plot. (I know, there’re no correlations here, but it looks like it and its built on a scatter plot, right?)."
},
{
"code": null,
"e": 565,
"s": 554,
"text": "github.com"
},
{
"code": null,
"e": 850,
"s": 565,
"text": "I work as a Data Analyst using a bit of Data Science and a lot of Data Visualization. Last December a coworker gave me for Christmas the book “Knowledge is Beautiful” which I loved. Its Data Visualizations are amazing and really complex. I like to read it when I want to get inspired."
},
{
"code": null,
"e": 1057,
"s": 850,
"text": "At the same time, I work for a VC fund, where frameworks and relationships are really important. Showing relationships between categorical variables is not always an easy thing due to their “string” nature."
},
{
"code": null,
"e": 1787,
"s": 1057,
"text": "These two situations motivated me to create and use a catscatter function. This function is based in scatter plots relationships but uses categorical variables in a beautiful and simple way. Actually, the visualization is closer to an “adjacency matrix” than a “scatter plot”: it means that we are not interested in where the markers are to find correlations but on which categories are connected to each other, or which ones are more connected to something than to something else. They can be seen as a kind of “graph” relationships. For that purpose it was important to not only plot the markers in the intersections between features but to draw horizontal and vertical lines in the background to follow easily the connections."
},
{
"code": null,
"e": 1877,
"s": 1787,
"text": "The function is built for Python over Matplotlib and Pandas. It has the following inputs:"
},
{
"code": null,
"e": 2067,
"s": 1877,
"text": "df: pandas DataFrame, required. It needs at least two columns with the categorical variables you want to relate, and the value of both (if it’s just an adjacent matrix write a column with )"
},
{
"code": null,
"e": 2139,
"s": 2067,
"text": "colx: string, required. The name of the column to display horizontally."
},
{
"code": null,
"e": 2209,
"s": 2139,
"text": "coly: string, required. The name of the column to display vertically."
},
{
"code": null,
"e": 2298,
"s": 2209,
"text": "cols: string, required. The name of the column with the value between the two variables."
},
{
"code": null,
"e": 2523,
"s": 2298,
"text": "color: list, optional. Colors to display in the visualization, the length can be two or three. The two first are the colors for the lines in the matrix, the last one the font color and markers color. default [‘grey’,’black’]"
},
{
"code": null,
"e": 2623,
"s": 2523,
"text": "ratio: int or float, optional. A ratio for controlling the relative size of the markers. default 10"
},
{
"code": null,
"e": 2705,
"s": 2623,
"text": "font: string, optional. The font for the ticks on the matrix. default ‘Helvetica’"
},
{
"code": null,
"e": 2799,
"s": 2705,
"text": "save: bool, optional. True for saving as an image in the same path as the code. default False"
},
{
"code": null,
"e": 2907,
"s": 2799,
"text": "save_name: string, optional. The name used for saving the image (then the code ads .png) default: “Default”"
},
{
"code": null,
"e": 3015,
"s": 2907,
"text": "There’s no output. The object is not closed so it can be initiated or changed by the user before and after."
},
{
"code": null,
"e": 3563,
"s": 3015,
"text": "Imagine you invite some of your friends to have dinner at home. You can build a catscatter to see everyone favorite food and buy what’s more suitable for all of them. You need a DataFrame containing the relationships between your friends and food. For example, you know that Ignacio loves Hamburguers but also likes Pizza, so you built a relationship between “Ignacio” and “Hamburguer” with a grade “5” and a relationship between “Ignacio” and “Pizza” of grade “3”. You do the same for everything you know about your friends and plot a catscatter."
},
{
"code": null,
"e": 4005,
"s": 3563,
"text": "import pandas as pdimport matplotlib as pltfrom catscatter import catscatter# example data framedata=pd.DataFrame({‘friend’:[‘Peter’,’Marc’,’Ignacio’,’Marta’,’Marta’,’Ignacio’,’Maria’,’Pedro’,’Bea’,’Pedro’], ‘favorite_food’:[‘Salmon’,’Chocolate’,’Hamburguer’,’Pizza’,’Apples’,’Pizza’,’Pizza’,’Hamburguer’,’Salmon’,’Banana’], ‘favorite_grade’:[1,5,5,3,2,3,4,4,3,1]})#plot itcatscatter(data,’friend’,’favorite_food’,’favorite_grade’)plt.show()"
},
{
"code": null,
"e": 4013,
"s": 4005,
"text": "Output:"
},
{
"code": null,
"e": 4297,
"s": 4013,
"text": "Here you can see that Pizza is the most liked food, but if you are inviting Bea and Peter maybe ordering Salmon Tataki is the best option. Don’t waste your time buying fruit. For Marc, I’m sure you’ve only had desserts with him, you should invite him to a dinner to gather more data!"
},
{
"code": null,
"e": 4372,
"s": 4297,
"text": "This example is the same than the one before but bigger and more colorful."
},
{
"code": null,
"e": 4948,
"s": 4372,
"text": "import pandas as pdimport matplotlib as pltfrom catscatter import catscatter# example dataframedata=pd.DataFrame({‘friend’:[‘Peter’,’Marc’,’Ignacio’,’Marta’,’Marta’,’Ignacio’,’Maria’,’Pedro’,’Bea’,’Pedro’], ‘favorite_food’:[‘Salmon’,’Chocolate’,’Hamburguer’,’Pizza’,’Apples’,’Pizza’,’Pizza’,’Hamburguer’,’Salmon’,’Banana’], ‘favorite_grade’:[1,5,5,3,2,3,4,4,3,1]})colors=[‘green’,’grey’,’orange’]# create the plotplt.figure(figsize=(8,8))catscatter(data,’friend’,’favorite_food’,’favorite_grade’,color=colors,ratio=100)plt.xticks(fontsize=14)plt.yticks(fontsize=14)plt.show()"
},
{
"code": null,
"e": 4956,
"s": 4948,
"text": "Output:"
},
{
"code": null,
"e": 5336,
"s": 4956,
"text": "At my office we wanted to know which EU Seed Investors are more active in which Industries. I gather information about all the seed rounds between 2015 and 2019 in Europe and prepare a dataset with the number of deals each Investor made by Industry (if no deals there’s no row). The number of deals is how strong or weak is the relationship between the Industry and the Investor."
},
{
"code": null,
"e": 5504,
"s": 5336,
"text": "import pandas as pdimport matplotlib.pyplot as pltfrom catscatter import catscatter# read the dataframedf=pd.read_csv(“top-european-investors-seed-rounds-15–19.csv”)df"
},
{
"code": null,
"e": 5512,
"s": 5504,
"text": "Output:"
},
{
"code": null,
"e": 5737,
"s": 5512,
"text": "kcolors=[‘#F73972’,’#F2B3C6',’#144962']# create the plotplt.figure(figsize=(50,20))catscatter(df,’Investor’,’Company Industry’,’Announced Date’,color=kcolors, ratio=20)plt.xticks(fontsize=20)plt.yticks(fontsize=20)plt.show()"
},
{
"code": null,
"e": 5745,
"s": 5737,
"text": "Output:"
},
{
"code": null,
"e": 5952,
"s": 5745,
"text": "We had 700 Investors and 600 Industries, but for this visualization I only leave the top 100 Investors and top 50 Industries more active. At my office we created two posters that you can find here and here."
},
{
"code": null,
"e": 6459,
"s": 5952,
"text": "In the one displayed here, you can see that “High-Tech Grunderfonds” made deals in almost all of the top sectors, but with more focus on “Information Technology” and “Software”. Also “Innogest Capital” and “Inbox Capital” have made nearly the same number of deals, but “Inbox Capital” is generalist and “Innogest Capital” focused only on “Ecommerce” and “Fashion”. We can see also that “Advertising” is not really common but “Software” is, and there’re Investors that focus on “Medical” but not on “Travel”"
},
{
"code": null,
"e": 6590,
"s": 6459,
"text": "I can’t share the df used for the last one, but I hope it helps seeing the potential of my little piece of code at a bigger scale."
},
{
"code": null,
"e": 6647,
"s": 6590,
"text": "If you want to try catscatter here’s the code for you! 👇"
},
{
"code": null,
"e": 6658,
"s": 6647,
"text": "github.com"
},
{
"code": null,
"e": 6813,
"s": 6658,
"text": "What do you think? Do you find it useful? What other ways do you have to plot relations between categorical features? Let me know in the comments section!"
}
] |
Create a Letter-Spacing Animation Effect using HTML and CSS - GeeksforGeeks | 22 Oct, 2021
In this article, we are going to create a letter-spacing animation using CSS. Letter spacing is the available space between the letters in a particular word, we will walk through each step to achieve this animation effect for our web page.
Approach:
Initially, letter-spacing will be -15px.
At 20%, letter-spacing will be 10px.
Finally, at 100% letter-spacing will be at 2px.
Example: In this example, we will animate the letter-spacing of a word. We have used the animation property which is used for creating animation in CSS. We have set a duration of 3 seconds. We have to use @keyframes rules which are responsible for making an element to animate. We can use percentage values for creating animation for an element. In this case, we are using three percentage values for our text. In our case we will animate the values of letter-spacing which is a property for text in CSS.
HTML
<!DOCTYPE html><html lang="en"> <head> <!-- CSS Code --> <style> * { margin: 0; padding: 0; } #text_container { display: flex; align-items: center; justify-content: center; text-align: center; height: 100vh; } #text { font-weight: 100; opacity: 1; animation: animate 3s ease-out forwards infinite; animation-delay: 1s; } /* For animation */ @keyframes animate { 0% { letter-spacing: -15px; } 20% { letter-spacing: 10px; } 100% { letter-spacing: 2px; } } </style></head> <body> <div id="text_container"> <h1 id="text">Geeks for Geeks</h1> </div></body> </html>
Output:
Letter Spacing animation
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 24985,
"s": 24957,
"text": "\n22 Oct, 2021"
},
{
"code": null,
"e": 25225,
"s": 24985,
"text": "In this article, we are going to create a letter-spacing animation using CSS. Letter spacing is the available space between the letters in a particular word, we will walk through each step to achieve this animation effect for our web page."
},
{
"code": null,
"e": 25235,
"s": 25225,
"text": "Approach:"
},
{
"code": null,
"e": 25276,
"s": 25235,
"text": "Initially, letter-spacing will be -15px."
},
{
"code": null,
"e": 25313,
"s": 25276,
"text": "At 20%, letter-spacing will be 10px."
},
{
"code": null,
"e": 25361,
"s": 25313,
"text": "Finally, at 100% letter-spacing will be at 2px."
},
{
"code": null,
"e": 25866,
"s": 25361,
"text": "Example: In this example, we will animate the letter-spacing of a word. We have used the animation property which is used for creating animation in CSS. We have set a duration of 3 seconds. We have to use @keyframes rules which are responsible for making an element to animate. We can use percentage values for creating animation for an element. In this case, we are using three percentage values for our text. In our case we will animate the values of letter-spacing which is a property for text in CSS."
},
{
"code": null,
"e": 25871,
"s": 25866,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- CSS Code --> <style> * { margin: 0; padding: 0; } #text_container { display: flex; align-items: center; justify-content: center; text-align: center; height: 100vh; } #text { font-weight: 100; opacity: 1; animation: animate 3s ease-out forwards infinite; animation-delay: 1s; } /* For animation */ @keyframes animate { 0% { letter-spacing: -15px; } 20% { letter-spacing: 10px; } 100% { letter-spacing: 2px; } } </style></head> <body> <div id=\"text_container\"> <h1 id=\"text\">Geeks for Geeks</h1> </div></body> </html>",
"e": 26767,
"s": 25871,
"text": null
},
{
"code": null,
"e": 26775,
"s": 26767,
"text": "Output:"
},
{
"code": null,
"e": 26800,
"s": 26775,
"text": "Letter Spacing animation"
},
{
"code": null,
"e": 26937,
"s": 26800,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26952,
"s": 26937,
"text": "CSS-Properties"
},
{
"code": null,
"e": 26966,
"s": 26952,
"text": "CSS-Questions"
},
{
"code": null,
"e": 26981,
"s": 26966,
"text": "HTML-Questions"
},
{
"code": null,
"e": 26988,
"s": 26981,
"text": "Picked"
},
{
"code": null,
"e": 26992,
"s": 26988,
"text": "CSS"
},
{
"code": null,
"e": 26997,
"s": 26992,
"text": "HTML"
},
{
"code": null,
"e": 27014,
"s": 26997,
"text": "Web Technologies"
},
{
"code": null,
"e": 27019,
"s": 27014,
"text": "HTML"
},
{
"code": null,
"e": 27117,
"s": 27019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27126,
"s": 27117,
"text": "Comments"
},
{
"code": null,
"e": 27139,
"s": 27126,
"text": "Old Comments"
},
{
"code": null,
"e": 27176,
"s": 27139,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27205,
"s": 27176,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27244,
"s": 27205,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 27286,
"s": 27244,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 27321,
"s": 27286,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 27381,
"s": 27321,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 27442,
"s": 27381,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 27495,
"s": 27442,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 27545,
"s": 27495,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
What is the difference between height and line-height? | Height is the vertical measurement of the container, for example, height of a div.
Line-height is a CSS property to specify the line height i.e. the distance from the top of the first line of text to the top of the second. It is the space between the lines of two paragraphs.
You can try to run the following code to learn the difference between height and line height:
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.height {
height: 20px;
}
.lheight {
line-height: 15px;
}
.lheightbigger {
line-height: 35px;
}
</style>
</head>
<body>
<h2>Height</h2>
<div class="height">
This is demo text. This is demo text.
This is demo text. This is demo text.
This is demo text. This is demo text.
</div>
<h2>Line Height with less space</h2>
<div class="lheight">
This is demo text showing line height example. This is demo text showing line height example.
This is demo text showing line height example. This is demo text showing line height example.
This is demo text showing line height example.This is demo text showing line height example.
</div>
<h2>Normal Text</h2>
<div>
This is normal text.
This is normal text.
This is normal text.
</div>
<h2>Line Height with more space</h2>
<div class="lheightbigger">
This is normal text. This is normal text.This is normal text.
This is normal text. This is normal text.This is normal text.
This is normal text. This is normal text.This is normal text.
</div>
</body>
</html> | [
{
"code": null,
"e": 1145,
"s": 1062,
"text": "Height is the vertical measurement of the container, for example, height of a div."
},
{
"code": null,
"e": 1338,
"s": 1145,
"text": "Line-height is a CSS property to specify the line height i.e. the distance from the top of the first line of text to the top of the second. It is the space between the lines of two paragraphs."
},
{
"code": null,
"e": 1432,
"s": 1338,
"text": "You can try to run the following code to learn the difference between height and line height:"
},
{
"code": null,
"e": 1442,
"s": 1432,
"text": "Live Demo"
},
{
"code": null,
"e": 2744,
"s": 1442,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .height {\n height: 20px;\n }\n\n .lheight {\n line-height: 15px;\n }\n\n .lheightbigger {\n line-height: 35px;\n }\n </style>\n </head>\n <body>\n <h2>Height</h2>\n <div class=\"height\">\n This is demo text. This is demo text.\n This is demo text. This is demo text.\n This is demo text. This is demo text.\n </div>\n\n <h2>Line Height with less space</h2>\n <div class=\"lheight\">\n This is demo text showing line height example. This is demo text showing line height example.\n This is demo text showing line height example. This is demo text showing line height example.\n This is demo text showing line height example.This is demo text showing line height example.\n </div>\n\n <h2>Normal Text</h2>\n <div>\n This is normal text.\n This is normal text.\n This is normal text.\n </div>\n\n <h2>Line Height with more space</h2>\n <div class=\"lheightbigger\">\n This is normal text. This is normal text.This is normal text.\n This is normal text. This is normal text.This is normal text.\n This is normal text. This is normal text.This is normal text.\n </div>\n</body>\n</html>"
}
] |
HTML | <table> cellpadding Attribute - GeeksforGeeks | 29 May, 2019
The HTML <table> cellpadding Attribute is used to specify the space between the cell content and cell wall. The cellpadding attribute is set in terms of pixels.
Syntax:
<table cellpadding="pixels">
Attribute Values:
pixels: It holds the space between the cell content and cell wall in terms of pixels.
Note: The <table> cellpadding Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html> <head> <title> HTML table cellpadding Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table cellpadding Attribute</h2> <table border="1" cellpadding="15"> <caption>Author Details</caption> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAM</td> <td>21</td> <td>ECE</td> </tr> </table></body> </html>
Output:
Supported Browsers: The browser supported by HTML <table> cellpadding Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 24576,
"s": 24548,
"text": "\n29 May, 2019"
},
{
"code": null,
"e": 24737,
"s": 24576,
"text": "The HTML <table> cellpadding Attribute is used to specify the space between the cell content and cell wall. The cellpadding attribute is set in terms of pixels."
},
{
"code": null,
"e": 24745,
"s": 24737,
"text": "Syntax:"
},
{
"code": null,
"e": 24774,
"s": 24745,
"text": "<table cellpadding=\"pixels\">"
},
{
"code": null,
"e": 24792,
"s": 24774,
"text": "Attribute Values:"
},
{
"code": null,
"e": 24878,
"s": 24792,
"text": "pixels: It holds the space between the cell content and cell wall in terms of pixels."
},
{
"code": null,
"e": 24946,
"s": 24878,
"text": "Note: The <table> cellpadding Attribute is not supported by HTML 5."
},
{
"code": null,
"e": 24955,
"s": 24946,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML table cellpadding Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML table cellpadding Attribute</h2> <table border=\"1\" cellpadding=\"15\"> <caption>Author Details</caption> <tr> <th>NAME</th> <th>AGE</th> <th>BRANCH</th> </tr> <tr> <td>BITTU</td> <td>22</td> <td>CSE</td> </tr> <tr> <td>RAM</td> <td>21</td> <td>ECE</td> </tr> </table></body> </html>",
"e": 25554,
"s": 24955,
"text": null
},
{
"code": null,
"e": 25562,
"s": 25554,
"text": "Output:"
},
{
"code": null,
"e": 25660,
"s": 25562,
"text": "Supported Browsers: The browser supported by HTML <table> cellpadding Attribute are listed below:"
},
{
"code": null,
"e": 25674,
"s": 25660,
"text": "Google Chrome"
},
{
"code": null,
"e": 25692,
"s": 25674,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25700,
"s": 25692,
"text": "Firefox"
},
{
"code": null,
"e": 25707,
"s": 25700,
"text": "Safari"
},
{
"code": null,
"e": 25713,
"s": 25707,
"text": "Opera"
},
{
"code": null,
"e": 25850,
"s": 25713,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25866,
"s": 25850,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 25871,
"s": 25866,
"text": "HTML"
},
{
"code": null,
"e": 25888,
"s": 25871,
"text": "Web Technologies"
},
{
"code": null,
"e": 25893,
"s": 25888,
"text": "HTML"
},
{
"code": null,
"e": 25991,
"s": 25893,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26039,
"s": 25991,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26089,
"s": 26039,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26139,
"s": 26089,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26163,
"s": 26139,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26200,
"s": 26163,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26242,
"s": 26200,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26275,
"s": 26242,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26318,
"s": 26275,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26363,
"s": 26318,
"text": "Convert a string to an integer in JavaScript"
}
] |
How to change the text color of font in the legend using Matplotlib? | To change the text color of font in the legend in matplotlib, we can take the following steps−
Create x and y data points using numpy.
Plot x and y using plot() method, where color of line is red and label is "y=exp(x)".
To place the legend, use legend() method with location of the legend and store the returned value to set the color of the text.
To set the color of the text, use set_color() method with green color.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-2, 2, 100)
y = np.exp(x)
plt.plot(x, y, label="y=exp(x)", c='red')
leg = plt.legend(loc='upper left')
for text in leg.get_texts():
text.set_color("green")
plt.show() | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "To change the text color of font in the legend in matplotlib, we can take the following steps−"
},
{
"code": null,
"e": 1197,
"s": 1157,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1283,
"s": 1197,
"text": "Plot x and y using plot() method, where color of line is red and label is \"y=exp(x)\"."
},
{
"code": null,
"e": 1411,
"s": 1283,
"text": "To place the legend, use legend() method with location of the legend and store the returned value to set the color of the text."
},
{
"code": null,
"e": 1482,
"s": 1411,
"text": "To set the color of the text, use set_color() method with green color."
},
{
"code": null,
"e": 1524,
"s": 1482,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1850,
"s": 1524,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.linspace(-2, 2, 100)\ny = np.exp(x)\nplt.plot(x, y, label=\"y=exp(x)\", c='red')\nleg = plt.legend(loc='upper left')\nfor text in leg.get_texts():\ntext.set_color(\"green\")\nplt.show()"
}
] |
MediaPlayer class to implement a basic Audio Player in an Android Kotlin app? | This example demonstrates how to implement a MediaPlayer class to implement a basic Audio Player in an Android Kotlin 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="Now Playing: "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@android:color/holo_red_dark"
android:textSize="16sp"
android:textStyle="bold|italic" />
<TextView
android:id="@+id/txtSongName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView"
android:layout_toEndOf="@+id/textView"
android:textColor="@android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold|italic" />
<ImageButton
android:id="@+id/btnBackward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/ic_back" />
<ImageButton
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnBackward"
android:layout_marginStart="10dp"
android:layout_toEndOf="@+id/btnBackward"
android:src="@drawable/ic_play" />
<ImageButton
android:id="@+id/btnPause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnPlay"
android:layout_marginStart="10dp"
android:layout_toEndOf="@+id/btnPlay"
android:src="@drawable/ic_pause" />
<ImageButton
android:id="@+id/btnForward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnPause"
android:layout_marginStart="10dp"
android:layout_toEndOf="@+id/btnPause"
android:contentDescription="@+id/imageButton3"
android:src="@drawable/ic_forward" />
<TextView
android:id="@+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/seekBar"
android:text="0 min, 0 sec" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/btnBackward"
android:layout_toStartOf="@+id/txtSongTime"
android:layout_toEndOf="@+id/txtStartTime" />
<TextView
android:id="@+id/txtSongTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/seekBar"
android:layout_toEndOf="@+id/btnForward"
android:text="0 min, 0 sec " />
</RelativeLayout>
Step 3 − Add the following code to MainActivity.kt
import android.media.MediaPlayer
import android.os.Bundle
import android.os.Handler
import android.widget.ImageButton
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
lateinit var forwardBtn: ImageButton
lateinit var backwardBtn: ImageButton
lateinit var pauseBtn: ImageButton
lateinit var playBtn: ImageButton
lateinit var mediaPlayer: MediaPlayer
private lateinit var songName: TextView
private lateinit var startTime: TextView
private lateinit var songTime: TextView
private lateinit var seekBar: SeekBar
private var handler: Handler = Handler()
private var onTime: Int = 0
private var playTime: Int = 0
private var endTime: Int = 0
private var forwardTime: Int = 5000
private var backwardTime: Int = 5000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
backwardBtn = findViewById(R.id.btnBackward)
forwardBtn = findViewById(R.id.btnForward)
playBtn = findViewById(R.id.btnPlay)
pauseBtn = findViewById(R.id.btnPause)
songName = findViewById(R.id.txtSongName)
startTime = findViewById(R.id.txtStartTime)
songTime = findViewById(R.id.txtSongTime)
songName.text = "SpeakerBox - Fast & Furious"
mediaPlayer = MediaPlayer.create(this, R.raw.fast_and_furious)
seekBar = findViewById(R.id.seekBar)
seekBar.isClickable = false
pauseBtn.isEnabled = true
playBtn.setOnClickListener {
Toast.makeText(this, "Playing Audio", Toast.LENGTH_SHORT).show()
mediaPlayer.start()
endTime = mediaPlayer.duration
playTime = mediaPlayer.currentPosition
seekBar.max = endTime
onTime = 1
songTime.text = String.format(
"%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(endTime.toLong()),
TimeUnit.MILLISECONDS.toSeconds(endTime.toLong()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(endTime.toLong()))
)
startTime.text = String.format(
"%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()),
TimeUnit.MILLISECONDS.toSeconds(playTime.toLong()) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()))
)
seekBar.progress = playTime
handler.postDelayed(updateSongTime, 100)
pauseBtn.isEnabled = true
playBtn.isEnabled = false
}
btnPause.setOnClickListener {
mediaPlayer.pause()
pauseBtn.isEnabled = false
playBtn.isEnabled = true
Toast.makeText(applicationContext, "Audio Paused", Toast.LENGTH_SHORT).show()
}
btnForward.setOnClickListener {
if ((playTime + forwardTime) <= endTime) {
playTime += forwardTime
mediaPlayer.seekTo(playTime)
}
else {
Toast.makeText(
applicationContext,
"Cannot jump forward 5 seconds",
Toast.LENGTH_SHORT
).show()
}
if (!playBtn.isEnabled) {
playBtn.isEnabled = true
}
}
btnBackward.setOnClickListener {
if ((playTime - backwardTime) > 0) {
playTime -= backwardTime
mediaPlayer.seekTo(playTime)
}
else {
Toast.makeText(
applicationContext,
"Cannot jump backward 5 seconds",
Toast.LENGTH_SHORT
).show()
}
if (!playBtn.isEnabled) {
playBtn.isEnabled = true
}
}
}
private val updateSongTime = object : Runnable {
override fun run() {
playTime = mediaPlayer.currentPosition
startTime.text = String.format(
"%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()
(TimeUnit.MILLISECONDS.toSeconds(playTime.toLong()) - TimeUnit.MINUTES.toSeconds
(TimeUnit.MILLISECONDS.toMinutes(
playTime.toLong()
)
))
)
seekBar.progress = playTime
handler.postDelayed(this, 100)
}
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.kotlipapp">
<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 the 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": 1185,
"s": 1062,
"text": "This example demonstrates how to implement a MediaPlayer class to implement a basic Audio Player in an Android Kotlin app."
},
{
"code": null,
"e": 1314,
"s": 1185,
"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": 1379,
"s": 1314,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 4365,
"s": 1379,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingLeft=\"10dp\"\n android:paddingRight=\"10dp\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"30dp\"\n android:text=\"Now Playing: \"\n android:textAppearance=\"?android:attr/textAppearanceMedium\"\n android:textColor=\"@android:color/holo_red_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\" />\n <TextView\n android:id=\"@+id/txtSongName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignBaseline=\"@+id/textView\"\n android:layout_toEndOf=\"@+id/textView\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold|italic\" />\n <ImageButton\n android:id=\"@+id/btnBackward\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:src=\"@drawable/ic_back\" />\n <ImageButton\n android:id=\"@+id/btnPlay\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignTop=\"@+id/btnBackward\"\n android:layout_marginStart=\"10dp\"\n android:layout_toEndOf=\"@+id/btnBackward\"\n android:src=\"@drawable/ic_play\" />\n <ImageButton\n android:id=\"@+id/btnPause\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignTop=\"@+id/btnPlay\"\n android:layout_marginStart=\"10dp\"\n android:layout_toEndOf=\"@+id/btnPlay\"\n android:src=\"@drawable/ic_pause\" />\n <ImageButton\n android:id=\"@+id/btnForward\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignTop=\"@+id/btnPause\"\n android:layout_marginStart=\"10dp\"\n android:layout_toEndOf=\"@+id/btnPause\"\n android:contentDescription=\"@+id/imageButton3\"\n android:src=\"@drawable/ic_forward\" />\n <TextView\n android:id=\"@+id/txtStartTime\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignTop=\"@+id/seekBar\"\n android:text=\"0 min, 0 sec\" />\n <SeekBar\n android:id=\"@+id/seekBar\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@+id/btnBackward\"\n android:layout_toStartOf=\"@+id/txtSongTime\"\n android:layout_toEndOf=\"@+id/txtStartTime\" />\n <TextView\n android:id=\"@+id/txtSongTime\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignTop=\"@+id/seekBar\"\n android:layout_toEndOf=\"@+id/btnForward\"\n android:text=\"0 min, 0 sec \" />\n</RelativeLayout>"
},
{
"code": null,
"e": 4416,
"s": 4365,
"text": "Step 3 − Add the following code to MainActivity.kt"
},
{
"code": null,
"e": 8881,
"s": 4416,
"text": "import android.media.MediaPlayer\nimport android.os.Bundle\nimport android.os.Handler\nimport android.widget.ImageButton\nimport android.widget.SeekBar\nimport android.widget.TextView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport kotlinx.android.synthetic.main.activity_main.*\nimport java.util.concurrent.TimeUnit\nclass MainActivity : AppCompatActivity() {\n lateinit var forwardBtn: ImageButton\n lateinit var backwardBtn: ImageButton\n lateinit var pauseBtn: ImageButton\n lateinit var playBtn: ImageButton\n lateinit var mediaPlayer: MediaPlayer\n private lateinit var songName: TextView\n private lateinit var startTime: TextView\n private lateinit var songTime: TextView\n private lateinit var seekBar: SeekBar\n private var handler: Handler = Handler()\n private var onTime: Int = 0\n private var playTime: Int = 0\n private var endTime: Int = 0\n private var forwardTime: Int = 5000\n private var backwardTime: Int = 5000\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n backwardBtn = findViewById(R.id.btnBackward)\n forwardBtn = findViewById(R.id.btnForward)\n playBtn = findViewById(R.id.btnPlay)\n pauseBtn = findViewById(R.id.btnPause)\n songName = findViewById(R.id.txtSongName)\n startTime = findViewById(R.id.txtStartTime)\n songTime = findViewById(R.id.txtSongTime)\n songName.text = \"SpeakerBox - Fast & Furious\"\n mediaPlayer = MediaPlayer.create(this, R.raw.fast_and_furious)\n seekBar = findViewById(R.id.seekBar)\n seekBar.isClickable = false\n pauseBtn.isEnabled = true\n playBtn.setOnClickListener {\n Toast.makeText(this, \"Playing Audio\", Toast.LENGTH_SHORT).show()\n mediaPlayer.start()\n endTime = mediaPlayer.duration\n playTime = mediaPlayer.currentPosition\n seekBar.max = endTime\n onTime = 1\n songTime.text = String.format(\n \"%d min, %d sec\",\n TimeUnit.MILLISECONDS.toMinutes(endTime.toLong()),\n TimeUnit.MILLISECONDS.toSeconds(endTime.toLong()) -\n TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(endTime.toLong()))\n )\n startTime.text = String.format(\n \"%d min, %d sec\",\n TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()),\n TimeUnit.MILLISECONDS.toSeconds(playTime.toLong()) -\n TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()))\n )\n seekBar.progress = playTime\n handler.postDelayed(updateSongTime, 100)\n pauseBtn.isEnabled = true\n playBtn.isEnabled = false\n }\n btnPause.setOnClickListener {\n mediaPlayer.pause()\n pauseBtn.isEnabled = false\n playBtn.isEnabled = true\n Toast.makeText(applicationContext, \"Audio Paused\", Toast.LENGTH_SHORT).show()\n }\n btnForward.setOnClickListener {\n if ((playTime + forwardTime) <= endTime) {\n playTime += forwardTime\n mediaPlayer.seekTo(playTime)\n }\n else {\n Toast.makeText(\n applicationContext,\n \"Cannot jump forward 5 seconds\",\n Toast.LENGTH_SHORT\n ).show()\n }\n if (!playBtn.isEnabled) {\n playBtn.isEnabled = true\n }\n }\n btnBackward.setOnClickListener {\n if ((playTime - backwardTime) > 0) {\n playTime -= backwardTime\n mediaPlayer.seekTo(playTime)\n }\n else {\n Toast.makeText(\n applicationContext,\n \"Cannot jump backward 5 seconds\",\n Toast.LENGTH_SHORT\n ).show()\n }\n if (!playBtn.isEnabled) {\n playBtn.isEnabled = true\n }\n }\n }\n private val updateSongTime = object : Runnable {\n override fun run() {\n playTime = mediaPlayer.currentPosition\n startTime.text = String.format(\n \"%d min, %d sec\", TimeUnit.MILLISECONDS.toMinutes(playTime.toLong()\n (TimeUnit.MILLISECONDS.toSeconds(playTime.toLong()) - TimeUnit.MINUTES.toSeconds\n (TimeUnit.MILLISECONDS.toMinutes(\n playTime.toLong()\n )\n ))\n )\n seekBar.progress = playTime\n handler.postDelayed(this, 100)\n }\n }\n}"
},
{
"code": null,
"e": 8936,
"s": 8881,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 9612,
"s": 8936,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\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": 9963,
"s": 9612,
"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 the 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": 10004,
"s": 9963,
"text": "Click here to download the project code."
}
] |
Checking semiprime numbers - JavaScript | We are required to write a JavaScript function that takes in a number and the function establishes if the provided number is a semiprime or not.
A semiprime number is that number which is a special type of composite number that is a product of two prime numbers. For example: 6, 15, 10, 77 are all semiprime. The square of a prime number is also semiprime, like 4, 9, 25 etc.
Following is the code to check semi-prime numbers −
const num = 141;
const checkSemiprime = num => {
let cnt = 0;
for (let i = 2; cnt < 2 && i * i <= num; ++i){
while (num % i == 0){
num /= i, ++cnt;
}
}
if (num > 1){
++cnt;
}
// Return '1' if count is equal to '2' else
// return '0'
return cnt === 2;
}
console.log(checkSemiprime(num));
Following is the output in the console −
true | [
{
"code": null,
"e": 1207,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in a number and the function establishes if the provided number is a semiprime or not."
},
{
"code": null,
"e": 1438,
"s": 1207,
"text": "A semiprime number is that number which is a special type of composite number that is a product of two prime numbers. For example: 6, 15, 10, 77 are all semiprime. The square of a prime number is also semiprime, like 4, 9, 25 etc."
},
{
"code": null,
"e": 1490,
"s": 1438,
"text": "Following is the code to check semi-prime numbers −"
},
{
"code": null,
"e": 1828,
"s": 1490,
"text": "const num = 141;\nconst checkSemiprime = num => {\n let cnt = 0;\n for (let i = 2; cnt < 2 && i * i <= num; ++i){\n while (num % i == 0){\n num /= i, ++cnt;\n }\n }\n if (num > 1){\n ++cnt;\n }\n // Return '1' if count is equal to '2' else\n // return '0'\n return cnt === 2;\n}\nconsole.log(checkSemiprime(num));"
},
{
"code": null,
"e": 1869,
"s": 1828,
"text": "Following is the output in the console −"
},
{
"code": null,
"e": 1874,
"s": 1869,
"text": "true"
}
] |
Elegant Web Development With Emmett In Python | by Emmett Boudreau | Towards Data Science | Python web-development is a portion of Python programming that has been dominated by popular options such as Flask and Django for years. Those solutions are certainly great, and I have used them myself a lot. That being said, I think there are shortcomings to any software, as certain directions have to be taken, and some software is better at some things than other things. While actually looking to find an article I had written on machine-learning validation, I stumbled across the Emmett project.
Who would have thought that I would have a web-framework in Python named after me? Just a joke of course, the framework is actually named after Doctor Emmett Brown from Back To The Future. The logo for the framework sports his face with his iconic goggles on. I actually happen to be quite the fan of that movie, not the second one though (what even was that?) and given the name, the package peaked my curiosity, and I decided to try it out. If you would like to look more into the package, you may check it out on Github here:
github.com
I should start by saying that I typically do not expect much from these kinds of things, as there are so many great examples of web-frameworks available with better documentation and a lot more users. However, reading over the list of features, and taking a look at the methodology, I was certainly interested in this weird package. I cannot tell a lie though, it was weird importcuriousitying things from myself whenever I gave it a try. But I am very excited to show off this framework and what it is capable of! I also have two articles I have written in the past that discuss other solutions besides Emmett, Django, and Flask you may read here:
towardsdatascience.com
Or here:
towardsdatascience.com
The question that arises with any example of a web-framework coming to fruition, why choose Emmett over more popular solutions such as Flask or Django. When we compare Emmett between those two solutions, we should note that Emmett is in a lot of ways a combination of those two. Django is more commonly used for fullstack applications, and Flask is more commonly used for more data-driving, and simple applications. Both have a different methodology and syntax. Emmett is in a lot of ways, a great middle-ground between them.
The syntax is pretty close to Flask, and so is the methodology. Personally, I much prefer this. I never really liked the overwhelming templating nature of Django. While there is certainly nothing wrong with it, it generates a lot of directories and files to dive into right off the bat, rather than having the user create their own. Emmett acts in between this, but instead of relying on directories and files, the module calls are used instead, which I think is a lot more elegant. If you would like to read more about the differences between Flask and Django, I have another article that goes into a lot of detail on that:
towardsdatascience.com
First and foremost, Emmett has a methodology that is meant to be approachable and easy to use. With syntax similar to Flask’s, most users will find themselves at home when working with the framework. However, the framework is not as lightweight as Flask, meaning that there are a lot more great features that are built in than one might expect with Flask. It writes like Flask, but it works more like Django.
The module comes with database classes that make it easier to query things, tasks, and even authentication. All of these in my experience with the module have also been a lot easier to use than Django’s implementation. The project is also claimed to be production ready, which is certainly great for those who want to use this module in their tech stack.
Another cool thing about Emmett is that it is asynchronous. Websockets are awesome! Emmett is designed atop of asyncio, a venerable library for this sort of thing. This methodology makes Emmett non-blocking, and a lot more usable for many design patterns. Another cool thing is that the package comes with its own query interface.
The last cool thing about Emmett is the templating. In most web-frameworks, templating is often a complete mess. Sometimes they have their own templating framework that requires learning a new language, sometimes you might need to write some HTML and/or Javascript along with your Python in order to get the job done. Emmett has a quite robust templating system without all of the headaches of these traditional systems. The templates are coded in pure Python!
Using Emmett is incredibly simple and very approachable in my experience with the package. The documentation is also quite exceptional. You can install the package with
pip3 install emmett
Of course, I am no web-developer. What I look for in a web-framework might be different to those that traditionally use Python for full-stack. What I lack also happens to be what Emmett has, so that is definitely pretty cool! Emmett actually includes a great and easy to use querying framework that we can use, and I think it is actually very impressive. Check out the following example from the documentation where we create a schema with users, posts, and comments in only a few lines of code!
from emmett import session, nowfrom emmett.orm import Model, Field, belongs_to, has_manyfrom emmett.tools.auth import AuthUserclass User(AuthUser): # will create "users" table and groups/permissions ones has_many('posts', 'comments')class Post(Model): belongs_to('user') has_many('comments')title = Field() text = Field.text() date = Field.datetime()default_values = { 'user': lambda: session.auth.user.id, 'date': lambda: now } validation = { 'title': {'presence': True}, 'text': {'presence': True} } fields_rw = { 'user': False, 'date': False }class Comment(Model): belongs_to('user', 'post')text = Field.text() date = Field.datetime()default_values = { 'user': lambda: session.auth.user.id, 'date': lambda: now } validation = { 'text': {'presence': True} } fields_rw = { 'user': False, 'post': False, 'date': False }
We can route the app using the @app syntax. This is very unique and cool in my opinion, we use the @app.command() method and then we can call globally defined functions for our app to work with from there! Quite a popular Data Science and Data Engineering task is creating a simple endpoint, here is the code to do that with Emmett:
from emmett import App app = App(__name__) @app.route("/") async def hello(): return "Here is a simple endpoint!"
As you can likely tell, this endpoint is very similar to those made in Flask! In fact the code is nearly identical. However, it is easy to see that this framework is no Flask and brings along a whole load of features. In my opinion, it is really cool, high-level, and so declarative at times it seems to be just too easy to use. I do not often find myself falling in love with random packages I find like this one, but it is certainly worth checking out! I know I will be using it in the future! If you are more interested in Flask, I do have another really old article (from 2019!) that you can read to learn more about deploying endpoints in it!
towardsdatascience.com
Although it is a bit unsettling to be working with a package that has my name at times, this package is certainly worth dealing with that uncanny valley feeling. I really enjoyed using this package, and realizing how cool it was over and over again was shocking, to say the least. Of course, when I use a package like this, I always compare it to what I already use. Probably the choice I use the most in that regard is Flask, I really love how Flask can be both small and big. This web-framework, however, leaves me completely speechless on taking that same methodology and drilling it to the core. If I had to describe it in a sentence Python programmers would understand well, I would say “ It is like Flask, only with tons of amazing and useful features.” I certainly recommend this module, and not just because we share the same name. Thank you for reading, and I hope you consider trying this package out — It is awesome! | [
{
"code": null,
"e": 674,
"s": 172,
"text": "Python web-development is a portion of Python programming that has been dominated by popular options such as Flask and Django for years. Those solutions are certainly great, and I have used them myself a lot. That being said, I think there are shortcomings to any software, as certain directions have to be taken, and some software is better at some things than other things. While actually looking to find an article I had written on machine-learning validation, I stumbled across the Emmett project."
},
{
"code": null,
"e": 1203,
"s": 674,
"text": "Who would have thought that I would have a web-framework in Python named after me? Just a joke of course, the framework is actually named after Doctor Emmett Brown from Back To The Future. The logo for the framework sports his face with his iconic goggles on. I actually happen to be quite the fan of that movie, not the second one though (what even was that?) and given the name, the package peaked my curiosity, and I decided to try it out. If you would like to look more into the package, you may check it out on Github here:"
},
{
"code": null,
"e": 1214,
"s": 1203,
"text": "github.com"
},
{
"code": null,
"e": 1863,
"s": 1214,
"text": "I should start by saying that I typically do not expect much from these kinds of things, as there are so many great examples of web-frameworks available with better documentation and a lot more users. However, reading over the list of features, and taking a look at the methodology, I was certainly interested in this weird package. I cannot tell a lie though, it was weird importcuriousitying things from myself whenever I gave it a try. But I am very excited to show off this framework and what it is capable of! I also have two articles I have written in the past that discuss other solutions besides Emmett, Django, and Flask you may read here:"
},
{
"code": null,
"e": 1886,
"s": 1863,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1895,
"s": 1886,
"text": "Or here:"
},
{
"code": null,
"e": 1918,
"s": 1895,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2444,
"s": 1918,
"text": "The question that arises with any example of a web-framework coming to fruition, why choose Emmett over more popular solutions such as Flask or Django. When we compare Emmett between those two solutions, we should note that Emmett is in a lot of ways a combination of those two. Django is more commonly used for fullstack applications, and Flask is more commonly used for more data-driving, and simple applications. Both have a different methodology and syntax. Emmett is in a lot of ways, a great middle-ground between them."
},
{
"code": null,
"e": 3069,
"s": 2444,
"text": "The syntax is pretty close to Flask, and so is the methodology. Personally, I much prefer this. I never really liked the overwhelming templating nature of Django. While there is certainly nothing wrong with it, it generates a lot of directories and files to dive into right off the bat, rather than having the user create their own. Emmett acts in between this, but instead of relying on directories and files, the module calls are used instead, which I think is a lot more elegant. If you would like to read more about the differences between Flask and Django, I have another article that goes into a lot of detail on that:"
},
{
"code": null,
"e": 3092,
"s": 3069,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3501,
"s": 3092,
"text": "First and foremost, Emmett has a methodology that is meant to be approachable and easy to use. With syntax similar to Flask’s, most users will find themselves at home when working with the framework. However, the framework is not as lightweight as Flask, meaning that there are a lot more great features that are built in than one might expect with Flask. It writes like Flask, but it works more like Django."
},
{
"code": null,
"e": 3856,
"s": 3501,
"text": "The module comes with database classes that make it easier to query things, tasks, and even authentication. All of these in my experience with the module have also been a lot easier to use than Django’s implementation. The project is also claimed to be production ready, which is certainly great for those who want to use this module in their tech stack."
},
{
"code": null,
"e": 4187,
"s": 3856,
"text": "Another cool thing about Emmett is that it is asynchronous. Websockets are awesome! Emmett is designed atop of asyncio, a venerable library for this sort of thing. This methodology makes Emmett non-blocking, and a lot more usable for many design patterns. Another cool thing is that the package comes with its own query interface."
},
{
"code": null,
"e": 4648,
"s": 4187,
"text": "The last cool thing about Emmett is the templating. In most web-frameworks, templating is often a complete mess. Sometimes they have their own templating framework that requires learning a new language, sometimes you might need to write some HTML and/or Javascript along with your Python in order to get the job done. Emmett has a quite robust templating system without all of the headaches of these traditional systems. The templates are coded in pure Python!"
},
{
"code": null,
"e": 4817,
"s": 4648,
"text": "Using Emmett is incredibly simple and very approachable in my experience with the package. The documentation is also quite exceptional. You can install the package with"
},
{
"code": null,
"e": 4837,
"s": 4817,
"text": "pip3 install emmett"
},
{
"code": null,
"e": 5333,
"s": 4837,
"text": "Of course, I am no web-developer. What I look for in a web-framework might be different to those that traditionally use Python for full-stack. What I lack also happens to be what Emmett has, so that is definitely pretty cool! Emmett actually includes a great and easy to use querying framework that we can use, and I think it is actually very impressive. Check out the following example from the documentation where we create a schema with users, posts, and comments in only a few lines of code!"
},
{
"code": null,
"e": 6291,
"s": 5333,
"text": "from emmett import session, nowfrom emmett.orm import Model, Field, belongs_to, has_manyfrom emmett.tools.auth import AuthUserclass User(AuthUser): # will create \"users\" table and groups/permissions ones has_many('posts', 'comments')class Post(Model): belongs_to('user') has_many('comments')title = Field() text = Field.text() date = Field.datetime()default_values = { 'user': lambda: session.auth.user.id, 'date': lambda: now } validation = { 'title': {'presence': True}, 'text': {'presence': True} } fields_rw = { 'user': False, 'date': False }class Comment(Model): belongs_to('user', 'post')text = Field.text() date = Field.datetime()default_values = { 'user': lambda: session.auth.user.id, 'date': lambda: now } validation = { 'text': {'presence': True} } fields_rw = { 'user': False, 'post': False, 'date': False }"
},
{
"code": null,
"e": 6624,
"s": 6291,
"text": "We can route the app using the @app syntax. This is very unique and cool in my opinion, we use the @app.command() method and then we can call globally defined functions for our app to work with from there! Quite a popular Data Science and Data Engineering task is creating a simple endpoint, here is the code to do that with Emmett:"
},
{
"code": null,
"e": 6744,
"s": 6624,
"text": "from emmett import App app = App(__name__) @app.route(\"/\") async def hello(): return \"Here is a simple endpoint!\""
},
{
"code": null,
"e": 7392,
"s": 6744,
"text": "As you can likely tell, this endpoint is very similar to those made in Flask! In fact the code is nearly identical. However, it is easy to see that this framework is no Flask and brings along a whole load of features. In my opinion, it is really cool, high-level, and so declarative at times it seems to be just too easy to use. I do not often find myself falling in love with random packages I find like this one, but it is certainly worth checking out! I know I will be using it in the future! If you are more interested in Flask, I do have another really old article (from 2019!) that you can read to learn more about deploying endpoints in it!"
},
{
"code": null,
"e": 7415,
"s": 7392,
"text": "towardsdatascience.com"
}
] |
Introduction to Internet of Things (IoT) | Set 1 | 03 Jul, 2022
Internet of Things (IoT) is the networking of physical objects that contain electronics embedded within their architecture in order to communicate and sense interactions amongst each other or with respect to the external environment. In the upcoming years, IoT-based technology will offer advanced levels of services and practically change the way people lead their daily lives. Advancements in medicine, power, gene therapies, agriculture, smart cities, and smart homes are just a very few of the categorical examples where IoT is strongly established.
IoT is network of interconnected computing devices which are embedded in everyday objects, enabling them to send and receive data.
Over 9 billion ‘Things’ (physical objects) are currently connected to the Internet, as of now. In the near future, this number is expected to rise to a whopping 20 billion.
Main components used in IoT:
Low-power embedded systems: Less battery consumption, high performance are the inverse factors that play a significant role during the design of electronic systems.
Sensors : Sensors are the major part of any IoT applications. It is a physical device that measures and detect certain physical quantity and convert it into signal which can be provide as an input to processing or control unit for analysis purpose.
Different types of Sensors :Temperature SensorsImage SensorsGyro SensorsObstacle SensorsRF SensorIR SensorMQ-02/05 Gas SensorLDR SensorUltrasonic Distance Sensor
Different types of Sensors :
Temperature Sensors
Image Sensors
Gyro Sensors
Obstacle Sensors
RF Sensor
IR Sensor
MQ-02/05 Gas Sensor
LDR Sensor
Ultrasonic Distance Sensor
Control Units : It is a unit of small computer on a single integrated circuit containing microprocessor or processing core, memory and programmable input/output devices/peripherals. It is responsible for major processing work of IoT devices and all logical operations are carried out here.
Cloud computing: Data collected through IoT devices is massive and this data has to be stored on a reliable storage server. This is where cloud computing comes into play. The data is processed and learned, giving more room for us to discover where things like electrical faults/errors are within the system.
Availability of big data: We know that IoT relies heavily on sensors, especially in real-time. As these electronic devices spread throughout every field, their usage is going to trigger a massive flux of big data.
Networking connection: In order to communicate, internet connectivity is a must where each physical object is represented by an IP address. However, there are only a limited number of addresses available according to the IP naming. Due to the growing number of devices, this naming system will not be feasible anymore. Therefore, researchers are looking for another alternative naming system to represent each physical object.
There are two ways of building IoT:
Form a separate internetwork including only physical objects. Make the Internet ever more expansive, but this requires hard-core technologies such as rigorous cloud computing and rapid big data storage (expensive).
Form a separate internetwork including only physical objects.
Make the Internet ever more expansive, but this requires hard-core technologies such as rigorous cloud computing and rapid big data storage (expensive).
In the near future, IoT will become broader and more complex in terms of scope. It will change the world in terms of
“anytime, anyplace, anything in connectivity.”
IoT Enablers:
RFIDs: uses radio waves in order to electronically track the tags attached to each physical object.
Sensors: devices that are able to detect changes in an environment (ex: motion detectors).
Nanotechnology: as the name suggests, these are extremely small devices with dimensions usually less than a hundred nanometers.
Smart networks: (ex: mesh topology).
Working with IoT Devices :
Collect and Transmit Data : For this purpose sensors are widely used they are used as per requirements in different application areas.
Actuate device based on triggers produced by sensors or processing devices : If certain condition is satisfied or according to user’s requirements if certain trigger is activated then which action to performed that is shown by Actuator devices.
Receive Information : From network devices user or device can take certain information also for their analysis and processing purposes.
Communication Assistance : Communication assistance is the phenomena of communication between 2 network or communication between 2 or more IoT devices of same or different Networks. This can be achieved by different communication protocols like : MQTT , Constrained Application Protocol, ZigBee, FTP, HTTP etc.
Working of IoT
Characteristics of IoT:
Massively scalable and efficient
IP-based addressing will no longer be suitable in the upcoming future.
An abundance of physical objects is present that do not use IP, so IoT is made possible.
Devices typically consume less power. When not in use, they should be automatically programmed to sleep.
A device that is connected to another device right now may not be connected in another instant of time.
Intermittent connectivity – IoT devices aren’t always connected. In order to save bandwidth and battery consumption, devices will be powered off periodically when not in use. Otherwise, connections might turn unreliable and thus prove to be inefficient.
Desired Quality of any IoT Application :
Interconnectivity
It is the basic first requirement in any IoT infrastructure. Connectivity should be guaranteed from any devices on any network then only devices in a network can communicate with each other.
Heterogeneity
There can be diversity in IoT enabled devices like different hardware and software configuration or different network topologies or connections but they should connect and interact with each other despite of so much heterogeneity.
Dynamic in nature
IoT devices should dynamically adapt themselves to the changing surroundings like different situation and different prefaces.
Self adapting and self configuring technology
For example surveillance camera. It should be flexible to work in different weather conditions and different light situations (morning, afternoon, or night).
Intelligence
Just data collection is not enough in IoT, extraction of knowledge from the generated data is very important. For example, sensors generate data, but that data will only be useful if it is interpreted properly. So intelligence is one of the key characteristics in IoT. Because data interpretation is the major part in any IoT application because without data processing we can’t make any insights from data . Hence big data is also one of the most enabling technology in IoT field.
Scalability
The number of elements (devices) connected to IoT zone is increasing day by day. Therefore, an IoT setup should be capable of handling the expansion. It can be either expand capability in terms of processing power, Storage, etc. as vertical scaling or horizontal scaling by multiplying with easy cloning
Identity
Each IoT device has a unique identity (e.g., an IP address). This identity is helpful in communication, tracking and to know status of the things. If there is no identification then it will directly effect security and safety of any system because without discrimination we can’t identify with whom one network is connected or with whom we have to communicate. So there should be clear and appropriate discrimination technology available between IoT networks and devices.
Safety
Sensitive personal details of a user might be compromised when the devices are connected to the Internet. So data security is a major challenge. This could cause a loss to the user. Equipment in the huge IoT network may also be at risk. Therefore, equipment safety is also critical.
Architecture
It should be hybrid, supporting different manufacturer’s products to function in the IoT network.
As a quick note, IoT incorporates trillions of sensors, billions of smart systems, and millions of applications.
Application Domains: IoT is currently found in four different popular domains:
1) Manufacturing/Industrial business - 40.2%
2) Healthcare - 30.3%
3) Security - 7.7%
4) Retail - 8.3%
Modern Applications:
Smart Grids and energy savingSmart citiesSmart homes/Home automationHealthcareEarthquake detectionRadiation detection/hazardous gas detectionSmartphone detectionWater flow monitoringTraffic monitoringWearablesSmart door lock protection systemRobots and DronesHealthcare and Hospitals, Telemedicine applicationsSecurityBiochip Transponders(For animals in farms)Heart monitoring implants(Example Pacemaker, ECG real time tracking)
Smart Grids and energy saving
Smart cities
Smart homes/Home automation
Healthcare
Earthquake detection
Radiation detection/hazardous gas detection
Smartphone detection
Water flow monitoring
Traffic monitoring
Wearables
Smart door lock protection system
Robots and Drones
Healthcare and Hospitals, Telemedicine applications
Security
Biochip Transponders(For animals in farms)
Heart monitoring implants(Example Pacemaker, ECG real time tracking)
naveenkumarkharwal
winnar749
dev18kapadiaa
IoT
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write Regular Expressions?
Software Engineering | Prototyping Model
Association Rule
OOPs | Object Oriented Design
Recursive Functions
std::unique in C++
Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)
Java Math min() method with Examples
fgets() and gets() in C language
Distributed Database System | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jul, 2022"
},
{
"code": null,
"e": 609,
"s": 54,
"text": "Internet of Things (IoT) is the networking of physical objects that contain electronics embedded within their architecture in order to communicate and sense interactions amongst each other or with respect to the external environment. In the upcoming years, IoT-based technology will offer advanced levels of services and practically change the way people lead their daily lives. Advancements in medicine, power, gene therapies, agriculture, smart cities, and smart homes are just a very few of the categorical examples where IoT is strongly established. "
},
{
"code": null,
"e": 740,
"s": 609,
"text": "IoT is network of interconnected computing devices which are embedded in everyday objects, enabling them to send and receive data."
},
{
"code": null,
"e": 914,
"s": 740,
"text": "Over 9 billion ‘Things’ (physical objects) are currently connected to the Internet, as of now. In the near future, this number is expected to rise to a whopping 20 billion. "
},
{
"code": null,
"e": 945,
"s": 914,
"text": " Main components used in IoT: "
},
{
"code": null,
"e": 1111,
"s": 945,
"text": "Low-power embedded systems: Less battery consumption, high performance are the inverse factors that play a significant role during the design of electronic systems. "
},
{
"code": null,
"e": 1362,
"s": 1111,
"text": "Sensors : Sensors are the major part of any IoT applications. It is a physical device that measures and detect certain physical quantity and convert it into signal which can be provide as an input to processing or control unit for analysis purpose."
},
{
"code": null,
"e": 1524,
"s": 1362,
"text": "Different types of Sensors :Temperature SensorsImage SensorsGyro SensorsObstacle SensorsRF SensorIR SensorMQ-02/05 Gas SensorLDR SensorUltrasonic Distance Sensor"
},
{
"code": null,
"e": 1553,
"s": 1524,
"text": "Different types of Sensors :"
},
{
"code": null,
"e": 1573,
"s": 1553,
"text": "Temperature Sensors"
},
{
"code": null,
"e": 1587,
"s": 1573,
"text": "Image Sensors"
},
{
"code": null,
"e": 1600,
"s": 1587,
"text": "Gyro Sensors"
},
{
"code": null,
"e": 1617,
"s": 1600,
"text": "Obstacle Sensors"
},
{
"code": null,
"e": 1627,
"s": 1617,
"text": "RF Sensor"
},
{
"code": null,
"e": 1637,
"s": 1627,
"text": "IR Sensor"
},
{
"code": null,
"e": 1657,
"s": 1637,
"text": "MQ-02/05 Gas Sensor"
},
{
"code": null,
"e": 1668,
"s": 1657,
"text": "LDR Sensor"
},
{
"code": null,
"e": 1695,
"s": 1668,
"text": "Ultrasonic Distance Sensor"
},
{
"code": null,
"e": 1985,
"s": 1695,
"text": "Control Units : It is a unit of small computer on a single integrated circuit containing microprocessor or processing core, memory and programmable input/output devices/peripherals. It is responsible for major processing work of IoT devices and all logical operations are carried out here."
},
{
"code": null,
"e": 2294,
"s": 1985,
"text": "Cloud computing: Data collected through IoT devices is massive and this data has to be stored on a reliable storage server. This is where cloud computing comes into play. The data is processed and learned, giving more room for us to discover where things like electrical faults/errors are within the system. "
},
{
"code": null,
"e": 2509,
"s": 2294,
"text": "Availability of big data: We know that IoT relies heavily on sensors, especially in real-time. As these electronic devices spread throughout every field, their usage is going to trigger a massive flux of big data. "
},
{
"code": null,
"e": 2936,
"s": 2509,
"text": "Networking connection: In order to communicate, internet connectivity is a must where each physical object is represented by an IP address. However, there are only a limited number of addresses available according to the IP naming. Due to the growing number of devices, this naming system will not be feasible anymore. Therefore, researchers are looking for another alternative naming system to represent each physical object."
},
{
"code": null,
"e": 2973,
"s": 2936,
"text": "There are two ways of building IoT: "
},
{
"code": null,
"e": 3189,
"s": 2973,
"text": "Form a separate internetwork including only physical objects. Make the Internet ever more expansive, but this requires hard-core technologies such as rigorous cloud computing and rapid big data storage (expensive)."
},
{
"code": null,
"e": 3253,
"s": 3189,
"text": "Form a separate internetwork including only physical objects. "
},
{
"code": null,
"e": 3406,
"s": 3253,
"text": "Make the Internet ever more expansive, but this requires hard-core technologies such as rigorous cloud computing and rapid big data storage (expensive)."
},
{
"code": null,
"e": 3525,
"s": 3406,
"text": "In the near future, IoT will become broader and more complex in terms of scope. It will change the world in terms of "
},
{
"code": null,
"e": 3572,
"s": 3525,
"text": "“anytime, anyplace, anything in connectivity.”"
},
{
"code": null,
"e": 3587,
"s": 3572,
"text": " IoT Enablers:"
},
{
"code": null,
"e": 3687,
"s": 3587,
"text": "RFIDs: uses radio waves in order to electronically track the tags attached to each physical object."
},
{
"code": null,
"e": 3778,
"s": 3687,
"text": "Sensors: devices that are able to detect changes in an environment (ex: motion detectors)."
},
{
"code": null,
"e": 3906,
"s": 3778,
"text": "Nanotechnology: as the name suggests, these are extremely small devices with dimensions usually less than a hundred nanometers."
},
{
"code": null,
"e": 3945,
"s": 3906,
"text": "Smart networks: (ex: mesh topology). "
},
{
"code": null,
"e": 3972,
"s": 3945,
"text": "Working with IoT Devices :"
},
{
"code": null,
"e": 4107,
"s": 3972,
"text": "Collect and Transmit Data : For this purpose sensors are widely used they are used as per requirements in different application areas."
},
{
"code": null,
"e": 4353,
"s": 4107,
"text": "Actuate device based on triggers produced by sensors or processing devices : If certain condition is satisfied or according to user’s requirements if certain trigger is activated then which action to performed that is shown by Actuator devices. "
},
{
"code": null,
"e": 4489,
"s": 4353,
"text": "Receive Information : From network devices user or device can take certain information also for their analysis and processing purposes."
},
{
"code": null,
"e": 4800,
"s": 4489,
"text": "Communication Assistance : Communication assistance is the phenomena of communication between 2 network or communication between 2 or more IoT devices of same or different Networks. This can be achieved by different communication protocols like : MQTT , Constrained Application Protocol, ZigBee, FTP, HTTP etc."
},
{
"code": null,
"e": 4815,
"s": 4800,
"text": "Working of IoT"
},
{
"code": null,
"e": 4840,
"s": 4815,
"text": "Characteristics of IoT: "
},
{
"code": null,
"e": 4873,
"s": 4840,
"text": "Massively scalable and efficient"
},
{
"code": null,
"e": 4944,
"s": 4873,
"text": "IP-based addressing will no longer be suitable in the upcoming future."
},
{
"code": null,
"e": 5033,
"s": 4944,
"text": "An abundance of physical objects is present that do not use IP, so IoT is made possible."
},
{
"code": null,
"e": 5138,
"s": 5033,
"text": "Devices typically consume less power. When not in use, they should be automatically programmed to sleep."
},
{
"code": null,
"e": 5242,
"s": 5138,
"text": "A device that is connected to another device right now may not be connected in another instant of time."
},
{
"code": null,
"e": 5496,
"s": 5242,
"text": "Intermittent connectivity – IoT devices aren’t always connected. In order to save bandwidth and battery consumption, devices will be powered off periodically when not in use. Otherwise, connections might turn unreliable and thus prove to be inefficient."
},
{
"code": null,
"e": 5537,
"s": 5496,
"text": "Desired Quality of any IoT Application :"
},
{
"code": null,
"e": 5555,
"s": 5537,
"text": "Interconnectivity"
},
{
"code": null,
"e": 5746,
"s": 5555,
"text": "It is the basic first requirement in any IoT infrastructure. Connectivity should be guaranteed from any devices on any network then only devices in a network can communicate with each other."
},
{
"code": null,
"e": 5760,
"s": 5746,
"text": "Heterogeneity"
},
{
"code": null,
"e": 5991,
"s": 5760,
"text": "There can be diversity in IoT enabled devices like different hardware and software configuration or different network topologies or connections but they should connect and interact with each other despite of so much heterogeneity."
},
{
"code": null,
"e": 6009,
"s": 5991,
"text": "Dynamic in nature"
},
{
"code": null,
"e": 6135,
"s": 6009,
"text": "IoT devices should dynamically adapt themselves to the changing surroundings like different situation and different prefaces."
},
{
"code": null,
"e": 6181,
"s": 6135,
"text": "Self adapting and self configuring technology"
},
{
"code": null,
"e": 6339,
"s": 6181,
"text": "For example surveillance camera. It should be flexible to work in different weather conditions and different light situations (morning, afternoon, or night)."
},
{
"code": null,
"e": 6352,
"s": 6339,
"text": "Intelligence"
},
{
"code": null,
"e": 6834,
"s": 6352,
"text": "Just data collection is not enough in IoT, extraction of knowledge from the generated data is very important. For example, sensors generate data, but that data will only be useful if it is interpreted properly. So intelligence is one of the key characteristics in IoT. Because data interpretation is the major part in any IoT application because without data processing we can’t make any insights from data . Hence big data is also one of the most enabling technology in IoT field."
},
{
"code": null,
"e": 6846,
"s": 6834,
"text": "Scalability"
},
{
"code": null,
"e": 7150,
"s": 6846,
"text": "The number of elements (devices) connected to IoT zone is increasing day by day. Therefore, an IoT setup should be capable of handling the expansion. It can be either expand capability in terms of processing power, Storage, etc. as vertical scaling or horizontal scaling by multiplying with easy cloning"
},
{
"code": null,
"e": 7159,
"s": 7150,
"text": "Identity"
},
{
"code": null,
"e": 7631,
"s": 7159,
"text": "Each IoT device has a unique identity (e.g., an IP address). This identity is helpful in communication, tracking and to know status of the things. If there is no identification then it will directly effect security and safety of any system because without discrimination we can’t identify with whom one network is connected or with whom we have to communicate. So there should be clear and appropriate discrimination technology available between IoT networks and devices."
},
{
"code": null,
"e": 7638,
"s": 7631,
"text": "Safety"
},
{
"code": null,
"e": 7921,
"s": 7638,
"text": "Sensitive personal details of a user might be compromised when the devices are connected to the Internet. So data security is a major challenge. This could cause a loss to the user. Equipment in the huge IoT network may also be at risk. Therefore, equipment safety is also critical."
},
{
"code": null,
"e": 7934,
"s": 7921,
"text": "Architecture"
},
{
"code": null,
"e": 8032,
"s": 7934,
"text": "It should be hybrid, supporting different manufacturer’s products to function in the IoT network."
},
{
"code": null,
"e": 8146,
"s": 8032,
"text": "As a quick note, IoT incorporates trillions of sensors, billions of smart systems, and millions of applications. "
},
{
"code": null,
"e": 8226,
"s": 8146,
"text": "Application Domains: IoT is currently found in four different popular domains: "
},
{
"code": null,
"e": 8330,
"s": 8226,
"text": "1) Manufacturing/Industrial business - 40.2%\n2) Healthcare - 30.3%\n3) Security - 7.7%\n4) Retail - 8.3% "
},
{
"code": null,
"e": 8352,
"s": 8330,
"text": "Modern Applications: "
},
{
"code": null,
"e": 8781,
"s": 8352,
"text": "Smart Grids and energy savingSmart citiesSmart homes/Home automationHealthcareEarthquake detectionRadiation detection/hazardous gas detectionSmartphone detectionWater flow monitoringTraffic monitoringWearablesSmart door lock protection systemRobots and DronesHealthcare and Hospitals, Telemedicine applicationsSecurityBiochip Transponders(For animals in farms)Heart monitoring implants(Example Pacemaker, ECG real time tracking)"
},
{
"code": null,
"e": 8811,
"s": 8781,
"text": "Smart Grids and energy saving"
},
{
"code": null,
"e": 8824,
"s": 8811,
"text": "Smart cities"
},
{
"code": null,
"e": 8852,
"s": 8824,
"text": "Smart homes/Home automation"
},
{
"code": null,
"e": 8863,
"s": 8852,
"text": "Healthcare"
},
{
"code": null,
"e": 8884,
"s": 8863,
"text": "Earthquake detection"
},
{
"code": null,
"e": 8928,
"s": 8884,
"text": "Radiation detection/hazardous gas detection"
},
{
"code": null,
"e": 8949,
"s": 8928,
"text": "Smartphone detection"
},
{
"code": null,
"e": 8971,
"s": 8949,
"text": "Water flow monitoring"
},
{
"code": null,
"e": 8990,
"s": 8971,
"text": "Traffic monitoring"
},
{
"code": null,
"e": 9000,
"s": 8990,
"text": "Wearables"
},
{
"code": null,
"e": 9034,
"s": 9000,
"text": "Smart door lock protection system"
},
{
"code": null,
"e": 9052,
"s": 9034,
"text": "Robots and Drones"
},
{
"code": null,
"e": 9104,
"s": 9052,
"text": "Healthcare and Hospitals, Telemedicine applications"
},
{
"code": null,
"e": 9113,
"s": 9104,
"text": "Security"
},
{
"code": null,
"e": 9156,
"s": 9113,
"text": "Biochip Transponders(For animals in farms)"
},
{
"code": null,
"e": 9225,
"s": 9156,
"text": "Heart monitoring implants(Example Pacemaker, ECG real time tracking)"
},
{
"code": null,
"e": 9244,
"s": 9225,
"text": "naveenkumarkharwal"
},
{
"code": null,
"e": 9254,
"s": 9244,
"text": "winnar749"
},
{
"code": null,
"e": 9268,
"s": 9254,
"text": "dev18kapadiaa"
},
{
"code": null,
"e": 9272,
"s": 9268,
"text": "IoT"
},
{
"code": null,
"e": 9277,
"s": 9272,
"text": "Misc"
},
{
"code": null,
"e": 9282,
"s": 9277,
"text": "Misc"
},
{
"code": null,
"e": 9287,
"s": 9282,
"text": "Misc"
},
{
"code": null,
"e": 9385,
"s": 9287,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9419,
"s": 9385,
"text": "How to write Regular Expressions?"
},
{
"code": null,
"e": 9460,
"s": 9419,
"text": "Software Engineering | Prototyping Model"
},
{
"code": null,
"e": 9477,
"s": 9460,
"text": "Association Rule"
},
{
"code": null,
"e": 9507,
"s": 9477,
"text": "OOPs | Object Oriented Design"
},
{
"code": null,
"e": 9527,
"s": 9507,
"text": "Recursive Functions"
},
{
"code": null,
"e": 9546,
"s": 9527,
"text": "std::unique in C++"
},
{
"code": null,
"e": 9627,
"s": 9546,
"text": "Minimax Algorithm in Game Theory | Set 3 (Tic-Tac-Toe AI - Finding optimal move)"
},
{
"code": null,
"e": 9664,
"s": 9627,
"text": "Java Math min() method with Examples"
},
{
"code": null,
"e": 9697,
"s": 9664,
"text": "fgets() and gets() in C language"
}
] |
SQL – SELECT SUM | 21 Jul, 2021
SELECT SUM is used to calculate the total value of an expression in SQL. It is the same as using the AGGREGATE function SUM ( ) in SQL.
In this article, we are going to see how to use “SELECT SUM” in SQL using suitable examples.
Syntax :
SELECT SUM(expr)
FROM Table_Name
WHERE condition;
expr : Expression or column name
1. Creating a Database:
Use the following syntax to create a database:
CREATE DATABASE database_name
2. Creating a Table:
Use the below syntax to create a table:
CREATE TABLE Table_name(
col_1 TYPE col_1_constraint,
col_2 TYPE col_2 constraint
.....
)
col: Column name
TYPE: Data type whether an integer, variable character, etc
col_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc
3. Inserting into a Table:
Use the below syntax to insert data to the table:
INSERT INTO Table_name
VALUES(val_1, val_2, val_3, ..........)
val: Values in particular column
4. View The Table:
Use the below syntax to view the contents of the table:
SELECT * FROM Table_name
Now let’s look into some example use cases of the SELECT SUM function in SQL:
Example 1: Consider the purchase details of mobile phones from an E-commerce site as shown below :
Purchase Information Table
Query :
Find the sum of all the mobile phones sold on Big Billion Days whose price is less than 55,000 INR.
Example 2: Let’s see another example using the GROUP BY clause. Consider the employee details table of an organization shown below which consists of information about the salary, name, department in which employees are working.
Employee Details
Query :
Find out the total expenditure the company has to provide to the employees of every department.
In the above result, we can see that the number of employees in HR is 3 and each employee gets a salary of 50,000 INR per month. So, the total salary the company has to provide in the HR department is 1,50,000 INR per month.
sagar0719kumar
Picked
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 190,
"s": 54,
"text": "SELECT SUM is used to calculate the total value of an expression in SQL. It is the same as using the AGGREGATE function SUM ( ) in SQL."
},
{
"code": null,
"e": 283,
"s": 190,
"text": "In this article, we are going to see how to use “SELECT SUM” in SQL using suitable examples."
},
{
"code": null,
"e": 292,
"s": 283,
"text": "Syntax :"
},
{
"code": null,
"e": 376,
"s": 292,
"text": "SELECT SUM(expr)\nFROM Table_Name\nWHERE condition;\n\nexpr : Expression or column name"
},
{
"code": null,
"e": 401,
"s": 376,
"text": "1. Creating a Database: "
},
{
"code": null,
"e": 448,
"s": 401,
"text": "Use the following syntax to create a database:"
},
{
"code": null,
"e": 478,
"s": 448,
"text": "CREATE DATABASE database_name"
},
{
"code": null,
"e": 499,
"s": 478,
"text": "2. Creating a Table:"
},
{
"code": null,
"e": 539,
"s": 499,
"text": "Use the below syntax to create a table:"
},
{
"code": null,
"e": 794,
"s": 539,
"text": "CREATE TABLE Table_name(\ncol_1 TYPE col_1_constraint,\ncol_2 TYPE col_2 constraint\n.....\n)\n\ncol: Column name\nTYPE: Data type whether an integer, variable character, etc\ncol_constraint: Constraints in SQL like PRIMARY KEY, NOT NULL, UNIQUE, REFERENCES, etc"
},
{
"code": null,
"e": 821,
"s": 794,
"text": "3. Inserting into a Table:"
},
{
"code": null,
"e": 871,
"s": 821,
"text": "Use the below syntax to insert data to the table:"
},
{
"code": null,
"e": 968,
"s": 871,
"text": "INSERT INTO Table_name\nVALUES(val_1, val_2, val_3, ..........)\n\nval: Values in particular column"
},
{
"code": null,
"e": 987,
"s": 968,
"text": "4. View The Table:"
},
{
"code": null,
"e": 1043,
"s": 987,
"text": "Use the below syntax to view the contents of the table:"
},
{
"code": null,
"e": 1068,
"s": 1043,
"text": "SELECT * FROM Table_name"
},
{
"code": null,
"e": 1146,
"s": 1068,
"text": "Now let’s look into some example use cases of the SELECT SUM function in SQL:"
},
{
"code": null,
"e": 1245,
"s": 1146,
"text": "Example 1: Consider the purchase details of mobile phones from an E-commerce site as shown below :"
},
{
"code": null,
"e": 1272,
"s": 1245,
"text": "Purchase Information Table"
},
{
"code": null,
"e": 1281,
"s": 1272,
"text": "Query : "
},
{
"code": null,
"e": 1381,
"s": 1281,
"text": "Find the sum of all the mobile phones sold on Big Billion Days whose price is less than 55,000 INR."
},
{
"code": null,
"e": 1609,
"s": 1381,
"text": "Example 2: Let’s see another example using the GROUP BY clause. Consider the employee details table of an organization shown below which consists of information about the salary, name, department in which employees are working."
},
{
"code": null,
"e": 1626,
"s": 1609,
"text": "Employee Details"
},
{
"code": null,
"e": 1635,
"s": 1626,
"text": "Query : "
},
{
"code": null,
"e": 1731,
"s": 1635,
"text": "Find out the total expenditure the company has to provide to the employees of every department."
},
{
"code": null,
"e": 1956,
"s": 1731,
"text": "In the above result, we can see that the number of employees in HR is 3 and each employee gets a salary of 50,000 INR per month. So, the total salary the company has to provide in the HR department is 1,50,000 INR per month."
},
{
"code": null,
"e": 1971,
"s": 1956,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1978,
"s": 1971,
"text": "Picked"
},
{
"code": null,
"e": 1992,
"s": 1978,
"text": "SQL-Functions"
},
{
"code": null,
"e": 1996,
"s": 1992,
"text": "SQL"
},
{
"code": null,
"e": 2000,
"s": 1996,
"text": "SQL"
}
] |
wcstok() function in C++ with example | 12 Dec, 2021
The wcstok() function is defined in cwchar.h header file. The wcstok() function returns the next token in a null terminated wide string. The pointer delim points to the separator characters i.e. the delimiter.
.Syntax:
wchar_t* wcstok(wchar_t* str,
const wchar_t* delim,
wchar_t ** ptr);
Parameters: This method takes following parameters:
str: It represents pointer to the null-terminated wide string to tokenize.
delim: It represents pointer to the null terminated wide string that contains the separators.
ptr: It represents pointer to an object of type wchar_t*, which is used by wcstok to store its internal state.
Return Value: The wcstok() function returns the pointer to the beginning of next token if there is any. Otherwise it returns zero.Below program illustrate the above function:Example 1:
cpp
// c++ program to demonstrate// example of wcstok() function. #include <bits/stdc++.h>using namespace std; int main(){ // Get the string wchar_t str[] = L"A computer science portal for geeks"; // Creating the parameters of wcstok() method // Create the pointer of which // the next token is required wchar_t* ptr; // Define the delimiter of the string wchar_t delim[] = L" "; // Call the wcstok() method wchar_t* token = wcstok(str, delim, &ptr); // Print all tokens with the help of it while (token) { wcout << token << endl; token = wcstok(NULL, delim, &ptr); } return 0;}
A
computer
science
portal
for
geeks
anikaseth98
akshaysingh98088
CPP-Functions
CPP-Library
Picked
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "The wcstok() function is defined in cwchar.h header file. The wcstok() function returns the next token in a null terminated wide string. The pointer delim points to the separator characters i.e. the delimiter."
},
{
"code": null,
"e": 249,
"s": 238,
"text": ".Syntax: "
},
{
"code": null,
"e": 362,
"s": 249,
"text": "wchar_t* wcstok(wchar_t* str, \n const wchar_t* delim, \n wchar_t ** ptr);"
},
{
"code": null,
"e": 416,
"s": 362,
"text": "Parameters: This method takes following parameters: "
},
{
"code": null,
"e": 491,
"s": 416,
"text": "str: It represents pointer to the null-terminated wide string to tokenize."
},
{
"code": null,
"e": 585,
"s": 491,
"text": "delim: It represents pointer to the null terminated wide string that contains the separators."
},
{
"code": null,
"e": 696,
"s": 585,
"text": "ptr: It represents pointer to an object of type wchar_t*, which is used by wcstok to store its internal state."
},
{
"code": null,
"e": 882,
"s": 696,
"text": "Return Value: The wcstok() function returns the pointer to the beginning of next token if there is any. Otherwise it returns zero.Below program illustrate the above function:Example 1: "
},
{
"code": null,
"e": 886,
"s": 882,
"text": "cpp"
},
{
"code": "// c++ program to demonstrate// example of wcstok() function. #include <bits/stdc++.h>using namespace std; int main(){ // Get the string wchar_t str[] = L\"A computer science portal for geeks\"; // Creating the parameters of wcstok() method // Create the pointer of which // the next token is required wchar_t* ptr; // Define the delimiter of the string wchar_t delim[] = L\" \"; // Call the wcstok() method wchar_t* token = wcstok(str, delim, &ptr); // Print all tokens with the help of it while (token) { wcout << token << endl; token = wcstok(NULL, delim, &ptr); } return 0;}",
"e": 1524,
"s": 886,
"text": null
},
{
"code": null,
"e": 1560,
"s": 1524,
"text": "A\ncomputer\nscience\nportal\nfor\ngeeks"
},
{
"code": null,
"e": 1574,
"s": 1562,
"text": "anikaseth98"
},
{
"code": null,
"e": 1591,
"s": 1574,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 1605,
"s": 1591,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1617,
"s": 1605,
"text": "CPP-Library"
},
{
"code": null,
"e": 1624,
"s": 1617,
"text": "Picked"
},
{
"code": null,
"e": 1628,
"s": 1624,
"text": "C++"
},
{
"code": null,
"e": 1632,
"s": 1628,
"text": "CPP"
}
] |
K-fold Cross Validation in R Programming | 28 Dec, 2021
The prime aim of any machine learning model is to predict the outcome of real-time data. To check whether the developed model is efficient enough to predict the outcome of an unseen data point, performance evaluation of the applied machine learning model becomes very necessary. K-fold cross-validation technique is basically a method of resampling the data set in order to evaluate a machine learning model. In this technique, the parameter K refers to the number of different subsets that the given data set is to be split into. Further, K-1 subsets are used to train the model and the left out subsets are used as a validation set.
Split the data set into K subsets randomlyFor each one of the developed subsets of data pointsTreat that subset as the validation setUse all the rest subsets for training purposeTraining of the model and evaluate it on the validation set or test setCalculate prediction errorRepeat the above step K times i.e., until the model is not trained and tested on all subsetsGenerate overall prediction error by taking the average of prediction errors in every case
Split the data set into K subsets randomly
For each one of the developed subsets of data pointsTreat that subset as the validation setUse all the rest subsets for training purposeTraining of the model and evaluate it on the validation set or test setCalculate prediction error
Treat that subset as the validation set
Use all the rest subsets for training purpose
Training of the model and evaluate it on the validation set or test set
Calculate prediction error
Repeat the above step K times i.e., until the model is not trained and tested on all subsets
Generate overall prediction error by taking the average of prediction errors in every case
To implement all the steps involved in the K-fold method, the R language has rich libraries and packages of inbuilt functions through which it becomes very easy to carry out the complete task. The following are the step-by-step procedure to implement the K-fold technique as a cross-validation method on Classification and Regression machine learning models.
Classification machine learning models are preferred when the target variable consist of categorical values like spam, not spam, true or false, etc. Here Naive Bayes classifier will be used as a probabilistic classifier to predict the class label of the target variable.
The very first requirement is to set up the R environment by loading all required libraries as well as packages to carry out the complete process without any failure. Below is the implementation of this step.
R
# loading required packages # package to perform data manipulation# and visualizationlibrary(tidyverse) # package to compute# cross - validation methodslibrary(caret) # loading package to# import desired datasetlibrary(ISLR)
In order to perform manipulations on the data set, it is very necessary to inspect it first. It will give a clear idea about the structure as well as the various kinds of data types present in the data set. For this purpose, the data set must be assigned to a variable. Below is the code to do the same.
R
# assigning the complete dataset# Smarket to a variabledataset <- Smarket[complete.cases(Smarket), ] # display the dataset with details# like column name and its data type# along with values in each rowglimpse(dataset) # checking values present# in the Direction column# of the datasettable(dataset$Direction)
Output:
Rows: 1,250
Columns: 9
$ Year <dbl> 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, ...
$ Lag1 <dbl> 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0.546, -1...
$ Lag2 <dbl> -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0...
$ Lag3 <dbl> -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -...
$ Lag4 <dbl> -1.055, -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, ...
$ Lag5 <dbl> 5.010, -1.055, -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, ...
$ Volume <dbl> 1.19130, 1.29650, 1.41120, 1.27600, 1.20570, 1.34910, 1.44500, 1.40780, 1.16400, 1.23260, 1.30900, 1.25800, 1.09800, 1.05310, ...
$ Today <dbl> 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0.546, -1.747, 0...
$ Direction <fct> Up, Up, Down, Up, Up, Up, Down, Up, Up, Up, Down, Down, Up, Up, Down, Up, Down, Up, Down, Down, Down, Down, Up, Down, Down, Up...
> table(dataset$Direction)
Down Up
602 648
According to the above information, the dataset contains 250 rows and 9 columns. The data type of independent variables is <dbl> which comes from double and it means the double-precision floating-point number. The target variable is of <fct> data type means factor and it is desirable for a classification model. Moreover, the target variable has 2 outcomes, namely Down and Up where the ratio of these two categories is almost 1:1, i.e., they are balanced. All the categories of the target variable must be in approximately equal proportion to make an unbiased model.
For this purpose, there are many techniques like:
Down Sampling
Up Sampling
Hybrid Sampling using SMOTE and ROSE
In this step, the trainControl() function is defined to set the value of the K parameter and then the model is developed as per the steps involved in the K-fold technique. Below is the implementation.
R
# setting seed to generate a # reproducible random samplingset.seed(123) # define training control which# generates parameters that further# control how models are createdtrain_control <- trainControl(method = "cv", number = 10) # building the model and# predicting the target variable# as per the Naive Bayes classifiermodel <- train(Direction~., data = dataset, trControl = train_control, method = "nb")
After training and validation of the model, it is time to calculate the overall accuracy of the model. Below is the code to generate a summary of the model.
R
# summarize results of the# model after calculating# prediction error in each caseprint(model)
Output:
Naive Bayes
1250 samples
8 predictor
2 classes: ‘Down’, ‘Up’
No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 1125, 1125, 1125, 1126, 1125, 1124, ...
Resampling results across tuning parameters:
usekernel Accuracy Kappa
FALSE 0.9543996 0.9083514
TRUE 0.9711870 0.9422498
Tuning parameter ‘fL’ was held constant at a value of 0
Tuning parameter ‘adjust’ was held constant at a value of 1
Accuracy was used to select the optimal model using the largest value.
The final values used for the model were fL = 0, usekernel = TRUE and adjust = 1.
Regression machine learning models are used to predict the target variable which is of continuous nature like the price of a commodity or sales of a firm. Below are the complete steps for implementing the K-fold cross-validation technique on regression models.
Set up the R environment by importing all necessary packages and libraries. Below is the implementation of this step.
R
# loading required packages # package to perform data manipulation# and visualizationlibrary(tidyverse) # package to compute# cross - validation methodslibrary(caret) # installing package to# import desired datasetinstall.packages("datarium")
In this step, the desired dataset is loaded in the R environment. After that, some rows of the data set are printed in order to understand its structure. Below is the code to carry out this task.
R
# loading the datasetdata("marketing", package = "datarium") # inspecting the datasethead(marketing)
Output:
youtube facebook newspaper sales
1 276.12 45.36 83.04 26.52
2 53.40 47.16 54.12 12.48
3 20.64 55.08 83.16 11.16
4 181.80 49.56 70.20 22.20
5 216.96 12.96 70.08 15.48
6 10.44 58.68 90.00 8.64
The value of the K parameter is defined in the trainControl() function and the model is developed according to the steps mentioned in the algorithm of the K-fold cross-validation technique. Below is the implementation.
R
# setting seed to generate a # reproducible random samplingset.seed(125) # defining training control# as cross-validation and # value of K equal to 10train_control <- trainControl(method = "cv", number = 10) # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = "lm", trControl = train_control)
As mentioned in the algorithm of K-fold that model is tested against every unique fold(or subset) of the dataset and in each case, the prediction error is calculated and at last, the mean of all prediction errors is treated as the final performance score of the model. So, below is the code to print the final score and overall summary of the model.
R
# printing model performance metrics# along with other detailsprint(model)
Output:
Linear Regression
200 samples
3 predictor
No pre-processing
Resampling: Cross-Validated (10 fold)
Summary of sample sizes: 181, 180, 180, 179, 180, 180, ...
Resampling results:
RMSE Rsquared MAE
2.027409 0.9041909 1.539866
Tuning parameter ‘intercept’ was held constant at a value of TRUE
Fast computation speed.
A very effective method to estimate the prediction error and the accuracy of a model.
A lower value of K leads to a biased model and a higher value of K can lead to variability in the performance metrics of the model. Thus, it is very important to use the correct value of K for the model (generally K = 5 and K = 10 is desirable).
adnanirshad158
akshaysingh98088
kumar_satyam
R Data-science
R Machine-Learning
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 689,
"s": 54,
"text": "The prime aim of any machine learning model is to predict the outcome of real-time data. To check whether the developed model is efficient enough to predict the outcome of an unseen data point, performance evaluation of the applied machine learning model becomes very necessary. K-fold cross-validation technique is basically a method of resampling the data set in order to evaluate a machine learning model. In this technique, the parameter K refers to the number of different subsets that the given data set is to be split into. Further, K-1 subsets are used to train the model and the left out subsets are used as a validation set."
},
{
"code": null,
"e": 1147,
"s": 689,
"text": "Split the data set into K subsets randomlyFor each one of the developed subsets of data pointsTreat that subset as the validation setUse all the rest subsets for training purposeTraining of the model and evaluate it on the validation set or test setCalculate prediction errorRepeat the above step K times i.e., until the model is not trained and tested on all subsetsGenerate overall prediction error by taking the average of prediction errors in every case"
},
{
"code": null,
"e": 1190,
"s": 1147,
"text": "Split the data set into K subsets randomly"
},
{
"code": null,
"e": 1424,
"s": 1190,
"text": "For each one of the developed subsets of data pointsTreat that subset as the validation setUse all the rest subsets for training purposeTraining of the model and evaluate it on the validation set or test setCalculate prediction error"
},
{
"code": null,
"e": 1464,
"s": 1424,
"text": "Treat that subset as the validation set"
},
{
"code": null,
"e": 1510,
"s": 1464,
"text": "Use all the rest subsets for training purpose"
},
{
"code": null,
"e": 1582,
"s": 1510,
"text": "Training of the model and evaluate it on the validation set or test set"
},
{
"code": null,
"e": 1609,
"s": 1582,
"text": "Calculate prediction error"
},
{
"code": null,
"e": 1702,
"s": 1609,
"text": "Repeat the above step K times i.e., until the model is not trained and tested on all subsets"
},
{
"code": null,
"e": 1793,
"s": 1702,
"text": "Generate overall prediction error by taking the average of prediction errors in every case"
},
{
"code": null,
"e": 2152,
"s": 1793,
"text": "To implement all the steps involved in the K-fold method, the R language has rich libraries and packages of inbuilt functions through which it becomes very easy to carry out the complete task. The following are the step-by-step procedure to implement the K-fold technique as a cross-validation method on Classification and Regression machine learning models."
},
{
"code": null,
"e": 2425,
"s": 2152,
"text": "Classification machine learning models are preferred when the target variable consist of categorical values like spam, not spam, true or false, etc. Here Naive Bayes classifier will be used as a probabilistic classifier to predict the class label of the target variable. "
},
{
"code": null,
"e": 2634,
"s": 2425,
"text": "The very first requirement is to set up the R environment by loading all required libraries as well as packages to carry out the complete process without any failure. Below is the implementation of this step."
},
{
"code": null,
"e": 2636,
"s": 2634,
"text": "R"
},
{
"code": "# loading required packages # package to perform data manipulation# and visualizationlibrary(tidyverse) # package to compute# cross - validation methodslibrary(caret) # loading package to# import desired datasetlibrary(ISLR)",
"e": 2861,
"s": 2636,
"text": null
},
{
"code": null,
"e": 3165,
"s": 2861,
"text": "In order to perform manipulations on the data set, it is very necessary to inspect it first. It will give a clear idea about the structure as well as the various kinds of data types present in the data set. For this purpose, the data set must be assigned to a variable. Below is the code to do the same."
},
{
"code": null,
"e": 3167,
"s": 3165,
"text": "R"
},
{
"code": "# assigning the complete dataset# Smarket to a variabledataset <- Smarket[complete.cases(Smarket), ] # display the dataset with details# like column name and its data type# along with values in each rowglimpse(dataset) # checking values present# in the Direction column# of the datasettable(dataset$Direction)",
"e": 3477,
"s": 3167,
"text": null
},
{
"code": null,
"e": 3485,
"s": 3477,
"text": "Output:"
},
{
"code": null,
"e": 3497,
"s": 3485,
"text": "Rows: 1,250"
},
{
"code": null,
"e": 3508,
"s": 3497,
"text": "Columns: 9"
},
{
"code": null,
"e": 3656,
"s": 3508,
"text": "$ Year <dbl> 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, ..."
},
{
"code": null,
"e": 3804,
"s": 3656,
"text": "$ Lag1 <dbl> 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0.546, -1..."
},
{
"code": null,
"e": 3952,
"s": 3804,
"text": "$ Lag2 <dbl> -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0..."
},
{
"code": null,
"e": 4100,
"s": 3952,
"text": "$ Lag3 <dbl> -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -..."
},
{
"code": null,
"e": 4248,
"s": 4100,
"text": "$ Lag4 <dbl> -1.055, -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, ..."
},
{
"code": null,
"e": 4396,
"s": 4248,
"text": "$ Lag5 <dbl> 5.010, -1.055, -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, ..."
},
{
"code": null,
"e": 4544,
"s": 4396,
"text": "$ Volume <dbl> 1.19130, 1.29650, 1.41120, 1.27600, 1.20570, 1.34910, 1.44500, 1.40780, 1.16400, 1.23260, 1.30900, 1.25800, 1.09800, 1.05310, ..."
},
{
"code": null,
"e": 4692,
"s": 4544,
"text": "$ Today <dbl> 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0.546, -1.747, 0..."
},
{
"code": null,
"e": 4840,
"s": 4692,
"text": "$ Direction <fct> Up, Up, Down, Up, Up, Up, Down, Up, Up, Up, Down, Down, Up, Up, Down, Up, Down, Up, Down, Down, Down, Down, Up, Down, Down, Up..."
},
{
"code": null,
"e": 4867,
"s": 4840,
"text": "> table(dataset$Direction)"
},
{
"code": null,
"e": 4878,
"s": 4867,
"text": "Down Up "
},
{
"code": null,
"e": 4889,
"s": 4878,
"text": " 602 648 "
},
{
"code": null,
"e": 5459,
"s": 4889,
"text": "According to the above information, the dataset contains 250 rows and 9 columns. The data type of independent variables is <dbl> which comes from double and it means the double-precision floating-point number. The target variable is of <fct> data type means factor and it is desirable for a classification model. Moreover, the target variable has 2 outcomes, namely Down and Up where the ratio of these two categories is almost 1:1, i.e., they are balanced. All the categories of the target variable must be in approximately equal proportion to make an unbiased model. "
},
{
"code": null,
"e": 5509,
"s": 5459,
"text": "For this purpose, there are many techniques like:"
},
{
"code": null,
"e": 5523,
"s": 5509,
"text": "Down Sampling"
},
{
"code": null,
"e": 5535,
"s": 5523,
"text": "Up Sampling"
},
{
"code": null,
"e": 5572,
"s": 5535,
"text": "Hybrid Sampling using SMOTE and ROSE"
},
{
"code": null,
"e": 5774,
"s": 5572,
"text": "In this step, the trainControl() function is defined to set the value of the K parameter and then the model is developed as per the steps involved in the K-fold technique. Below is the implementation. "
},
{
"code": null,
"e": 5776,
"s": 5774,
"text": "R"
},
{
"code": "# setting seed to generate a # reproducible random samplingset.seed(123) # define training control which# generates parameters that further# control how models are createdtrain_control <- trainControl(method = \"cv\", number = 10) # building the model and# predicting the target variable# as per the Naive Bayes classifiermodel <- train(Direction~., data = dataset, trControl = train_control, method = \"nb\")",
"e": 6240,
"s": 5776,
"text": null
},
{
"code": null,
"e": 6398,
"s": 6240,
"text": "After training and validation of the model, it is time to calculate the overall accuracy of the model. Below is the code to generate a summary of the model. "
},
{
"code": null,
"e": 6400,
"s": 6398,
"text": "R"
},
{
"code": "# summarize results of the# model after calculating# prediction error in each caseprint(model)",
"e": 6495,
"s": 6400,
"text": null
},
{
"code": null,
"e": 6504,
"s": 6495,
"text": "Output: "
},
{
"code": null,
"e": 6517,
"s": 6504,
"text": "Naive Bayes "
},
{
"code": null,
"e": 6530,
"s": 6517,
"text": "1250 samples"
},
{
"code": null,
"e": 6545,
"s": 6530,
"text": " 8 predictor"
},
{
"code": null,
"e": 6573,
"s": 6545,
"text": " 2 classes: ‘Down’, ‘Up’ "
},
{
"code": null,
"e": 6591,
"s": 6573,
"text": "No pre-processing"
},
{
"code": null,
"e": 6630,
"s": 6591,
"text": "Resampling: Cross-Validated (10 fold) "
},
{
"code": null,
"e": 6696,
"s": 6630,
"text": "Summary of sample sizes: 1125, 1125, 1125, 1126, 1125, 1124, ... "
},
{
"code": null,
"e": 6741,
"s": 6696,
"text": "Resampling results across tuning parameters:"
},
{
"code": null,
"e": 6775,
"s": 6741,
"text": " usekernel Accuracy Kappa "
},
{
"code": null,
"e": 6809,
"s": 6775,
"text": " FALSE 0.9543996 0.9083514"
},
{
"code": null,
"e": 6843,
"s": 6809,
"text": " TRUE 0.9711870 0.9422498"
},
{
"code": null,
"e": 6899,
"s": 6843,
"text": "Tuning parameter ‘fL’ was held constant at a value of 0"
},
{
"code": null,
"e": 6959,
"s": 6899,
"text": "Tuning parameter ‘adjust’ was held constant at a value of 1"
},
{
"code": null,
"e": 7030,
"s": 6959,
"text": "Accuracy was used to select the optimal model using the largest value."
},
{
"code": null,
"e": 7112,
"s": 7030,
"text": "The final values used for the model were fL = 0, usekernel = TRUE and adjust = 1."
},
{
"code": null,
"e": 7373,
"s": 7112,
"text": "Regression machine learning models are used to predict the target variable which is of continuous nature like the price of a commodity or sales of a firm. Below are the complete steps for implementing the K-fold cross-validation technique on regression models."
},
{
"code": null,
"e": 7492,
"s": 7373,
"text": "Set up the R environment by importing all necessary packages and libraries. Below is the implementation of this step. "
},
{
"code": null,
"e": 7494,
"s": 7492,
"text": "R"
},
{
"code": "# loading required packages # package to perform data manipulation# and visualizationlibrary(tidyverse) # package to compute# cross - validation methodslibrary(caret) # installing package to# import desired datasetinstall.packages(\"datarium\")",
"e": 7737,
"s": 7494,
"text": null
},
{
"code": null,
"e": 7933,
"s": 7737,
"text": "In this step, the desired dataset is loaded in the R environment. After that, some rows of the data set are printed in order to understand its structure. Below is the code to carry out this task."
},
{
"code": null,
"e": 7935,
"s": 7933,
"text": "R"
},
{
"code": "# loading the datasetdata(\"marketing\", package = \"datarium\") # inspecting the datasethead(marketing)",
"e": 8036,
"s": 7935,
"text": null
},
{
"code": null,
"e": 8045,
"s": 8036,
"text": "Output: "
},
{
"code": null,
"e": 8290,
"s": 8045,
"text": " youtube facebook newspaper sales\n1 276.12 45.36 83.04 26.52\n2 53.40 47.16 54.12 12.48\n3 20.64 55.08 83.16 11.16\n4 181.80 49.56 70.20 22.20\n5 216.96 12.96 70.08 15.48\n6 10.44 58.68 90.00 8.64"
},
{
"code": null,
"e": 8510,
"s": 8290,
"text": "The value of the K parameter is defined in the trainControl() function and the model is developed according to the steps mentioned in the algorithm of the K-fold cross-validation technique. Below is the implementation. "
},
{
"code": null,
"e": 8512,
"s": 8510,
"text": "R"
},
{
"code": "# setting seed to generate a # reproducible random samplingset.seed(125) # defining training control# as cross-validation and # value of K equal to 10train_control <- trainControl(method = \"cv\", number = 10) # training the model by assigning sales column# as target variable and rest other column# as independent variablemodel <- train(sales ~., data = marketing, method = \"lm\", trControl = train_control)",
"e": 8977,
"s": 8512,
"text": null
},
{
"code": null,
"e": 9328,
"s": 8977,
"text": "As mentioned in the algorithm of K-fold that model is tested against every unique fold(or subset) of the dataset and in each case, the prediction error is calculated and at last, the mean of all prediction errors is treated as the final performance score of the model. So, below is the code to print the final score and overall summary of the model. "
},
{
"code": null,
"e": 9330,
"s": 9328,
"text": "R"
},
{
"code": "# printing model performance metrics# along with other detailsprint(model)",
"e": 9405,
"s": 9330,
"text": null
},
{
"code": null,
"e": 9415,
"s": 9405,
"text": " Output: "
},
{
"code": null,
"e": 9434,
"s": 9415,
"text": "Linear Regression "
},
{
"code": null,
"e": 9446,
"s": 9434,
"text": "200 samples"
},
{
"code": null,
"e": 9460,
"s": 9446,
"text": " 3 predictor"
},
{
"code": null,
"e": 9478,
"s": 9460,
"text": "No pre-processing"
},
{
"code": null,
"e": 9517,
"s": 9478,
"text": "Resampling: Cross-Validated (10 fold) "
},
{
"code": null,
"e": 9577,
"s": 9517,
"text": "Summary of sample sizes: 181, 180, 180, 179, 180, 180, ... "
},
{
"code": null,
"e": 9597,
"s": 9577,
"text": "Resampling results:"
},
{
"code": null,
"e": 9629,
"s": 9597,
"text": " RMSE Rsquared MAE "
},
{
"code": null,
"e": 9661,
"s": 9629,
"text": " 2.027409 0.9041909 1.539866"
},
{
"code": null,
"e": 9727,
"s": 9661,
"text": "Tuning parameter ‘intercept’ was held constant at a value of TRUE"
},
{
"code": null,
"e": 9751,
"s": 9727,
"text": "Fast computation speed."
},
{
"code": null,
"e": 9837,
"s": 9751,
"text": "A very effective method to estimate the prediction error and the accuracy of a model."
},
{
"code": null,
"e": 10083,
"s": 9837,
"text": "A lower value of K leads to a biased model and a higher value of K can lead to variability in the performance metrics of the model. Thus, it is very important to use the correct value of K for the model (generally K = 5 and K = 10 is desirable)."
},
{
"code": null,
"e": 10098,
"s": 10083,
"text": "adnanirshad158"
},
{
"code": null,
"e": 10115,
"s": 10098,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 10128,
"s": 10115,
"text": "kumar_satyam"
},
{
"code": null,
"e": 10143,
"s": 10128,
"text": "R Data-science"
},
{
"code": null,
"e": 10162,
"s": 10143,
"text": "R Machine-Learning"
},
{
"code": null,
"e": 10173,
"s": 10162,
"text": "R Language"
}
] |
Minimize a string by removing all occurrences of another string | 27 May, 2022
Given two strings S1 and S2 of length N and M respectively, consisting of lowercase letters, the task is to find the minimum length to which S1 can be reduced by removing all occurrences of the string S2 from the string S1.
Examples:
Input: S1 =”fffoxoxoxfxo”, S2 = “fox”;Output: 3Explanation:By removing “fox” starting from index 2, the string modifies to “ffoxoxfxo”.By removing “fox” starting from index 1, the string modifies to “foxfxo”.By removing “fox” starting from index 0, the string modifies to “fxo”.Therefore, the minimum length of string S1 after removing all occurrences of S2 is 3.
Input: S1 =”abcd”, S2 = “pqr”Output: 4
Approach: The idea to solve this problem is to use Stack Data Structure. Follow the steps below to solve the given problem:
Initialize a stack to store the characters of the string S1 in it.
Traverse the given string S1 and perform the following operations:Push the current character in the stack.If the size of the stack is at least M, then check if the top M characters of the stack form the string S2 or not. If found to be true, then remove those characters.
Push the current character in the stack.
If the size of the stack is at least M, then check if the top M characters of the stack form the string S2 or not. If found to be true, then remove those characters.
After completing the above steps, the remaining size of the stack is the required minimum length.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Function to find the minimum length// to which string str can be reduced to// by removing all occurrences of string Kint minLength(string str, int N, string K, int M){ // Initialize stack of characters stack<char> stackOfChar; for (int i = 0; i < N; i++) { // Push character into the stack stackOfChar.push(str[i]); // If stack size >= K.size() if (stackOfChar.size() >= M) { // Create empty string to // store characters of stack string l = ""; // Traverse the string K in reverse for (int j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K[j] != stackOfChar.top()) { // Push the elements // back into the stack int f = 0; while (f != l.size()) { stackOfChar.push(l[f]); f++; } break; } // Store the string else { l = stackOfChar.top() + l; // Remove top element stackOfChar.pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.size();} // Driver Codeint main(){ string S1 = "fffoxoxoxfxo"; string S2 = "fox"; int N = S1.length(); int M = S2.length(); // Function Call cout << minLength(S1, N, S2, M); return 0;}
// Java program for the above approachimport java.util.*;class GFG{ // Function to find the minimum length// to which String str can be reduced to// by removing all occurrences of String Kstatic int minLength(String str, int N, String K, int M){ // Initialize stack of characters Stack<Character> stackOfChar = new Stack<Character>(); for (int i = 0; i < N; i++) { // Push character into the stack stackOfChar.add(str.charAt(i)); // If stack size >= K.size() if (stackOfChar.size() >= M) { // Create empty String to // store characters of stack String l = ""; // Traverse the String K in reverse for (int j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K.charAt(j) != stackOfChar.peek()) { // Push the elements // back into the stack int f = 0; while (f != l.length()) { stackOfChar.add(l.charAt(f)); f++; } break; } // Store the String else { l = stackOfChar.peek() + l; // Remove top element stackOfChar.pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.size();} // Driver Codepublic static void main(String[] args){ String S1 = "fffoxoxoxfxo"; String S2 = "fox"; int N = S1.length(); int M = S2.length(); // Function Call System.out.print(minLength(S1, N, S2, M));}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to find the minimum length# to which string str can be reduced to# by removing all occurrences of string Kdef minLength(Str, N, K, M) : # Initialize stack of characters stackOfChar = [] for i in range(N) : # Push character into the stack stackOfChar.append(Str[i]) # If stack size >= K.size() if (len(stackOfChar) >= M) : # Create empty string to # store characters of stack l = "" # Traverse the string K in reverse for j in range(M - 1, -1, -1) : # If any of the characters # differ, it means that K # is not present in the stack if (K[j] != stackOfChar[-1]) : # Push the elements # back into the stack f = 0 while (f != len(l)) : stackOfChar.append(l[f]) f += 1 break # Store the string else : l = stackOfChar[-1] + l # Remove top element stackOfChar.pop() # Size of stack gives the # minimized length of str return len(stackOfChar) # Driver code S1 = "fffoxoxoxfxo"S2 = "fox" N = len(S1)M = len(S2) # Function Callprint(minLength(S1, N, S2, M)) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the minimum length// to which String str can be reduced to// by removing all occurrences of String Kstatic int minLength(String str, int N, String K, int M){ // Initialize stack of characters Stack<char> stackOfChar = new Stack<char>(); for (int i = 0; i < N; i++) { // Push character into the stack stackOfChar.Push(str[i]); // If stack size >= K.Count if (stackOfChar.Count >= M) { // Create empty String to // store characters of stack String l = ""; // Traverse the String K in reverse for (int j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K[j] != stackOfChar.Peek()) { // Push the elements // back into the stack int f = 0; while (f != l.Length) { stackOfChar.Push(l[f]); f++; } break; } // Store the String else { l = stackOfChar.Peek() + l; // Remove top element stackOfChar.Pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.Count;} // Driver Codepublic static void Main(String[] args){ String S1 = "fffoxoxoxfxo"; String S2 = "fox"; int N = S1.Length; int M = S2.Length; // Function Call Console.Write(minLength(S1, N, S2, M));}} // This code is contributed by 29AjayKumar
<script> // JavaScript program for the above approach // Function to find the minimum length// to which string str can be reduced to// by removing all occurrences of string Kfunction minLength(str, N, K, M){ // Initialize stack of characters var stackOfChar = []; for (var i = 0; i < N; i++) { // Push character into the stack stackOfChar.push(str[i]); // If stack size >= K.size() if (stackOfChar.length >= M) { // Create empty string to // store characters of stack var l = ""; // Traverse the string K in reverse for (var j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K[j] != stackOfChar[stackOfChar.length-1]) { // Push the elements // back into the stack var f = 0; while (f != l.length) { stackOfChar.push(l[f]); f++; } break; } // Store the string else { l = stackOfChar[stackOfChar.length-1] + l; // Remove top element stackOfChar.pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.length;} // Driver Codevar S1 = "fffoxoxoxfxo";var S2 = "fox";var N = S1.length;var M = S2.length; // Function Calldocument.write( minLength(S1, N, S2, M)); </script>
3
Time complexity: O(N*M), as we are using nested loops for traversing N*M times.Auxiliary Space: O(N), as we are using extra space for stack.
divyeshrabadiya07
29AjayKumar
rutvik_56
akshaysingh98088
rohitkumarsinghcna
cpp-stack-functions
substring
Stack
Strings
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Design a stack with operations on middle element
How to efficiently implement k stacks in a single array?
Real-time application of Data Structures
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 May, 2022"
},
{
"code": null,
"e": 278,
"s": 54,
"text": "Given two strings S1 and S2 of length N and M respectively, consisting of lowercase letters, the task is to find the minimum length to which S1 can be reduced by removing all occurrences of the string S2 from the string S1."
},
{
"code": null,
"e": 288,
"s": 278,
"text": "Examples:"
},
{
"code": null,
"e": 652,
"s": 288,
"text": "Input: S1 =”fffoxoxoxfxo”, S2 = “fox”;Output: 3Explanation:By removing “fox” starting from index 2, the string modifies to “ffoxoxfxo”.By removing “fox” starting from index 1, the string modifies to “foxfxo”.By removing “fox” starting from index 0, the string modifies to “fxo”.Therefore, the minimum length of string S1 after removing all occurrences of S2 is 3."
},
{
"code": null,
"e": 691,
"s": 652,
"text": "Input: S1 =”abcd”, S2 = “pqr”Output: 4"
},
{
"code": null,
"e": 815,
"s": 691,
"text": "Approach: The idea to solve this problem is to use Stack Data Structure. Follow the steps below to solve the given problem:"
},
{
"code": null,
"e": 882,
"s": 815,
"text": "Initialize a stack to store the characters of the string S1 in it."
},
{
"code": null,
"e": 1154,
"s": 882,
"text": "Traverse the given string S1 and perform the following operations:Push the current character in the stack.If the size of the stack is at least M, then check if the top M characters of the stack form the string S2 or not. If found to be true, then remove those characters."
},
{
"code": null,
"e": 1195,
"s": 1154,
"text": "Push the current character in the stack."
},
{
"code": null,
"e": 1361,
"s": 1195,
"text": "If the size of the stack is at least M, then check if the top M characters of the stack form the string S2 or not. If found to be true, then remove those characters."
},
{
"code": null,
"e": 1459,
"s": 1361,
"text": "After completing the above steps, the remaining size of the stack is the required minimum length."
},
{
"code": null,
"e": 1510,
"s": 1459,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1514,
"s": 1510,
"text": "C++"
},
{
"code": null,
"e": 1519,
"s": 1514,
"text": "Java"
},
{
"code": null,
"e": 1527,
"s": 1519,
"text": "Python3"
},
{
"code": null,
"e": 1530,
"s": 1527,
"text": "C#"
},
{
"code": null,
"e": 1541,
"s": 1530,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h> using namespace std; // Function to find the minimum length// to which string str can be reduced to// by removing all occurrences of string Kint minLength(string str, int N, string K, int M){ // Initialize stack of characters stack<char> stackOfChar; for (int i = 0; i < N; i++) { // Push character into the stack stackOfChar.push(str[i]); // If stack size >= K.size() if (stackOfChar.size() >= M) { // Create empty string to // store characters of stack string l = \"\"; // Traverse the string K in reverse for (int j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K[j] != stackOfChar.top()) { // Push the elements // back into the stack int f = 0; while (f != l.size()) { stackOfChar.push(l[f]); f++; } break; } // Store the string else { l = stackOfChar.top() + l; // Remove top element stackOfChar.pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.size();} // Driver Codeint main(){ string S1 = \"fffoxoxoxfxo\"; string S2 = \"fox\"; int N = S1.length(); int M = S2.length(); // Function Call cout << minLength(S1, N, S2, M); return 0;}",
"e": 3275,
"s": 1541,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the minimum length// to which String str can be reduced to// by removing all occurrences of String Kstatic int minLength(String str, int N, String K, int M){ // Initialize stack of characters Stack<Character> stackOfChar = new Stack<Character>(); for (int i = 0; i < N; i++) { // Push character into the stack stackOfChar.add(str.charAt(i)); // If stack size >= K.size() if (stackOfChar.size() >= M) { // Create empty String to // store characters of stack String l = \"\"; // Traverse the String K in reverse for (int j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K.charAt(j) != stackOfChar.peek()) { // Push the elements // back into the stack int f = 0; while (f != l.length()) { stackOfChar.add(l.charAt(f)); f++; } break; } // Store the String else { l = stackOfChar.peek() + l; // Remove top element stackOfChar.pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.size();} // Driver Codepublic static void main(String[] args){ String S1 = \"fffoxoxoxfxo\"; String S2 = \"fox\"; int N = S1.length(); int M = S2.length(); // Function Call System.out.print(minLength(S1, N, S2, M));}} // This code is contributed by 29AjayKumar",
"e": 5191,
"s": 3275,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the minimum length# to which string str can be reduced to# by removing all occurrences of string Kdef minLength(Str, N, K, M) : # Initialize stack of characters stackOfChar = [] for i in range(N) : # Push character into the stack stackOfChar.append(Str[i]) # If stack size >= K.size() if (len(stackOfChar) >= M) : # Create empty string to # store characters of stack l = \"\" # Traverse the string K in reverse for j in range(M - 1, -1, -1) : # If any of the characters # differ, it means that K # is not present in the stack if (K[j] != stackOfChar[-1]) : # Push the elements # back into the stack f = 0 while (f != len(l)) : stackOfChar.append(l[f]) f += 1 break # Store the string else : l = stackOfChar[-1] + l # Remove top element stackOfChar.pop() # Size of stack gives the # minimized length of str return len(stackOfChar) # Driver code S1 = \"fffoxoxoxfxo\"S2 = \"fox\" N = len(S1)M = len(S2) # Function Callprint(minLength(S1, N, S2, M)) # This code is contributed by divyeshrabadiya07",
"e": 6641,
"s": 5191,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the minimum length// to which String str can be reduced to// by removing all occurrences of String Kstatic int minLength(String str, int N, String K, int M){ // Initialize stack of characters Stack<char> stackOfChar = new Stack<char>(); for (int i = 0; i < N; i++) { // Push character into the stack stackOfChar.Push(str[i]); // If stack size >= K.Count if (stackOfChar.Count >= M) { // Create empty String to // store characters of stack String l = \"\"; // Traverse the String K in reverse for (int j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K[j] != stackOfChar.Peek()) { // Push the elements // back into the stack int f = 0; while (f != l.Length) { stackOfChar.Push(l[f]); f++; } break; } // Store the String else { l = stackOfChar.Peek() + l; // Remove top element stackOfChar.Pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.Count;} // Driver Codepublic static void Main(String[] args){ String S1 = \"fffoxoxoxfxo\"; String S2 = \"fox\"; int N = S1.Length; int M = S2.Length; // Function Call Console.Write(minLength(S1, N, S2, M));}} // This code is contributed by 29AjayKumar",
"e": 8539,
"s": 6641,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the minimum length// to which string str can be reduced to// by removing all occurrences of string Kfunction minLength(str, N, K, M){ // Initialize stack of characters var stackOfChar = []; for (var i = 0; i < N; i++) { // Push character into the stack stackOfChar.push(str[i]); // If stack size >= K.size() if (stackOfChar.length >= M) { // Create empty string to // store characters of stack var l = \"\"; // Traverse the string K in reverse for (var j = M - 1; j >= 0; j--) { // If any of the characters // differ, it means that K // is not present in the stack if (K[j] != stackOfChar[stackOfChar.length-1]) { // Push the elements // back into the stack var f = 0; while (f != l.length) { stackOfChar.push(l[f]); f++; } break; } // Store the string else { l = stackOfChar[stackOfChar.length-1] + l; // Remove top element stackOfChar.pop(); } } } } // Size of stack gives the // minimized length of str return stackOfChar.length;} // Driver Codevar S1 = \"fffoxoxoxfxo\";var S2 = \"fox\";var N = S1.length;var M = S2.length; // Function Calldocument.write( minLength(S1, N, S2, M)); </script>",
"e": 10199,
"s": 8539,
"text": null
},
{
"code": null,
"e": 10201,
"s": 10199,
"text": "3"
},
{
"code": null,
"e": 10344,
"s": 10203,
"text": "Time complexity: O(N*M), as we are using nested loops for traversing N*M times.Auxiliary Space: O(N), as we are using extra space for stack."
},
{
"code": null,
"e": 10362,
"s": 10344,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 10374,
"s": 10362,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10384,
"s": 10374,
"text": "rutvik_56"
},
{
"code": null,
"e": 10401,
"s": 10384,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 10420,
"s": 10401,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 10440,
"s": 10420,
"text": "cpp-stack-functions"
},
{
"code": null,
"e": 10450,
"s": 10440,
"text": "substring"
},
{
"code": null,
"e": 10456,
"s": 10450,
"text": "Stack"
},
{
"code": null,
"e": 10464,
"s": 10456,
"text": "Strings"
},
{
"code": null,
"e": 10472,
"s": 10464,
"text": "Strings"
},
{
"code": null,
"e": 10478,
"s": 10472,
"text": "Stack"
},
{
"code": null,
"e": 10576,
"s": 10478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10608,
"s": 10576,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 10672,
"s": 10608,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 10721,
"s": 10672,
"text": "Design a stack with operations on middle element"
},
{
"code": null,
"e": 10778,
"s": 10721,
"text": "How to efficiently implement k stacks in a single array?"
},
{
"code": null,
"e": 10819,
"s": 10778,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 10865,
"s": 10819,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10890,
"s": 10865,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10950,
"s": 10890,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 10965,
"s": 10950,
"text": "C++ Data Types"
}
] |
Java Program for Find largest prime factor of a number | 17 Feb, 2018
Given a positive integer \’n\'( 1 <= n <= 1015). Find the largest prime factor of a number.
Input: 6
Output: 3
Explanation
Prime factor of 6 are- 2, 3
Largest of them is \'3\'
Input: 15
Output: 5
Java
// Java Program to find largest// prime factor of numberimport java.io.*;import java.util.*; class GFG { // function to find largest prime factorstatic long maxPrimeFactors( long n){ // Initialize the maximum prime // factor variable with the // lowest one long maxPrime = -1; // Print the number of 2s // that divide n while (n % 2 == 0) { maxPrime = 2; // equivalent to n /= 2 n >>= 1; } // n must be odd at this point, // thus skip the even numbers // and iterate only for odd // integers for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { maxPrime = i; n = n / i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) maxPrime = n; return maxPrime;} // Driver codepublic static void main(String[] args){ Long n = 15l; System.out.println(maxPrimeFactors(n)); n = 25698751364526l; System.out.println(maxPrimeFactors(n));}} // This code is contributed by Gitanjali
5
328513
Time complexity: Auxiliary space:
Please refer complete article on Find largest prime factor of a number for more details!
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Feb, 2018"
},
{
"code": null,
"e": 144,
"s": 52,
"text": "Given a positive integer \\’n\\'( 1 <= n <= 1015). Find the largest prime factor of a number."
},
{
"code": null,
"e": 250,
"s": 144,
"text": "Input: 6\nOutput: 3\nExplanation\nPrime factor of 6 are- 2, 3\nLargest of them is \\'3\\'\n\nInput: 15\nOutput: 5\n"
},
{
"code": null,
"e": 255,
"s": 250,
"text": "Java"
},
{
"code": "// Java Program to find largest// prime factor of numberimport java.io.*;import java.util.*; class GFG { // function to find largest prime factorstatic long maxPrimeFactors( long n){ // Initialize the maximum prime // factor variable with the // lowest one long maxPrime = -1; // Print the number of 2s // that divide n while (n % 2 == 0) { maxPrime = 2; // equivalent to n /= 2 n >>= 1; } // n must be odd at this point, // thus skip the even numbers // and iterate only for odd // integers for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { maxPrime = i; n = n / i; } } // This condition is to handle // the case when n is a prime // number greater than 2 if (n > 2) maxPrime = n; return maxPrime;} // Driver codepublic static void main(String[] args){ Long n = 15l; System.out.println(maxPrimeFactors(n)); n = 25698751364526l; System.out.println(maxPrimeFactors(n));}} // This code is contributed by Gitanjali",
"e": 1345,
"s": 255,
"text": null
},
{
"code": null,
"e": 1355,
"s": 1345,
"text": "5\n328513\n"
},
{
"code": null,
"e": 1390,
"s": 1355,
"text": "Time complexity: Auxiliary space: "
},
{
"code": null,
"e": 1479,
"s": 1390,
"text": "Please refer complete article on Find largest prime factor of a number for more details!"
},
{
"code": null,
"e": 1493,
"s": 1479,
"text": "Java Programs"
}
] |
Remove Last character from String in Linux | 29 Jun, 2021
In this article, we will discuss how to remove the last character from the string in Linux.
In Linux, there are various commands and techniques present by which you can do this task in an easier way if you have some basic knowledge about the commands in Linux. Here, you will see the different commands by which you can remove the last character of a string in Linux.
Method 1: Using the cut command
The cut command is used to extract some specific section from the string or from a file and prints the result to standard output. You can also use this command for removing the characters from a string. There are two ways to remove the last character from the string using the cut command. These are as follows:
When you know the length of a string
Syntax:
cut <character> <range>
Example:
$ echo "linux" | cut -c 1-4
This method works when you know the length of the given string. It first takes the string and pipes it with the cut command. You have to provide a range from the start of the string to the 2nd last character of the string. It extracts the characters from that range, leaving the last character, and prints the result to standard output.
Output:
Another way is to use the complement option of the cut command.
Syntax:
cut --complement <complement pattern>
Example:
$ echo "linux" | cut --complement -c 5
In this method, you have to use the complement option present in the cut command. The complement command can work with bytes, characters, and fields. Here we are using character -c. So here we have provided (length of string)-1 after the -c command, which will cut the last character and print the result, leaving the last character of the string.
Output:
When you don’t know the length of the string
Syntax:
$ echo "linux" | rev | cut -c2- | rev
In this method, you have to use the rev command. The rev command is used to reverse the line of string characterwise. Here, the rev command will reverse the string, and then the -c option will remove the first character. After this, the rev command will reverse the string again and you will get your output.
Output:
Method 2: Using the sed command
The sed command stands for stream editor. It is a powerful tool that is used for manipulating and editing streams of text. It also supports regular expressions which can be used for pattern matching. You can also use the sed command to remove the characters from the strings.
$ echo "linux" | sed 's/.$//'
In this method, the string is piped with the sed command and the regular expression is used to remove the last character where the (.) will match the single character and the $ matches any character present at the end of the string.
Output:
Method 3: Using awk
The awk is a scripting language that is used for pattern matching and text processing. Mostly it is used as a reporting and analyzing tool. So now you will see how we can use awk to remove the last character from the given string.
$ echo "linux" | awk '{ print substr( $0, 1, length($0)-1 ) }'
This method works as our given string pipes with the awk and then in awk, the string is processed. Here the length($0)-1 means removing the last character by deducting ‘1’ from the string’s total length. Through this process, the command will print the string from the 1st character up to the 2nd character.
Output:
Linux-text-processing-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 121,
"s": 28,
"text": "In this article, we will discuss how to remove the last character from the string in Linux. "
},
{
"code": null,
"e": 398,
"s": 121,
"text": "In Linux, there are various commands and techniques present by which you can do this task in an easier way if you have some basic knowledge about the commands in Linux. Here, you will see the different commands by which you can remove the last character of a string in Linux. "
},
{
"code": null,
"e": 430,
"s": 398,
"text": "Method 1: Using the cut command"
},
{
"code": null,
"e": 742,
"s": 430,
"text": "The cut command is used to extract some specific section from the string or from a file and prints the result to standard output. You can also use this command for removing the characters from a string. There are two ways to remove the last character from the string using the cut command. These are as follows:"
},
{
"code": null,
"e": 779,
"s": 742,
"text": "When you know the length of a string"
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Syntax:"
},
{
"code": null,
"e": 812,
"s": 787,
"text": "cut <character> <range> "
},
{
"code": null,
"e": 821,
"s": 812,
"text": "Example:"
},
{
"code": null,
"e": 849,
"s": 821,
"text": "$ echo \"linux\" | cut -c 1-4"
},
{
"code": null,
"e": 1186,
"s": 849,
"text": "This method works when you know the length of the given string. It first takes the string and pipes it with the cut command. You have to provide a range from the start of the string to the 2nd last character of the string. It extracts the characters from that range, leaving the last character, and prints the result to standard output."
},
{
"code": null,
"e": 1195,
"s": 1186,
"text": "Output: "
},
{
"code": null,
"e": 1259,
"s": 1195,
"text": "Another way is to use the complement option of the cut command."
},
{
"code": null,
"e": 1267,
"s": 1259,
"text": "Syntax:"
},
{
"code": null,
"e": 1305,
"s": 1267,
"text": "cut --complement <complement pattern>"
},
{
"code": null,
"e": 1314,
"s": 1305,
"text": "Example:"
},
{
"code": null,
"e": 1353,
"s": 1314,
"text": "$ echo \"linux\" | cut --complement -c 5"
},
{
"code": null,
"e": 1701,
"s": 1353,
"text": "In this method, you have to use the complement option present in the cut command. The complement command can work with bytes, characters, and fields. Here we are using character -c. So here we have provided (length of string)-1 after the -c command, which will cut the last character and print the result, leaving the last character of the string."
},
{
"code": null,
"e": 1709,
"s": 1701,
"text": "Output:"
},
{
"code": null,
"e": 1754,
"s": 1709,
"text": "When you don’t know the length of the string"
},
{
"code": null,
"e": 1762,
"s": 1754,
"text": "Syntax:"
},
{
"code": null,
"e": 1800,
"s": 1762,
"text": "$ echo \"linux\" | rev | cut -c2- | rev"
},
{
"code": null,
"e": 2109,
"s": 1800,
"text": "In this method, you have to use the rev command. The rev command is used to reverse the line of string characterwise. Here, the rev command will reverse the string, and then the -c option will remove the first character. After this, the rev command will reverse the string again and you will get your output."
},
{
"code": null,
"e": 2117,
"s": 2109,
"text": "Output:"
},
{
"code": null,
"e": 2149,
"s": 2117,
"text": "Method 2: Using the sed command"
},
{
"code": null,
"e": 2425,
"s": 2149,
"text": "The sed command stands for stream editor. It is a powerful tool that is used for manipulating and editing streams of text. It also supports regular expressions which can be used for pattern matching. You can also use the sed command to remove the characters from the strings."
},
{
"code": null,
"e": 2455,
"s": 2425,
"text": "$ echo \"linux\" | sed 's/.$//'"
},
{
"code": null,
"e": 2688,
"s": 2455,
"text": "In this method, the string is piped with the sed command and the regular expression is used to remove the last character where the (.) will match the single character and the $ matches any character present at the end of the string."
},
{
"code": null,
"e": 2696,
"s": 2688,
"text": "Output:"
},
{
"code": null,
"e": 2717,
"s": 2696,
"text": "Method 3: Using awk "
},
{
"code": null,
"e": 2948,
"s": 2717,
"text": "The awk is a scripting language that is used for pattern matching and text processing. Mostly it is used as a reporting and analyzing tool. So now you will see how we can use awk to remove the last character from the given string."
},
{
"code": null,
"e": 3011,
"s": 2948,
"text": "$ echo \"linux\" | awk '{ print substr( $0, 1, length($0)-1 ) }'"
},
{
"code": null,
"e": 3320,
"s": 3011,
"text": "This method works as our given string pipes with the awk and then in awk, the string is processed. Here the length($0)-1 means removing the last character by deducting ‘1’ from the string’s total length. Through this process, the command will print the string from the 1st character up to the 2nd character. "
},
{
"code": null,
"e": 3328,
"s": 3320,
"text": "Output:"
},
{
"code": null,
"e": 3359,
"s": 3328,
"text": "Linux-text-processing-commands"
},
{
"code": null,
"e": 3366,
"s": 3359,
"text": "Picked"
},
{
"code": null,
"e": 3377,
"s": 3366,
"text": "Linux-Unix"
}
] |
Java.lang.String class in Java | Set 2 | 04 Apr, 2022
public int codePointAt(int index) – It takes as parameter a index which must be from 0 to length() – 1. ad returns a character unicode point of a index.public int codePointBefore(int index) – It takes as parameter a index which must be from 0 to length() – 1. and returns a unicode point of a character just before the index .public int codePointCount(int start_index, int end_index) – It takes as parameter start_index and end_index and returns the count of Unicode code points between the range.public CharSequence subSequence(int start_index, int end_index) – This method returns CharSequence which is a subsequence of the String on which this method is invoked. Note: It behaves similarly to subString(int start_index, int end_index), but subString() returns String while subSequence returns CharSequence.public boolean contains(CharSequence char_seq) – It returns true if the given CharSquence is present in the String on which its invoked.public boolean contentEquals(CharSequence char_seq) – It returns true only if the given CharSequence exactly matches the String on which its invokedpublic boolean endsWith(String suf) – It takes in parameter a String suffix and return true if the String has same suffix.public boolean startsWith(String pre) – It takes in parameter a String prefix and returns true if the String has a same prefixpublic void getChars(int start, int end, char[] destination, int destination_start) : It takes in four parameters, start and end refers to the range which is to copied to the character array, destination is the character array to be copied to, and destination_start is the starting location of the destination array.public char[] toCharArray() – It converts the entire String to the character array. Note :- getChars provide more flexibility when, a range of characters is to be copied to an existing array or a new array while toCharArray converts the entire string to a new character array.public int hashCode() – It returns hashcode of the given String. There is predefined formula to compute the hashcode of the String:
public int codePointAt(int index) – It takes as parameter a index which must be from 0 to length() – 1. ad returns a character unicode point of a index.
public int codePointBefore(int index) – It takes as parameter a index which must be from 0 to length() – 1. and returns a unicode point of a character just before the index .
public int codePointCount(int start_index, int end_index) – It takes as parameter start_index and end_index and returns the count of Unicode code points between the range.
public CharSequence subSequence(int start_index, int end_index) – This method returns CharSequence which is a subsequence of the String on which this method is invoked. Note: It behaves similarly to subString(int start_index, int end_index), but subString() returns String while subSequence returns CharSequence.
public boolean contains(CharSequence char_seq) – It returns true if the given CharSquence is present in the String on which its invoked.
public boolean contentEquals(CharSequence char_seq) – It returns true only if the given CharSequence exactly matches the String on which its invoked
public boolean endsWith(String suf) – It takes in parameter a String suffix and return true if the String has same suffix.
public boolean startsWith(String pre) – It takes in parameter a String prefix and returns true if the String has a same prefix
public void getChars(int start, int end, char[] destination, int destination_start) : It takes in four parameters, start and end refers to the range which is to copied to the character array, destination is the character array to be copied to, and destination_start is the starting location of the destination array.
public char[] toCharArray() – It converts the entire String to the character array. Note :- getChars provide more flexibility when, a range of characters is to be copied to an existing array or a new array while toCharArray converts the entire string to a new character array.
public int hashCode() – It returns hashcode of the given String. There is predefined formula to compute the hashcode of the String:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
where,
n - is the length of the String
i - is the ith character of the string
public String intern() – It returns the canonical form of the String object on which it is invoked. ” When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. ” – Java String Documentation.public boolean isEmpty() – It returns true if the length of the String is 0.public static String format(String f, Object... arguments) – Returns the formatted String according to the format specifier f, the arguments should exactly equal to the number of format specifier used . Variation: public static String format(Locale l, String f, Object... arguments)– Returns the formatted String as per Locale used.public boolean matches(String reg_exp) – It returns true if the string matches the regular expression( reg_exp).public boolean regionMatches(int start_OString, String another, int start_AString, int no_of_char) – It returns true if the region of original string starting with index start_OString matches with the region of another string starting with string_AString, and no_of_char refers to the number of character to be compared. Variation : public boolean regionMatches(boolean ignore_case, int start_OString, String another, int start_AString, int no_of_char) – This variation of a method provide flexibility when we want to ignore the case while comparing substring. If the first parameter i.e. ignore_case is true it neglects the case and compares but if it is false it behaves similarly as the first version of the method without ignore_casepublic String[] split(String reg_exp) – It splits the string around the regular expression and returns a String array. Variation : public String[] split(String reg_exp, int limit) – It splits the string around the regular expression and limit refers to the number of times the reg_exp is applied and it is the length of the resulting array and reg_exp is n is applied only length – 1 times.public static String join(CharSequence de_limiter, CharSequence... elements) – It returns a string which contains all the elements joins by the de_limiter. Variation: public static String join(CharSequence de_limiter, Iterable elements) – It performs the same function but the second parameter is Iterable which makes it flexible to work with different collection classes.public String replaceAll(String reg_exp, String replacement) – It replaces all the Substring of the original string that matches the reg_exp with replacement and returns the modified String.public String replaceFirst(String reg_exp, String replacement) – It replaces the first occurrence of the reg-exp in the original string with the replacement and returns the modified String. Note :- replaceAll and replaceFirst doesn’t changes the original String rather it creates a new string with modification.
public String intern() – It returns the canonical form of the String object on which it is invoked. ” When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. ” – Java String Documentation.
public boolean isEmpty() – It returns true if the length of the String is 0.
public static String format(String f, Object... arguments) – Returns the formatted String according to the format specifier f, the arguments should exactly equal to the number of format specifier used . Variation: public static String format(Locale l, String f, Object... arguments)– Returns the formatted String as per Locale used.
public boolean matches(String reg_exp) – It returns true if the string matches the regular expression( reg_exp).
public boolean regionMatches(int start_OString, String another, int start_AString, int no_of_char) – It returns true if the region of original string starting with index start_OString matches with the region of another string starting with string_AString, and no_of_char refers to the number of character to be compared. Variation : public boolean regionMatches(boolean ignore_case, int start_OString, String another, int start_AString, int no_of_char) – This variation of a method provide flexibility when we want to ignore the case while comparing substring. If the first parameter i.e. ignore_case is true it neglects the case and compares but if it is false it behaves similarly as the first version of the method without ignore_case
public String[] split(String reg_exp) – It splits the string around the regular expression and returns a String array. Variation : public String[] split(String reg_exp, int limit) – It splits the string around the regular expression and limit refers to the number of times the reg_exp is applied and it is the length of the resulting array and reg_exp is n is applied only length – 1 times.
public static String join(CharSequence de_limiter, CharSequence... elements) – It returns a string which contains all the elements joins by the de_limiter. Variation: public static String join(CharSequence de_limiter, Iterable elements) – It performs the same function but the second parameter is Iterable which makes it flexible to work with different collection classes.
public String replaceAll(String reg_exp, String replacement) – It replaces all the Substring of the original string that matches the reg_exp with replacement and returns the modified String.
public String replaceFirst(String reg_exp, String replacement) – It replaces the first occurrence of the reg-exp in the original string with the replacement and returns the modified String. Note :- replaceAll and replaceFirst doesn’t changes the original String rather it creates a new string with modification.
For more methods on String refer to String class in java Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html This article is contributed by Sumit Ghosh. 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.
bhaktiramnan
ManasChhabra2
shubham_singh
nidhi_biet
sooda367
khushboogoyal499
hiteshkhutade11
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 2117,
"s": 52,
"text": "public int codePointAt(int index) – It takes as parameter a index which must be from 0 to length() – 1. ad returns a character unicode point of a index.public int codePointBefore(int index) – It takes as parameter a index which must be from 0 to length() – 1. and returns a unicode point of a character just before the index .public int codePointCount(int start_index, int end_index) – It takes as parameter start_index and end_index and returns the count of Unicode code points between the range.public CharSequence subSequence(int start_index, int end_index) – This method returns CharSequence which is a subsequence of the String on which this method is invoked. Note: It behaves similarly to subString(int start_index, int end_index), but subString() returns String while subSequence returns CharSequence.public boolean contains(CharSequence char_seq) – It returns true if the given CharSquence is present in the String on which its invoked.public boolean contentEquals(CharSequence char_seq) – It returns true only if the given CharSequence exactly matches the String on which its invokedpublic boolean endsWith(String suf) – It takes in parameter a String suffix and return true if the String has same suffix.public boolean startsWith(String pre) – It takes in parameter a String prefix and returns true if the String has a same prefixpublic void getChars(int start, int end, char[] destination, int destination_start) : It takes in four parameters, start and end refers to the range which is to copied to the character array, destination is the character array to be copied to, and destination_start is the starting location of the destination array.public char[] toCharArray() – It converts the entire String to the character array. Note :- getChars provide more flexibility when, a range of characters is to be copied to an existing array or a new array while toCharArray converts the entire string to a new character array.public int hashCode() – It returns hashcode of the given String. There is predefined formula to compute the hashcode of the String:"
},
{
"code": null,
"e": 2270,
"s": 2117,
"text": "public int codePointAt(int index) – It takes as parameter a index which must be from 0 to length() – 1. ad returns a character unicode point of a index."
},
{
"code": null,
"e": 2445,
"s": 2270,
"text": "public int codePointBefore(int index) – It takes as parameter a index which must be from 0 to length() – 1. and returns a unicode point of a character just before the index ."
},
{
"code": null,
"e": 2617,
"s": 2445,
"text": "public int codePointCount(int start_index, int end_index) – It takes as parameter start_index and end_index and returns the count of Unicode code points between the range."
},
{
"code": null,
"e": 2930,
"s": 2617,
"text": "public CharSequence subSequence(int start_index, int end_index) – This method returns CharSequence which is a subsequence of the String on which this method is invoked. Note: It behaves similarly to subString(int start_index, int end_index), but subString() returns String while subSequence returns CharSequence."
},
{
"code": null,
"e": 3067,
"s": 2930,
"text": "public boolean contains(CharSequence char_seq) – It returns true if the given CharSquence is present in the String on which its invoked."
},
{
"code": null,
"e": 3216,
"s": 3067,
"text": "public boolean contentEquals(CharSequence char_seq) – It returns true only if the given CharSequence exactly matches the String on which its invoked"
},
{
"code": null,
"e": 3339,
"s": 3216,
"text": "public boolean endsWith(String suf) – It takes in parameter a String suffix and return true if the String has same suffix."
},
{
"code": null,
"e": 3466,
"s": 3339,
"text": "public boolean startsWith(String pre) – It takes in parameter a String prefix and returns true if the String has a same prefix"
},
{
"code": null,
"e": 3783,
"s": 3466,
"text": "public void getChars(int start, int end, char[] destination, int destination_start) : It takes in four parameters, start and end refers to the range which is to copied to the character array, destination is the character array to be copied to, and destination_start is the starting location of the destination array."
},
{
"code": null,
"e": 4060,
"s": 3783,
"text": "public char[] toCharArray() – It converts the entire String to the character array. Note :- getChars provide more flexibility when, a range of characters is to be copied to an existing array or a new array while toCharArray converts the entire string to a new character array."
},
{
"code": null,
"e": 4192,
"s": 4060,
"text": "public int hashCode() – It returns hashcode of the given String. There is predefined formula to compute the hashcode of the String:"
},
{
"code": null,
"e": 4315,
"s": 4192,
"text": "s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]\nwhere,\nn - is the length of the String\ni - is the ith character of the string"
},
{
"code": null,
"e": 7258,
"s": 4315,
"text": "public String intern() – It returns the canonical form of the String object on which it is invoked. ” When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. ” – Java String Documentation.public boolean isEmpty() – It returns true if the length of the String is 0.public static String format(String f, Object... arguments) – Returns the formatted String according to the format specifier f, the arguments should exactly equal to the number of format specifier used . Variation: public static String format(Locale l, String f, Object... arguments)– Returns the formatted String as per Locale used.public boolean matches(String reg_exp) – It returns true if the string matches the regular expression( reg_exp).public boolean regionMatches(int start_OString, String another, int start_AString, int no_of_char) – It returns true if the region of original string starting with index start_OString matches with the region of another string starting with string_AString, and no_of_char refers to the number of character to be compared. Variation : public boolean regionMatches(boolean ignore_case, int start_OString, String another, int start_AString, int no_of_char) – This variation of a method provide flexibility when we want to ignore the case while comparing substring. If the first parameter i.e. ignore_case is true it neglects the case and compares but if it is false it behaves similarly as the first version of the method without ignore_casepublic String[] split(String reg_exp) – It splits the string around the regular expression and returns a String array. Variation : public String[] split(String reg_exp, int limit) – It splits the string around the regular expression and limit refers to the number of times the reg_exp is applied and it is the length of the resulting array and reg_exp is n is applied only length – 1 times.public static String join(CharSequence de_limiter, CharSequence... elements) – It returns a string which contains all the elements joins by the de_limiter. Variation: public static String join(CharSequence de_limiter, Iterable elements) – It performs the same function but the second parameter is Iterable which makes it flexible to work with different collection classes.public String replaceAll(String reg_exp, String replacement) – It replaces all the Substring of the original string that matches the reg_exp with replacement and returns the modified String.public String replaceFirst(String reg_exp, String replacement) – It replaces the first occurrence of the reg-exp in the original string with the replacement and returns the modified String. Note :- replaceAll and replaceFirst doesn’t changes the original String rather it creates a new string with modification."
},
{
"code": null,
"e": 7681,
"s": 7258,
"text": "public String intern() – It returns the canonical form of the String object on which it is invoked. ” When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. ” – Java String Documentation."
},
{
"code": null,
"e": 7758,
"s": 7681,
"text": "public boolean isEmpty() – It returns true if the length of the String is 0."
},
{
"code": null,
"e": 8091,
"s": 7758,
"text": "public static String format(String f, Object... arguments) – Returns the formatted String according to the format specifier f, the arguments should exactly equal to the number of format specifier used . Variation: public static String format(Locale l, String f, Object... arguments)– Returns the formatted String as per Locale used."
},
{
"code": null,
"e": 8204,
"s": 8091,
"text": "public boolean matches(String reg_exp) – It returns true if the string matches the regular expression( reg_exp)."
},
{
"code": null,
"e": 8942,
"s": 8204,
"text": "public boolean regionMatches(int start_OString, String another, int start_AString, int no_of_char) – It returns true if the region of original string starting with index start_OString matches with the region of another string starting with string_AString, and no_of_char refers to the number of character to be compared. Variation : public boolean regionMatches(boolean ignore_case, int start_OString, String another, int start_AString, int no_of_char) – This variation of a method provide flexibility when we want to ignore the case while comparing substring. If the first parameter i.e. ignore_case is true it neglects the case and compares but if it is false it behaves similarly as the first version of the method without ignore_case"
},
{
"code": null,
"e": 9333,
"s": 8942,
"text": "public String[] split(String reg_exp) – It splits the string around the regular expression and returns a String array. Variation : public String[] split(String reg_exp, int limit) – It splits the string around the regular expression and limit refers to the number of times the reg_exp is applied and it is the length of the resulting array and reg_exp is n is applied only length – 1 times."
},
{
"code": null,
"e": 9706,
"s": 9333,
"text": "public static String join(CharSequence de_limiter, CharSequence... elements) – It returns a string which contains all the elements joins by the de_limiter. Variation: public static String join(CharSequence de_limiter, Iterable elements) – It performs the same function but the second parameter is Iterable which makes it flexible to work with different collection classes."
},
{
"code": null,
"e": 9897,
"s": 9706,
"text": "public String replaceAll(String reg_exp, String replacement) – It replaces all the Substring of the original string that matches the reg_exp with replacement and returns the modified String."
},
{
"code": null,
"e": 10209,
"s": 9897,
"text": "public String replaceFirst(String reg_exp, String replacement) – It replaces the first occurrence of the reg-exp in the original string with the replacement and returns the modified String. Note :- replaceAll and replaceFirst doesn’t changes the original String rather it creates a new string with modification."
},
{
"code": null,
"e": 10761,
"s": 10209,
"text": "For more methods on String refer to String class in java Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html This article is contributed by Sumit Ghosh. 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": 10774,
"s": 10761,
"text": "bhaktiramnan"
},
{
"code": null,
"e": 10788,
"s": 10774,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 10802,
"s": 10788,
"text": "shubham_singh"
},
{
"code": null,
"e": 10813,
"s": 10802,
"text": "nidhi_biet"
},
{
"code": null,
"e": 10822,
"s": 10813,
"text": "sooda367"
},
{
"code": null,
"e": 10839,
"s": 10822,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 10855,
"s": 10839,
"text": "hiteshkhutade11"
},
{
"code": null,
"e": 10873,
"s": 10855,
"text": "Java-lang package"
},
{
"code": null,
"e": 10886,
"s": 10873,
"text": "Java-Strings"
},
{
"code": null,
"e": 10891,
"s": 10886,
"text": "Java"
},
{
"code": null,
"e": 10904,
"s": 10891,
"text": "Java-Strings"
},
{
"code": null,
"e": 10909,
"s": 10904,
"text": "Java"
}
] |
HTML vs XML | 25 May, 2022
HTML: HTML (Hyper Text Markup Language) is used to create web pages and web applications. It is a markup language. By HTML we can create our own static page. It is used for displaying the data not to transport the data. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages. This language is used to annotate (make notes for the computer) text so that a machine can understand it and manipulate text accordingly.
Example:
html
<!DOCTYPE html><html><head> <title>GeeksforGeeks</title></head><body> <h1>GeeksforGeeks</h1> <p>A Computer Science portal for geeks</p> </body></html>
Output:
XML: XML (eXtensible Markup Language) is also used to create web pages and web applications. It is dynamic because it is used to transport the data not for displaying the data. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.Example:
html
<?xml version = "1.0"?><contactinfo> <address category = "college"> <name>G4G</name> <College>Geeksforgeeks</College> <mobile>2345456767</mobile> </address></contactinfo>
Output:
G4G
Geeksforgeeks
2345456767
Difference between HTML and XML: There are many differences between HTML and XML. These important differences are given below:
XML document size is relatively large as the approach of formatting
and the codes both are lengthy.
Additional application is not required for parsing of
JavaScript code into the HTML document.
DOM(Document Object Model) is required for parsing JavaScript
codes and mapping of text.
anshitaagarwal
shalinipriya1011
siddharthredhu01
HTML and XML
Difference Between
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Differences between IPv4 and IPv6
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?
REST API (Introduction)
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 May, 2022"
},
{
"code": null,
"e": 626,
"s": 52,
"text": "HTML: HTML (Hyper Text Markup Language) is used to create web pages and web applications. It is a markup language. By HTML we can create our own static page. It is used for displaying the data not to transport the data. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages. This language is used to annotate (make notes for the computer) text so that a machine can understand it and manipulate text accordingly. "
},
{
"code": null,
"e": 636,
"s": 626,
"text": "Example: "
},
{
"code": null,
"e": 641,
"s": 636,
"text": "html"
},
{
"code": "<!DOCTYPE html><html><head> <title>GeeksforGeeks</title></head><body> <h1>GeeksforGeeks</h1> <p>A Computer Science portal for geeks</p> </body></html>",
"e": 805,
"s": 641,
"text": null
},
{
"code": null,
"e": 815,
"s": 805,
"text": "Output: "
},
{
"code": null,
"e": 1349,
"s": 815,
"text": "XML: XML (eXtensible Markup Language) is also used to create web pages and web applications. It is dynamic because it is used to transport the data not for displaying the data. The design goals of XML focus on simplicity, generality, and usability across the Internet. It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.Example: "
},
{
"code": null,
"e": 1354,
"s": 1349,
"text": "html"
},
{
"code": "<?xml version = \"1.0\"?><contactinfo> <address category = \"college\"> <name>G4G</name> <College>Geeksforgeeks</College> <mobile>2345456767</mobile> </address></contactinfo>",
"e": 1552,
"s": 1354,
"text": null
},
{
"code": null,
"e": 1561,
"s": 1552,
"text": "Output: "
},
{
"code": null,
"e": 1590,
"s": 1561,
"text": "G4G\nGeeksforgeeks\n2345456767"
},
{
"code": null,
"e": 1718,
"s": 1590,
"text": "Difference between HTML and XML: There are many differences between HTML and XML. These important differences are given below: "
},
{
"code": null,
"e": 1786,
"s": 1718,
"text": "XML document size is relatively large as the approach of formatting"
},
{
"code": null,
"e": 1818,
"s": 1786,
"text": "and the codes both are lengthy."
},
{
"code": null,
"e": 1872,
"s": 1818,
"text": "Additional application is not required for parsing of"
},
{
"code": null,
"e": 1912,
"s": 1872,
"text": "JavaScript code into the HTML document."
},
{
"code": null,
"e": 1974,
"s": 1912,
"text": "DOM(Document Object Model) is required for parsing JavaScript"
},
{
"code": null,
"e": 2001,
"s": 1974,
"text": "codes and mapping of text."
},
{
"code": null,
"e": 2016,
"s": 2001,
"text": "anshitaagarwal"
},
{
"code": null,
"e": 2033,
"s": 2016,
"text": "shalinipriya1011"
},
{
"code": null,
"e": 2050,
"s": 2033,
"text": "siddharthredhu01"
},
{
"code": null,
"e": 2063,
"s": 2050,
"text": "HTML and XML"
},
{
"code": null,
"e": 2082,
"s": 2063,
"text": "Difference Between"
},
{
"code": null,
"e": 2087,
"s": 2082,
"text": "HTML"
},
{
"code": null,
"e": 2104,
"s": 2087,
"text": "Web Technologies"
},
{
"code": null,
"e": 2109,
"s": 2104,
"text": "HTML"
},
{
"code": null,
"e": 2207,
"s": 2109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2268,
"s": 2207,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2336,
"s": 2268,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 2374,
"s": 2336,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 2427,
"s": 2374,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2461,
"s": 2427,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 2509,
"s": 2461,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2571,
"s": 2509,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2621,
"s": 2571,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2645,
"s": 2621,
"text": "REST API (Introduction)"
}
] |
Node.js v8.serialize() Method | 28 Jul, 2020
The v8.serialize() method is an inbuilt application programming interface of the v8 module which is used to serialize any type of data into a buffer using default serializer.
Syntax:
v8.serialize(value);
Parameters: This method one parameter as described below and mentioned above.
value: This is a required parameter, refers to any type of data to be serialized by default serializer
Return Value: This method returns a buffer containing serialized data of the passed value.
Below examples illustrate the use of v8.serialize() method in Node.js.
Example 1: Filename: index.js
// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.serialize() console.log(v8.serialize("geeksforgeeks"));
Run index.js file using the following command:
node index.js
Output:
<Buffer ff 0d 22 0d 67 65 65 6b 73 66 6f 72 67 65 65 6b 73>
Example 2: Filename: index.js
// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.serialize() serialized_data = v8.serialize("abcdefg");console.log("\nSerialized data is ");console.log(serialized_data); serialized_data = v8.serialize(58375693);console.log("\nSerialized data is ");console.log(serialized_data); serialized_data = v8.serialize(73847.0234);console.log("\nSerialized data is ");console.log(serialized_data); serialized_data = v8.serialize('\n');console.log("\nSerialized data is ");console.log(serialized_data);
Run index.js file using the following command:
node index.js
Output:
Serialized data is
<Buffer ff 0d 22 07 61 62 63 64 65 66 67>
Serialized data is
<Buffer ff 0d 49 9a f8 d5 37>
Serialized data is
<Buffer ff 0d 4e ac ad d8 5f 70 07 f2 40>
Serialized data is
<Buffer ff 0d 22 01 0a>
Reference: https://nodejs.org/api/v8.html#v8_v8_serialize_value
Node.js-V8-Module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 203,
"s": 28,
"text": "The v8.serialize() method is an inbuilt application programming interface of the v8 module which is used to serialize any type of data into a buffer using default serializer."
},
{
"code": null,
"e": 211,
"s": 203,
"text": "Syntax:"
},
{
"code": null,
"e": 232,
"s": 211,
"text": "v8.serialize(value);"
},
{
"code": null,
"e": 310,
"s": 232,
"text": "Parameters: This method one parameter as described below and mentioned above."
},
{
"code": null,
"e": 413,
"s": 310,
"text": "value: This is a required parameter, refers to any type of data to be serialized by default serializer"
},
{
"code": null,
"e": 504,
"s": 413,
"text": "Return Value: This method returns a buffer containing serialized data of the passed value."
},
{
"code": null,
"e": 575,
"s": 504,
"text": "Below examples illustrate the use of v8.serialize() method in Node.js."
},
{
"code": null,
"e": 605,
"s": 575,
"text": "Example 1: Filename: index.js"
},
{
"code": "// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.serialize() console.log(v8.serialize(\"geeksforgeeks\"));",
"e": 724,
"s": 605,
"text": null
},
{
"code": null,
"e": 771,
"s": 724,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 785,
"s": 771,
"text": "node index.js"
},
{
"code": null,
"e": 793,
"s": 785,
"text": "Output:"
},
{
"code": null,
"e": 854,
"s": 793,
"text": "<Buffer ff 0d 22 0d 67 65 65 6b 73 66 6f 72 67 65 65 6b 73>\n"
},
{
"code": null,
"e": 884,
"s": 854,
"text": "Example 2: Filename: index.js"
},
{
"code": "// Accessing v8 moduleconst v8 = require('v8'); // Calling v8.serialize() serialized_data = v8.serialize(\"abcdefg\");console.log(\"\\nSerialized data is \");console.log(serialized_data); serialized_data = v8.serialize(58375693);console.log(\"\\nSerialized data is \");console.log(serialized_data); serialized_data = v8.serialize(73847.0234);console.log(\"\\nSerialized data is \");console.log(serialized_data); serialized_data = v8.serialize('\\n');console.log(\"\\nSerialized data is \");console.log(serialized_data);",
"e": 1393,
"s": 884,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1393,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 1454,
"s": 1440,
"text": "node index.js"
},
{
"code": null,
"e": 1462,
"s": 1454,
"text": "Output:"
},
{
"code": null,
"e": 1680,
"s": 1462,
"text": "Serialized data is\n<Buffer ff 0d 22 07 61 62 63 64 65 66 67>\n\nSerialized data is\n<Buffer ff 0d 49 9a f8 d5 37>\n\nSerialized data is\n<Buffer ff 0d 4e ac ad d8 5f 70 07 f2 40>\n\nSerialized data is\n<Buffer ff 0d 22 01 0a>\n"
},
{
"code": null,
"e": 1744,
"s": 1680,
"text": "Reference: https://nodejs.org/api/v8.html#v8_v8_serialize_value"
},
{
"code": null,
"e": 1762,
"s": 1744,
"text": "Node.js-V8-Module"
},
{
"code": null,
"e": 1770,
"s": 1762,
"text": "Node.js"
},
{
"code": null,
"e": 1787,
"s": 1770,
"text": "Web Technologies"
}
] |
<cfloat> float.h in C/C++ with Examples | 25 Nov, 2019
This header file consists of platform-dependent and implementation specific floating point values. A floating point has four parts.
SignIts value can be either negative or non-negative.
BaseIt is also known as radix of exponent representation which represents different numbers with single number i.e. 2 for binary, 10 for decimal, 16 for hexadecimal, ...
MantissaIt is also known as significand.It is a series of digits of the base. The number of digits in the series is known as precision.
ExponentIt is also known as characteristic is an integer between minimum emin and maximum emax.
Value of floating point = ± precision X baseexponent
Macro constants
Library macros are hardware-specific values for the floating-point types.FLT implies type float, DBL implies double, and LDBL implies long double, DIG implies digits, MANT implies mantissa, EXP implies exponent.
FLT_RADIX: Base for all floating-point typesMinimum value is 2FLT_DIG: Number of decimal digits that can be rounded into a floating-point type and back again to the same decimal digits, without loss in precision.Minimum value is 6DBL_DIG or LDBL_DIG: Number of decimal digits that can be rounded into a floating-point and back without change in the number of decimal digits.Minimum value is 10DECIMAL_DIG: Decimal digits needed to represent floating-point valueNo Minimum valueFLT_MANT_DIG or DBL_MANT_DIG or LDBL_MANT_DIG: Precision of mantissa i.e. the number of digits that conform the significand.No Minimum valueFLT_MIN_EXP or DBL_MIN_EXP or LDBL_MIN_EXP: Minimum negative integer value for the exponent that generates a normalized floating-point number.No Minimum valueFLT_MIN_10_EXP or DBL_MIN_10_EXP or LDBL_MIN_10_EXP: Minimum negative integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Maximum value is -37FLT_MAX_EXP or DBL_MAX_EXP or LDBL_MAX_EXP: Maximum integer value for the exponent that generates a normalized floating-point number.No Minimum valueFLT_MAX_10_EXP or DBL_MAX_10_EXP or LDBL_MAX_10_EXP: Maximum integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Minimum value is 37FLT_MAX or DBL_MAX or LDBL_MAX: Maximum finite representable floating-point number.Minimum value is 1037FLT_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-5DBL_EPSILON or LDBL_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-9FLT_MIN or DBL_MIN or LDBL_MIN: Minimum representable positive floating-point number.Maximum value is 10-37FLT_ROUNDS: Rounds off the floating-point numberDifferent possible values are:-1 : indeterminate
0 : towards zero
1 : towards one
2 : towards positive infinity
3 : towards negative infinity
FLT_EVAL_METHOD: Rounds off the floating-point numberDifferent possible values are:-1 : undetermined
0 : evaluate just to the range
and precision of the type
1 : evaluate float and double as double,
and long double as long double.
2 : evaluate all as long double and Other
negative values indicate an
implementation defined behavior.
FLT_RADIX: Base for all floating-point typesMinimum value is 2
Minimum value is 2
FLT_DIG: Number of decimal digits that can be rounded into a floating-point type and back again to the same decimal digits, without loss in precision.Minimum value is 6
Minimum value is 6
DBL_DIG or LDBL_DIG: Number of decimal digits that can be rounded into a floating-point and back without change in the number of decimal digits.Minimum value is 10
Minimum value is 10
DECIMAL_DIG: Decimal digits needed to represent floating-point valueNo Minimum value
No Minimum value
FLT_MANT_DIG or DBL_MANT_DIG or LDBL_MANT_DIG: Precision of mantissa i.e. the number of digits that conform the significand.No Minimum value
No Minimum value
FLT_MIN_EXP or DBL_MIN_EXP or LDBL_MIN_EXP: Minimum negative integer value for the exponent that generates a normalized floating-point number.No Minimum value
No Minimum value
FLT_MIN_10_EXP or DBL_MIN_10_EXP or LDBL_MIN_10_EXP: Minimum negative integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Maximum value is -37
Maximum value is -37
FLT_MAX_EXP or DBL_MAX_EXP or LDBL_MAX_EXP: Maximum integer value for the exponent that generates a normalized floating-point number.No Minimum value
No Minimum value
FLT_MAX_10_EXP or DBL_MAX_10_EXP or LDBL_MAX_10_EXP: Maximum integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Minimum value is 37
Minimum value is 37
FLT_MAX or DBL_MAX or LDBL_MAX: Maximum finite representable floating-point number.Minimum value is 1037
Minimum value is 1037
FLT_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-5
Maximum value is 10-5
DBL_EPSILON or LDBL_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-9
Maximum value is 10-9
FLT_MIN or DBL_MIN or LDBL_MIN: Minimum representable positive floating-point number.Maximum value is 10-37
Maximum value is 10-37
FLT_ROUNDS: Rounds off the floating-point numberDifferent possible values are:-1 : indeterminate
0 : towards zero
1 : towards one
2 : towards positive infinity
3 : towards negative infinity
-1 : indeterminate
0 : towards zero
1 : towards one
2 : towards positive infinity
3 : towards negative infinity
FLT_EVAL_METHOD: Rounds off the floating-point numberDifferent possible values are:-1 : undetermined
0 : evaluate just to the range
and precision of the type
1 : evaluate float and double as double,
and long double as long double.
2 : evaluate all as long double and Other
negative values indicate an
implementation defined behavior.
-1 : undetermined
0 : evaluate just to the range
and precision of the type
1 : evaluate float and double as double,
and long double as long double.
2 : evaluate all as long double and Other
negative values indicate an
implementation defined behavior.
Below is the program to demonstrate the working of macros constants in cfloat library.
// C++ program to demonstrate working// of macros constants in cfloat library #include <cfloat>#include <iostream>using namespace std; int main(){ cout << "FLT_RADIX : " << FLT_RADIX << endl; cout << "FLT_DIG : " << FLT_DIG << endl; cout << "DECIMAL_DIG : " << DECIMAL_DIG << endl; cout << "FLT_MIN_10_EXP : " << FLT_MIN_10_EXP << endl; cout << "FLT_MAX_EXP : " << FLT_MAX_EXP << endl; cout << "FLT_MAX_10_EXP : " << FLT_MAX_10_EXP << endl; cout << "FLT_MAX : " << FLT_MAX << endl; cout << "FLT_MIN : " << FLT_MIN << endl; return 0;}
FLT_RADIX : 2
FLT_DIG : 6
DECIMAL_DIG : 21
FLT_MIN_10_EXP : -37
FLT_MAX_EXP : 128
FLT_MAX_10_EXP : 38
FLT_MAX : 3.40282e+38
FLT_MIN : 1.17549e-38
Reference: http://www.cplusplus.com/reference/cfloat/
C-Library
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 184,
"s": 52,
"text": "This header file consists of platform-dependent and implementation specific floating point values. A floating point has four parts."
},
{
"code": null,
"e": 238,
"s": 184,
"text": "SignIts value can be either negative or non-negative."
},
{
"code": null,
"e": 408,
"s": 238,
"text": "BaseIt is also known as radix of exponent representation which represents different numbers with single number i.e. 2 for binary, 10 for decimal, 16 for hexadecimal, ..."
},
{
"code": null,
"e": 544,
"s": 408,
"text": "MantissaIt is also known as significand.It is a series of digits of the base. The number of digits in the series is known as precision."
},
{
"code": null,
"e": 640,
"s": 544,
"text": "ExponentIt is also known as characteristic is an integer between minimum emin and maximum emax."
},
{
"code": null,
"e": 693,
"s": 640,
"text": "Value of floating point = ± precision X baseexponent"
},
{
"code": null,
"e": 709,
"s": 693,
"text": "Macro constants"
},
{
"code": null,
"e": 921,
"s": 709,
"text": "Library macros are hardware-specific values for the floating-point types.FLT implies type float, DBL implies double, and LDBL implies long double, DIG implies digits, MANT implies mantissa, EXP implies exponent."
},
{
"code": null,
"e": 3241,
"s": 921,
"text": "FLT_RADIX: Base for all floating-point typesMinimum value is 2FLT_DIG: Number of decimal digits that can be rounded into a floating-point type and back again to the same decimal digits, without loss in precision.Minimum value is 6DBL_DIG or LDBL_DIG: Number of decimal digits that can be rounded into a floating-point and back without change in the number of decimal digits.Minimum value is 10DECIMAL_DIG: Decimal digits needed to represent floating-point valueNo Minimum valueFLT_MANT_DIG or DBL_MANT_DIG or LDBL_MANT_DIG: Precision of mantissa i.e. the number of digits that conform the significand.No Minimum valueFLT_MIN_EXP or DBL_MIN_EXP or LDBL_MIN_EXP: Minimum negative integer value for the exponent that generates a normalized floating-point number.No Minimum valueFLT_MIN_10_EXP or DBL_MIN_10_EXP or LDBL_MIN_10_EXP: Minimum negative integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Maximum value is -37FLT_MAX_EXP or DBL_MAX_EXP or LDBL_MAX_EXP: Maximum integer value for the exponent that generates a normalized floating-point number.No Minimum valueFLT_MAX_10_EXP or DBL_MAX_10_EXP or LDBL_MAX_10_EXP: Maximum integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Minimum value is 37FLT_MAX or DBL_MAX or LDBL_MAX: Maximum finite representable floating-point number.Minimum value is 1037FLT_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-5DBL_EPSILON or LDBL_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-9FLT_MIN or DBL_MIN or LDBL_MIN: Minimum representable positive floating-point number.Maximum value is 10-37FLT_ROUNDS: Rounds off the floating-point numberDifferent possible values are:-1 : indeterminate\n 0 : towards zero\n 1 : towards one\n 2 : towards positive infinity\n 3 : towards negative infinity\nFLT_EVAL_METHOD: Rounds off the floating-point numberDifferent possible values are:-1 : undetermined\n 0 : evaluate just to the range \n and precision of the type\n 1 : evaluate float and double as double,\n and long double as long double.\n 2 : evaluate all as long double and Other \n negative values indicate an \n implementation defined behavior.\n"
},
{
"code": null,
"e": 3304,
"s": 3241,
"text": "FLT_RADIX: Base for all floating-point typesMinimum value is 2"
},
{
"code": null,
"e": 3323,
"s": 3304,
"text": "Minimum value is 2"
},
{
"code": null,
"e": 3492,
"s": 3323,
"text": "FLT_DIG: Number of decimal digits that can be rounded into a floating-point type and back again to the same decimal digits, without loss in precision.Minimum value is 6"
},
{
"code": null,
"e": 3511,
"s": 3492,
"text": "Minimum value is 6"
},
{
"code": null,
"e": 3675,
"s": 3511,
"text": "DBL_DIG or LDBL_DIG: Number of decimal digits that can be rounded into a floating-point and back without change in the number of decimal digits.Minimum value is 10"
},
{
"code": null,
"e": 3695,
"s": 3675,
"text": "Minimum value is 10"
},
{
"code": null,
"e": 3780,
"s": 3695,
"text": "DECIMAL_DIG: Decimal digits needed to represent floating-point valueNo Minimum value"
},
{
"code": null,
"e": 3797,
"s": 3780,
"text": "No Minimum value"
},
{
"code": null,
"e": 3938,
"s": 3797,
"text": "FLT_MANT_DIG or DBL_MANT_DIG or LDBL_MANT_DIG: Precision of mantissa i.e. the number of digits that conform the significand.No Minimum value"
},
{
"code": null,
"e": 3955,
"s": 3938,
"text": "No Minimum value"
},
{
"code": null,
"e": 4114,
"s": 3955,
"text": "FLT_MIN_EXP or DBL_MIN_EXP or LDBL_MIN_EXP: Minimum negative integer value for the exponent that generates a normalized floating-point number.No Minimum value"
},
{
"code": null,
"e": 4131,
"s": 4114,
"text": "No Minimum value"
},
{
"code": null,
"e": 4332,
"s": 4131,
"text": "FLT_MIN_10_EXP or DBL_MIN_10_EXP or LDBL_MIN_10_EXP: Minimum negative integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Maximum value is -37"
},
{
"code": null,
"e": 4353,
"s": 4332,
"text": "Maximum value is -37"
},
{
"code": null,
"e": 4503,
"s": 4353,
"text": "FLT_MAX_EXP or DBL_MAX_EXP or LDBL_MAX_EXP: Maximum integer value for the exponent that generates a normalized floating-point number.No Minimum value"
},
{
"code": null,
"e": 4520,
"s": 4503,
"text": "No Minimum value"
},
{
"code": null,
"e": 4711,
"s": 4520,
"text": "FLT_MAX_10_EXP or DBL_MAX_10_EXP or LDBL_MAX_10_EXP: Maximum integer value for the exponent of a base-10 expression that would generate a normalized floating-point number.Minimum value is 37"
},
{
"code": null,
"e": 4731,
"s": 4711,
"text": "Minimum value is 37"
},
{
"code": null,
"e": 4836,
"s": 4731,
"text": "FLT_MAX or DBL_MAX or LDBL_MAX: Maximum finite representable floating-point number.Minimum value is 1037"
},
{
"code": null,
"e": 4858,
"s": 4836,
"text": "Minimum value is 1037"
},
{
"code": null,
"e": 4971,
"s": 4858,
"text": "FLT_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-5"
},
{
"code": null,
"e": 4993,
"s": 4971,
"text": "Maximum value is 10-5"
},
{
"code": null,
"e": 5122,
"s": 4993,
"text": "DBL_EPSILON or LDBL_EPSILON: Difference between 1 and the least value greater than 1 that is representable.Maximum value is 10-9"
},
{
"code": null,
"e": 5144,
"s": 5122,
"text": "Maximum value is 10-9"
},
{
"code": null,
"e": 5252,
"s": 5144,
"text": "FLT_MIN or DBL_MIN or LDBL_MIN: Minimum representable positive floating-point number.Maximum value is 10-37"
},
{
"code": null,
"e": 5275,
"s": 5252,
"text": "Maximum value is 10-37"
},
{
"code": null,
"e": 5470,
"s": 5275,
"text": "FLT_ROUNDS: Rounds off the floating-point numberDifferent possible values are:-1 : indeterminate\n 0 : towards zero\n 1 : towards one\n 2 : towards positive infinity\n 3 : towards negative infinity\n"
},
{
"code": null,
"e": 5587,
"s": 5470,
"text": "-1 : indeterminate\n 0 : towards zero\n 1 : towards one\n 2 : towards positive infinity\n 3 : towards negative infinity\n"
},
{
"code": null,
"e": 5948,
"s": 5587,
"text": "FLT_EVAL_METHOD: Rounds off the floating-point numberDifferent possible values are:-1 : undetermined\n 0 : evaluate just to the range \n and precision of the type\n 1 : evaluate float and double as double,\n and long double as long double.\n 2 : evaluate all as long double and Other \n negative values indicate an \n implementation defined behavior.\n"
},
{
"code": null,
"e": 6226,
"s": 5948,
"text": "-1 : undetermined\n 0 : evaluate just to the range \n and precision of the type\n 1 : evaluate float and double as double,\n and long double as long double.\n 2 : evaluate all as long double and Other \n negative values indicate an \n implementation defined behavior.\n"
},
{
"code": null,
"e": 6313,
"s": 6226,
"text": "Below is the program to demonstrate the working of macros constants in cfloat library."
},
{
"code": "// C++ program to demonstrate working// of macros constants in cfloat library #include <cfloat>#include <iostream>using namespace std; int main(){ cout << \"FLT_RADIX : \" << FLT_RADIX << endl; cout << \"FLT_DIG : \" << FLT_DIG << endl; cout << \"DECIMAL_DIG : \" << DECIMAL_DIG << endl; cout << \"FLT_MIN_10_EXP : \" << FLT_MIN_10_EXP << endl; cout << \"FLT_MAX_EXP : \" << FLT_MAX_EXP << endl; cout << \"FLT_MAX_10_EXP : \" << FLT_MAX_10_EXP << endl; cout << \"FLT_MAX : \" << FLT_MAX << endl; cout << \"FLT_MIN : \" << FLT_MIN << endl; return 0;}",
"e": 6940,
"s": 6313,
"text": null
},
{
"code": null,
"e": 7087,
"s": 6940,
"text": "FLT_RADIX : 2\nFLT_DIG : 6\nDECIMAL_DIG : 21\nFLT_MIN_10_EXP : -37\nFLT_MAX_EXP : 128\nFLT_MAX_10_EXP : 38\nFLT_MAX : 3.40282e+38\nFLT_MIN : 1.17549e-38\n"
},
{
"code": null,
"e": 7141,
"s": 7087,
"text": "Reference: http://www.cplusplus.com/reference/cfloat/"
},
{
"code": null,
"e": 7151,
"s": 7141,
"text": "C-Library"
},
{
"code": null,
"e": 7163,
"s": 7151,
"text": "CPP-Library"
},
{
"code": null,
"e": 7174,
"s": 7163,
"text": "C Language"
},
{
"code": null,
"e": 7178,
"s": 7174,
"text": "C++"
},
{
"code": null,
"e": 7182,
"s": 7178,
"text": "CPP"
}
] |
What happens if we does not initialize variables of an interface in java? | In Java final is the access modifier which can be used with a filed class and a method.
When a method if final it cannot be overridden.
When a variable is final its value cannot be modified further.
When a class is finale it cannot be extended.
If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don’t you will get a compilation error.
In the following java program, we a have an interface with a public, static, final variable with name num and, a public, abstract method with name demo.
public interface MyInterface {
public static final int num;
public abstract void demo();
}
On compiling, the above program generates the following error.
MyInterface.java:2: error: = expected
public static final int num;
^
1 error | [
{
"code": null,
"e": 1150,
"s": 1062,
"text": "In Java final is the access modifier which can be used with a filed class and a method."
},
{
"code": null,
"e": 1198,
"s": 1150,
"text": "When a method if final it cannot be overridden."
},
{
"code": null,
"e": 1261,
"s": 1198,
"text": "When a variable is final its value cannot be modified further."
},
{
"code": null,
"e": 1307,
"s": 1261,
"text": "When a class is finale it cannot be extended."
},
{
"code": null,
"e": 1458,
"s": 1307,
"text": "If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don’t you will get a compilation error."
},
{
"code": null,
"e": 1611,
"s": 1458,
"text": "In the following java program, we a have an interface with a public, static, final variable with name num and, a public, abstract method with name demo."
},
{
"code": null,
"e": 1708,
"s": 1611,
"text": "public interface MyInterface {\n public static final int num;\n public abstract void demo();\n}"
},
{
"code": null,
"e": 1771,
"s": 1708,
"text": "On compiling, the above program generates the following error."
},
{
"code": null,
"e": 1851,
"s": 1771,
"text": "MyInterface.java:2: error: = expected\n public static final int num;\n^\n1 error"
}
] |
JUnit - Ignore Test | Sometimes it so happens that our code is not completely ready while running a test case. As a result, the test case fails. The @Ignore annotation helps in this scenario.
A test method annotated with @Ignore will not be executed.
A test method annotated with @Ignore will not be executed.
If a test class is annotated with @Ignore, then none of its test methods will be executed.
If a test class is annotated with @Ignore, then none of its test methods will be executed.
Now let's see @Ignore in action.
Create a java class to be tested, say, MessageUtil.java in C:\>JUNIT_WORKSPACE.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message){
this.message = message;
}
// prints the message
public String printMessage(){
System.out.println(message);
return message;
}
// add "Hi!" to the message
public String salutationMessage(){
message = "Hi!" + message;
System.out.println(message);
return message;
}
}
Create a java test class, say, TestJunit.java.
Create a java test class, say, TestJunit.java.
Add a test method testPrintMessage() or testSalutationMessage() to your test class.
Add a test method testPrintMessage() or testSalutationMessage() to your test class.
Add an Annotaion @Ignore to method testPrintMessage().
Add an Annotaion @Ignore to method testPrintMessage().
Create a java class file named TestJunit.java in C:\ JUNIT_WORKSPACE.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
public class TestJunit {
String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);
@Ignore
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = "Robert";
assertEquals(message,messageUtil.printMessage());
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
Create a java class file named TestRunner.java in C:\>JUNIT_WORKSPACE to execute test case(s).
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Compile the MessageUtil, Test case and Test Runner classes using javac.
C:\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java
Now run the Test Runner, which will not run the testPrintMessage() test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output. testPrintMessage() test case is not tested.
Inside testSalutationMessage()
Hi!Robert
true
Now, update TestJunit in C:\>JUNIT_WORKSPACE to ignore all test cases. Add @Ignore at class level.
import org.junit.Test;
import org.junit.Ignore;
import static org.junit.Assert.assertEquals;
@Ignore
public class TestJunit {
String message = "Robert";
MessageUtil messageUtil = new MessageUtil(message);
@Test
public void testPrintMessage() {
System.out.println("Inside testPrintMessage()");
message = "Robert";
assertEquals(message,messageUtil.printMessage());
}
@Test
public void testSalutationMessage() {
System.out.println("Inside testSalutationMessage()");
message = "Hi!" + "Robert";
assertEquals(message,messageUtil.salutationMessage());
}
}
Compile the test case using javac.
C:\JUNIT_WORKSPACE>javac TestJunit.java
Keep your Test Runner unchanged as follows −
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunit.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Now run the Test Runner, which will not run any test case defined in the provided Test Case class.
C:\JUNIT_WORKSPACE>java TestRunner
Verify the output. No test case is tested.
true
24 Lectures
2.5 hours
Nishita Bhatt
56 Lectures
7.5 hours
Dinesh Varyani
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2142,
"s": 1972,
"text": "Sometimes it so happens that our code is not completely ready while running a test case. As a result, the test case fails. The @Ignore annotation helps in this scenario."
},
{
"code": null,
"e": 2201,
"s": 2142,
"text": "A test method annotated with @Ignore will not be executed."
},
{
"code": null,
"e": 2260,
"s": 2201,
"text": "A test method annotated with @Ignore will not be executed."
},
{
"code": null,
"e": 2351,
"s": 2260,
"text": "If a test class is annotated with @Ignore, then none of its test methods will be executed."
},
{
"code": null,
"e": 2442,
"s": 2351,
"text": "If a test class is annotated with @Ignore, then none of its test methods will be executed."
},
{
"code": null,
"e": 2475,
"s": 2442,
"text": "Now let's see @Ignore in action."
},
{
"code": null,
"e": 2555,
"s": 2475,
"text": "Create a java class to be tested, say, MessageUtil.java in C:\\>JUNIT_WORKSPACE."
},
{
"code": null,
"e": 3092,
"s": 2555,
"text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message){\n this.message = message; \n }\n\n // prints the message\n public String printMessage(){\n System.out.println(message);\n return message;\n } \n\n // add \"Hi!\" to the message\n public String salutationMessage(){\n message = \"Hi!\" + message;\n System.out.println(message);\n return message;\n } \n\t\n} "
},
{
"code": null,
"e": 3139,
"s": 3092,
"text": "Create a java test class, say, TestJunit.java."
},
{
"code": null,
"e": 3186,
"s": 3139,
"text": "Create a java test class, say, TestJunit.java."
},
{
"code": null,
"e": 3270,
"s": 3186,
"text": "Add a test method testPrintMessage() or testSalutationMessage() to your test class."
},
{
"code": null,
"e": 3354,
"s": 3270,
"text": "Add a test method testPrintMessage() or testSalutationMessage() to your test class."
},
{
"code": null,
"e": 3409,
"s": 3354,
"text": "Add an Annotaion @Ignore to method testPrintMessage()."
},
{
"code": null,
"e": 3464,
"s": 3409,
"text": "Add an Annotaion @Ignore to method testPrintMessage()."
},
{
"code": null,
"e": 3534,
"s": 3464,
"text": "Create a java class file named TestJunit.java in C:\\ JUNIT_WORKSPACE."
},
{
"code": null,
"e": 4157,
"s": 3534,
"text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\npublic class TestJunit {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Ignore\n @Test\n public void testPrintMessage() {\n System.out.println(\"Inside testPrintMessage()\");\n message = \"Robert\";\n assertEquals(message,messageUtil.printMessage());\n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n\t\n}"
},
{
"code": null,
"e": 4252,
"s": 4157,
"text": "Create a java class file named TestRunner.java in C:\\>JUNIT_WORKSPACE to execute test case(s)."
},
{
"code": null,
"e": 4671,
"s": 4252,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 4743,
"s": 4671,
"text": "Compile the MessageUtil, Test case and Test Runner classes using javac."
},
{
"code": null,
"e": 4817,
"s": 4743,
"text": "C:\\JUNIT_WORKSPACE>javac MessageUtil.java TestJunit.java TestRunner.java\n"
},
{
"code": null,
"e": 4935,
"s": 4817,
"text": "Now run the Test Runner, which will not run the testPrintMessage() test case defined in the provided Test Case class."
},
{
"code": null,
"e": 4971,
"s": 4935,
"text": "C:\\JUNIT_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 5034,
"s": 4971,
"text": "Verify the output. testPrintMessage() test case is not tested."
},
{
"code": null,
"e": 5081,
"s": 5034,
"text": "Inside testSalutationMessage()\nHi!Robert\ntrue\n"
},
{
"code": null,
"e": 5180,
"s": 5081,
"text": "Now, update TestJunit in C:\\>JUNIT_WORKSPACE to ignore all test cases. Add @Ignore at class level."
},
{
"code": null,
"e": 5802,
"s": 5180,
"text": "import org.junit.Test;\nimport org.junit.Ignore;\nimport static org.junit.Assert.assertEquals;\n\n@Ignore\npublic class TestJunit {\n\n String message = \"Robert\";\t\n MessageUtil messageUtil = new MessageUtil(message);\n \n @Test\n public void testPrintMessage() {\n System.out.println(\"Inside testPrintMessage()\");\n message = \"Robert\";\n assertEquals(message,messageUtil.printMessage());\n }\n\n @Test\n public void testSalutationMessage() {\n System.out.println(\"Inside testSalutationMessage()\");\n message = \"Hi!\" + \"Robert\";\n assertEquals(message,messageUtil.salutationMessage());\n }\n\t\n}"
},
{
"code": null,
"e": 5837,
"s": 5802,
"text": "Compile the test case using javac."
},
{
"code": null,
"e": 5878,
"s": 5837,
"text": "C:\\JUNIT_WORKSPACE>javac TestJunit.java\n"
},
{
"code": null,
"e": 5923,
"s": 5878,
"text": "Keep your Test Runner unchanged as follows −"
},
{
"code": null,
"e": 6341,
"s": 5923,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(TestJunit.class);\n\t\t\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n\t\t\n System.out.println(result.wasSuccessful());\n }\n}"
},
{
"code": null,
"e": 6440,
"s": 6341,
"text": "Now run the Test Runner, which will not run any test case defined in the provided Test Case class."
},
{
"code": null,
"e": 6476,
"s": 6440,
"text": "C:\\JUNIT_WORKSPACE>java TestRunner\n"
},
{
"code": null,
"e": 6519,
"s": 6476,
"text": "Verify the output. No test case is tested."
},
{
"code": null,
"e": 6525,
"s": 6519,
"text": "true\n"
},
{
"code": null,
"e": 6560,
"s": 6525,
"text": "\n 24 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6575,
"s": 6560,
"text": " Nishita Bhatt"
},
{
"code": null,
"e": 6610,
"s": 6575,
"text": "\n 56 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6626,
"s": 6610,
"text": " Dinesh Varyani"
},
{
"code": null,
"e": 6633,
"s": 6626,
"text": " Print"
},
{
"code": null,
"e": 6644,
"s": 6633,
"text": " Add Notes"
}
] |
Apache HIVE - Database Options - GeeksforGeeks | 04 Nov, 2020
Apache hive is a data-warehousing tool built on top of Hadoop. The structured data can be handled with the Hive query language. In this article, we are going to see options that are available with databases in the Hive.
The database is used for storing information. The hive will create a directory for each of its created databases. All the tables that are created inside the database will be stored inside the sub-directories of the database directory. We can find the location on HDFS(Hadoop Distributed File System) where the directories for the database are made by checking hive.metastore.warehouse.dir property in /conf/hive-site.xml file.
/user/hive/warehouse is the default directory location set in hive.metastore.warehouse.dir property where all database and table directories are made. The location is configurable and we can change it as per our requirement. For example, if we have created the database with the name Test then Hive will create the directory /user/hive/warehouse/Test.db. Let’s perform a quick demo on this.
Step 1: Start all the Hadoop daemons.
Step 2: Start Hive shell.
Step 3: Create a database with the name Test.
Syntax:
CREATE DATABASE <database-name>;
Command:
create database Test;
Step 4: Check the location /user/hive/warehouse on HDFS to see whether the database directory is made or not. For Hadoop 3 go to http://localhost:9870 and For Hadoop 2 go to http://localhost:50070 to browse the name node. Click on Utilities -> Browse the file system then move to /user/hive/warehouse.
In the above image, we can see that the Test.db database is available.
1. Location
The Location option helps the user to override the default location where the database directory is made. As we know the default directory where the databases made is /user/hive/warehouse. so we can change this directory with this option.
Let’s create a directory with the name hive_db on HDFS with the help of the below command.
hdfs dfs -mkdir /hive_db
Now, the syntax to use the Location option with the create database command is shown below.
CREATE DATABASE <database_name>
LOCATION '/<directory_path_on_HDFS>';
Example:
Create the database with the name Temp in /hive_db directory on HDFS. Here, the LOCATION will override the default location where the database directory is made. Now the tables you make for this database will be created inside /hive_db in HDFS.
CREATE DATABASE Temp
LOCATION '/hive_db';
2. COMMENT
We can add comments with the database we have created. We can add a few reasons why we have created that database etc.
Syntax:
CREATE DATABASE <database_name>
COMMENT '<comment you are adding>';
Example:
CREATE DATABASE student
COMMENT 'The DB stores data of students';
3. DESCRIBE
We can use DESCRIBE to describe our database. It is used with databases, tables, and view in the hive. The option will show the database location and the other information regarding that database.
Syntax:
DESCRIBE DATABASE <database_name>;
Example:
DESCRIBE DATABASE Temp;
DESCRIBE DATABASE student;
4. WITH DBPROPERTIES
We can add some properties or information to our database in the form of a key-value pair with this option. The properties added with this option can only be viewed by using EXTENDED option with DESCRIBE DATABASE command.
Syntax:
CREATE DATABASE <database_name>
WITH DBPROPERTIES ('<key-name>' = '<value>');
Example:
CREATE DATABASE employee
WITH DBPROPERTIES ('made by' = 'GFG', 'date' = '2020-10-10', 'company' = 'GeeksForGeeks');
Now, let’s see these values with the Describe database.
DESCRIBE DATABASE employee; # does not show the property added with WITH DBPRROPERTIES
DESCRIBE DATABASE EXTENDED employee; # shows the property added with WITH DBPROPERTIES
5. USE
The USE command is used to use databases to work on it. Since multiple databases are available so we can select or choose the database to use with the USE command or option.
Syntax:
USE <database-name>;
Example:
USE employee;
6. DROP
DROP is used to drop the existing database.
Syntax:
DROP DATABASE <database_name>;
Example:
DROP DATABASE employee;
7. SHOW
SHOW is used to show the existing available database list.
Command:
SHOW DATABASES;
Apache-Hive
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create Table in Hive?
Hadoop - Schedulers and Types of Schedulers
Hive - Alter Table
Import and Export Data using SQOOP
MapReduce - Combiners
Hadoop - File Blocks and Replication Factor
MapReduce - Understanding With Real-Life Example
Hadoop - HDFS (Hadoop Distributed File System)
Difference Between Hadoop 2.x vs Hadoop 3.x
Hadoop - Reducer in Map-Reduce | [
{
"code": null,
"e": 24346,
"s": 24318,
"text": "\n04 Nov, 2020"
},
{
"code": null,
"e": 24566,
"s": 24346,
"text": "Apache hive is a data-warehousing tool built on top of Hadoop. The structured data can be handled with the Hive query language. In this article, we are going to see options that are available with databases in the Hive."
},
{
"code": null,
"e": 24995,
"s": 24566,
"text": "The database is used for storing information. The hive will create a directory for each of its created databases. All the tables that are created inside the database will be stored inside the sub-directories of the database directory. We can find the location on HDFS(Hadoop Distributed File System) where the directories for the database are made by checking hive.metastore.warehouse.dir property in /conf/hive-site.xml file. "
},
{
"code": null,
"e": 25386,
"s": 24995,
"text": "/user/hive/warehouse is the default directory location set in hive.metastore.warehouse.dir property where all database and table directories are made. The location is configurable and we can change it as per our requirement. For example, if we have created the database with the name Test then Hive will create the directory /user/hive/warehouse/Test.db. Let’s perform a quick demo on this."
},
{
"code": null,
"e": 25425,
"s": 25386,
"text": "Step 1: Start all the Hadoop daemons. "
},
{
"code": null,
"e": 25451,
"s": 25425,
"text": "Step 2: Start Hive shell."
},
{
"code": null,
"e": 25497,
"s": 25451,
"text": "Step 3: Create a database with the name Test."
},
{
"code": null,
"e": 25505,
"s": 25497,
"text": "Syntax:"
},
{
"code": null,
"e": 25539,
"s": 25505,
"text": "CREATE DATABASE <database-name>;\n"
},
{
"code": null,
"e": 25548,
"s": 25539,
"text": "Command:"
},
{
"code": null,
"e": 25571,
"s": 25548,
"text": "create database Test;\n"
},
{
"code": null,
"e": 25875,
"s": 25571,
"text": "Step 4: Check the location /user/hive/warehouse on HDFS to see whether the database directory is made or not. For Hadoop 3 go to http://localhost:9870 and For Hadoop 2 go to http://localhost:50070 to browse the name node. Click on Utilities -> Browse the file system then move to /user/hive/warehouse. "
},
{
"code": null,
"e": 25946,
"s": 25875,
"text": "In the above image, we can see that the Test.db database is available."
},
{
"code": null,
"e": 25958,
"s": 25946,
"text": "1. Location"
},
{
"code": null,
"e": 26197,
"s": 25958,
"text": "The Location option helps the user to override the default location where the database directory is made. As we know the default directory where the databases made is /user/hive/warehouse. so we can change this directory with this option."
},
{
"code": null,
"e": 26289,
"s": 26197,
"text": "Let’s create a directory with the name hive_db on HDFS with the help of the below command. "
},
{
"code": null,
"e": 26315,
"s": 26289,
"text": "hdfs dfs -mkdir /hive_db\n"
},
{
"code": null,
"e": 26407,
"s": 26315,
"text": "Now, the syntax to use the Location option with the create database command is shown below."
},
{
"code": null,
"e": 26478,
"s": 26407,
"text": "CREATE DATABASE <database_name>\nLOCATION '/<directory_path_on_HDFS>';\n"
},
{
"code": null,
"e": 26488,
"s": 26478,
"text": " Example:"
},
{
"code": null,
"e": 26735,
"s": 26488,
"text": "Create the database with the name Temp in /hive_db directory on HDFS. Here, the LOCATION will override the default location where the database directory is made. Now the tables you make for this database will be created inside /hive_db in HDFS. "
},
{
"code": null,
"e": 26778,
"s": 26735,
"text": "CREATE DATABASE Temp\nLOCATION '/hive_db';\n"
},
{
"code": null,
"e": 26789,
"s": 26778,
"text": "2. COMMENT"
},
{
"code": null,
"e": 26908,
"s": 26789,
"text": "We can add comments with the database we have created. We can add a few reasons why we have created that database etc."
},
{
"code": null,
"e": 26916,
"s": 26908,
"text": "Syntax:"
},
{
"code": null,
"e": 26985,
"s": 26916,
"text": "CREATE DATABASE <database_name>\nCOMMENT '<comment you are adding>';\n"
},
{
"code": null,
"e": 26994,
"s": 26985,
"text": "Example:"
},
{
"code": null,
"e": 27061,
"s": 26994,
"text": "CREATE DATABASE student\nCOMMENT 'The DB stores data of students';\n"
},
{
"code": null,
"e": 27073,
"s": 27061,
"text": "3. DESCRIBE"
},
{
"code": null,
"e": 27271,
"s": 27073,
"text": "We can use DESCRIBE to describe our database. It is used with databases, tables, and view in the hive. The option will show the database location and the other information regarding that database. "
},
{
"code": null,
"e": 27279,
"s": 27271,
"text": "Syntax:"
},
{
"code": null,
"e": 27315,
"s": 27279,
"text": "DESCRIBE DATABASE <database_name>;\n"
},
{
"code": null,
"e": 27324,
"s": 27315,
"text": "Example:"
},
{
"code": null,
"e": 27377,
"s": 27324,
"text": "DESCRIBE DATABASE Temp;\n\nDESCRIBE DATABASE student;\n"
},
{
"code": null,
"e": 27399,
"s": 27377,
"text": "4. WITH DBPROPERTIES"
},
{
"code": null,
"e": 27621,
"s": 27399,
"text": "We can add some properties or information to our database in the form of a key-value pair with this option. The properties added with this option can only be viewed by using EXTENDED option with DESCRIBE DATABASE command."
},
{
"code": null,
"e": 27629,
"s": 27621,
"text": "Syntax:"
},
{
"code": null,
"e": 27708,
"s": 27629,
"text": "CREATE DATABASE <database_name>\nWITH DBPROPERTIES ('<key-name>' = '<value>');\n"
},
{
"code": null,
"e": 27717,
"s": 27708,
"text": "Example:"
},
{
"code": null,
"e": 27835,
"s": 27717,
"text": "CREATE DATABASE employee\nWITH DBPROPERTIES ('made by' = 'GFG', 'date' = '2020-10-10', 'company' = 'GeeksForGeeks'); \n"
},
{
"code": null,
"e": 27891,
"s": 27835,
"text": "Now, let’s see these values with the Describe database."
},
{
"code": null,
"e": 28079,
"s": 27891,
"text": "DESCRIBE DATABASE employee; # does not show the property added with WITH DBPRROPERTIES\n\nDESCRIBE DATABASE EXTENDED employee; # shows the property added with WITH DBPROPERTIES \n"
},
{
"code": null,
"e": 28086,
"s": 28079,
"text": "5. USE"
},
{
"code": null,
"e": 28260,
"s": 28086,
"text": "The USE command is used to use databases to work on it. Since multiple databases are available so we can select or choose the database to use with the USE command or option."
},
{
"code": null,
"e": 28268,
"s": 28260,
"text": "Syntax:"
},
{
"code": null,
"e": 28290,
"s": 28268,
"text": "USE <database-name>;\n"
},
{
"code": null,
"e": 28299,
"s": 28290,
"text": "Example:"
},
{
"code": null,
"e": 28314,
"s": 28299,
"text": "USE employee;\n"
},
{
"code": null,
"e": 28322,
"s": 28314,
"text": "6. DROP"
},
{
"code": null,
"e": 28366,
"s": 28322,
"text": "DROP is used to drop the existing database."
},
{
"code": null,
"e": 28374,
"s": 28366,
"text": "Syntax:"
},
{
"code": null,
"e": 28406,
"s": 28374,
"text": "DROP DATABASE <database_name>;\n"
},
{
"code": null,
"e": 28415,
"s": 28406,
"text": "Example:"
},
{
"code": null,
"e": 28440,
"s": 28415,
"text": "DROP DATABASE employee;\n"
},
{
"code": null,
"e": 28448,
"s": 28440,
"text": "7. SHOW"
},
{
"code": null,
"e": 28507,
"s": 28448,
"text": "SHOW is used to show the existing available database list."
},
{
"code": null,
"e": 28516,
"s": 28507,
"text": "Command:"
},
{
"code": null,
"e": 28534,
"s": 28516,
"text": "SHOW DATABASES; \n"
},
{
"code": null,
"e": 28546,
"s": 28534,
"text": "Apache-Hive"
},
{
"code": null,
"e": 28553,
"s": 28546,
"text": "Hadoop"
},
{
"code": null,
"e": 28560,
"s": 28553,
"text": "Hadoop"
},
{
"code": null,
"e": 28658,
"s": 28560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28687,
"s": 28658,
"text": "How to Create Table in Hive?"
},
{
"code": null,
"e": 28731,
"s": 28687,
"text": "Hadoop - Schedulers and Types of Schedulers"
},
{
"code": null,
"e": 28750,
"s": 28731,
"text": "Hive - Alter Table"
},
{
"code": null,
"e": 28785,
"s": 28750,
"text": "Import and Export Data using SQOOP"
},
{
"code": null,
"e": 28807,
"s": 28785,
"text": "MapReduce - Combiners"
},
{
"code": null,
"e": 28851,
"s": 28807,
"text": "Hadoop - File Blocks and Replication Factor"
},
{
"code": null,
"e": 28900,
"s": 28851,
"text": "MapReduce - Understanding With Real-Life Example"
},
{
"code": null,
"e": 28947,
"s": 28900,
"text": "Hadoop - HDFS (Hadoop Distributed File System)"
},
{
"code": null,
"e": 28991,
"s": 28947,
"text": "Difference Between Hadoop 2.x vs Hadoop 3.x"
}
] |
Build with PyCaret, Deploy with FastAPI | by Moez Ali | Towards Data Science | This is a step-by-step, beginner-friendly tutorial on how to build an end-to-end Machine Learning Pipeline with PyCaret and deploy it in production as a web API using FastAPI.
Build an end-to-end machine learning pipeline using PyCaret
What is a deployment and why do we deploy machine learning models
Develop an API using FastAPI to generate predictions on unseen data
Use Python to send a request to API for generating predictions programmatically.
This tutorial will cover the entire machine learning life cycle at a high level which is broken down into the following sections:
PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to build and deploy end-to-end ML prototypes quickly and efficiently.
PyCaret is an alternate low-code library that can replace hundreds of code lines with few lines only. This makes the experiment cycle exponentially fast and efficient.
PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it.
To learn more about PyCaret, check out their GitHub.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. The key features are:
Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.
Fast to code: Increase the speed to develop features by about 200% to 300%.
Easy: Designed to be easy to use and learn. Less time reading docs.
To learn more about FastAPI, check out their GitHub.
Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries.
PyCaret’s default installation is a slim version of pycaret that only installs hard dependencies listed here.
# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]
When you install the full version of pycaret, all the optional dependencies as listed here are also installed.
You can install FastAPI from pip.
pip install fastapi
For this tutorial, I will be using a very popular case study by Darden School of Business, published in Harvard Business. The case is regarding the story of two people who are going to be married in the future. The guy named Greg wanted to buy a ring to propose to a girl named Sarah. The problem is to find the ring Sarah will like, but after a suggestion from his close friend, Greg decides to buy a diamond stone instead so that Sarah can decide her choice. Greg then collects data of 6000 diamonds with their price and attributes like cut, color, shape, etc.
In this tutorial, I will be using a dataset from a very popular case study by the Darden School of Business, published in Harvard Business. The goal of this tutorial is to predict the diamond price based on its attributes like carat weight, cut, color, etc. You can download the dataset from PyCaret’s repository.
# load the dataset from pycaretfrom pycaret.datasets import get_datadata = get_data('diamond')
Let’s do some quick visualization to assess the relationship of independent features (weight, cut, color, clarity, etc.) with the target variable i.e. Price
# plot scatter carat_weight and Priceimport plotly.express as pxfig = px.scatter(x=data['Carat Weight'], y=data['Price'], facet_col = data['Cut'], opacity = 0.25, template = 'plotly_dark', trendline='ols', trendline_color_override = 'red', title = 'SARAH GETS A DIAMOND - A CASE STUDY')fig.show()
Let’s check the distribution of the target variable.
# plot histogramfig = px.histogram(data, x=["Price"], template = 'plotly_dark', title = 'Histogram of Price')fig.show()
Notice that distribution of Price is right-skewed, we can quickly check to see if log transformation can make Price approximately normal to give fighting chance to algorithms that assume normality.
import numpy as np# create a copy of datadata_copy = data.copy()# create a new feature Log_Pricedata_copy['Log_Price'] = np.log(data['Price'])# plot histogramfig = px.histogram(data_copy, x=["Log_Price"], title = 'Histgram of Log Price', template = 'plotly_dark')fig.show()
This confirms our hypothesis. The transformation will help us to get away with skewness and make the target variable approximately normal. Based on this, we will transform the Price variable before training our models.
Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link.
# init setupfrom pycaret.regression import *s = setup(data, target = 'Price', transform_target = True)
Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. In this case, you can see except for Carat Weight all the other features are inferred as categorical, which is correct. You can press enter to continue.
Notice that I have used transform_target = True inside the setup. PyCaret will transform the Price variable behind the scene using box-cox transformation. It affects the distribution of data in a similar way as log transformation (technically different). If you would like to learn more about box-cox transformations, you can refer to this link.
Now that data preparation is done, let’s start the training process by using compare_models functionality. This function trains all the algorithms available in the model library and evaluates multiple performance metrics using cross-validation.
# compare all modelsbest = compare_models()
The best model based on Mean Absolute Error (MAE) is CatBoost Regressor. MAE using 10-fold cross-validation is $543 compared to the average diamond value of $11,600. This is less than 5%. Not bad for the efforts we have put in so far.
# check the residuals of trained modelplot_model(best, plot = 'residuals_interactive')
# check feature importanceplot_model(best, plot = 'feature')
Let’s now finalize the best model i.e. train the best model on the entire dataset including the test set and then save the pipeline as a pickle file.
# finalize the modelfinal_best = finalize_model(best)# save model to disksave_model(final_best, 'diamond-pipeline')
First, let’s understand why to deploy machine learning models?
The deployment of machine learning models is the process of making models available in production where web applications, enterprise software, and APIs can consume the trained model by providing new data points and generating predictions. Normally machine learning models are built so that they can be used to predict an outcome (binary value i.e. 1 or 0 for Classification, continuous values for Regression, labels for Clustering, etc. There are two broad ways of generating predictions (i) predict by batch; and (ii) predict in real-time. This tutorial will show how you can deploy your machine learning models as API to predict in real-time.
Now that we understand why deployment is necessary and we have everything we need to create an API i.e. Trained Model Pipeline as a pickle file. Creating an API is extremely simple using FastAPI.
The first few lines of the code are simple imports. Line 8 is initializing an app by calling FastAPI() . Line 11 is loading the trained model diamond-pipeline from your disk (Your script must be in the same folder as the file). Line 15–20 is defining a function called predict which will take the input and internally uses PyCaret’s predict_model function to generate predictions and return the value as a dictionary (Line 20).
You can then run this script by running the following command in your command prompt. You must be in the same directory as the python script and the model pickle file is, before executing this command.
uvicorn main:app --reload
This will initialize an API service on your localhost. On your browser type http://localhost:8000/docs and it should show something like this:
Click on green POST button and it will be open a form like this:
Click on “Try it out” on the top right corner and fill in some values in the form and click on “Execute”. If you have done everything correctly, you will see this response:
Notice that under the response body we have a prediction value of 5396 (this is based on values I entered in the form). This means that given all the attributes you entered, the predicted price of this diamond is $5,396.
This is great, this shows that our API is working. Now we can use the requests library in Python or any other language to connect to API and generate predictions. I have created the script shown below for that:
Let’s see this function in action:
Notice that prediction is 5396 that's because I have used the same values here as I have used in the form above. (1.1, ‘Ideal’, ‘H’, ‘SII’, ‘VG’, ‘EX’, ‘GIA’)
I hope that you will appreciate the ease of use and simplicity in PyCaret and FastAPI. In less than 25 lines of code and few minutes of experimentation, I have trained and evaluated multiple models using PyCaret and deployed ML Pipeline using an API.
Next week I will be writing a tutorial to advance deployment to the next level, I will introduce the concepts like Containerization and Dockers in my next tutorial. Please follow me on Medium, LinkedIn, and Twitter to get more updates.
There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository.
To hear more about PyCaret follow us on LinkedIn and Youtube.
Join us on our slack channel. Invite link here.
Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE
DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret
Click on the links below to see the documentation and working examples.
ClassificationRegressionClusteringAnomaly DetectionNatural Language ProcessingAssociation Rule Mining | [
{
"code": null,
"e": 348,
"s": 172,
"text": "This is a step-by-step, beginner-friendly tutorial on how to build an end-to-end Machine Learning Pipeline with PyCaret and deploy it in production as a web API using FastAPI."
},
{
"code": null,
"e": 408,
"s": 348,
"text": "Build an end-to-end machine learning pipeline using PyCaret"
},
{
"code": null,
"e": 474,
"s": 408,
"text": "What is a deployment and why do we deploy machine learning models"
},
{
"code": null,
"e": 542,
"s": 474,
"text": "Develop an API using FastAPI to generate predictions on unseen data"
},
{
"code": null,
"e": 623,
"s": 542,
"text": "Use Python to send a request to API for generating predictions programmatically."
},
{
"code": null,
"e": 753,
"s": 623,
"text": "This tutorial will cover the entire machine learning life cycle at a high level which is broken down into the following sections:"
},
{
"code": null,
"e": 1050,
"s": 753,
"text": "PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to build and deploy end-to-end ML prototypes quickly and efficiently."
},
{
"code": null,
"e": 1218,
"s": 1050,
"text": "PyCaret is an alternate low-code library that can replace hundreds of code lines with few lines only. This makes the experiment cycle exponentially fast and efficient."
},
{
"code": null,
"e": 1539,
"s": 1218,
"text": "PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for deployment. Whether it’s imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it."
},
{
"code": null,
"e": 1592,
"s": 1539,
"text": "To learn more about PyCaret, check out their GitHub."
},
{
"code": null,
"e": 1746,
"s": 1592,
"text": "FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. The key features are:"
},
{
"code": null,
"e": 1885,
"s": 1746,
"text": "Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available."
},
{
"code": null,
"e": 1961,
"s": 1885,
"text": "Fast to code: Increase the speed to develop features by about 200% to 300%."
},
{
"code": null,
"e": 2029,
"s": 1961,
"text": "Easy: Designed to be easy to use and learn. Less time reading docs."
},
{
"code": null,
"e": 2082,
"s": 2029,
"text": "To learn more about FastAPI, check out their GitHub."
},
{
"code": null,
"e": 2245,
"s": 2082,
"text": "Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries."
},
{
"code": null,
"e": 2355,
"s": 2245,
"text": "PyCaret’s default installation is a slim version of pycaret that only installs hard dependencies listed here."
},
{
"code": null,
"e": 2458,
"s": 2355,
"text": "# install slim version (default)pip install pycaret# install the full versionpip install pycaret[full]"
},
{
"code": null,
"e": 2569,
"s": 2458,
"text": "When you install the full version of pycaret, all the optional dependencies as listed here are also installed."
},
{
"code": null,
"e": 2603,
"s": 2569,
"text": "You can install FastAPI from pip."
},
{
"code": null,
"e": 2623,
"s": 2603,
"text": "pip install fastapi"
},
{
"code": null,
"e": 3186,
"s": 2623,
"text": "For this tutorial, I will be using a very popular case study by Darden School of Business, published in Harvard Business. The case is regarding the story of two people who are going to be married in the future. The guy named Greg wanted to buy a ring to propose to a girl named Sarah. The problem is to find the ring Sarah will like, but after a suggestion from his close friend, Greg decides to buy a diamond stone instead so that Sarah can decide her choice. Greg then collects data of 6000 diamonds with their price and attributes like cut, color, shape, etc."
},
{
"code": null,
"e": 3500,
"s": 3186,
"text": "In this tutorial, I will be using a dataset from a very popular case study by the Darden School of Business, published in Harvard Business. The goal of this tutorial is to predict the diamond price based on its attributes like carat weight, cut, color, etc. You can download the dataset from PyCaret’s repository."
},
{
"code": null,
"e": 3595,
"s": 3500,
"text": "# load the dataset from pycaretfrom pycaret.datasets import get_datadata = get_data('diamond')"
},
{
"code": null,
"e": 3752,
"s": 3595,
"text": "Let’s do some quick visualization to assess the relationship of independent features (weight, cut, color, clarity, etc.) with the target variable i.e. Price"
},
{
"code": null,
"e": 4082,
"s": 3752,
"text": "# plot scatter carat_weight and Priceimport plotly.express as pxfig = px.scatter(x=data['Carat Weight'], y=data['Price'], facet_col = data['Cut'], opacity = 0.25, template = 'plotly_dark', trendline='ols', trendline_color_override = 'red', title = 'SARAH GETS A DIAMOND - A CASE STUDY')fig.show()"
},
{
"code": null,
"e": 4135,
"s": 4082,
"text": "Let’s check the distribution of the target variable."
},
{
"code": null,
"e": 4255,
"s": 4135,
"text": "# plot histogramfig = px.histogram(data, x=[\"Price\"], template = 'plotly_dark', title = 'Histogram of Price')fig.show()"
},
{
"code": null,
"e": 4453,
"s": 4255,
"text": "Notice that distribution of Price is right-skewed, we can quickly check to see if log transformation can make Price approximately normal to give fighting chance to algorithms that assume normality."
},
{
"code": null,
"e": 4727,
"s": 4453,
"text": "import numpy as np# create a copy of datadata_copy = data.copy()# create a new feature Log_Pricedata_copy['Log_Price'] = np.log(data['Price'])# plot histogramfig = px.histogram(data_copy, x=[\"Log_Price\"], title = 'Histgram of Log Price', template = 'plotly_dark')fig.show()"
},
{
"code": null,
"e": 4946,
"s": 4727,
"text": "This confirms our hypothesis. The transformation will help us to get away with skewness and make the target variable approximately normal. Based on this, we will transform the Price variable before training our models."
},
{
"code": null,
"e": 5386,
"s": 4946,
"text": "Common to all modules in PyCaret, the setup is the first and the only mandatory step in any machine learning experiment performed in PyCaret. This function takes care of all the data preparation required prior to training models. Besides performing some basic default processing tasks, PyCaret also offers a wide array of pre-processing features. To learn more about all the preprocessing functionalities in PyCaret, you can see this link."
},
{
"code": null,
"e": 5489,
"s": 5386,
"text": "# init setupfrom pycaret.regression import *s = setup(data, target = 'Price', transform_target = True)"
},
{
"code": null,
"e": 5771,
"s": 5489,
"text": "Whenever you initialize the setup function in PyCaret, it profiles the dataset and infers the data types for all input features. In this case, you can see except for Carat Weight all the other features are inferred as categorical, which is correct. You can press enter to continue."
},
{
"code": null,
"e": 6117,
"s": 5771,
"text": "Notice that I have used transform_target = True inside the setup. PyCaret will transform the Price variable behind the scene using box-cox transformation. It affects the distribution of data in a similar way as log transformation (technically different). If you would like to learn more about box-cox transformations, you can refer to this link."
},
{
"code": null,
"e": 6362,
"s": 6117,
"text": "Now that data preparation is done, let’s start the training process by using compare_models functionality. This function trains all the algorithms available in the model library and evaluates multiple performance metrics using cross-validation."
},
{
"code": null,
"e": 6406,
"s": 6362,
"text": "# compare all modelsbest = compare_models()"
},
{
"code": null,
"e": 6641,
"s": 6406,
"text": "The best model based on Mean Absolute Error (MAE) is CatBoost Regressor. MAE using 10-fold cross-validation is $543 compared to the average diamond value of $11,600. This is less than 5%. Not bad for the efforts we have put in so far."
},
{
"code": null,
"e": 6728,
"s": 6641,
"text": "# check the residuals of trained modelplot_model(best, plot = 'residuals_interactive')"
},
{
"code": null,
"e": 6789,
"s": 6728,
"text": "# check feature importanceplot_model(best, plot = 'feature')"
},
{
"code": null,
"e": 6939,
"s": 6789,
"text": "Let’s now finalize the best model i.e. train the best model on the entire dataset including the test set and then save the pipeline as a pickle file."
},
{
"code": null,
"e": 7055,
"s": 6939,
"text": "# finalize the modelfinal_best = finalize_model(best)# save model to disksave_model(final_best, 'diamond-pipeline')"
},
{
"code": null,
"e": 7118,
"s": 7055,
"text": "First, let’s understand why to deploy machine learning models?"
},
{
"code": null,
"e": 7763,
"s": 7118,
"text": "The deployment of machine learning models is the process of making models available in production where web applications, enterprise software, and APIs can consume the trained model by providing new data points and generating predictions. Normally machine learning models are built so that they can be used to predict an outcome (binary value i.e. 1 or 0 for Classification, continuous values for Regression, labels for Clustering, etc. There are two broad ways of generating predictions (i) predict by batch; and (ii) predict in real-time. This tutorial will show how you can deploy your machine learning models as API to predict in real-time."
},
{
"code": null,
"e": 7959,
"s": 7763,
"text": "Now that we understand why deployment is necessary and we have everything we need to create an API i.e. Trained Model Pipeline as a pickle file. Creating an API is extremely simple using FastAPI."
},
{
"code": null,
"e": 8387,
"s": 7959,
"text": "The first few lines of the code are simple imports. Line 8 is initializing an app by calling FastAPI() . Line 11 is loading the trained model diamond-pipeline from your disk (Your script must be in the same folder as the file). Line 15–20 is defining a function called predict which will take the input and internally uses PyCaret’s predict_model function to generate predictions and return the value as a dictionary (Line 20)."
},
{
"code": null,
"e": 8589,
"s": 8387,
"text": "You can then run this script by running the following command in your command prompt. You must be in the same directory as the python script and the model pickle file is, before executing this command."
},
{
"code": null,
"e": 8615,
"s": 8589,
"text": "uvicorn main:app --reload"
},
{
"code": null,
"e": 8758,
"s": 8615,
"text": "This will initialize an API service on your localhost. On your browser type http://localhost:8000/docs and it should show something like this:"
},
{
"code": null,
"e": 8823,
"s": 8758,
"text": "Click on green POST button and it will be open a form like this:"
},
{
"code": null,
"e": 8996,
"s": 8823,
"text": "Click on “Try it out” on the top right corner and fill in some values in the form and click on “Execute”. If you have done everything correctly, you will see this response:"
},
{
"code": null,
"e": 9217,
"s": 8996,
"text": "Notice that under the response body we have a prediction value of 5396 (this is based on values I entered in the form). This means that given all the attributes you entered, the predicted price of this diamond is $5,396."
},
{
"code": null,
"e": 9428,
"s": 9217,
"text": "This is great, this shows that our API is working. Now we can use the requests library in Python or any other language to connect to API and generate predictions. I have created the script shown below for that:"
},
{
"code": null,
"e": 9463,
"s": 9428,
"text": "Let’s see this function in action:"
},
{
"code": null,
"e": 9622,
"s": 9463,
"text": "Notice that prediction is 5396 that's because I have used the same values here as I have used in the form above. (1.1, ‘Ideal’, ‘H’, ‘SII’, ‘VG’, ‘EX’, ‘GIA’)"
},
{
"code": null,
"e": 9873,
"s": 9622,
"text": "I hope that you will appreciate the ease of use and simplicity in PyCaret and FastAPI. In less than 25 lines of code and few minutes of experimentation, I have trained and evaluated multiple models using PyCaret and deployed ML Pipeline using an API."
},
{
"code": null,
"e": 10109,
"s": 9873,
"text": "Next week I will be writing a tutorial to advance deployment to the next level, I will introduce the concepts like Containerization and Dockers in my next tutorial. Please follow me on Medium, LinkedIn, and Twitter to get more updates."
},
{
"code": null,
"e": 10299,
"s": 10109,
"text": "There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository."
},
{
"code": null,
"e": 10361,
"s": 10299,
"text": "To hear more about PyCaret follow us on LinkedIn and Youtube."
},
{
"code": null,
"e": 10409,
"s": 10361,
"text": "Join us on our slack channel. Invite link here."
},
{
"code": null,
"e": 10872,
"s": 10409,
"text": "Build your own AutoML in Power BI using PyCaret 2.0Deploy Machine Learning Pipeline on Azure using DockerDeploy Machine Learning Pipeline on Google Kubernetes EngineDeploy Machine Learning Pipeline on AWS FargateBuild and deploy your first machine learning web appDeploy PyCaret and Streamlit app using AWS Fargate serverlessBuild and deploy machine learning web app using PyCaret and StreamlitDeploy Machine Learning App built using Streamlit and PyCaret on GKE"
},
{
"code": null,
"e": 10963,
"s": 10872,
"text": "DocumentationBlogGitHubStackOverflowInstall PyCaretNotebook TutorialsContribute in PyCaret"
},
{
"code": null,
"e": 11035,
"s": 10963,
"text": "Click on the links below to see the documentation and working examples."
}
] |
MFC - Progress Bars | Besides the Progress control, Visual C++ provides two other progress-oriented controls −
The Microsoft Progress Control Version 5.0
The Microsoft Progress Control Version 6.0
The main difference is in their ability to assume one or two orientations.
Let us look into a simple example.
Step 1 − Right-click on the dialog in the designer window.
Step 2 − Select Insert ActiveX Control.
Step 3 − Select the Microsoft ProgressBar Control 6.0 and click OK
Step 4 − Select the progress bar and set its Orientation in the Properties Window to 1 – ccOrientationVertical
Step 5 − Add control variable for Progress bar.
Step 6 − Add the following code in the OnInitDialog()
m_progBarCtrl.SetScrollRange(0,100,TRUE);
m_progBarCtrl.put_Value(53);
Step 7 − Run this application again and you will see the progress bar in Vertical direction as well.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2156,
"s": 2067,
"text": "Besides the Progress control, Visual C++ provides two other progress-oriented controls −"
},
{
"code": null,
"e": 2199,
"s": 2156,
"text": "The Microsoft Progress Control Version 5.0"
},
{
"code": null,
"e": 2242,
"s": 2199,
"text": "The Microsoft Progress Control Version 6.0"
},
{
"code": null,
"e": 2317,
"s": 2242,
"text": "The main difference is in their ability to assume one or two orientations."
},
{
"code": null,
"e": 2352,
"s": 2317,
"text": "Let us look into a simple example."
},
{
"code": null,
"e": 2411,
"s": 2352,
"text": "Step 1 − Right-click on the dialog in the designer window."
},
{
"code": null,
"e": 2451,
"s": 2411,
"text": "Step 2 − Select Insert ActiveX Control."
},
{
"code": null,
"e": 2518,
"s": 2451,
"text": "Step 3 − Select the Microsoft ProgressBar Control 6.0 and click OK"
},
{
"code": null,
"e": 2630,
"s": 2518,
"text": "Step 4 − Select the progress bar and set its Orientation in the Properties Window to 1 – ccOrientationVertical"
},
{
"code": null,
"e": 2678,
"s": 2630,
"text": "Step 5 − Add control variable for Progress bar."
},
{
"code": null,
"e": 2732,
"s": 2678,
"text": "Step 6 − Add the following code in the OnInitDialog()"
},
{
"code": null,
"e": 2805,
"s": 2732,
"text": "m_progBarCtrl.SetScrollRange(0,100,TRUE); \nm_progBarCtrl.put_Value(53); "
},
{
"code": null,
"e": 2906,
"s": 2805,
"text": "Step 7 − Run this application again and you will see the progress bar in Vertical direction as well."
},
{
"code": null,
"e": 2913,
"s": 2906,
"text": " Print"
},
{
"code": null,
"e": 2924,
"s": 2913,
"text": " Add Notes"
}
] |
Number of Binary Trees for given Preorder Sequence length - GeeksforGeeks | 30 Apr, 2021
Count the number of Binary Tree possible for a given Preorder Sequence length n.Examples:
Input : n = 1
Output : 1
Input : n = 2
Output : 2
Input : n = 3
Output : 5
Background :
In Preorder traversal, we process the root node first, then traverse the left child node and then right child node. For example preorder traversal of below tree is 1 2 4 5 3 6 7
Finding number of trees with given Preorder:
Number of Binary Tree possible if such a traversal length (let’s say n) is given.Let’s take an Example : Given Preorder Sequence –> 2 4 6 8 10 (length 5).
Assume there is only 1 node (that is 2 in this case), So only 1 Binary tree is Possible
Now, assume there are 2 nodes (namely 2 and 4), So only 2 Binary Tree are Possible:
Now, when there are 3 nodes (namely 2, 4 and 6), So Possible Binary tree are 5
Consider 4 nodes (that are 2, 4, 6 and 8), So Possible Binary Tree are 14. Let’s say BT(1) denotes number of Binary tree for 1 node. (We assume BT(0)=1) BT(4) = BT(0) * BT(3) + BT(1) * BT(2) + BT(2) * BT(1) + BT(3) * BT(0) BT(4) = 1 * 5 + 1 * 2 + 2 * 1 + 5 * 1 = 14
Similarly, considering all the 5 nodes (2, 4, 6, 8 and 10). Possible number of Binary Tree are: BT(5) = BT(0) * BT(4) + BT(1) * BT(3) + BT(2) * BT(2) + BT(3) * BT(1) + BT(4) * BT(0) BT(5) = 1 * 14 + 1 * 5 + 2 * 2 + 5 * 1 + 14 * 1 = 42
Hence, Total binary Tree for Pre-order sequence of length 5 is 42.We use Dynamic programming to calculate the possible number of Binary Tree. We take one node at a time and calculate the possible Trees using previously calculated Trees.
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to count possible binary trees// using dynamic programming#include <bits/stdc++.h>using namespace std; int countTrees(int n){ // Array to store number of Binary tree // for every count of nodes int BT[n + 1]; memset(BT, 0, sizeof(BT)); BT[0] = BT[1] = 1; // Start finding from 2 nodes, since // already know for 1 node. for (int i = 2; i <= n; ++i) for (int j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n];} // Driver codeint main(){ int n = 5; cout << "Total Possible Binary Trees are : " << countTrees(n) << endl; return 0;}
// Java Program to count// possible binary trees// using dynamic programmingimport java.io.*; class GFG{static int countTrees(int n){ // Array to store number // of Binary tree for // every count of nodes int BT[] = new int[n + 1]; for(int i = 0; i <= n; i++) BT[i] = 0; BT[0] = BT[1] = 1; // Start finding from 2 // nodes, since already // know for 1 node. for (int i = 2; i <= n; ++i) for (int j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n];} // Driver codepublic static void main (String[] args){int n = 5;System.out.println("Total Possible " + "Binary Trees are : " + countTrees(n));}} // This code is contributed by anuj_67.
# Python3 Program to count possible binary# trees using dynamic programming def countTrees(n) : # Array to store number of Binary # tree for every count of nodes BT = [0] * (n + 1) BT[0] = BT[1] = 1 # Start finding from 2 nodes, since # already know for 1 node. for i in range(2, n + 1): for j in range(i): BT[i] += BT[j] * BT[i - j - 1] return BT[n] # Driver Codeif __name__ == '__main__': n = 5 print("Total Possible Binary Trees are : ", countTrees(n)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# Program to count// possible binary trees// using dynamic programmingusing System; class GFG{static int countTrees(int n){ // Array to store number // of Binary tree for // every count of nodes int []BT = new int[n + 1]; for(int i = 0; i <= n; i++) BT[i] = 0; BT[0] = BT[1] = 1; // Start finding from 2 // nodes, since already // know for 1 node. for (int i = 2; i <= n; ++i) for (int j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n];} // Driver codestatic public void Main (String []args){ int n = 5; Console.WriteLine("Total Possible " + "Binary Trees are : " + countTrees(n));}} // This code is contributed// by Arnab Kundu
<?php// PHP Program to count possible binary// trees using dynamic programming function countTrees($n){ // Array to store number of Binary // tree for every count of nodes $BT[$n + 1] = array(); $BT = array_fill(0, $n + 1, NULL); $BT[0] = $BT[1] = 1; // Start finding from 2 nodes, since // already know for 1 node. for ($i = 2; $i <= $n; ++$i) for ($j = 0; $j < $i; $j++) $BT[$i] += $BT[$j] * $BT[$i - $j - 1]; return $BT[$n];} // Driver code$n = 5;echo "Total Possible Binary Trees are : ", countTrees($n), "\n"; // This code is contributed by ajit.?>
<script> // Javascript Program to count // possible binary trees // using dynamic programming function countTrees(n) { // Array to store number // of Binary tree for // every count of nodes let BT = new Array(n + 1); for(let i = 0; i <= n; i++) BT[i] = 0; BT[0] = BT[1] = 1; // Start finding from 2 // nodes, since already // know for 1 node. for (let i = 2; i <= n; ++i) for (let j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n]; } let n = 5; document.write("Total Possible " + "Binary Trees are : " + countTrees(n)); </script>
Output:
Total Possible Binary Trees are : 42
Alternative : This can also be done using Catalan number Cn = (2n)!/(n+1)!*n!For n = 0, 1, 2, 3, ... values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees.This article is contributed by Shubham Rana. 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.
vt_m
andrew1234
jit_t
SHUBHAMSINGH10
divyesh072019
catalan
Combinatorial
Tree
Combinatorial
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Factorial of a large number
Count ways to reach the nth stair using step 1, 2 or 3
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion | [
{
"code": null,
"e": 35848,
"s": 35820,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 35940,
"s": 35848,
"text": "Count the number of Binary Tree possible for a given Preorder Sequence length n.Examples: "
},
{
"code": null,
"e": 36017,
"s": 35940,
"text": "Input : n = 1\nOutput : 1\n\nInput : n = 2\nOutput : 2\n\nInput : n = 3\nOutput : 5"
},
{
"code": null,
"e": 36034,
"s": 36021,
"text": "Background :"
},
{
"code": null,
"e": 36214,
"s": 36034,
"text": "In Preorder traversal, we process the root node first, then traverse the left child node and then right child node. For example preorder traversal of below tree is 1 2 4 5 3 6 7 "
},
{
"code": null,
"e": 36261,
"s": 36216,
"text": "Finding number of trees with given Preorder:"
},
{
"code": null,
"e": 36418,
"s": 36261,
"text": "Number of Binary Tree possible if such a traversal length (let’s say n) is given.Let’s take an Example : Given Preorder Sequence –> 2 4 6 8 10 (length 5). "
},
{
"code": null,
"e": 36506,
"s": 36418,
"text": "Assume there is only 1 node (that is 2 in this case), So only 1 Binary tree is Possible"
},
{
"code": null,
"e": 36590,
"s": 36506,
"text": "Now, assume there are 2 nodes (namely 2 and 4), So only 2 Binary Tree are Possible:"
},
{
"code": null,
"e": 36669,
"s": 36590,
"text": "Now, when there are 3 nodes (namely 2, 4 and 6), So Possible Binary tree are 5"
},
{
"code": null,
"e": 36935,
"s": 36669,
"text": "Consider 4 nodes (that are 2, 4, 6 and 8), So Possible Binary Tree are 14. Let’s say BT(1) denotes number of Binary tree for 1 node. (We assume BT(0)=1) BT(4) = BT(0) * BT(3) + BT(1) * BT(2) + BT(2) * BT(1) + BT(3) * BT(0) BT(4) = 1 * 5 + 1 * 2 + 2 * 1 + 5 * 1 = 14"
},
{
"code": null,
"e": 37170,
"s": 36935,
"text": "Similarly, considering all the 5 nodes (2, 4, 6, 8 and 10). Possible number of Binary Tree are: BT(5) = BT(0) * BT(4) + BT(1) * BT(3) + BT(2) * BT(2) + BT(3) * BT(1) + BT(4) * BT(0) BT(5) = 1 * 14 + 1 * 5 + 2 * 2 + 5 * 1 + 14 * 1 = 42"
},
{
"code": null,
"e": 37411,
"s": 37172,
"text": "Hence, Total binary Tree for Pre-order sequence of length 5 is 42.We use Dynamic programming to calculate the possible number of Binary Tree. We take one node at a time and calculate the possible Trees using previously calculated Trees. "
},
{
"code": null,
"e": 37415,
"s": 37411,
"text": "C++"
},
{
"code": null,
"e": 37420,
"s": 37415,
"text": "Java"
},
{
"code": null,
"e": 37428,
"s": 37420,
"text": "Python3"
},
{
"code": null,
"e": 37431,
"s": 37428,
"text": "C#"
},
{
"code": null,
"e": 37435,
"s": 37431,
"text": "PHP"
},
{
"code": null,
"e": 37446,
"s": 37435,
"text": "Javascript"
},
{
"code": "// C++ Program to count possible binary trees// using dynamic programming#include <bits/stdc++.h>using namespace std; int countTrees(int n){ // Array to store number of Binary tree // for every count of nodes int BT[n + 1]; memset(BT, 0, sizeof(BT)); BT[0] = BT[1] = 1; // Start finding from 2 nodes, since // already know for 1 node. for (int i = 2; i <= n; ++i) for (int j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n];} // Driver codeint main(){ int n = 5; cout << \"Total Possible Binary Trees are : \" << countTrees(n) << endl; return 0;}",
"e": 38068,
"s": 37446,
"text": null
},
{
"code": "// Java Program to count// possible binary trees// using dynamic programmingimport java.io.*; class GFG{static int countTrees(int n){ // Array to store number // of Binary tree for // every count of nodes int BT[] = new int[n + 1]; for(int i = 0; i <= n; i++) BT[i] = 0; BT[0] = BT[1] = 1; // Start finding from 2 // nodes, since already // know for 1 node. for (int i = 2; i <= n; ++i) for (int j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n];} // Driver codepublic static void main (String[] args){int n = 5;System.out.println(\"Total Possible \" + \"Binary Trees are : \" + countTrees(n));}} // This code is contributed by anuj_67.",
"e": 38828,
"s": 38068,
"text": null
},
{
"code": "# Python3 Program to count possible binary# trees using dynamic programming def countTrees(n) : # Array to store number of Binary # tree for every count of nodes BT = [0] * (n + 1) BT[0] = BT[1] = 1 # Start finding from 2 nodes, since # already know for 1 node. for i in range(2, n + 1): for j in range(i): BT[i] += BT[j] * BT[i - j - 1] return BT[n] # Driver Codeif __name__ == '__main__': n = 5 print(\"Total Possible Binary Trees are : \", countTrees(n)) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 39463,
"s": 38828,
"text": null
},
{
"code": "// C# Program to count// possible binary trees// using dynamic programmingusing System; class GFG{static int countTrees(int n){ // Array to store number // of Binary tree for // every count of nodes int []BT = new int[n + 1]; for(int i = 0; i <= n; i++) BT[i] = 0; BT[0] = BT[1] = 1; // Start finding from 2 // nodes, since already // know for 1 node. for (int i = 2; i <= n; ++i) for (int j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n];} // Driver codestatic public void Main (String []args){ int n = 5; Console.WriteLine(\"Total Possible \" + \"Binary Trees are : \" + countTrees(n));}} // This code is contributed// by Arnab Kundu",
"e": 40249,
"s": 39463,
"text": null
},
{
"code": "<?php// PHP Program to count possible binary// trees using dynamic programming function countTrees($n){ // Array to store number of Binary // tree for every count of nodes $BT[$n + 1] = array(); $BT = array_fill(0, $n + 1, NULL); $BT[0] = $BT[1] = 1; // Start finding from 2 nodes, since // already know for 1 node. for ($i = 2; $i <= $n; ++$i) for ($j = 0; $j < $i; $j++) $BT[$i] += $BT[$j] * $BT[$i - $j - 1]; return $BT[$n];} // Driver code$n = 5;echo \"Total Possible Binary Trees are : \", countTrees($n), \"\\n\"; // This code is contributed by ajit.?>",
"e": 40891,
"s": 40249,
"text": null
},
{
"code": "<script> // Javascript Program to count // possible binary trees // using dynamic programming function countTrees(n) { // Array to store number // of Binary tree for // every count of nodes let BT = new Array(n + 1); for(let i = 0; i <= n; i++) BT[i] = 0; BT[0] = BT[1] = 1; // Start finding from 2 // nodes, since already // know for 1 node. for (let i = 2; i <= n; ++i) for (let j = 0; j < i; j++) BT[i] += BT[j] * BT[i - j - 1]; return BT[n]; } let n = 5; document.write(\"Total Possible \" + \"Binary Trees are : \" + countTrees(n)); </script>",
"e": 41618,
"s": 40891,
"text": null
},
{
"code": null,
"e": 41628,
"s": 41618,
"text": "Output: "
},
{
"code": null,
"e": 41665,
"s": 41628,
"text": "Total Possible Binary Trees are : 42"
},
{
"code": null,
"e": 42301,
"s": 41665,
"text": "Alternative : This can also be done using Catalan number Cn = (2n)!/(n+1)!*n!For n = 0, 1, 2, 3, ... values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, .... So are numbers of Binary Search Trees.This article is contributed by Shubham Rana. 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": 42306,
"s": 42301,
"text": "vt_m"
},
{
"code": null,
"e": 42317,
"s": 42306,
"text": "andrew1234"
},
{
"code": null,
"e": 42323,
"s": 42317,
"text": "jit_t"
},
{
"code": null,
"e": 42338,
"s": 42323,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 42352,
"s": 42338,
"text": "divyesh072019"
},
{
"code": null,
"e": 42360,
"s": 42352,
"text": "catalan"
},
{
"code": null,
"e": 42374,
"s": 42360,
"text": "Combinatorial"
},
{
"code": null,
"e": 42379,
"s": 42374,
"text": "Tree"
},
{
"code": null,
"e": 42393,
"s": 42379,
"text": "Combinatorial"
},
{
"code": null,
"e": 42398,
"s": 42393,
"text": "Tree"
},
{
"code": null,
"e": 42496,
"s": 42398,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42556,
"s": 42496,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 42594,
"s": 42556,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 42671,
"s": 42594,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 42699,
"s": 42671,
"text": "Factorial of a large number"
},
{
"code": null,
"e": 42754,
"s": 42699,
"text": "Count ways to reach the nth stair using step 1, 2 or 3"
},
{
"code": null,
"e": 42804,
"s": 42754,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 42839,
"s": 42804,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 42873,
"s": 42839,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 42902,
"s": 42873,
"text": "AVL Tree | Set 1 (Insertion)"
}
] |
Redis - Set Srandmember Command | Redis SRANDMEMBER command is used to get a random member from set stored at specified key. If called with the additional count argument, return an array of count distinct elements if count is positive. If called with a negative count the behavior changes and the command is allowed to return the same element multiple times. In this case the numer of returned elements is the absolute value of the specified count.
String reply, without the additional count argument. The command returns a Bulk Reply with the randomly selected element, or nil when the key does not exist. Array reply, when the additional count argument is passed the command returns an array of elements, or an empty array when the key does not exist.
Following is the basic syntax of Redis SRANDMEMBER command.
redis 127.0.0.1:6379> SRANDMEMBER KEY [count]
redis 127.0.0.1:6379> SADD myset1 "hello"
(integer) 1
redis 127.0.0.1:6379> SADD myset1 "world"
(integer) 1
redis 127.0.0.1:6379> SADD myset1 "bar"
(integer) 1
redis 127.0.0.1:6379> SRANDMEMBER myset1
"bar"
redis 127.0.0.1:6379> SRANDMEMBER myset1 2
1) "Hello"
2) "world"
22 Lectures
40 mins
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2460,
"s": 2045,
"text": "Redis SRANDMEMBER command is used to get a random member from set stored at specified key. If called with the additional count argument, return an array of count distinct elements if count is positive. If called with a negative count the behavior changes and the command is allowed to return the same element multiple times. In this case the numer of returned elements is the absolute value of the specified count."
},
{
"code": null,
"e": 2765,
"s": 2460,
"text": "String reply, without the additional count argument. The command returns a Bulk Reply with the randomly selected element, or nil when the key does not exist. Array reply, when the additional count argument is passed the command returns an array of elements, or an empty array when the key does not exist."
},
{
"code": null,
"e": 2825,
"s": 2765,
"text": "Following is the basic syntax of Redis SRANDMEMBER command."
},
{
"code": null,
"e": 2873,
"s": 2825,
"text": "redis 127.0.0.1:6379> SRANDMEMBER KEY [count] \n"
},
{
"code": null,
"e": 3156,
"s": 2873,
"text": "redis 127.0.0.1:6379> SADD myset1 \"hello\" \n(integer) 1 \nredis 127.0.0.1:6379> SADD myset1 \"world\" \n(integer) 1 \nredis 127.0.0.1:6379> SADD myset1 \"bar\" \n(integer) 1 \nredis 127.0.0.1:6379> SRANDMEMBER myset1 \n\"bar\" \nredis 127.0.0.1:6379> SRANDMEMBER myset1 2 \n1) \"Hello\" \n2) \"world\"\n"
},
{
"code": null,
"e": 3188,
"s": 3156,
"text": "\n 22 Lectures \n 40 mins\n"
},
{
"code": null,
"e": 3208,
"s": 3188,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 3215,
"s": 3208,
"text": " Print"
},
{
"code": null,
"e": 3226,
"s": 3215,
"text": " Add Notes"
}
] |
ASP.NET - Ad Rotator | The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that the link should follow in the AdvertisementFile and the Target property respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />
Before going into the details of the AdRotator control and its properties, let us look into the construction of the advertisement file.
The advertisement file is an XML file, which contains the information about the advertisements to be displayed.
Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-based markup language that enables you to store data in a structured format by using meaningful tags. The term 'extensible' implies that you can extend your ability to describe a document by defining meaningful tags for the application.
XML is not a language in itself, like HTML, but a set of rules for creating new markup languages. It is a meta-markup language. It allows developers to create custom tag sets for special uses. It structures, stores, and transports the information.
Following is an example of XML file:
<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a structured text file with well-defined tags delineating the data. There are the following standard XML elements that are commonly used in the advertisement file:
Apart from these tags, customs tags with custom attributes could also be included. The following code illustrates an advertisement file ads.xml:
<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>
<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>
<Ad>
<ImageUrl>rose4.jpg</ImageUrl>
<NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>
The AdRotator class is derived from the WebControl class and inherits its properties. Apart from those, the AdRotator class has the following properties:
Following are the important events of the AdRotator class:
Create a new web page and place an AdRotator control on it.
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile ="~/ads.xml" onadcreated="AdRotator1_AdCreated" />
</div>
</form>
The ads.xml file and the image files should be located in the root directory of the web site.
Try to execute the above application and observe that each time the page is reloaded, the ad is changed.
51 Lectures
5.5 hours
Anadi Sharma
44 Lectures
4.5 hours
Kaushik Roy Chowdhury
42 Lectures
18 hours
SHIVPRASAD KOIRALA
57 Lectures
3.5 hours
University Code
40 Lectures
2.5 hours
University Code
138 Lectures
9 hours
Bhrugen Patel
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2534,
"s": 2347,
"text": "The AdRotator control randomly selects banner graphics from a list, which is specified in an external XML schedule file. This external XML schedule file is called the advertisement file."
},
{
"code": null,
"e": 2715,
"s": 2534,
"text": "The AdRotator control allows you to specify the advertisement file and the type of window that the link should follow in the AdvertisementFile and the Target property respectively."
},
{
"code": null,
"e": 2770,
"s": 2715,
"text": "The basic syntax of adding an AdRotator is as follows:"
},
{
"code": null,
"e": 2859,
"s": 2770,
"text": "<asp:AdRotator runat = \"server\" AdvertisementFile = \"adfile.xml\" Target = \"_blank\" />"
},
{
"code": null,
"e": 2995,
"s": 2859,
"text": "Before going into the details of the AdRotator control and its properties, let us look into the construction of the advertisement file."
},
{
"code": null,
"e": 3107,
"s": 2995,
"text": "The advertisement file is an XML file, which contains the information about the advertisements to be displayed."
},
{
"code": null,
"e": 3434,
"s": 3107,
"text": "Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-based markup language that enables you to store data in a structured format by using meaningful tags. The term 'extensible' implies that you can extend your ability to describe a document by defining meaningful tags for the application."
},
{
"code": null,
"e": 3682,
"s": 3434,
"text": "XML is not a language in itself, like HTML, but a set of rules for creating new markup languages. It is a meta-markup language. It allows developers to create custom tag sets for special uses. It structures, stores, and transports the information."
},
{
"code": null,
"e": 3719,
"s": 3682,
"text": "Following is an example of XML file:"
},
{
"code": null,
"e": 3871,
"s": 3719,
"text": "<BOOK>\n <NAME> Learn XML </NAME>\n <AUTHOR> Samuel Peterson </AUTHOR>\n <PUBLISHER> NSS Publications </PUBLISHER>\n <PRICE> $30.00</PRICE>\n</BOOK>"
},
{
"code": null,
"e": 4090,
"s": 3871,
"text": "Like all XML files, the advertisement file needs to be a structured text file with well-defined tags delineating the data. There are the following standard XML elements that are commonly used in the advertisement file:"
},
{
"code": null,
"e": 4235,
"s": 4090,
"text": "Apart from these tags, customs tags with custom attributes could also be included. The following code illustrates an advertisement file ads.xml:"
},
{
"code": null,
"e": 5271,
"s": 4235,
"text": "<Advertisements>\n <Ad>\n <ImageUrl>rose1.jpg</ImageUrl>\n <NavigateUrl>http://www.1800flowers.com</NavigateUrl>\n <AlternateText>\n Order flowers, roses, gifts and more\n </AlternateText>\n <Impressions>20</Impressions>\n <Keyword>flowers</Keyword>\n </Ad>\n\n <Ad>\n <ImageUrl>rose2.jpg</ImageUrl>\n <NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>\n <AlternateText>Order roses and flowers</AlternateText>\n <Impressions>20</Impressions>\n <Keyword>gifts</Keyword>\n </Ad>\n\n <Ad>\n <ImageUrl>rose3.jpg</ImageUrl>\n <NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>\n <AlternateText>Send flowers to Russia</AlternateText>\n <Impressions>20</Impressions>\n <Keyword>russia</Keyword>\n </Ad>\n\n <Ad>\n <ImageUrl>rose4.jpg</ImageUrl>\n <NavigateUrl>http://www.edibleblooms.com</NavigateUrl>\n <AlternateText>Edible Blooms</AlternateText>\n <Impressions>20</Impressions>\n <Keyword>gifts</Keyword>\n </Ad>\n</Advertisements>"
},
{
"code": null,
"e": 5425,
"s": 5271,
"text": "The AdRotator class is derived from the WebControl class and inherits its properties. Apart from those, the AdRotator class has the following properties:"
},
{
"code": null,
"e": 5484,
"s": 5425,
"text": "Following are the important events of the AdRotator class:"
},
{
"code": null,
"e": 5544,
"s": 5484,
"text": "Create a new web page and place an AdRotator control on it."
},
{
"code": null,
"e": 5726,
"s": 5544,
"text": "<form id=\"form1\" runat=\"server\">\n <div>\n <asp:AdRotator ID=\"AdRotator1\" runat=\"server\" AdvertisementFile =\"~/ads.xml\" onadcreated=\"AdRotator1_AdCreated\" />\n </div>\n</form>"
},
{
"code": null,
"e": 5820,
"s": 5726,
"text": "The ads.xml file and the image files should be located in the root directory of the web site."
},
{
"code": null,
"e": 5925,
"s": 5820,
"text": "Try to execute the above application and observe that each time the page is reloaded, the ad is changed."
},
{
"code": null,
"e": 5960,
"s": 5925,
"text": "\n 51 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5974,
"s": 5960,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6009,
"s": 5974,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6032,
"s": 6009,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6066,
"s": 6032,
"text": "\n 42 Lectures \n 18 hours \n"
},
{
"code": null,
"e": 6086,
"s": 6066,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 6121,
"s": 6086,
"text": "\n 57 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6138,
"s": 6121,
"text": " University Code"
},
{
"code": null,
"e": 6173,
"s": 6138,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6190,
"s": 6173,
"text": " University Code"
},
{
"code": null,
"e": 6224,
"s": 6190,
"text": "\n 138 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6239,
"s": 6224,
"text": " Bhrugen Patel"
},
{
"code": null,
"e": 6246,
"s": 6239,
"text": " Print"
},
{
"code": null,
"e": 6257,
"s": 6246,
"text": " Add Notes"
}
] |
Calculate the Number of Months between two specific dates in SQL - GeeksforGeeks | 26 Apr, 2021
In this article, we will discuss the overview of SQL Query to Calculate the Number of Months between two specific dates and will implement with the help of an example for better understanding. Let’s discuss it step by step.
Overview :Here we will see, how to calculate the number of months between the two given dates with the help of SQL query using the DATEDIFF() function. For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“. There are the following steps to implement SQL Query to Calculate the Number of Months between two specific dates as follows.
Step-1: Creating the Database :Use the below SQL statement to create a database called geeks as follows.
CREATE DATABASE geeks;
Step-2: Using the Database :Use the below SQL statement to switch the database context to geeks as follows.
USE geeks;
Step-3: Table Definition :We have the following demo table in our geeks database.
CREATE TABLE demo_orders
(
ORDER_ID INT IDENTITY(1,1) PRIMARY KEY,
--IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL.
--Starts from 1 and increases by 1 with each inserted row.
ITEM_NAME VARCHAR(30) NOT NULL,
ORDER_DATE DATE
);
Step-4: Verifying :You can use the below statement to query the description of the created table:
EXEC SP_COLUMNS demo_orders;
Output :
Step-5: Adding data to the table :Use the below statement to add data to the demo_orders table as follows.
INSERT INTO demo_orders
--no need to mention columns explicitly as we are inserting into all columns and ID gets
--automatically incremented.
VALUES
('Maserati', '2007-10-03'),
('BMW', '2010-07-23'),
('Mercedes Benz', '2012-11-12'),
('Ferrari', '2016-05-09'),
('Lamborghini', '2020-10-20');
Step-6: Verifying :To verify the contents of the table use the below statement as follows.
SELECT * FROM demo_orders;
Output :
Step-7: SQL Query to Calculate the Number of Months between two specific dates :Now let’s find the number of months between the dates of an order of ‘Maserati’ and ‘Ferrari’ in the table using the DATEDIFF() function. Below is a syntax for the DATEDIFF() function.
DATEDIFF(day/month/year, <start_date>, <end_date>);
Example –
DECLARE
@start VARCHAR(10) = (
SELECT order_date FROM demo_orders
WHERE item_name = 'Maserati'),
@end VARCHAR(10) = (
SELECT order_date FROM demo_orders
WHERE item_name = 'Ferrari')
--@start variable holds the start date(i.e date of Maserati being purchased).
--@end variable holds the end date (i.e date of Ferrari being purchased).
SELECT DATEDIFF(month, @start, @end) AS number_of_months;
--In place of month we could use year or day and that would give the respective no. of years and
--days in between those dates.
Output :
DBMS-SQL
Picked
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Alter Multiple Columns at Once in SQL Server?
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL | Subquery
SQL | Date functions
SQL Query for Matching Multiple Values in the Same Column
SQL Query to Convert VARCHAR to INT
SQL | DROP, TRUNCATE | [
{
"code": null,
"e": 24268,
"s": 24240,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 24492,
"s": 24268,
"text": "In this article, we will discuss the overview of SQL Query to Calculate the Number of Months between two specific dates and will implement with the help of an example for better understanding. Let’s discuss it step by step."
},
{
"code": null,
"e": 24874,
"s": 24492,
"text": "Overview :Here we will see, how to calculate the number of months between the two given dates with the help of SQL query using the DATEDIFF() function. For the purpose of demonstration, we will be creating a demo_orders table in a database called “geeks“. There are the following steps to implement SQL Query to Calculate the Number of Months between two specific dates as follows."
},
{
"code": null,
"e": 24979,
"s": 24874,
"text": "Step-1: Creating the Database :Use the below SQL statement to create a database called geeks as follows."
},
{
"code": null,
"e": 25002,
"s": 24979,
"text": "CREATE DATABASE geeks;"
},
{
"code": null,
"e": 25110,
"s": 25002,
"text": "Step-2: Using the Database :Use the below SQL statement to switch the database context to geeks as follows."
},
{
"code": null,
"e": 25121,
"s": 25110,
"text": "USE geeks;"
},
{
"code": null,
"e": 25203,
"s": 25121,
"text": "Step-3: Table Definition :We have the following demo table in our geeks database."
},
{
"code": null,
"e": 25434,
"s": 25203,
"text": "CREATE TABLE demo_orders \n(\nORDER_ID INT IDENTITY(1,1) PRIMARY KEY, \n--IDENTITY(1,1) is same as AUTO_INCREMENT in MySQL.\n--Starts from 1 and increases by 1 with each inserted row.\nITEM_NAME VARCHAR(30) NOT NULL,\nORDER_DATE DATE\n);"
},
{
"code": null,
"e": 25532,
"s": 25434,
"text": "Step-4: Verifying :You can use the below statement to query the description of the created table:"
},
{
"code": null,
"e": 25561,
"s": 25532,
"text": "EXEC SP_COLUMNS demo_orders;"
},
{
"code": null,
"e": 25570,
"s": 25561,
"text": "Output :"
},
{
"code": null,
"e": 25677,
"s": 25570,
"text": "Step-5: Adding data to the table :Use the below statement to add data to the demo_orders table as follows."
},
{
"code": null,
"e": 25969,
"s": 25677,
"text": "INSERT INTO demo_orders \n--no need to mention columns explicitly as we are inserting into all columns and ID gets\n--automatically incremented.\nVALUES\n('Maserati', '2007-10-03'),\n('BMW', '2010-07-23'),\n('Mercedes Benz', '2012-11-12'),\n('Ferrari', '2016-05-09'),\n('Lamborghini', '2020-10-20');"
},
{
"code": null,
"e": 26060,
"s": 25969,
"text": "Step-6: Verifying :To verify the contents of the table use the below statement as follows."
},
{
"code": null,
"e": 26087,
"s": 26060,
"text": "SELECT * FROM demo_orders;"
},
{
"code": null,
"e": 26096,
"s": 26087,
"text": "Output :"
},
{
"code": null,
"e": 26361,
"s": 26096,
"text": "Step-7: SQL Query to Calculate the Number of Months between two specific dates :Now let’s find the number of months between the dates of an order of ‘Maserati’ and ‘Ferrari’ in the table using the DATEDIFF() function. Below is a syntax for the DATEDIFF() function."
},
{
"code": null,
"e": 26413,
"s": 26361,
"text": "DATEDIFF(day/month/year, <start_date>, <end_date>);"
},
{
"code": null,
"e": 26424,
"s": 26413,
"text": "Example – "
},
{
"code": null,
"e": 26961,
"s": 26424,
"text": "DECLARE \n@start VARCHAR(10) = (\n SELECT order_date FROM demo_orders\n WHERE item_name = 'Maserati'),\n@end VARCHAR(10) = (\n SELECT order_date FROM demo_orders\n WHERE item_name = 'Ferrari')\n \n\n--@start variable holds the start date(i.e date of Maserati being purchased).\n\n--@end variable holds the end date (i.e date of Ferrari being purchased).\n\nSELECT DATEDIFF(month, @start, @end) AS number_of_months;\n\n--In place of month we could use year or day and that would give the respective no. of years and \n--days in between those dates."
},
{
"code": null,
"e": 26970,
"s": 26961,
"text": "Output :"
},
{
"code": null,
"e": 26979,
"s": 26970,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 26986,
"s": 26979,
"text": "Picked"
},
{
"code": null,
"e": 26990,
"s": 26986,
"text": "SQL"
},
{
"code": null,
"e": 26994,
"s": 26990,
"text": "SQL"
},
{
"code": null,
"e": 27092,
"s": 26994,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27101,
"s": 27092,
"text": "Comments"
},
{
"code": null,
"e": 27114,
"s": 27101,
"text": "Old Comments"
},
{
"code": null,
"e": 27167,
"s": 27114,
"text": "How to Alter Multiple Columns at Once in SQL Server?"
},
{
"code": null,
"e": 27233,
"s": 27167,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27265,
"s": 27233,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27282,
"s": 27265,
"text": "SQL using Python"
},
{
"code": null,
"e": 27360,
"s": 27282,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27375,
"s": 27360,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27396,
"s": 27375,
"text": "SQL | Date functions"
},
{
"code": null,
"e": 27454,
"s": 27396,
"text": "SQL Query for Matching Multiple Values in the Same Column"
},
{
"code": null,
"e": 27490,
"s": 27454,
"text": "SQL Query to Convert VARCHAR to INT"
}
] |
Python 3 - Tkinter tkMessageBox | The tkMessageBox module is used to display message boxes in your applications. This module provides a number of functions that you can use to display an appropriate message.
Some of these functions are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, and askretryignore.
Here is the simple syntax to create this widget −
tkMessageBox.FunctionName(title, message [, options])
FunctionName − This is the name of the appropriate message box function.
FunctionName − This is the name of the appropriate message box function.
title − This is the text to be displayed in the title bar of a message box.
title − This is the text to be displayed in the title bar of a message box.
message − This is the text to be displayed as a message.
message − This is the text to be displayed as a message.
options − options are alternative choices that you may use to tailor a standard message box. Some of the options that you can use are default and parent. The default option is used to specify the default button, such as ABORT, RETRY, or IGNORE in the message box. The parent option is used to specify the window on top of which the message box is to be displayed.
options − options are alternative choices that you may use to tailor a standard message box. Some of the options that you can use are default and parent. The default option is used to specify the default button, such as ABORT, RETRY, or IGNORE in the message box. The parent option is used to specify the window on top of which the message box is to be displayed.
You could use one of the following functions with dialogue box −
showinfo()
showinfo()
showwarning()
showwarning()
showerror ()
showerror ()
askquestion()
askquestion()
askokcancel()
askokcancel()
askyesno ()
askyesno ()
askretrycancel ()
askretrycancel ()
Try the following example yourself −
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def hello():
messagebox.showinfo("Say Hello", "Hello World")
B1 = Button(top, text = "Say Hello", command = hello)
B1.place(x = 35,y = 50)
top.mainloop()
When the above code is executed, it produces the following result −
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": 2514,
"s": 2340,
"text": "The tkMessageBox module is used to display message boxes in your applications. This module provides a number of functions that you can use to display an appropriate message."
},
{
"code": null,
"e": 2632,
"s": 2514,
"text": "Some of these functions are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, and askretryignore."
},
{
"code": null,
"e": 2682,
"s": 2632,
"text": "Here is the simple syntax to create this widget −"
},
{
"code": null,
"e": 2737,
"s": 2682,
"text": "tkMessageBox.FunctionName(title, message [, options])\n"
},
{
"code": null,
"e": 2810,
"s": 2737,
"text": "FunctionName − This is the name of the appropriate message box function."
},
{
"code": null,
"e": 2883,
"s": 2810,
"text": "FunctionName − This is the name of the appropriate message box function."
},
{
"code": null,
"e": 2959,
"s": 2883,
"text": "title − This is the text to be displayed in the title bar of a message box."
},
{
"code": null,
"e": 3035,
"s": 2959,
"text": "title − This is the text to be displayed in the title bar of a message box."
},
{
"code": null,
"e": 3092,
"s": 3035,
"text": "message − This is the text to be displayed as a message."
},
{
"code": null,
"e": 3149,
"s": 3092,
"text": "message − This is the text to be displayed as a message."
},
{
"code": null,
"e": 3513,
"s": 3149,
"text": "options − options are alternative choices that you may use to tailor a standard message box. Some of the options that you can use are default and parent. The default option is used to specify the default button, such as ABORT, RETRY, or IGNORE in the message box. The parent option is used to specify the window on top of which the message box is to be displayed."
},
{
"code": null,
"e": 3877,
"s": 3513,
"text": "options − options are alternative choices that you may use to tailor a standard message box. Some of the options that you can use are default and parent. The default option is used to specify the default button, such as ABORT, RETRY, or IGNORE in the message box. The parent option is used to specify the window on top of which the message box is to be displayed."
},
{
"code": null,
"e": 3942,
"s": 3877,
"text": "You could use one of the following functions with dialogue box −"
},
{
"code": null,
"e": 3953,
"s": 3942,
"text": "showinfo()"
},
{
"code": null,
"e": 3964,
"s": 3953,
"text": "showinfo()"
},
{
"code": null,
"e": 3978,
"s": 3964,
"text": "showwarning()"
},
{
"code": null,
"e": 3992,
"s": 3978,
"text": "showwarning()"
},
{
"code": null,
"e": 4005,
"s": 3992,
"text": "showerror ()"
},
{
"code": null,
"e": 4018,
"s": 4005,
"text": "showerror ()"
},
{
"code": null,
"e": 4032,
"s": 4018,
"text": "askquestion()"
},
{
"code": null,
"e": 4046,
"s": 4032,
"text": "askquestion()"
},
{
"code": null,
"e": 4060,
"s": 4046,
"text": "askokcancel()"
},
{
"code": null,
"e": 4074,
"s": 4060,
"text": "askokcancel()"
},
{
"code": null,
"e": 4086,
"s": 4074,
"text": "askyesno ()"
},
{
"code": null,
"e": 4098,
"s": 4086,
"text": "askyesno ()"
},
{
"code": null,
"e": 4116,
"s": 4098,
"text": "askretrycancel ()"
},
{
"code": null,
"e": 4134,
"s": 4116,
"text": "askretrycancel ()"
},
{
"code": null,
"e": 4171,
"s": 4134,
"text": "Try the following example yourself −"
},
{
"code": null,
"e": 4440,
"s": 4171,
"text": "# !/usr/bin/python3\nfrom tkinter import *\n\nfrom tkinter import messagebox\n\ntop = Tk()\ntop.geometry(\"100x100\")\ndef hello():\n messagebox.showinfo(\"Say Hello\", \"Hello World\")\n\nB1 = Button(top, text = \"Say Hello\", command = hello)\nB1.place(x = 35,y = 50)\n\ntop.mainloop()"
},
{
"code": null,
"e": 4508,
"s": 4440,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 4545,
"s": 4508,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4561,
"s": 4545,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4594,
"s": 4561,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4613,
"s": 4594,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4648,
"s": 4613,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4670,
"s": 4648,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4704,
"s": 4670,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4732,
"s": 4704,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4767,
"s": 4732,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4781,
"s": 4767,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4814,
"s": 4781,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4831,
"s": 4814,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4838,
"s": 4831,
"text": " Print"
},
{
"code": null,
"e": 4849,
"s": 4838,
"text": " Add Notes"
}
] |
JSF - Quick Guide | JavaServer Faces (JSF) is a MVC web framework that simplifies the construction of User Interfaces (UI) for server-based applications using reusable UI components in a page. JSF provides a facility to connect UI widgets with data sources and to server-side event handlers. The JSF specification defines a set of standard UI components and provides an Application Programming Interface (API) for developing components. JSF enables the reuse and extension of the existing standard UI components.
JSF reduces the effort in creating and maintaining applications, which will run on a Java application server and will render application UI on to a target client. JSF facilitates Web application development by −
Providing reusable UI components
Making easy data transfer between UI components
Managing UI state across multiple server requests
Enabling implementation of custom components
Wiring client-side event to server-side application code
JSF provides the developers with the capability to create Web application from collections of UI components that can render themselves in different ways for multiple client types (for example - HTML browser, wireless, or WAP device).
JSF provides −
Core library
Core library
A set of base UI components - standard HTML input elements
A set of base UI components - standard HTML input elements
Extension of the base UI components to create additional UI component libraries or to extend existing components
Extension of the base UI components to create additional UI component libraries or to extend existing components
Multiple rendering capabilities that enable JSF UI components to render themselves differently depending on the client types
Multiple rendering capabilities that enable JSF UI components to render themselves differently depending on the client types
This chapter will guide you on how to prepare a development environment to start your work with JSF Framework. You will learn how to setup JDK, Eclipse, Maven, and Tomcat on your machine before you set up JSF Framework.
JSF requires JDK 1.5 or higher so the very first requirement is to have JDK installed on your machine.
Follow the given steps to setup your environment to start with JSF application development.
Open console and execute the following Java command.
Let's verify the output for all the operating systems −
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)
If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine.
For example −
Append Java compiler location to System Path.
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. Otherwise, carry out a proper setup according to the given document of the IDE.
All the examples in this tutorial have been written using Eclipse IDE. Hence, we suggest you should have the latest version of Eclipse installed on your machine based on your operating system.
To install Eclipse IDE, download the latest Eclipse binaries with WTP support from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it will display the following result.
*Note − Install m2eclipse plugin to eclipse using the following eclipse software update site
m2eclipse Plugin - https://m2eclipse.sonatype.org/update/.
This plugin enables the developers to run maven commands within eclipse with embedded/external maven installation.
Download Maven 2.2.1 from https://maven.apache.org/download.html
Extract the archive to the directory you wish to install Maven 2.2.1. The subdirectory apache-maven-2.2.1 will be created from the archive.
Add M2_HOME, M2, MAVEN_OPTS to environment variables.
Set the environment variables using system properties.
M2_HOME=C:\Program Files\Apache Software Foundation\apachemaven-2.2.1
M2=%M2_HOME%\bin
MAVEN_OPTS=-Xms256m -Xmx512m
Open command terminal and set environment variables.
export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
export M2=%M2_HOME%\bin
export MAVEN_OPTS=-Xms256m -Xmx512m
Open command terminal and set environment variables.
export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
export M2=%M2_HOME%\bin
export MAVEN_OPTS=-Xms256m -Xmx512m
Now append M2 variable to System Path.
Open console, execute the following mvn command.
Finally, verify the output of the above commands, which should be as shown in the following table.
Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)
Java version: 1.6.0_21
Java home: C:\Program Files\Java\jdk1.6.0_21\jre
Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)
Java version: 1.6.0_21
Java home: C:\Program Files\Java\jdk1.6.0_21\jre
Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)
Java version: 1.6.0_21
Java home: C:\Program Files\Java\jdk1.6.0_21\jre
You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\apache-tomcat-6.0.33 on Windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations.
Tomcat can be started by executing the following commands on Windows machine, or you can simply double-click on startup.bat
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-6.0.33\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine.
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-6.0.33/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it will display the following result.
Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org
Tomcat can be stopped by executing the following commands on Windows machine.
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine.
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
JSF technology is a framework for developing, building server-side User Interface Components and using them in a web application. JSF technology is based on the Model View Controller (MVC) architecture for separating logic from presentation.
MVC design pattern designs an application using three separate modules −
Model
Carries Data and login
View
Shows User Interface
Controller
Handles processing of an application.
The purpose of MVC design pattern is to separate model and presentation enabling developers to focus on their core skills and collaborate more clearly.
Web designers have to concentrate only on view layer rather than model and controller layer. Developers can change the code for model and typically need not change view layer. Controllers are used to process user actions. In this process, layer model and views may be changed.
JSF application is similar to any other Java technology-based web application; it runs in a Java servlet container, and contains −
JavaBeans components as models containing application-specific functionality and data
JavaBeans components as models containing application-specific functionality and data
A custom tag library for representing event handlers and validators
A custom tag library for representing event handlers and validators
A custom tag library for rendering UI components
A custom tag library for rendering UI components
UI components represented as stateful objects on the server
UI components represented as stateful objects on the server
Server-side helper classes
Server-side helper classes
Validators, event handlers, and navigation handlers
Validators, event handlers, and navigation handlers
Application configuration resource file for configuring application resources
Application configuration resource file for configuring application resources
There are controllers which can be used to perform user actions. UI can be created by web page authors and the business logic can be utilized by managed beans.
JSF provides several mechanisms for rendering an individual component. It is upto the web page designer to pick the desired representation, and the application developer doesn't need to know which mechanism was used to render a JSF UI component.
JSF application life cycle consists of six phases which are as follows −
Restore view phase
Apply request values phase; process events
Process validations phase; process events
Update model values phase; process events
Invoke application phase; process events
Render response phase
The six phases show the order in which JSF processes a form. The list shows the phases in their likely order of execution with event processing at each phase.
JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request.
During this phase, JSF builds the view, wires event handlers and validators to UI components and saves the view in the FacesContext instance. The FacesContext instance will now contain all the information required to process a request.
After the component tree is created/restored, each component in the component tree uses the decode method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors.
If any decode methods event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase.
During this phase, JSF processes all validators registered on the component tree. It examines the component attribute rules for the validation and compares these rules to the local value stored for the component.
If the local value is invalid, JSF adds an error message to the FacesContext instance, and the life cycle advances to the render response phase and displays the same page again with the error message.
After the JSF checks that the data is valid, it walks over the component tree and sets the corresponding server-side object properties to the components' local values. JSF will update the bean properties corresponding to the input component's value attribute.
If any updateModels methods called renderResponse on the current FacesContext instance, JSF moves to the render response phase.
During this phase, JSF handles any application-level events, such as submitting a form/linking to another page.
During this phase, JSF asks container/application server to render the page if the application is using JSP pages. For initial request, the components represented on the page will be added to the component tree as JSP container executes the page. If this is not an initial request, the component tree is already built so components need not be added again. In either case, the components will render themselves as the JSP container/Application server traverses the tags in the page.
After the content of the view is rendered, the response state is saved so that subsequent requests can access it and it is available to the restore view phase.
To create a simple JSF application, we'll use maven-archetype-webapp plugin. In the following example, we'll create a maven-based web application project in C:\JSF folder.
Let's open command console, go the C:\ > JSF directory and execute the following mvn command.
C:\JSF>mvn archetype:create
-DgroupId = com.tutorialspoint.test
-DartifactId = helloworld
-DarchetypeArtifactId = maven-archetype-webapp
Maven will start processing and will create the complete java web application project structure.
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'archetype'.
[INFO] -------------------------------------------------------------
[INFO] Building Maven Default Project
[INFO] task-segment: [archetype:create] (aggregator-style)
[INFO] -------------------------------------------------------------
[INFO] [archetype:create {execution: default-cli}]
[INFO] Defaulting package to group ID: com.tutorialspoint.test
[INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp:
checking for updates from central
[INFO] -------------------------------------------------------------
[INFO] Using following parameters for creating project
from Old (1.x) Archetype: maven-archetype-webapp:RELEASE
[INFO] -------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.tutorialspoint.test
[INFO] Parameter: packageName, Value: com.tutorialspoint.test
[INFO] Parameter: package, Value: com.tutorialspoint.test
[INFO] Parameter: artifactId, Value: helloworld
[INFO] Parameter: basedir, Value: C:\JSF
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir:
C:\JSF\helloworld
[INFO] -------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------
[INFO] Total time: 7 seconds
[INFO] Finished at: Mon Nov 05 16:05:04 IST 2012
[INFO] Final Memory: 12M/84M
[INFO] -------------------------------------------------------------
Now go to C:/JSF directory. You'll see a Java web application project created, named helloworld (as specified in artifactId). Maven uses a standard directory layout as shown in the following screenshot.
Using the above example, we can understand the following key concepts.
helloworld
Contains src folder and pom.xml
src/main/wepapp
Contains WEB-INF folder and index.jsp page
src/main/resources
It contains images/properties files (In the above example, we need to create this structure manually)
Add the following JSF dependencies.
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
</dependencies>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Let's open the command console. Go the C:\ > JSF > helloworld directory and execute the following mvn command.
C:\JSF\helloworld>mvn eclipse:eclipse -Dwtpversion = 2.0
Maven will start processing, create the eclipse ready project, and will add wtp capability.
Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/
maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.pom
5K downloaded (maven-compiler-plugin-2.3.1.pom)
Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/
maven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.jar
29K downloaded (maven-compiler-plugin-2.3.1.jar)
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------
[INFO] Building helloworld Maven Webapp
[INFO] task-segment: [eclipse:eclipse]
[INFO] ------------------------------------------------------------
[INFO] Preparing eclipse:eclipse
[INFO] No goals needed for project - skipping
[INFO] [eclipse:eclipse {execution: default-cli}]
[INFO] Adding support for WTP version 2.0.
[INFO] Using Eclipse Workspace: null
[INFO] Adding default classpath container: org.eclipse.jdt.
launching.JRE_CONTAINER
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.pom
12K downloaded (jsf-api-2.1.7.pom)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.pom
10K downloaded (jsf-impl-2.1.7.pom)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.jar
619K downloaded (jsf-api-2.1.7.jar)
Downloading: http://repo.maven.apache.org/
com/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.jar
1916K downloaded (jsf-impl-2.1.7.jar)
[INFO] Wrote settings to C:\JSF\helloworld\.settings\
org.eclipse.jdt.core.prefs
[INFO] Wrote Eclipse project for "helloworld" to C:\JSF\helloworld.
[INFO]
[INFO] -----------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -----------------------------------------------------------
[INFO] Total time: 6 minutes 7 seconds
[INFO] Finished at: Mon Nov 05 16:16:25 IST 2012
[INFO] Final Memory: 10M/89M
[INFO] -----------------------------------------------------------
Following are the steps −
Import project in eclipse using Import wizard.
Import project in eclipse using Import wizard.
Go to File → Import... → Existing project into workspace.
Go to File → Import... → Existing project into workspace.
Select root directory to helloworld.
Select root directory to helloworld.
Keep Copy projects into workspace to be checked.
Keep Copy projects into workspace to be checked.
Click Finish button.
Click Finish button.
Eclipse will import and copy the project in its workspace C:\ → Projects → Data → WorkSpace.
Eclipse will import and copy the project in its workspace C:\ → Projects → Data → WorkSpace.
Locate web.xml in webapp → WEB-INF folder and update it as shown below.
<?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_2_5.xsd"
id = "WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>faces/home.xhtml</welcome-file>
</welcome-file-list>
<!--
FacesServlet is main servlet responsible to handle all request.
It acts as central controller.
This servlet initializes the JSF components before the JSP is displayed.
-->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
Create a package structure under src → main → java as com → tutorialspoint → test. Create HelloWorld.java class in this package. Update the code of HelloWorld.java as shown below.
package com.tutorialspoint.test;
import javax.faces.bean.ManagedBean;
@ManagedBean(name = "helloWorld", eager = true)
public class HelloWorld {
public HelloWorld() {
System.out.println("HelloWorld started!");
}
public String getMessage() {
return "Hello World!";
}
}
Create a page home.xhtml under webapp folder. Update the code of home.xhtml as shown below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>JSF Tutorial!</title>
</head>
<body>
#{helloWorld.getMessage()}
</body>
</html>
Following are the steps.
Select helloworld project in eclipse
Select helloworld project in eclipse
Use Run As wizard
Use Run As wizard
Select Run As → Maven package
Select Run As → Maven package
Maven will start building the project and will create helloworld.war under C:\ → Projects → Data → WorkSpace → helloworld → target folder.
Maven will start building the project and will create helloworld.war under C:\ → Projects → Data → WorkSpace → helloworld → target folder.
[INFO] Scanning for projects...
[INFO] -----------------------------------------------------
[INFO] Building helloworld Maven Webapp
[INFO]
[INFO] Id: com.tutorialspoint.test:helloworld:war:1.0-SNAPSHOT
[INFO] task-segment: [package]
[INFO] -----------------------------------------------------
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] No sources to compile
[INFO] [surefire:test]
[INFO] Surefire report directory:
C:\Projects\Data\WorkSpace\helloworld\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
There are no tests to run.
Results :
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] [war:war]
[INFO] Packaging webapp
[INFO] Assembling webapp[helloworld] in
[C:\Projects\Data\WorkSpace\helloworld\target\helloworld]
[INFO] Processing war project
[INFO] Webapp assembled in[150 msecs]
[INFO] Building war:
C:\Projects\Data\WorkSpace\helloworld\target\helloworld.war
[INFO] ------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------
[INFO] Total time: 3 seconds
[INFO] Finished at: Mon Nov 05 16:34:46 IST 2012
[INFO] Final Memory: 2M/15M
[INFO] ------------------------------------------------
Following are the steps.
Stop the tomcat server.
Stop the tomcat server.
Copy the helloworld.war file to tomcat installation directory → webapps folder.
Copy the helloworld.war file to tomcat installation directory → webapps folder.
Start the tomcat server.
Start the tomcat server.
Look inside webapps directory, there should be a folder helloworld got created.
Look inside webapps directory, there should be a folder helloworld got created.
Now helloworld.war is successfully deployed in Tomcat Webserver root.
Now helloworld.war is successfully deployed in Tomcat Webserver root.
Enter a url in web browser: http://localhost:8080/helloworld/home.jsf to launch the application.
Server name (localhost) and port (8080) may vary as per your tomcat configuration.
Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a Java bean managed by JSF framework. Managed bean contains the getter and setter methods, business logic, or even a backing bean (a bean contains all the HTML form value).
Managed beans works as Model for UI component. Managed Bean can be accessed from JSF page.
In JSF 1.2, a managed bean had to register it in JSF configuration file such as facesconfig.xml. From JSF 2.0 onwards, managed beans can be easily registered using annotations. This approach keeps beans and its registration at one place hence it becomes easier to manage.
<managed-bean>
<managed-bean-name>helloWorld</managed-bean-name>
<managed-bean-class>com.tutorialspoint.test.HelloWorld</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>message</managed-bean-name>
<managed-bean-class>com.tutorialspoint.test.Message</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
@ManagedProperty(value = "#{message}")
private Message message;
...
}
@ManagedBean marks a bean to be a managed bean with the name specified in name attribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case, it would be helloWorld.
Another important attribute is eager. If eager = "true" then managed bean is created before it is requested for the first time otherwise "lazy" initialization is used in which bean will be created only when it is requested.
Scope annotations set the scope into which the managed bean will be placed. If the scope is not specified, then bean will default to request scope. Each scope is briefly discussed in the following table.
@RequestScoped
Bean lives as long as the HTTP request-response lives. It gets created upon a HTTP request and gets destroyed when the HTTP response associated with the HTTP request is finished.
@NoneScoped
Bean lives as long as a single EL evaluation. It gets created upon an EL evaluation and gets destroyed immediately after the EL evaluation.
@ViewScoped
Bean lives as long as the user is interacting with the same JSF view in the browser window/tab. It gets created upon a HTTP request and gets destroyed once the user postbacks to a different view.
@SessionScoped
Bean lives as long as the HTTP session lives. It gets created upon the first HTTP request involving this bean in the session and gets destroyed when the HTTP session is invalidated.
@ApplicationScoped
Bean lives as long as the web application lives. It gets created upon the first HTTP request involving this bean in the application (or when the web application starts up and the eager=true attribute is set in @ManagedBean) and gets destroyed when the web application shuts down.
@CustomScoped
Bean lives as long as the bean's entry in the custom Map, which is created for this scope lives.
JSF is a simple static Dependency Injection (DI) framework. Using @ManagedProperty annotation, a managed bean's property can be injected in another managed bean.
Let us create a test JSF application to test the above annotations for managed beans.
package com.tutorialspoint.test;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
@ManagedBean(name = "helloWorld", eager = true)
@RequestScoped
public class HelloWorld {
@ManagedProperty(value = "#{message}")
private Message messageBean;
private String message;
public HelloWorld() {
System.out.println("HelloWorld started!");
}
public String getMessage() {
if(messageBean != null) {
message = messageBean.getMessage();
}
return message;
}
public void setMessageBean(Message message) {
this.messageBean = message;
}
}
package com.tutorialspoint.test;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
@ManagedBean(name = "message", eager = true)
@RequestScoped
public class Message {
private String message = "Hello World!";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>JSF Tutorial!</title>
</head>
<body>
#{helloWorld.message}
</body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result.
Navigation rules are those rules provided by JSF Framework that describes which view is to be shown when a button or a link is clicked.
Navigation rules can be defined in JSF configuration file named faces-config.xml. They can be defined in managed beans.
Navigation rules can contain conditions based on which the resulted view can be shown. JSF 2.0 provides implicit navigation as well in which there is no need to define navigation rules as such.
JSF 2.0 provides auto view page resolver mechanism named implicit navigation. In this case, you only need to put view name in action attribute and JSF will search the correct view page automatically in the deployed application.
Set view name in action attribute of any JSF UI Component.
<h:form>
<h3>Using JSF outcome</h3>
<h:commandButton action = "page2" value = "Page2" />
</h:form>
Here, when Page2 button is clicked, JSF will resolve the view name, page2 as page2.xhtml extension, and find the corresponding view file page2.xhtml in the current directory.
Define a method in managed bean to return a view name.
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
public String moveToPage1() {
return "page1";
}
}
Get view name in action attribute of any JSF UI Component using managed bean.
<h:form>
<h3> Using Managed Bean</h3>
<h:commandButton action = "#{navigationController.moveToPage1}"
value = "Page1" /glt;
</h:form>
Here, when Page1 button is clicked, JSF will resolve the view name, page1 as page1.xhtml extension, and find the corresponding view file page1.xhtml in the current directory.
Using managed bean, we can very easily control the navigation. Look at the following code in a managed bean.
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
//this managed property will read value from request parameter pageId
@ManagedProperty(value = "#{param.pageId}")
private String pageId;
//condional navigation based on pageId
//if pageId is 1 show page1.xhtml,
//if pageId is 2 show page2.xhtml
//else show home.xhtml
public String showPage() {
if(pageId == null) {
return "home";
}
if(pageId.equals("1")) {
return "page1";
}else if(pageId.equals("2")) {
return "page2";
}else {
return "home";
}
}
}
Pass pageId as a request parameter in JSF UI Component.
<h:form>
<h:commandLink action = "#{navigationController.showPage}" value = "Page1">
<f:param name = "pageId" value = "1" />
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}" value = "Page2">
<f:param name = "pageId" value = "2" />
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}" value = "Home">
<f:param name = "pageId" value = "3" />
</h:commandLink>
</h:form>
Here, when "Page1" button is clicked.
JSF will create a request with parameter pageId = 1
JSF will create a request with parameter pageId = 1
Then JSF will pass this parameter to managed property pageId of navigationController
Then JSF will pass this parameter to managed property pageId of navigationController
Now navigationController.showPage() is called which will return view as page1 after checking the pageId
Now navigationController.showPage() is called which will return view as page1 after checking the pageId
JSF will resolve the view name, page1 as page1.xhtml extension
JSF will resolve the view name, page1 as page1.xhtml extension
Find the corresponding view file page1.xhtml in the current directory
Find the corresponding view file page1.xhtml in the current directory
JSF provides navigation resolution option even if managed bean different methods returns the same view name.
Look at the following code in a managed bean.
public String processPage1() {
return "page";
}
public String processPage2() {
return "page";
}
To resolve views, define the following navigation rules in faces-config.xml
<navigation-rule>
<from-view-id>home.xhtml</from-view-id>
<navigation-case>
<from-action>#{navigationController.processPage1}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page1.jsf</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page2.jsf</to-view-id>
</navigation-case>
</navigation-rule>
Here, when Page1 button is clicked −
navigationController.processPage1() is called which will return view as page
navigationController.processPage1() is called which will return view as page
JSF will resolve the view name, page1 as view name is page and from-action in faces-config is navigationController.processPage1
JSF will resolve the view name, page1 as view name is page and from-action in faces-config is navigationController.processPage1
Find the corresponding view file page1.xhtml in the current directory
Find the corresponding view file page1.xhtml in the current directory
JSF by default performs a server page forward while navigating to another page and the URL of the application does not change.
To enable the page redirection, append faces-redirect=true at the end of the view name.
<h:form>
<h3>Forward</h3>
<h:commandButton action = "page1" value = "Page1" />
<h3>Redirect</h3>
<h:commandButton action = "page1?faces-redirect = true" value = "Page1" />
</h:form>
Here, when Page1 button under Forward is clicked, you will get the following result.
Here when Page1 button under Redirect is clicked, you will get the following result.
Let us create a test JSF application to test all of the above navigation examples.
package com.tutorialspoint.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
@ManagedBean(name = "navigationController", eager = true)
@RequestScoped
public class NavigationController implements Serializable {
private static final long serialVersionUID = 1L;
@ManagedProperty(value = "#{param.pageId}")
private String pageId;
public String moveToPage1() {
return "page1";
}
public String moveToPage2() {
return "page2";
}
public String moveToHomePage() {
return "home";
}
public String processPage1() {
return "page";
}
public String processPage2() {
return "page";
}
public String showPage() {
if(pageId == null) {
return "home";
}
if(pageId.equals("1")) {
return "page1";
}else if(pageId.equals("2")) {
return "page2";
}else {
return "home";
}
}
public String getPageId() {
return pageId;
}
public void setPageId(String pageId) {
this.pageId = pageId;
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<faces-config
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version = "2.0">
<navigation-rule>
<from-view-id>home.xhtml</from-view-id>
<navigation-case>
<from-action>#{navigationController.processPage1}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page1.jsf</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{navigationController.processPage2}</from-action>
<from-outcome>page</from-outcome>
<to-view-id>page2.jsf</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
<h:body>
<h2>This is Page1</h2>
<h:form>
<h:commandButton action = "home?faces-redirect = true"
value = "Back To Home Page" />
</h:form>
</h:body>
</html>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
<h:body>
<h2>This is Page2</h2>
<h:form>
<h:commandButton action = "home?faces-redirect = true"
value = "Back To Home Page" />
</h:form>
</h:body>
</html>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:body>
<h2>Implicit Navigation</h2>
<hr />
<h:form>
<h3>Using Managed Bean</h3>
<h:commandButton action = "#{navigationController.moveToPage1}"
value = "Page1" />
<h3>Using JSF outcome</h3>
<h:commandButton action = "page2" value = "Page2" />
</h:form>
<br/>
<h2>Conditional Navigation</h2>
<hr />
<h:form>
<h:commandLink action = "#{navigationController.showPage}"
value="Page1">
<f:param name = "pageId" value = "1" />
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}"
value="Page2">
<f:param name = "pageId" value = "2" />
</h:commandLink>
<h:commandLink action = "#{navigationController.showPage}"
value = "Home">
<f:param name = "pageId" value = "3" />
</h:commandLink>
</h:form>
<br/>
<h2>"From Action" Navigation</h2>
<hr />
<h:form>
<h:commandLink action = "#{navigationController.processPage1}"
value = "Page1" />
<h:commandLink action = "#{navigationController.processPage2}"
value = "Page2" />
</h:form>
<br/>
<h2>Forward vs Redirection Navigation</h2>
<hr />
<h:form>
<h3>Forward</h3>
<h:commandButton action = "page1" value = "Page1" />
<h3>Redirect</h3>
<h:commandButton action = "page1?faces-redirect = true"
value = "Page1" />
</h:form>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result.
In this chapter, you will learn about various types of basic JSF tags.
JSF provides a standard HTML tag library. These tags get rendered into corresponding html output.
For these tags you need to use the following namespaces of URI in html node.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
Following are the important Basic Tags in JSF 2.0.
Renders a HTML input of type="text", text box.
Renders a HTML input of type="password", text box.
Renders a HTML textarea field.
Renders a HTML input of type="hidden".
Renders a single HTML check box.
Renders a group of HTML check boxes.
Renders a single HTML radio button.
Renders a HTML single list box.
Renders a HTML multiple list box.
Renders a HTML combo box.
Renders a HTML text.
Renders a HTML text. It accepts parameters.
Renders an image.
Includes a CSS style sheet in HTML output.
Includes a script in HTML output.
Renders a HTML input of type="submit" button.
Renders a HTML anchor.
Renders a HTML anchor.
Renders a HTML anchor.
Renders an HTML Table in form of grid.
Renders message for a JSF UI Component.
Renders all message for JSF UI Components.
Pass parameters to JSF UI Component.
Pass attribute to a JSF UI Component.
Sets value of a managed bean's property.
JSF provides special tags to create common layout for a web application called facelets tags. These tags provide flexibility to manage common parts of multiple pages at one place.
For these tags, you need to use the following namespaces of URI in html node.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:ui = "http://java.sun.com/jsf/facelets">
Following are important Facelets Tags in JSF 2.0.
We'll demonstrate how to use templates using the following tags
<ui:insert>
<ui:define>
<ui:include>
<ui:composition>
We'll demonstrate how to pass parameters to a template file using the following tag
<ui:param>
We'll demonstrate how to create custom tags
We'll demonstrate capability to remove JSF code from generated HTML page
JSF provides inbuilt convertors to convert its UI component's data to object used in a managed bean and vice versa. For example, these tags can convert a text into date object and can validate the format of input as well.
For these tags, you need to use the following namespaces of URI in html node.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core">
Following are important Convertor Tags in JSF 2.0 −
Converts a String into a Number of desired format
Converts a String into a Date of desired format
Creating a custom convertor
JSF provides inbuilt validators to validate its UI components. These tags can validate the length of the field, the type of input which can be a custom object.
For these tags you need to use the following namespaces of URI in html node.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core">
Following are important Validator Tags in JSF 2.0−
Validates the length of a string
Validates the range of a numeric value
Validates the range of a float value
Validates JSF component with a given regular expression
Creates a custom validator
JSF provides a rich control named DataTable to render and format html tables.
DataTable can iterate over a collection or array of values to display data.
DataTable can iterate over a collection or array of values to display data.
DataTable provides attributes to modify its data in an easy way.
DataTable provides attributes to modify its data in an easy way.
<html
xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html">
</html>
Following are important DataTable operations in JSF 2.0 −
How to display a dataTable
How to add a new row in a dataTable
How to edit a row in a dataTable
How to delete a row in dataTable
Use DataModel to display row numbers in a dataTable
JSF provides the developers with a powerful capability to define their own custom components, which can be used to render custom contents.
Defining a custom component in JSF is a two-step process.
Create a resources folder.
Create a xhtml file in resources folder with a composite namespace.
Use composite tags composite:interface, composite:attribute and composite:implementation, to define content of the composite component. Use cc.attrs in composite:implementation to get variable defined using composite:attribute in composite:interface.
Create a folder tutorialspoint in resources folder and create a file loginComponent.xhtml in it.
Use composite namespace in html header.
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:composite = "http://java.sun.com/jsf/composite">
...
</html>
Following table describes the use of composite tags.
composite:interface
Declares configurable values to be used in composite:implementation.
composite:attribute
Configuration values are declared using this tag.
composite:implementation
Declares JSF component. Can access the configurable values defined in composite:interface using #{cc.attrs.attribute-name} expression.
<composite:interface>
<composite:attribute name = "usernameLabel" />
<composite:attribute name = "usernameValue" />
</composite:interface>
<composite:implementation>
<h:form>
#{cc.attrs.usernameLabel} :
<h:inputText id = "username" value = "#{cc.attrs.usernameValue}" />
</h:form>
Using a custom component in JSF is a simple process.
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:ui = "http://java.sun.com/jsf/facelets">
xmlns:tp = "http://java.sun.com/jsf/composite/tutorialspoint">
<h:form>
<tp:loginComponent
usernameLabel = "Enter User Name: "
usernameValue = "#{userData.name}" />
</h:form>
Let us create a test JSF application to test the custom component in JSF.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:composite = "http://java.sun.com/jsf/composite">
<composite:interface>
<composite:attribute name = "usernameLabel" />
<composite:attribute name = "usernameValue" />
<composite:attribute name = "passwordLabel" />
<composite:attribute name = "passwordValue" />
<composite:attribute name = "loginButtonLabel" />
<composite:attribute name = "loginButtonAction"
method-signature = "java.lang.String login()" />
</composite:interface>
<composite:implementation>
<h:form>
<h:message for = "loginPanel" style = "color:red;" />
<h:panelGrid columns = "2" id = "loginPanel">
#{cc.attrs.usernameLabel} :
<h:inputText id = "username" value = "#{cc.attrs.usernameValue}" />
#{cc.attrs.passwordLabel} :
<h:inputSecret id = "password" value = "#{cc.attrs.passwordValue}" />
</h:panelGrid>
<h:commandButton action = "#{cc.attrs.loginButtonAction}"
value = "#{cc.attrs.loginButtonLabel}"/>
</h:form>
</composite:implementation>
</html>
package com.tutorialspoint.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String login() {
return "result";
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:tp = "http://java.sun.com/jsf/composite/tutorialspoint">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>Custom Component Example</h2>
<h:form>
<tp:loginComponent
usernameLabel = "Enter User Name: "
usernameValue = "#{userData.name}"
passwordLabel = "Enter Password: "
passwordValue = "#{userData.password}"
loginButtonLabel = "Login"
loginButtonAction = "#{userData.login}" />
</h:form>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
AJAX stands for Asynchronous JavaScript and Xml.
Ajax is a technique to use HTTPXMLObject of JavaScript to send data to the server and receive data from the server asynchronously. Thus using Ajax technique, javascript code exchanges data with the server, updates parts of the web page without reloading the whole page.
JSF provides execellent support for making ajax call. It provides f:ajax tag to handle ajax calls.
<f:ajax execute = "input-component-name" render = "output-component-name" />
disabled
If true, the Ajax behavior will be applied to any parent or child components. If false, the Ajax behavior will be disabled.
Event
The event that will invoke Ajax requests, for example "click", "change", "blur", "keypress", etc.
Execute
A space-separated list of IDs for components that should be included in the Ajax request.
Immediate
If "true" behavior events generated from this behavior are broadcast during Apply Request Values phase. Otherwise, the events will be broadcast during Invoke Applications phase.
Listener
An EL expression for a method in a backing bean to be called during the Ajax request.
Onerror
The name of a JavaScript callback function that will be invoked if there is an error during the Ajax request.
Onevent
The name of a JavaScript callback function that will be invoked to handle UI events.
Render
A space-separated list of IDs for components that will be updated after an Ajax request.
Let us create a test JSF application to test the custom component in JSF.
package com.tutorialspoint.test;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWelcomeMessage() {
return "Hello " + name;
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:tp = "http://java.sun.com/jsf/composite/tutorialspoint">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>Ajax Example</h2>
<h:form>
<h:inputText id = "inputName" value = "#{userData.name}"></h:inputText>
<h:commandButton value = "Show Message">
<f:ajax execute = "inputName" render = "outputMessage" />
</h:commandButton>
<h2><h:outputText id = "outputMessage"
value = "#{userData.welcomeMessage != null ?
userData.welcomeMessage : ''}"
/></h2>
</h:form>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Enter the name and press the Show Message button. You will see the following result without page refresh/form submit.
When a user clicks a JSF button or link or changes any value in the text field, JSF UI component fires an event, which will be handled by the application code. To handle such an event, an event handler is to be registered in the application code or managed bean.
When a UI component checks that a user event has occured, it creates an instance of the corresponding event class and adds it to an event list. Then, Component fires the event, i.e., checks the list of listeners for that event and calls the event notification method on each listener or handler.
JSF also provide system level event handlers, which can be used to perform some tasks when the application starts or is stopping.
Following are some important Event Handler in JSF 2.0 −
Value change events get fired when the user make changes in input components.
Action events get fired when the user clicks a button or link component.
Events firing during JSF lifecycle: PostConstructApplicationEvent, PreDestroyApplicationEvent , PreRenderViewEvent.
In this article, we'll demonstrate how to integrate database in JSF using JDBC.
Following are the database requirements to run this example.
Open Source and lightweight database
JDBC driver for PostgreSQL 9.1 and JDK 1.5 or above
Put PostgreSQL JDBC4 Driver jar in tomcat web server's lib directory.
create user user1;
create database testdb with owner = user1;
CREATE TABLE IF NOT EXISTS authors (
id int PRIMARY KEY,
name VARCHAR(25)
);
INSERT INTO authors(id, name) VALUES(1, 'Rob Bal');
INSERT INTO authors(id, name) VALUES(2, 'John Carter');
INSERT INTO authors(id, name) VALUES(3, 'Chris London');
INSERT INTO authors(id, name) VALUES(4, 'Truman De Bal');
INSERT INTO authors(id, name) VALUES(5, 'Emile Capote');
INSERT INTO authors(id, name) VALUES(7, 'Breech Jabber');
INSERT INTO authors(id, name) VALUES(8, 'Bob Carter');
INSERT INTO authors(id, name) VALUES(9, 'Nelson Mand');
INSERT INTO authors(id, name) VALUES(10, 'Tennant Mark');
alter user user1 with password 'user1';
grant all on authors to user1;
Let us create a test JSF application to test JDBC integration.
.authorTable {
border-collapse:collapse;
border-bottom:1px solid #000000;
}
.authorTableHeader {
text-align:center;
background:none repeat scroll 0 0 #B5B5B5;
border-bottom:1px solid #000000;
border-top:1px solid #000000;
padding:2px;
}
.authorTableOddRow {
text-align:center;
background:none repeat scroll 0 0 #FFFFFFF;
}
.authorTableEvenRow {
text-align:center;
background:none repeat scroll 0 0 #D3D3D3;
}
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url >
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/helloworld/resources
</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.tutorialspoint.test;
public class Author {
int id;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.tutorialspoint.test;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ComponentSystemEvent;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
public List<Author> getAuthors() {
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = getConnection();
String stm = "Select * from authors";
List<Author> records = new ArrayList<Author>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while(rs.next()) {
Author author = new Author();
author.setId(rs.getInt(1));
author.setName(rs.getString(2));
records.add(author);
}
} catch (SQLException e) {
e.printStackTrace();
}
return records;
}
public Connection getConnection() {
Connection con = null;
String url = "jdbc:postgresql://localhost/testdb";
String user = "user1";
String password = "user1";
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("Connection completed.");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
finally {
}
return con;
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
<h:outputStylesheet library = "css" name = "styles.css" />
</h:head>
<h:body>
<h2>JDBC Integration Example</h2>
<h:dataTable value = "#{userData.authors}" var = "c"
styleClass = "authorTable"
headerClass = "authorTableHeader"
rowClasses = "authorTableOddRow,authorTableEvenRow">
<h:column><f:facet name = "header">Author ID</f:facet>
#{c.id}
</h:column>
<h:column><f:facet name = "header">Name</f:facet>
#{c.name}
</h:column>
</h:dataTable>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Spring provides special class DelegatingVariableResolver to integrate JSF and Spring together in a seamless manner.
Following steps are required to integrate Spring Dependency Injection (IOC) feature in JSF.
Add a variable-resolver entry in faces-config.xml to point to spring class DelegatingVariableResolver.
<faces-config>
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
...
</faces-config>
Add ContextLoaderListener and RequestContextListener listener provided by spring framework in web.xml.
<web-app>
...
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>
Define bean(s) in applicationContext.xml which will be used as dependency in managed bean.
<beans>
<bean id = "messageService"
class = "com.tutorialspoint.test.MessageServiceImpl">
<property name = "message" value = "Hello World!" />
</bean>
</beans>
DelegatingVariableResolver first delegates value lookups to the default resolver of the JSF and then to Spring's WebApplicationContext. This allows one to easily inject springbased dependencies into one's JSF-managed beans.
We've injected messageService as spring-based dependency here.
<faces-config>
...
<managed-bean>
<managed-bean-name>userData</managed-bean-name>
<managed-bean-class>com.tutorialspoint.test.UserData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>messageService</property-name>
<value>#{messageService}</value>
</managed-property>
</managed-bean>
</faces-config>
//jsf managed bean
public class UserData {
//spring managed dependency
private MessageService messageService;
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
public String getGreetingMessage() {
return messageService.getGreetingMessage();
}
}
Let us create a test JSF application to test spring integration.
<project xmlns = "http://maven.apache.org/POM/4.0.0"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.test</groupId>
<artifactId>helloworld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>helloworld Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>helloworld</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/helloworld/resources
</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version = "1.0" encoding = "UTF-8"?>
<faces-config
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version = "2.0">
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
</application>
<managed-bean>
<managed-bean-name>userData</managed-bean-name>
<managed-bean-class>com.tutorialspoint.test.UserData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>messageService</property-name>
<value>#{messageService}</value>
</managed-property>
</managed-bean>
</faces-config>
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
</web-app>
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id = "messageService"
class = "com.tutorialspoint.test.MessageServiceImpl">
<property name = "message" value = "Hello World!" />
</bean>
</beans>
package com.tutorialspoint.test;
public interface MessageService {
String getGreetingMessage();
}
package com.tutorialspoint.test;
public class MessageServiceImpl implements MessageService {
private String message;
public String getGreetingMessage() {
return message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package com.tutorialspoint.test;
import java.io.Serializable;
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private MessageService messageService;
public MessageService getMessageService() {
return messageService;
}
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
public String getGreetingMessage() {
return messageService.getGreetingMessage();
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
</h:head>
<h:body>
<h2>Spring Integration Example</h2>
#{userData.greetingMessage}
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
JSF provides a rich expression language. We can write normal operations using #{operation-expression} notation. Following are some of the advantages of JSF Expression languages.
Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean.
Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean.
Provides easy access to elements of a collection which can be a list, map or an array.
Provides easy access to elements of a collection which can be a list, map or an array.
Provides easy access to predefined objects such as a request.
Provides easy access to predefined objects such as a request.
Arithmetic, logical and relational operations can be done using expression language.
Arithmetic, logical and relational operations can be done using expression language.
Automatic type conversion.
Automatic type conversion.
Shows missing values as empty strings instead of NullPointerException.
Shows missing values as empty strings instead of NullPointerException.
Let us create a test JSF application to test expression language.
package com.tutorialspoint.test;
import java.io.Serializable;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private Date createTime = new Date();
private String message = "Hello World!";
public Date getCreateTime() {
return(createTime);
}
public String getMessage() {
return(message);
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:f = "http://java.sun.com/jsf/core"
xmlns:h = "http://java.sun.com/jsf/html">
<h:head>
<title>JSF Tutorial!</title>
</h:head>
<h:body>
<h2>Expression Language Example</h2>
Creation time:
<h:outputText value = "#{userData.createTime}"/>
<br/><br/>
Message:
<h:outputText value = "#{userData.message}"/>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Internationalization is a technique in which status messages, GUI component labels, currency, date are not hardcoded in the program. Instead, they are stored outside the source code in resource bundles and retrieved dynamically. JSF provides a very convenient way to handle resource bundle.
Following steps are required to internalize a JSF application.
Create properties file for each locale. Name should be in <file-name>_<locale>.properties format.
Default locale can be omitted in file name.
greeting = Hello World!
greeting = Bonjour tout le monde!
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
<resource-bundle>
<base-name>com.tutorialspoint.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
<h:outputText value = "#{msg['greeting']}" />
Let us create a test JSF application to test internationalization in JSF.
greeting = Hello World!
greeting = Bonjour tout le monde!
<?xml version = "1.0" encoding = "UTF-8"?>
<faces-config
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version = "2.0">
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
<resource-bundle>
<base-name>com.tutorialspoint.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
</faces-config>
package com.tutorialspoint.test;
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
private static final long serialVersionUID = 1L;
private String locale;
private static Map<String,Object> countries;
static {
countries = new LinkedHashMap<String,Object>();
countries.put("English", Locale.ENGLISH);
countries.put("French", Locale.FRENCH);
}
public Map<String, Object> getCountries() {
return countries;
}
public String getLocale() {
return locale;
}
public void setLocale(String locale) {
this.locale = locale;
}
//value change event listener
public void localeChanged(ValueChangeEvent e) {
String newLocaleValue = e.getNewValue().toString();
for (Map.Entry<String, Object> entry : countries.entrySet()) {
if(entry.getValue().toString().equals(newLocaleValue)) {
FacesContext.getCurrentInstance()
.getViewRoot().setLocale((Locale)entry.getValue());
}
}
}
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core">
<h:head>
<title>JSF tutorial</title>
</h:head>
<h:body>
<h2>Internalization Language Example</h2>
<h:form>
<h3><h:outputText value = "#{msg['greeting']}" /></h3>
<h:panelGrid columns = "2">
Language :
<h:selectOneMenu value = "#{userData.locale}" onchange = "submit()"
valueChangeListener = "#{userData.localeChanged}">
<f:selectItems value = "#{userData.countries}" />
</h:selectOneMenu>
</h:panelGrid>
</h:form>
</h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.
Change language from dropdown. You will see the following output.
37 Lectures
3.5 hours
Chaand Sheikh
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2445,
"s": 1952,
"text": "JavaServer Faces (JSF) is a MVC web framework that simplifies the construction of User Interfaces (UI) for server-based applications using reusable UI components in a page. JSF provides a facility to connect UI widgets with data sources and to server-side event handlers. The JSF specification defines a set of standard UI components and provides an Application Programming Interface (API) for developing components. JSF enables the reuse and extension of the existing standard UI components."
},
{
"code": null,
"e": 2657,
"s": 2445,
"text": "JSF reduces the effort in creating and maintaining applications, which will run on a Java application server and will render application UI on to a target client. JSF facilitates Web application development by −"
},
{
"code": null,
"e": 2690,
"s": 2657,
"text": "Providing reusable UI components"
},
{
"code": null,
"e": 2738,
"s": 2690,
"text": "Making easy data transfer between UI components"
},
{
"code": null,
"e": 2788,
"s": 2738,
"text": "Managing UI state across multiple server requests"
},
{
"code": null,
"e": 2833,
"s": 2788,
"text": "Enabling implementation of custom components"
},
{
"code": null,
"e": 2890,
"s": 2833,
"text": "Wiring client-side event to server-side application code"
},
{
"code": null,
"e": 3124,
"s": 2890,
"text": "JSF provides the developers with the capability to create Web application from collections of UI components that can render themselves in different ways for multiple client types (for example - HTML browser, wireless, or WAP device)."
},
{
"code": null,
"e": 3139,
"s": 3124,
"text": "JSF provides −"
},
{
"code": null,
"e": 3152,
"s": 3139,
"text": "Core library"
},
{
"code": null,
"e": 3165,
"s": 3152,
"text": "Core library"
},
{
"code": null,
"e": 3224,
"s": 3165,
"text": "A set of base UI components - standard HTML input elements"
},
{
"code": null,
"e": 3283,
"s": 3224,
"text": "A set of base UI components - standard HTML input elements"
},
{
"code": null,
"e": 3396,
"s": 3283,
"text": "Extension of the base UI components to create additional UI component libraries or to extend existing components"
},
{
"code": null,
"e": 3509,
"s": 3396,
"text": "Extension of the base UI components to create additional UI component libraries or to extend existing components"
},
{
"code": null,
"e": 3634,
"s": 3509,
"text": "Multiple rendering capabilities that enable JSF UI components to render themselves differently depending on the client types"
},
{
"code": null,
"e": 3759,
"s": 3634,
"text": "Multiple rendering capabilities that enable JSF UI components to render themselves differently depending on the client types"
},
{
"code": null,
"e": 3979,
"s": 3759,
"text": "This chapter will guide you on how to prepare a development environment to start your work with JSF Framework. You will learn how to setup JDK, Eclipse, Maven, and Tomcat on your machine before you set up JSF Framework."
},
{
"code": null,
"e": 4082,
"s": 3979,
"text": "JSF requires JDK 1.5 or higher so the very first requirement is to have JDK installed on your machine."
},
{
"code": null,
"e": 4174,
"s": 4082,
"text": "Follow the given steps to setup your environment to start with JSF application development."
},
{
"code": null,
"e": 4227,
"s": 4174,
"text": "Open console and execute the following Java command."
},
{
"code": null,
"e": 4283,
"s": 4227,
"text": "Let's verify the output for all the operating systems −"
},
{
"code": null,
"e": 4307,
"s": 4283,
"text": "java version \"1.6.0_21\""
},
{
"code": null,
"e": 4360,
"s": 4307,
"text": "Java(TM) SE Runtime Environment (build 1.6.0_21-b07)"
},
{
"code": null,
"e": 4425,
"s": 4360,
"text": "Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)"
},
{
"code": null,
"e": 4449,
"s": 4425,
"text": "java version \"1.6.0_21\""
},
{
"code": null,
"e": 4502,
"s": 4449,
"text": "Java(TM) SE Runtime Environment (build 1.6.0_21-b07)"
},
{
"code": null,
"e": 4567,
"s": 4502,
"text": "Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)"
},
{
"code": null,
"e": 4591,
"s": 4567,
"text": "java version \"1.6.0_21\""
},
{
"code": null,
"e": 4644,
"s": 4591,
"text": "Java(TM) SE Runtime Environment (build 1.6.0_21-b07)"
},
{
"code": null,
"e": 4715,
"s": 4644,
"text": "Java HotSpot(TM)64-Bit Server VM (build 17.0-b17, mixed mode, sharing)"
},
{
"code": null,
"e": 5164,
"s": 4715,
"text": "If you do not have Java installed then you can install the Java Software Development Kit (SDK) from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively."
},
{
"code": null,
"e": 5284,
"s": 5164,
"text": "Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine."
},
{
"code": null,
"e": 5298,
"s": 5284,
"text": "For example −"
},
{
"code": null,
"e": 5344,
"s": 5298,
"text": "Append Java compiler location to System Path."
},
{
"code": null,
"e": 5649,
"s": 5344,
"text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java. Otherwise, carry out a proper setup according to the given document of the IDE."
},
{
"code": null,
"e": 5842,
"s": 5649,
"text": "All the examples in this tutorial have been written using Eclipse IDE. Hence, we suggest you should have the latest version of Eclipse installed on your machine based on your operating system."
},
{
"code": null,
"e": 6176,
"s": 5842,
"text": "To install Eclipse IDE, download the latest Eclipse binaries with WTP support from https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately."
},
{
"code": null,
"e": 6301,
"s": 6176,
"text": "Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe"
},
{
"code": null,
"e": 6326,
"s": 6301,
"text": "%C:\\eclipse\\eclipse.exe\n"
},
{
"code": null,
"e": 6426,
"s": 6326,
"text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −"
},
{
"code": null,
"e": 6455,
"s": 6426,
"text": "$/usr/local/eclipse/eclipse\n"
},
{
"code": null,
"e": 6548,
"s": 6455,
"text": "After a successful startup, if everything is fine then it will display the following result."
},
{
"code": null,
"e": 6641,
"s": 6548,
"text": "*Note − Install m2eclipse plugin to eclipse using the following eclipse software update site"
},
{
"code": null,
"e": 6700,
"s": 6641,
"text": "m2eclipse Plugin - https://m2eclipse.sonatype.org/update/."
},
{
"code": null,
"e": 6815,
"s": 6700,
"text": "This plugin enables the developers to run maven commands within eclipse with embedded/external maven installation."
},
{
"code": null,
"e": 6880,
"s": 6815,
"text": "Download Maven 2.2.1 from https://maven.apache.org/download.html"
},
{
"code": null,
"e": 7020,
"s": 6880,
"text": "Extract the archive to the directory you wish to install Maven 2.2.1. The subdirectory apache-maven-2.2.1 will be created from the archive."
},
{
"code": null,
"e": 7074,
"s": 7020,
"text": "Add M2_HOME, M2, MAVEN_OPTS to environment variables."
},
{
"code": null,
"e": 7129,
"s": 7074,
"text": "Set the environment variables using system properties."
},
{
"code": null,
"e": 7199,
"s": 7129,
"text": "M2_HOME=C:\\Program Files\\Apache Software Foundation\\apachemaven-2.2.1"
},
{
"code": null,
"e": 7216,
"s": 7199,
"text": "M2=%M2_HOME%\\bin"
},
{
"code": null,
"e": 7245,
"s": 7216,
"text": "MAVEN_OPTS=-Xms256m -Xmx512m"
},
{
"code": null,
"e": 7298,
"s": 7245,
"text": "Open command terminal and set environment variables."
},
{
"code": null,
"e": 7356,
"s": 7298,
"text": "export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1"
},
{
"code": null,
"e": 7380,
"s": 7356,
"text": "export M2=%M2_HOME%\\bin"
},
{
"code": null,
"e": 7416,
"s": 7380,
"text": "export MAVEN_OPTS=-Xms256m -Xmx512m"
},
{
"code": null,
"e": 7469,
"s": 7416,
"text": "Open command terminal and set environment variables."
},
{
"code": null,
"e": 7527,
"s": 7469,
"text": "export M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1"
},
{
"code": null,
"e": 7551,
"s": 7527,
"text": "export M2=%M2_HOME%\\bin"
},
{
"code": null,
"e": 7587,
"s": 7551,
"text": "export MAVEN_OPTS=-Xms256m -Xmx512m"
},
{
"code": null,
"e": 7626,
"s": 7587,
"text": "Now append M2 variable to System Path."
},
{
"code": null,
"e": 7675,
"s": 7626,
"text": "Open console, execute the following mvn command."
},
{
"code": null,
"e": 7774,
"s": 7675,
"text": "Finally, verify the output of the above commands, which should be as shown in the following table."
},
{
"code": null,
"e": 7829,
"s": 7774,
"text": "Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)"
},
{
"code": null,
"e": 7852,
"s": 7829,
"text": "Java version: 1.6.0_21"
},
{
"code": null,
"e": 7902,
"s": 7852,
"text": "Java home: C:\\Program Files\\Java\\jdk1.6.0_21\\jre "
},
{
"code": null,
"e": 7957,
"s": 7902,
"text": "Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)"
},
{
"code": null,
"e": 7980,
"s": 7957,
"text": "Java version: 1.6.0_21"
},
{
"code": null,
"e": 8030,
"s": 7980,
"text": "Java home: C:\\Program Files\\Java\\jdk1.6.0_21\\jre "
},
{
"code": null,
"e": 8085,
"s": 8030,
"text": "Apache Maven 2.2.1 (r801777; 2009-08-07 00:46:01+0530)"
},
{
"code": null,
"e": 8108,
"s": 8085,
"text": "Java version: 1.6.0_21"
},
{
"code": null,
"e": 8157,
"s": 8108,
"text": "Java home: C:\\Program Files\\Java\\jdk1.6.0_21\\jre"
},
{
"code": null,
"e": 8515,
"s": 8157,
"text": "You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\apache-tomcat-6.0.33 on Windows, or /usr/local/apache-tomcat-6.0.33 on Linux/Unix and set CATALINA_HOME environment variable pointing to the installation locations."
},
{
"code": null,
"e": 8639,
"s": 8515,
"text": "Tomcat can be started by executing the following commands on Windows machine, or you can simply double-click on startup.bat"
},
{
"code": null,
"e": 8717,
"s": 8639,
"text": "%CATALINA_HOME%\\bin\\startup.bat \nor \nC:\\apache-tomcat-6.0.33\\bin\\startup.bat\n"
},
{
"code": null,
"e": 8815,
"s": 8717,
"text": "Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine."
},
{
"code": null,
"e": 8898,
"s": 8815,
"text": "$CATALINA_HOME/bin/startup.sh \nor \n/usr/local/apache-tomcat-6.0.33/bin/startup.sh\n"
},
{
"code": null,
"e": 9096,
"s": 8898,
"text": "After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it will display the following result."
},
{
"code": null,
"e": 9263,
"s": 9096,
"text": "Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org"
},
{
"code": null,
"e": 9341,
"s": 9263,
"text": "Tomcat can be stopped by executing the following commands on Windows machine."
},
{
"code": null,
"e": 9414,
"s": 9341,
"text": "%CATALINA_HOME%\\bin\\shutdown \nor \nC:\\apache-tomcat-5.5.29\\bin\\shutdown \n"
},
{
"code": null,
"e": 9512,
"s": 9414,
"text": "Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine."
},
{
"code": null,
"e": 9597,
"s": 9512,
"text": "$CATALINA_HOME/bin/shutdown.sh \nor \n/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh\n"
},
{
"code": null,
"e": 9839,
"s": 9597,
"text": "JSF technology is a framework for developing, building server-side User Interface Components and using them in a web application. JSF technology is based on the Model View Controller (MVC) architecture for separating logic from presentation."
},
{
"code": null,
"e": 9912,
"s": 9839,
"text": "MVC design pattern designs an application using three separate modules −"
},
{
"code": null,
"e": 9918,
"s": 9912,
"text": "Model"
},
{
"code": null,
"e": 9941,
"s": 9918,
"text": "Carries Data and login"
},
{
"code": null,
"e": 9946,
"s": 9941,
"text": "View"
},
{
"code": null,
"e": 9967,
"s": 9946,
"text": "Shows User Interface"
},
{
"code": null,
"e": 9978,
"s": 9967,
"text": "Controller"
},
{
"code": null,
"e": 10016,
"s": 9978,
"text": "Handles processing of an application."
},
{
"code": null,
"e": 10168,
"s": 10016,
"text": "The purpose of MVC design pattern is to separate model and presentation enabling developers to focus on their core skills and collaborate more clearly."
},
{
"code": null,
"e": 10445,
"s": 10168,
"text": "Web designers have to concentrate only on view layer rather than model and controller layer. Developers can change the code for model and typically need not change view layer. Controllers are used to process user actions. In this process, layer model and views may be changed."
},
{
"code": null,
"e": 10576,
"s": 10445,
"text": "JSF application is similar to any other Java technology-based web application; it runs in a Java servlet container, and contains −"
},
{
"code": null,
"e": 10662,
"s": 10576,
"text": "JavaBeans components as models containing application-specific functionality and data"
},
{
"code": null,
"e": 10748,
"s": 10662,
"text": "JavaBeans components as models containing application-specific functionality and data"
},
{
"code": null,
"e": 10816,
"s": 10748,
"text": "A custom tag library for representing event handlers and validators"
},
{
"code": null,
"e": 10884,
"s": 10816,
"text": "A custom tag library for representing event handlers and validators"
},
{
"code": null,
"e": 10933,
"s": 10884,
"text": "A custom tag library for rendering UI components"
},
{
"code": null,
"e": 10982,
"s": 10933,
"text": "A custom tag library for rendering UI components"
},
{
"code": null,
"e": 11042,
"s": 10982,
"text": "UI components represented as stateful objects on the server"
},
{
"code": null,
"e": 11102,
"s": 11042,
"text": "UI components represented as stateful objects on the server"
},
{
"code": null,
"e": 11129,
"s": 11102,
"text": "Server-side helper classes"
},
{
"code": null,
"e": 11156,
"s": 11129,
"text": "Server-side helper classes"
},
{
"code": null,
"e": 11208,
"s": 11156,
"text": "Validators, event handlers, and navigation handlers"
},
{
"code": null,
"e": 11260,
"s": 11208,
"text": "Validators, event handlers, and navigation handlers"
},
{
"code": null,
"e": 11338,
"s": 11260,
"text": "Application configuration resource file for configuring application resources"
},
{
"code": null,
"e": 11416,
"s": 11338,
"text": "Application configuration resource file for configuring application resources"
},
{
"code": null,
"e": 11576,
"s": 11416,
"text": "There are controllers which can be used to perform user actions. UI can be created by web page authors and the business logic can be utilized by managed beans."
},
{
"code": null,
"e": 11822,
"s": 11576,
"text": "JSF provides several mechanisms for rendering an individual component. It is upto the web page designer to pick the desired representation, and the application developer doesn't need to know which mechanism was used to render a JSF UI component."
},
{
"code": null,
"e": 11895,
"s": 11822,
"text": "JSF application life cycle consists of six phases which are as follows −"
},
{
"code": null,
"e": 11914,
"s": 11895,
"text": "Restore view phase"
},
{
"code": null,
"e": 11957,
"s": 11914,
"text": "Apply request values phase; process events"
},
{
"code": null,
"e": 11999,
"s": 11957,
"text": "Process validations phase; process events"
},
{
"code": null,
"e": 12041,
"s": 11999,
"text": "Update model values phase; process events"
},
{
"code": null,
"e": 12082,
"s": 12041,
"text": "Invoke application phase; process events"
},
{
"code": null,
"e": 12104,
"s": 12082,
"text": "Render response phase"
},
{
"code": null,
"e": 12263,
"s": 12104,
"text": "The six phases show the order in which JSF processes a form. The list shows the phases in their likely order of execution with event processing at each phase."
},
{
"code": null,
"e": 12366,
"s": 12263,
"text": "JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request."
},
{
"code": null,
"e": 12602,
"s": 12366,
"text": "During this phase, JSF builds the view, wires event handlers and validators to UI components and saves the view in the FacesContext instance. The FacesContext instance will now contain all the information required to process a request."
},
{
"code": null,
"e": 12973,
"s": 12602,
"text": "After the component tree is created/restored, each component in the component tree uses the decode method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors."
},
{
"code": null,
"e": 13115,
"s": 12973,
"text": "If any decode methods event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase."
},
{
"code": null,
"e": 13328,
"s": 13115,
"text": "During this phase, JSF processes all validators registered on the component tree. It examines the component attribute rules for the validation and compares these rules to the local value stored for the component."
},
{
"code": null,
"e": 13529,
"s": 13328,
"text": "If the local value is invalid, JSF adds an error message to the FacesContext instance, and the life cycle advances to the render response phase and displays the same page again with the error message."
},
{
"code": null,
"e": 13789,
"s": 13529,
"text": "After the JSF checks that the data is valid, it walks over the component tree and sets the corresponding server-side object properties to the components' local values. JSF will update the bean properties corresponding to the input component's value attribute."
},
{
"code": null,
"e": 13917,
"s": 13789,
"text": "If any updateModels methods called renderResponse on the current FacesContext instance, JSF moves to the render response phase."
},
{
"code": null,
"e": 14029,
"s": 13917,
"text": "During this phase, JSF handles any application-level events, such as submitting a form/linking to another page."
},
{
"code": null,
"e": 14512,
"s": 14029,
"text": "During this phase, JSF asks container/application server to render the page if the application is using JSP pages. For initial request, the components represented on the page will be added to the component tree as JSP container executes the page. If this is not an initial request, the component tree is already built so components need not be added again. In either case, the components will render themselves as the JSP container/Application server traverses the tags in the page."
},
{
"code": null,
"e": 14672,
"s": 14512,
"text": "After the content of the view is rendered, the response state is saved so that subsequent requests can access it and it is available to the restore view phase."
},
{
"code": null,
"e": 14844,
"s": 14672,
"text": "To create a simple JSF application, we'll use maven-archetype-webapp plugin. In the following example, we'll create a maven-based web application project in C:\\JSF folder."
},
{
"code": null,
"e": 14938,
"s": 14844,
"text": "Let's open command console, go the C:\\ > JSF directory and execute the following mvn command."
},
{
"code": null,
"e": 15083,
"s": 14938,
"text": "C:\\JSF>mvn archetype:create \n-DgroupId = com.tutorialspoint.test \n-DartifactId = helloworld \n-DarchetypeArtifactId = maven-archetype-webapp \n"
},
{
"code": null,
"e": 15180,
"s": 15083,
"text": "Maven will start processing and will create the complete java web application project structure."
},
{
"code": null,
"e": 16739,
"s": 15180,
"text": "[INFO] Scanning for projects... \n[INFO] Searching repository for plugin with prefix: 'archetype'. \n[INFO] ------------------------------------------------------------- \n[INFO] Building Maven Default Project \n[INFO] task-segment: [archetype:create] (aggregator-style) \n[INFO] ------------------------------------------------------------- \n[INFO] [archetype:create {execution: default-cli}] \n[INFO] Defaulting package to group ID: com.tutorialspoint.test \n[INFO] artifact org.apache.maven.archetypes:maven-archetype-webapp: \nchecking for updates from central \n[INFO] ------------------------------------------------------------- \n[INFO] Using following parameters for creating project \nfrom Old (1.x) Archetype: maven-archetype-webapp:RELEASE \n[INFO] ------------------------------------------------------------- \n[INFO] Parameter: groupId, Value: com.tutorialspoint.test \n[INFO] Parameter: packageName, Value: com.tutorialspoint.test \n[INFO] Parameter: package, Value: com.tutorialspoint.test \n[INFO] Parameter: artifactId, Value: helloworld \n[INFO] Parameter: basedir, Value: C:\\JSF \n[INFO] Parameter: version, Value: 1.0-SNAPSHOT \n[INFO] project created from Old (1.x) Archetype in dir: \nC:\\JSF\\helloworld \n[INFO] ------------------------------------------------------------- \n[INFO] BUILD SUCCESSFUL \n[INFO] ------------------------------------------------------------- \n[INFO] Total time: 7 seconds \n[INFO] Finished at: Mon Nov 05 16:05:04 IST 2012 \n[INFO] Final Memory: 12M/84M \n[INFO] ------------------------------------------------------------- \n"
},
{
"code": null,
"e": 16942,
"s": 16739,
"text": "Now go to C:/JSF directory. You'll see a Java web application project created, named helloworld (as specified in artifactId). Maven uses a standard directory layout as shown in the following screenshot."
},
{
"code": null,
"e": 17013,
"s": 16942,
"text": "Using the above example, we can understand the following key concepts."
},
{
"code": null,
"e": 17024,
"s": 17013,
"text": "helloworld"
},
{
"code": null,
"e": 17056,
"s": 17024,
"text": "Contains src folder and pom.xml"
},
{
"code": null,
"e": 17072,
"s": 17056,
"text": "src/main/wepapp"
},
{
"code": null,
"e": 17115,
"s": 17072,
"text": "Contains WEB-INF folder and index.jsp page"
},
{
"code": null,
"e": 17134,
"s": 17115,
"text": "src/main/resources"
},
{
"code": null,
"e": 17236,
"s": 17134,
"text": "It contains images/properties files (In the above example, we need to create this structure manually)"
},
{
"code": null,
"e": 17272,
"s": 17236,
"text": "Add the following JSF dependencies."
},
{
"code": null,
"e": 17594,
"s": 17272,
"text": "<dependencies>\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\n</dependencies> "
},
{
"code": null,
"e": 19057,
"s": 17594,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/maven-v4_0_0.xsd\">\n\t\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.test</groupId>\n <artifactId>helloworld</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>helloworld Maven Webapp</name>\n <url>http://maven.apache.org</url>\n\t\n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n\t\t\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\t\n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n\t\t\n </dependencies>\n\t\n <build>\n <finalName>helloworld</finalName>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.1</version>\n\t\t\t\t\n <configuration>\n <source>1.6</source>\n <target>1.6</target>\n </configuration>\n </plugin>\n </plugins>\n \n </build>\t\t\n</project>"
},
{
"code": null,
"e": 19168,
"s": 19057,
"text": "Let's open the command console. Go the C:\\ > JSF > helloworld directory and execute the following mvn command."
},
{
"code": null,
"e": 19226,
"s": 19168,
"text": "C:\\JSF\\helloworld>mvn eclipse:eclipse -Dwtpversion = 2.0\n"
},
{
"code": null,
"e": 19318,
"s": 19226,
"text": "Maven will start processing, create the eclipse ready project, and will add wtp capability."
},
{
"code": null,
"e": 21255,
"s": 19318,
"text": "Downloading: http://repo.maven.apache.org/org/apache/maven/plugins/\nmaven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.pom\n5K downloaded (maven-compiler-plugin-2.3.1.pom)\nDownloading: http://repo.maven.apache.org/org/apache/maven/plugins/\nmaven-compiler-plugin/2.3.1/maven-compiler-plugin-2.3.1.jar\n29K downloaded (maven-compiler-plugin-2.3.1.jar)\n[INFO] Searching repository for plugin with prefix: 'eclipse'.\n[INFO] ------------------------------------------------------------\n[INFO] Building helloworld Maven Webapp\n[INFO] task-segment: [eclipse:eclipse]\n[INFO] ------------------------------------------------------------\n[INFO] Preparing eclipse:eclipse\n[INFO] No goals needed for project - skipping\n[INFO] [eclipse:eclipse {execution: default-cli}]\n[INFO] Adding support for WTP version 2.0.\n[INFO] Using Eclipse Workspace: null\n[INFO] Adding default classpath container: org.eclipse.jdt.\nlaunching.JRE_CONTAINER\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.pom\n12K downloaded (jsf-api-2.1.7.pom)\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.pom\n10K downloaded (jsf-impl-2.1.7.pom)\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-api/2.1.7/jsf-api-2.1.7.jar\n619K downloaded (jsf-api-2.1.7.jar)\nDownloading: http://repo.maven.apache.org/\ncom/sun/faces/jsf-impl/2.1.7/jsf-impl-2.1.7.jar\n1916K downloaded (jsf-impl-2.1.7.jar)\n[INFO] Wrote settings to C:\\JSF\\helloworld\\.settings\\\norg.eclipse.jdt.core.prefs\n[INFO] Wrote Eclipse project for \"helloworld\" to C:\\JSF\\helloworld.\n[INFO]\n[INFO] -----------------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] -----------------------------------------------------------\n[INFO] Total time: 6 minutes 7 seconds\n[INFO] Finished at: Mon Nov 05 16:16:25 IST 2012\n[INFO] Final Memory: 10M/89M\n[INFO] -----------------------------------------------------------\n"
},
{
"code": null,
"e": 21281,
"s": 21255,
"text": "Following are the steps −"
},
{
"code": null,
"e": 21328,
"s": 21281,
"text": "Import project in eclipse using Import wizard."
},
{
"code": null,
"e": 21375,
"s": 21328,
"text": "Import project in eclipse using Import wizard."
},
{
"code": null,
"e": 21433,
"s": 21375,
"text": "Go to File → Import... → Existing project into workspace."
},
{
"code": null,
"e": 21491,
"s": 21433,
"text": "Go to File → Import... → Existing project into workspace."
},
{
"code": null,
"e": 21528,
"s": 21491,
"text": "Select root directory to helloworld."
},
{
"code": null,
"e": 21565,
"s": 21528,
"text": "Select root directory to helloworld."
},
{
"code": null,
"e": 21614,
"s": 21565,
"text": "Keep Copy projects into workspace to be checked."
},
{
"code": null,
"e": 21663,
"s": 21614,
"text": "Keep Copy projects into workspace to be checked."
},
{
"code": null,
"e": 21684,
"s": 21663,
"text": "Click Finish button."
},
{
"code": null,
"e": 21705,
"s": 21684,
"text": "Click Finish button."
},
{
"code": null,
"e": 21798,
"s": 21705,
"text": "Eclipse will import and copy the project in its workspace C:\\ → Projects → Data → WorkSpace."
},
{
"code": null,
"e": 21891,
"s": 21798,
"text": "Eclipse will import and copy the project in its workspace C:\\ → Projects → Data → WorkSpace."
},
{
"code": null,
"e": 21963,
"s": 21891,
"text": "Locate web.xml in webapp → WEB-INF folder and update it as shown below."
},
{
"code": null,
"e": 23383,
"s": 21963,
"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_2_5.xsd\"\n id = \"WebApp_ID\" version=\"2.5\">\n\t\n <welcome-file-list>\n <welcome-file>faces/home.xhtml</welcome-file>\n </welcome-file-list>\n\t\n <!-- \n FacesServlet is main servlet responsible to handle all request. \n It acts as central controller.\n This servlet initializes the JSF components before the JSP is displayed.\n -->\n\t\n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n <load-on-startup>1</load-on-startup>\n </servlet>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>/faces/*</url-pattern>\n </servlet-mapping>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.faces</url-pattern>\n </servlet-mapping>\n\t\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.xhtml</url-pattern>\n </servlet-mapping>\n\t\n</web-app>"
},
{
"code": null,
"e": 23563,
"s": 23383,
"text": "Create a package structure under src → main → java as com → tutorialspoint → test. Create HelloWorld.java class in this package. Update the code of HelloWorld.java as shown below."
},
{
"code": null,
"e": 23862,
"s": 23563,
"text": "package com.tutorialspoint.test;\n\nimport javax.faces.bean.ManagedBean;\n\n@ManagedBean(name = \"helloWorld\", eager = true)\npublic class HelloWorld {\n \n public HelloWorld() {\n System.out.println(\"HelloWorld started!\");\n }\n\t\n public String getMessage() {\n return \"Hello World!\";\n }\n}"
},
{
"code": null,
"e": 23954,
"s": 23862,
"text": "Create a page home.xhtml under webapp folder. Update the code of home.xhtml as shown below."
},
{
"code": null,
"e": 24245,
"s": 23954,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n\n <body>\n #{helloWorld.getMessage()}\n </body>\n</html>"
},
{
"code": null,
"e": 24270,
"s": 24245,
"text": "Following are the steps."
},
{
"code": null,
"e": 24307,
"s": 24270,
"text": "Select helloworld project in eclipse"
},
{
"code": null,
"e": 24344,
"s": 24307,
"text": "Select helloworld project in eclipse"
},
{
"code": null,
"e": 24362,
"s": 24344,
"text": "Use Run As wizard"
},
{
"code": null,
"e": 24380,
"s": 24362,
"text": "Use Run As wizard"
},
{
"code": null,
"e": 24410,
"s": 24380,
"text": "Select Run As → Maven package"
},
{
"code": null,
"e": 24440,
"s": 24410,
"text": "Select Run As → Maven package"
},
{
"code": null,
"e": 24579,
"s": 24440,
"text": "Maven will start building the project and will create helloworld.war under C:\\ → Projects → Data → WorkSpace → helloworld → target folder."
},
{
"code": null,
"e": 24718,
"s": 24579,
"text": "Maven will start building the project and will create helloworld.war under C:\\ → Projects → Data → WorkSpace → helloworld → target folder."
},
{
"code": null,
"e": 26253,
"s": 24718,
"text": "[INFO] Scanning for projects...\n[INFO] -----------------------------------------------------\n[INFO] Building helloworld Maven Webapp\n[INFO] \n[INFO] Id: com.tutorialspoint.test:helloworld:war:1.0-SNAPSHOT\n[INFO] task-segment: [package]\n[INFO] -----------------------------------------------------\n[INFO] [resources:resources]\n[INFO] Using default encoding to copy filtered resources.\n[INFO] [compiler:compile]\n[INFO] Nothing to compile - all classes are up to date\n[INFO] [resources:testResources]\n[INFO] Using default encoding to copy filtered resources.\n[INFO] [compiler:testCompile]\n[INFO] No sources to compile\n[INFO] [surefire:test]\n[INFO] Surefire report directory: \nC:\\Projects\\Data\\WorkSpace\\helloworld\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nThere are no tests to run.\n\nResults :\n\nTests run: 0, Failures: 0, Errors: 0, Skipped: 0\n\n[INFO] [war:war]\n[INFO] Packaging webapp\n[INFO] Assembling webapp[helloworld] in\n[C:\\Projects\\Data\\WorkSpace\\helloworld\\target\\helloworld]\n[INFO] Processing war project\n[INFO] Webapp assembled in[150 msecs]\n[INFO] Building war: \nC:\\Projects\\Data\\WorkSpace\\helloworld\\target\\helloworld.war\n[INFO] ------------------------------------------------\n[INFO] BUILD SUCCESSFUL\n[INFO] ------------------------------------------------\n[INFO] Total time: 3 seconds\n[INFO] Finished at: Mon Nov 05 16:34:46 IST 2012\n[INFO] Final Memory: 2M/15M\n[INFO] ------------------------------------------------\n"
},
{
"code": null,
"e": 26278,
"s": 26253,
"text": "Following are the steps."
},
{
"code": null,
"e": 26302,
"s": 26278,
"text": "Stop the tomcat server."
},
{
"code": null,
"e": 26326,
"s": 26302,
"text": "Stop the tomcat server."
},
{
"code": null,
"e": 26406,
"s": 26326,
"text": "Copy the helloworld.war file to tomcat installation directory → webapps folder."
},
{
"code": null,
"e": 26486,
"s": 26406,
"text": "Copy the helloworld.war file to tomcat installation directory → webapps folder."
},
{
"code": null,
"e": 26511,
"s": 26486,
"text": "Start the tomcat server."
},
{
"code": null,
"e": 26536,
"s": 26511,
"text": "Start the tomcat server."
},
{
"code": null,
"e": 26616,
"s": 26536,
"text": "Look inside webapps directory, there should be a folder helloworld got created."
},
{
"code": null,
"e": 26696,
"s": 26616,
"text": "Look inside webapps directory, there should be a folder helloworld got created."
},
{
"code": null,
"e": 26766,
"s": 26696,
"text": "Now helloworld.war is successfully deployed in Tomcat Webserver root."
},
{
"code": null,
"e": 26836,
"s": 26766,
"text": "Now helloworld.war is successfully deployed in Tomcat Webserver root."
},
{
"code": null,
"e": 26933,
"s": 26836,
"text": "Enter a url in web browser: http://localhost:8080/helloworld/home.jsf to launch the application."
},
{
"code": null,
"e": 27016,
"s": 26933,
"text": "Server name (localhost) and port (8080) may vary as per your tomcat configuration."
},
{
"code": null,
"e": 27285,
"s": 27016,
"text": "Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a Java bean managed by JSF framework. Managed bean contains the getter and setter methods, business logic, or even a backing bean (a bean contains all the HTML form value)."
},
{
"code": null,
"e": 27376,
"s": 27285,
"text": "Managed beans works as Model for UI component. Managed Bean can be accessed from JSF page."
},
{
"code": null,
"e": 27648,
"s": 27376,
"text": "In JSF 1.2, a managed bean had to register it in JSF configuration file such as facesconfig.xml. From JSF 2.0 onwards, managed beans can be easily registered using annotations. This approach keeps beans and its registration at one place hence it becomes easier to manage."
},
{
"code": null,
"e": 28075,
"s": 27648,
"text": "<managed-bean>\n <managed-bean-name>helloWorld</managed-bean-name>\n <managed-bean-class>com.tutorialspoint.test.HelloWorld</managed-bean-class>\n <managed-bean-scope>request</managed-bean-scope>\n</managed-bean> \n\n<managed-bean>\n <managed-bean-name>message</managed-bean-name>\n <managed-bean-class>com.tutorialspoint.test.Message</managed-bean-class>\n <managed-bean-scope>request</managed-bean-scope>\n</managed-bean> "
},
{
"code": null,
"e": 28243,
"s": 28075,
"text": "@ManagedBean(name = \"helloWorld\", eager = true)\n@RequestScoped\npublic class HelloWorld {\n @ManagedProperty(value = \"#{message}\")\n private Message message;\n ...\n}"
},
{
"code": null,
"e": 28507,
"s": 28243,
"text": "@ManagedBean marks a bean to be a managed bean with the name specified in name attribute. If the name attribute is not specified, then the managed bean name will default to class name portion of the fully qualified class name. In our case, it would be helloWorld."
},
{
"code": null,
"e": 28731,
"s": 28507,
"text": "Another important attribute is eager. If eager = \"true\" then managed bean is created before it is requested for the first time otherwise \"lazy\" initialization is used in which bean will be created only when it is requested."
},
{
"code": null,
"e": 28935,
"s": 28731,
"text": "Scope annotations set the scope into which the managed bean will be placed. If the scope is not specified, then bean will default to request scope. Each scope is briefly discussed in the following table."
},
{
"code": null,
"e": 28950,
"s": 28935,
"text": "@RequestScoped"
},
{
"code": null,
"e": 29129,
"s": 28950,
"text": "Bean lives as long as the HTTP request-response lives. It gets created upon a HTTP request and gets destroyed when the HTTP response associated with the HTTP request is finished."
},
{
"code": null,
"e": 29141,
"s": 29129,
"text": "@NoneScoped"
},
{
"code": null,
"e": 29281,
"s": 29141,
"text": "Bean lives as long as a single EL evaluation. It gets created upon an EL evaluation and gets destroyed immediately after the EL evaluation."
},
{
"code": null,
"e": 29293,
"s": 29281,
"text": "@ViewScoped"
},
{
"code": null,
"e": 29489,
"s": 29293,
"text": "Bean lives as long as the user is interacting with the same JSF view in the browser window/tab. It gets created upon a HTTP request and gets destroyed once the user postbacks to a different view."
},
{
"code": null,
"e": 29504,
"s": 29489,
"text": "@SessionScoped"
},
{
"code": null,
"e": 29686,
"s": 29504,
"text": "Bean lives as long as the HTTP session lives. It gets created upon the first HTTP request involving this bean in the session and gets destroyed when the HTTP session is invalidated."
},
{
"code": null,
"e": 29705,
"s": 29686,
"text": "@ApplicationScoped"
},
{
"code": null,
"e": 29985,
"s": 29705,
"text": "Bean lives as long as the web application lives. It gets created upon the first HTTP request involving this bean in the application (or when the web application starts up and the eager=true attribute is set in @ManagedBean) and gets destroyed when the web application shuts down."
},
{
"code": null,
"e": 29999,
"s": 29985,
"text": "@CustomScoped"
},
{
"code": null,
"e": 30096,
"s": 29999,
"text": "Bean lives as long as the bean's entry in the custom Map, which is created for this scope lives."
},
{
"code": null,
"e": 30258,
"s": 30096,
"text": "JSF is a simple static Dependency Injection (DI) framework. Using @ManagedProperty annotation, a managed bean's property can be injected in another managed bean."
},
{
"code": null,
"e": 30344,
"s": 30258,
"text": "Let us create a test JSF application to test the above annotations for managed beans."
},
{
"code": null,
"e": 31028,
"s": 30344,
"text": "package com.tutorialspoint.test;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.ManagedProperty;\nimport javax.faces.bean.RequestScoped;\n\n@ManagedBean(name = \"helloWorld\", eager = true)\n@RequestScoped\npublic class HelloWorld {\n @ManagedProperty(value = \"#{message}\")\n private Message messageBean;\n private String message;\n \n public HelloWorld() {\n System.out.println(\"HelloWorld started!\"); \n }\n \n public String getMessage() {\n \n if(messageBean != null) {\n message = messageBean.getMessage();\n } \n return message;\n }\n \n public void setMessageBean(Message message) {\n this.messageBean = message;\n }\n}"
},
{
"code": null,
"e": 31408,
"s": 31028,
"text": "package com.tutorialspoint.test;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.RequestScoped;\n\n@ManagedBean(name = \"message\", eager = true)\n@RequestScoped\npublic class Message {\n private String message = \"Hello World!\";\n\t\n public String getMessage() {\n return message;\n }\n public void setMessage(String message) {\n this.message = message;\n }\n}"
},
{
"code": null,
"e": 31697,
"s": 31408,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <body>\n #{helloWorld.message}\n </body>\n</html>"
},
{
"code": null,
"e": 31914,
"s": 31697,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 32050,
"s": 31914,
"text": "Navigation rules are those rules provided by JSF Framework that describes which view is to be shown when a button or a link is clicked."
},
{
"code": null,
"e": 32170,
"s": 32050,
"text": "Navigation rules can be defined in JSF configuration file named faces-config.xml. They can be defined in managed beans."
},
{
"code": null,
"e": 32364,
"s": 32170,
"text": "Navigation rules can contain conditions based on which the resulted view can be shown. JSF 2.0 provides implicit navigation as well in which there is no need to define navigation rules as such."
},
{
"code": null,
"e": 32592,
"s": 32364,
"text": "JSF 2.0 provides auto view page resolver mechanism named implicit navigation. In this case, you only need to put view name in action attribute and JSF will search the correct view page automatically in the deployed application."
},
{
"code": null,
"e": 32651,
"s": 32592,
"text": "Set view name in action attribute of any JSF UI Component."
},
{
"code": null,
"e": 32756,
"s": 32651,
"text": "<h:form>\n <h3>Using JSF outcome</h3>\n <h:commandButton action = \"page2\" value = \"Page2\" />\n</h:form>"
},
{
"code": null,
"e": 32931,
"s": 32756,
"text": "Here, when Page2 button is clicked, JSF will resolve the view name, page2 as page2.xhtml extension, and find the corresponding view file page2.xhtml in the current directory."
},
{
"code": null,
"e": 32986,
"s": 32931,
"text": "Define a method in managed bean to return a view name."
},
{
"code": null,
"e": 33182,
"s": 32986,
"text": "@ManagedBean(name = \"navigationController\", eager = true)\n@RequestScoped\n\npublic class NavigationController implements Serializable {\n public String moveToPage1() {\n return \"page1\";\n }\n}"
},
{
"code": null,
"e": 33260,
"s": 33182,
"text": "Get view name in action attribute of any JSF UI Component using managed bean."
},
{
"code": null,
"e": 33409,
"s": 33260,
"text": "<h:form> \n <h3> Using Managed Bean</h3> \n <h:commandButton action = \"#{navigationController.moveToPage1}\" \n value = \"Page1\" /glt; \n</h:form> "
},
{
"code": null,
"e": 33584,
"s": 33409,
"text": "Here, when Page1 button is clicked, JSF will resolve the view name, page1 as page1.xhtml extension, and find the corresponding view file page1.xhtml in the current directory."
},
{
"code": null,
"e": 33693,
"s": 33584,
"text": "Using managed bean, we can very easily control the navigation. Look at the following code in a managed bean."
},
{
"code": null,
"e": 34388,
"s": 33693,
"text": "@ManagedBean(name = \"navigationController\", eager = true)\n@RequestScoped\n\npublic class NavigationController implements Serializable {\n //this managed property will read value from request parameter pageId\n @ManagedProperty(value = \"#{param.pageId}\")\n private String pageId;\n\n //condional navigation based on pageId\n //if pageId is 1 show page1.xhtml,\n //if pageId is 2 show page2.xhtml\n //else show home.xhtml\n \n public String showPage() {\n if(pageId == null) {\n return \"home\";\n }\n \n if(pageId.equals(\"1\")) {\n return \"page1\";\n }else if(pageId.equals(\"2\")) {\n return \"page2\";\n }else {\n return \"home\";\n }\n }\n}"
},
{
"code": null,
"e": 34444,
"s": 34388,
"text": "Pass pageId as a request parameter in JSF UI Component."
},
{
"code": null,
"e": 34897,
"s": 34444,
"text": "<h:form>\n <h:commandLink action = \"#{navigationController.showPage}\" value = \"Page1\">\n <f:param name = \"pageId\" value = \"1\" />\n </h:commandLink>\n <h:commandLink action = \"#{navigationController.showPage}\" value = \"Page2\">\n <f:param name = \"pageId\" value = \"2\" />\n </h:commandLink>\n <h:commandLink action = \"#{navigationController.showPage}\" value = \"Home\">\n <f:param name = \"pageId\" value = \"3\" />\n </h:commandLink>\n</h:form>"
},
{
"code": null,
"e": 34935,
"s": 34897,
"text": "Here, when \"Page1\" button is clicked."
},
{
"code": null,
"e": 34987,
"s": 34935,
"text": "JSF will create a request with parameter pageId = 1"
},
{
"code": null,
"e": 35039,
"s": 34987,
"text": "JSF will create a request with parameter pageId = 1"
},
{
"code": null,
"e": 35124,
"s": 35039,
"text": "Then JSF will pass this parameter to managed property pageId of navigationController"
},
{
"code": null,
"e": 35209,
"s": 35124,
"text": "Then JSF will pass this parameter to managed property pageId of navigationController"
},
{
"code": null,
"e": 35313,
"s": 35209,
"text": "Now navigationController.showPage() is called which will return view as page1 after checking the pageId"
},
{
"code": null,
"e": 35417,
"s": 35313,
"text": "Now navigationController.showPage() is called which will return view as page1 after checking the pageId"
},
{
"code": null,
"e": 35480,
"s": 35417,
"text": "JSF will resolve the view name, page1 as page1.xhtml extension"
},
{
"code": null,
"e": 35543,
"s": 35480,
"text": "JSF will resolve the view name, page1 as page1.xhtml extension"
},
{
"code": null,
"e": 35613,
"s": 35543,
"text": "Find the corresponding view file page1.xhtml in the current directory"
},
{
"code": null,
"e": 35683,
"s": 35613,
"text": "Find the corresponding view file page1.xhtml in the current directory"
},
{
"code": null,
"e": 35792,
"s": 35683,
"text": "JSF provides navigation resolution option even if managed bean different methods returns the same view name."
},
{
"code": null,
"e": 35838,
"s": 35792,
"text": "Look at the following code in a managed bean."
},
{
"code": null,
"e": 35946,
"s": 35838,
"text": "public String processPage1() { \n return \"page\"; \n} \npublic String processPage2() { \n return \"page\"; \n} "
},
{
"code": null,
"e": 36022,
"s": 35946,
"text": "To resolve views, define the following navigation rules in faces-config.xml"
},
{
"code": null,
"e": 36512,
"s": 36022,
"text": "<navigation-rule> \n <from-view-id>home.xhtml</from-view-id> \n \n <navigation-case> \n <from-action>#{navigationController.processPage1}</from-action> \n <from-outcome>page</from-outcome> \n <to-view-id>page1.jsf</to-view-id> \n </navigation-case> \n \n <navigation-case> \n <from-action>#{navigationController.processPage2}</from-action> \n <from-outcome>page</from-outcome> \n <to-view-id>page2.jsf</to-view-id> \n </navigation-case> \n\n</navigation-rule> "
},
{
"code": null,
"e": 36549,
"s": 36512,
"text": "Here, when Page1 button is clicked −"
},
{
"code": null,
"e": 36626,
"s": 36549,
"text": "navigationController.processPage1() is called which will return view as page"
},
{
"code": null,
"e": 36703,
"s": 36626,
"text": "navigationController.processPage1() is called which will return view as page"
},
{
"code": null,
"e": 36831,
"s": 36703,
"text": "JSF will resolve the view name, page1 as view name is page and from-action in faces-config is navigationController.processPage1"
},
{
"code": null,
"e": 36959,
"s": 36831,
"text": "JSF will resolve the view name, page1 as view name is page and from-action in faces-config is navigationController.processPage1"
},
{
"code": null,
"e": 37029,
"s": 36959,
"text": "Find the corresponding view file page1.xhtml in the current directory"
},
{
"code": null,
"e": 37099,
"s": 37029,
"text": "Find the corresponding view file page1.xhtml in the current directory"
},
{
"code": null,
"e": 37226,
"s": 37099,
"text": "JSF by default performs a server page forward while navigating to another page and the URL of the application does not change."
},
{
"code": null,
"e": 37314,
"s": 37226,
"text": "To enable the page redirection, append faces-redirect=true at the end of the view name."
},
{
"code": null,
"e": 37508,
"s": 37314,
"text": "<h:form>\n <h3>Forward</h3>\n <h:commandButton action = \"page1\" value = \"Page1\" />\n <h3>Redirect</h3>\n <h:commandButton action = \"page1?faces-redirect = true\" value = \"Page1\" />\n</h:form>"
},
{
"code": null,
"e": 37593,
"s": 37508,
"text": "Here, when Page1 button under Forward is clicked, you will get the following result."
},
{
"code": null,
"e": 37678,
"s": 37593,
"text": "Here when Page1 button under Redirect is clicked, you will get the following result."
},
{
"code": null,
"e": 37761,
"s": 37678,
"text": "Let us create a test JSF application to test all of the above navigation examples."
},
{
"code": null,
"e": 39129,
"s": 37761,
"text": "package com.tutorialspoint.test;\n \nimport java.io.Serializable; \n\nimport javax.faces.bean.ManagedBean; \nimport javax.faces.bean.ManagedProperty; \nimport javax.faces.bean.RequestScoped; \n\n@ManagedBean(name = \"navigationController\", eager = true) \n@RequestScoped \npublic class NavigationController implements Serializable { \n private static final long serialVersionUID = 1L; \n @ManagedProperty(value = \"#{param.pageId}\") \n private String pageId; \n \n public String moveToPage1() { \n return \"page1\"; \n } \n \n public String moveToPage2() { \n return \"page2\"; \n } \n \n public String moveToHomePage() { \n return \"home\"; \n } \n \n public String processPage1() { \n return \"page\"; \n } \n \n public String processPage2() { \n return \"page\"; \n } \n \n public String showPage() { \n if(pageId == null) { \n return \"home\"; \n } \n \n if(pageId.equals(\"1\")) { \n return \"page1\"; \n }else if(pageId.equals(\"2\")) { \n return \"page2\"; \n }else { \n return \"home\"; \n } \n } \n \n public String getPageId() { \n return pageId; \n } \n \n public void setPageId(String pageId) { \n this.pageId = pageId; \n } \n} "
},
{
"code": null,
"e": 39962,
"s": 39129,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<faces-config\n xmlns = \"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version = \"2.0\">\n \n <navigation-rule>\n <from-view-id>home.xhtml</from-view-id>\n <navigation-case>\n <from-action>#{navigationController.processPage1}</from-action>\n <from-outcome>page</from-outcome>\n <to-view-id>page1.jsf</to-view-id>\n </navigation-case>\n <navigation-case>\n <from-action>#{navigationController.processPage2}</from-action>\n <from-outcome>page</from-outcome>\n <to-view-id>page2.jsf</to-view-id>\n </navigation-case>\n </navigation-rule>\n\n</faces-config>"
},
{
"code": null,
"e": 40759,
"s": 39962,
"text": "<!DOCTYPE web-app PUBLIC\n \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n \"http://java.sun.com/dtd/web-app_2_3.dtd\" >\n\n<web-app>\n <display-name>Archetype Created Web Application</display-name>\n\n <context-param>\n <param-name>javax.faces.PROJECT_STAGE</param-name>\n <param-value>Development</param-value>\n </context-param>\n <context-param>\n <param-name>javax.faces.CONFIG_FILES</param-name>\n <param-value>/WEB-INF/faces-config.xml</param-value>\n </context-param>\n \n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n </servlet>\n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n\n</web-app>"
},
{
"code": null,
"e": 41221,
"s": 40759,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:body>\n <h2>This is Page1</h2>\n <h:form>\n <h:commandButton action = \"home?faces-redirect = true\"\n value = \"Back To Home Page\" />\n </h:form>\n </h:body>\n</html>"
},
{
"code": null,
"e": 41683,
"s": 41221,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:body>\n <h2>This is Page2</h2>\n <h:form>\n <h:commandButton action = \"home?faces-redirect = true\"\n value = \"Back To Home Page\" />\n </h:form>\n </h:body>\n</html>"
},
{
"code": null,
"e": 43673,
"s": 41683,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\"\n xmlns:h = \"http://java.sun.com/jsf/html\">\n\n <h:body>\n <h2>Implicit Navigation</h2>\n <hr />\n \n <h:form>\n <h3>Using Managed Bean</h3>\n <h:commandButton action = \"#{navigationController.moveToPage1}\"\n value = \"Page1\" />\n <h3>Using JSF outcome</h3>\n <h:commandButton action = \"page2\" value = \"Page2\" />\n </h:form>\n <br/>\n \n <h2>Conditional Navigation</h2>\n <hr />\n <h:form>\n <h:commandLink action = \"#{navigationController.showPage}\"\n value=\"Page1\">\n <f:param name = \"pageId\" value = \"1\" />\n </h:commandLink>\n \n \n <h:commandLink action = \"#{navigationController.showPage}\"\n value=\"Page2\">\n <f:param name = \"pageId\" value = \"2\" />\n </h:commandLink>\n \n \n <h:commandLink action = \"#{navigationController.showPage}\"\n value = \"Home\">\n <f:param name = \"pageId\" value = \"3\" />\n </h:commandLink>\n </h:form>\n <br/>\n \n <h2>\"From Action\" Navigation</h2>\n <hr />\n \n <h:form>\n <h:commandLink action = \"#{navigationController.processPage1}\"\n value = \"Page1\" />\n \n <h:commandLink action = \"#{navigationController.processPage2}\"\n value = \"Page2\" />\n \n </h:form>\n <br/>\n \n <h2>Forward vs Redirection Navigation</h2>\n <hr />\n <h:form>\n <h3>Forward</h3>\n <h:commandButton action = \"page1\" value = \"Page1\" />\n <h3>Redirect</h3>\n <h:commandButton action = \"page1?faces-redirect = true\"\n value = \"Page1\" />\n </h:form>\n </h:body>\n</html>"
},
{
"code": null,
"e": 43890,
"s": 43673,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - Create Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 43961,
"s": 43890,
"text": "In this chapter, you will learn about various types of basic JSF tags."
},
{
"code": null,
"e": 44059,
"s": 43961,
"text": "JSF provides a standard HTML tag library. These tags get rendered into corresponding html output."
},
{
"code": null,
"e": 44136,
"s": 44059,
"text": "For these tags you need to use the following namespaces of URI in html node."
},
{
"code": null,
"e": 44232,
"s": 44136,
"text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n"
},
{
"code": null,
"e": 44283,
"s": 44232,
"text": "Following are the important Basic Tags in JSF 2.0."
},
{
"code": null,
"e": 44330,
"s": 44283,
"text": "Renders a HTML input of type=\"text\", text box."
},
{
"code": null,
"e": 44381,
"s": 44330,
"text": "Renders a HTML input of type=\"password\", text box."
},
{
"code": null,
"e": 44412,
"s": 44381,
"text": "Renders a HTML textarea field."
},
{
"code": null,
"e": 44451,
"s": 44412,
"text": "Renders a HTML input of type=\"hidden\"."
},
{
"code": null,
"e": 44484,
"s": 44451,
"text": "Renders a single HTML check box."
},
{
"code": null,
"e": 44521,
"s": 44484,
"text": "Renders a group of HTML check boxes."
},
{
"code": null,
"e": 44557,
"s": 44521,
"text": "Renders a single HTML radio button."
},
{
"code": null,
"e": 44589,
"s": 44557,
"text": "Renders a HTML single list box."
},
{
"code": null,
"e": 44623,
"s": 44589,
"text": "Renders a HTML multiple list box."
},
{
"code": null,
"e": 44649,
"s": 44623,
"text": "Renders a HTML combo box."
},
{
"code": null,
"e": 44670,
"s": 44649,
"text": "Renders a HTML text."
},
{
"code": null,
"e": 44714,
"s": 44670,
"text": "Renders a HTML text. It accepts parameters."
},
{
"code": null,
"e": 44732,
"s": 44714,
"text": "Renders an image."
},
{
"code": null,
"e": 44775,
"s": 44732,
"text": "Includes a CSS style sheet in HTML output."
},
{
"code": null,
"e": 44809,
"s": 44775,
"text": "Includes a script in HTML output."
},
{
"code": null,
"e": 44855,
"s": 44809,
"text": "Renders a HTML input of type=\"submit\" button."
},
{
"code": null,
"e": 44878,
"s": 44855,
"text": "Renders a HTML anchor."
},
{
"code": null,
"e": 44901,
"s": 44878,
"text": "Renders a HTML anchor."
},
{
"code": null,
"e": 44924,
"s": 44901,
"text": "Renders a HTML anchor."
},
{
"code": null,
"e": 44963,
"s": 44924,
"text": "Renders an HTML Table in form of grid."
},
{
"code": null,
"e": 45003,
"s": 44963,
"text": "Renders message for a JSF UI Component."
},
{
"code": null,
"e": 45046,
"s": 45003,
"text": "Renders all message for JSF UI Components."
},
{
"code": null,
"e": 45083,
"s": 45046,
"text": "Pass parameters to JSF UI Component."
},
{
"code": null,
"e": 45121,
"s": 45083,
"text": "Pass attribute to a JSF UI Component."
},
{
"code": null,
"e": 45162,
"s": 45121,
"text": "Sets value of a managed bean's property."
},
{
"code": null,
"e": 45342,
"s": 45162,
"text": "JSF provides special tags to create common layout for a web application called facelets tags. These tags provide flexibility to manage common parts of multiple pages at one place."
},
{
"code": null,
"e": 45420,
"s": 45342,
"text": "For these tags, you need to use the following namespaces of URI in html node."
},
{
"code": null,
"e": 45523,
"s": 45420,
"text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n"
},
{
"code": null,
"e": 45573,
"s": 45523,
"text": "Following are important Facelets Tags in JSF 2.0."
},
{
"code": null,
"e": 45637,
"s": 45573,
"text": "We'll demonstrate how to use templates using the following tags"
},
{
"code": null,
"e": 45649,
"s": 45637,
"text": "<ui:insert>"
},
{
"code": null,
"e": 45661,
"s": 45649,
"text": "<ui:define>"
},
{
"code": null,
"e": 45674,
"s": 45661,
"text": "<ui:include>"
},
{
"code": null,
"e": 45691,
"s": 45674,
"text": "<ui:composition>"
},
{
"code": null,
"e": 45775,
"s": 45691,
"text": "We'll demonstrate how to pass parameters to a template file using the following tag"
},
{
"code": null,
"e": 45786,
"s": 45775,
"text": "<ui:param>"
},
{
"code": null,
"e": 45830,
"s": 45786,
"text": "We'll demonstrate how to create custom tags"
},
{
"code": null,
"e": 45903,
"s": 45830,
"text": "We'll demonstrate capability to remove JSF code from generated HTML page"
},
{
"code": null,
"e": 46125,
"s": 45903,
"text": "JSF provides inbuilt convertors to convert its UI component's data to object used in a managed bean and vice versa. For example, these tags can convert a text into date object and can validate the format of input as well."
},
{
"code": null,
"e": 46203,
"s": 46125,
"text": "For these tags, you need to use the following namespaces of URI in html node."
},
{
"code": null,
"e": 46298,
"s": 46203,
"text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:f = \"http://java.sun.com/jsf/core\">"
},
{
"code": null,
"e": 46350,
"s": 46298,
"text": "Following are important Convertor Tags in JSF 2.0 −"
},
{
"code": null,
"e": 46400,
"s": 46350,
"text": "Converts a String into a Number of desired format"
},
{
"code": null,
"e": 46448,
"s": 46400,
"text": "Converts a String into a Date of desired format"
},
{
"code": null,
"e": 46476,
"s": 46448,
"text": "Creating a custom convertor"
},
{
"code": null,
"e": 46636,
"s": 46476,
"text": "JSF provides inbuilt validators to validate its UI components. These tags can validate the length of the field, the type of input which can be a custom object."
},
{
"code": null,
"e": 46713,
"s": 46636,
"text": "For these tags you need to use the following namespaces of URI in html node."
},
{
"code": null,
"e": 46809,
"s": 46713,
"text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:f = \"http://java.sun.com/jsf/core\">\n"
},
{
"code": null,
"e": 46860,
"s": 46809,
"text": "Following are important Validator Tags in JSF 2.0−"
},
{
"code": null,
"e": 46893,
"s": 46860,
"text": "Validates the length of a string"
},
{
"code": null,
"e": 46932,
"s": 46893,
"text": "Validates the range of a numeric value"
},
{
"code": null,
"e": 46969,
"s": 46932,
"text": "Validates the range of a float value"
},
{
"code": null,
"e": 47025,
"s": 46969,
"text": "Validates JSF component with a given regular expression"
},
{
"code": null,
"e": 47052,
"s": 47025,
"text": "Creates a custom validator"
},
{
"code": null,
"e": 47130,
"s": 47052,
"text": "JSF provides a rich control named DataTable to render and format html tables."
},
{
"code": null,
"e": 47206,
"s": 47130,
"text": "DataTable can iterate over a collection or array of values to display data."
},
{
"code": null,
"e": 47282,
"s": 47206,
"text": "DataTable can iterate over a collection or array of values to display data."
},
{
"code": null,
"e": 47347,
"s": 47282,
"text": "DataTable provides attributes to modify its data in an easy way."
},
{
"code": null,
"e": 47412,
"s": 47347,
"text": "DataTable provides attributes to modify its data in an easy way."
},
{
"code": null,
"e": 47518,
"s": 47412,
"text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n</html>\n"
},
{
"code": null,
"e": 47576,
"s": 47518,
"text": "Following are important DataTable operations in JSF 2.0 −"
},
{
"code": null,
"e": 47603,
"s": 47576,
"text": "How to display a dataTable"
},
{
"code": null,
"e": 47639,
"s": 47603,
"text": "How to add a new row in a dataTable"
},
{
"code": null,
"e": 47672,
"s": 47639,
"text": "How to edit a row in a dataTable"
},
{
"code": null,
"e": 47705,
"s": 47672,
"text": "How to delete a row in dataTable"
},
{
"code": null,
"e": 47757,
"s": 47705,
"text": "Use DataModel to display row numbers in a dataTable"
},
{
"code": null,
"e": 47896,
"s": 47757,
"text": "JSF provides the developers with a powerful capability to define their own custom components, which can be used to render custom contents."
},
{
"code": null,
"e": 47954,
"s": 47896,
"text": "Defining a custom component in JSF is a two-step process."
},
{
"code": null,
"e": 47981,
"s": 47954,
"text": "Create a resources folder."
},
{
"code": null,
"e": 48049,
"s": 47981,
"text": "Create a xhtml file in resources folder with a composite namespace."
},
{
"code": null,
"e": 48300,
"s": 48049,
"text": "Use composite tags composite:interface, composite:attribute and composite:implementation, to define content of the composite component. Use cc.attrs in composite:implementation to get variable defined using composite:attribute in composite:interface."
},
{
"code": null,
"e": 48397,
"s": 48300,
"text": "Create a folder tutorialspoint in resources folder and create a file loginComponent.xhtml in it."
},
{
"code": null,
"e": 48437,
"s": 48397,
"text": "Use composite namespace in html header."
},
{
"code": null,
"e": 48643,
"s": 48437,
"text": "<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:f = \"http://java.sun.com/jsf/core\"\n xmlns:composite = \"http://java.sun.com/jsf/composite\">\n...\n</html>"
},
{
"code": null,
"e": 48696,
"s": 48643,
"text": "Following table describes the use of composite tags."
},
{
"code": null,
"e": 48716,
"s": 48696,
"text": "composite:interface"
},
{
"code": null,
"e": 48785,
"s": 48716,
"text": "Declares configurable values to be used in composite:implementation."
},
{
"code": null,
"e": 48805,
"s": 48785,
"text": "composite:attribute"
},
{
"code": null,
"e": 48855,
"s": 48805,
"text": "Configuration values are declared using this tag."
},
{
"code": null,
"e": 48880,
"s": 48855,
"text": "composite:implementation"
},
{
"code": null,
"e": 49015,
"s": 48880,
"text": "Declares JSF component. Can access the configurable values defined in composite:interface using #{cc.attrs.attribute-name} expression."
},
{
"code": null,
"e": 49310,
"s": 49015,
"text": "<composite:interface>\n <composite:attribute name = \"usernameLabel\" />\n <composite:attribute name = \"usernameValue\" />\n</composite:interface>\n\n<composite:implementation>\n<h:form>\n #{cc.attrs.usernameLabel} : \n <h:inputText id = \"username\" value = \"#{cc.attrs.usernameValue}\" />\n</h:form>"
},
{
"code": null,
"e": 49363,
"s": 49310,
"text": "Using a custom component in JSF is a simple process."
},
{
"code": null,
"e": 49571,
"s": 49363,
"text": "<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n xmlns:tp = \"http://java.sun.com/jsf/composite/tutorialspoint\">"
},
{
"code": null,
"e": 49700,
"s": 49571,
"text": "<h:form>\n <tp:loginComponent \n usernameLabel = \"Enter User Name: \" \n usernameValue = \"#{userData.name}\" />\n</h:form>"
},
{
"code": null,
"e": 49774,
"s": 49700,
"text": "Let us create a test JSF application to test the custom component in JSF."
},
{
"code": null,
"e": 51202,
"s": 49774,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:f = \"http://java.sun.com/jsf/core\"\n xmlns:composite = \"http://java.sun.com/jsf/composite\">\n \n <composite:interface>\n <composite:attribute name = \"usernameLabel\" />\n <composite:attribute name = \"usernameValue\" />\n <composite:attribute name = \"passwordLabel\" />\n <composite:attribute name = \"passwordValue\" />\n <composite:attribute name = \"loginButtonLabel\" />\n <composite:attribute name = \"loginButtonAction\" \n method-signature = \"java.lang.String login()\" />\n </composite:interface>\n \n <composite:implementation>\n <h:form>\n <h:message for = \"loginPanel\" style = \"color:red;\" />\n \n <h:panelGrid columns = \"2\" id = \"loginPanel\">\n #{cc.attrs.usernameLabel} : \n <h:inputText id = \"username\" value = \"#{cc.attrs.usernameValue}\" />\n #{cc.attrs.passwordLabel} : \n <h:inputSecret id = \"password\" value = \"#{cc.attrs.passwordValue}\" />\n </h:panelGrid>\n \n <h:commandButton action = \"#{cc.attrs.loginButtonAction}\" \n value = \"#{cc.attrs.loginButtonLabel}\"/>\n </h:form>\n </composite:implementation>\n</html>"
},
{
"code": null,
"e": 51899,
"s": 51202,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n private String name;\n private String password;\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public String getPassword() {\n return password;\n }\n \n public void setPassword(String password) {\n this.password = password;\n }\t\n \n public String login() {\n return \"result\";\n }\t\n}"
},
{
"code": null,
"e": 52753,
"s": 51899,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:f = \"http://java.sun.com/jsf/core\"\n xmlns:tp = \"http://java.sun.com/jsf/composite/tutorialspoint\">\n \n <h:head>\n <title>JSF tutorial</title>\t\t \n </h:head>\n \n <h:body> \n <h2>Custom Component Example</h2>\n \n <h:form>\n <tp:loginComponent \n usernameLabel = \"Enter User Name: \" \n usernameValue = \"#{userData.name}\" \n passwordLabel = \"Enter Password: \" \n passwordValue = \"#{userData.password}\"\n loginButtonLabel = \"Login\" \n loginButtonAction = \"#{userData.login}\" />\n </h:form>\n </h:body>\n</html>"
},
{
"code": null,
"e": 52969,
"s": 52753,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 53018,
"s": 52969,
"text": "AJAX stands for Asynchronous JavaScript and Xml."
},
{
"code": null,
"e": 53288,
"s": 53018,
"text": "Ajax is a technique to use HTTPXMLObject of JavaScript to send data to the server and receive data from the server asynchronously. Thus using Ajax technique, javascript code exchanges data with the server, updates parts of the web page without reloading the whole page."
},
{
"code": null,
"e": 53387,
"s": 53288,
"text": "JSF provides execellent support for making ajax call. It provides f:ajax tag to handle ajax calls."
},
{
"code": null,
"e": 53464,
"s": 53387,
"text": "<f:ajax execute = \"input-component-name\" render = \"output-component-name\" />"
},
{
"code": null,
"e": 53473,
"s": 53464,
"text": "disabled"
},
{
"code": null,
"e": 53597,
"s": 53473,
"text": "If true, the Ajax behavior will be applied to any parent or child components. If false, the Ajax behavior will be disabled."
},
{
"code": null,
"e": 53603,
"s": 53597,
"text": "Event"
},
{
"code": null,
"e": 53701,
"s": 53603,
"text": "The event that will invoke Ajax requests, for example \"click\", \"change\", \"blur\", \"keypress\", etc."
},
{
"code": null,
"e": 53709,
"s": 53701,
"text": "Execute"
},
{
"code": null,
"e": 53799,
"s": 53709,
"text": "A space-separated list of IDs for components that should be included in the Ajax request."
},
{
"code": null,
"e": 53809,
"s": 53799,
"text": "Immediate"
},
{
"code": null,
"e": 53987,
"s": 53809,
"text": "If \"true\" behavior events generated from this behavior are broadcast during Apply Request Values phase. Otherwise, the events will be broadcast during Invoke Applications phase."
},
{
"code": null,
"e": 53996,
"s": 53987,
"text": "Listener"
},
{
"code": null,
"e": 54082,
"s": 53996,
"text": "An EL expression for a method in a backing bean to be called during the Ajax request."
},
{
"code": null,
"e": 54090,
"s": 54082,
"text": "Onerror"
},
{
"code": null,
"e": 54200,
"s": 54090,
"text": "The name of a JavaScript callback function that will be invoked if there is an error during the Ajax request."
},
{
"code": null,
"e": 54208,
"s": 54200,
"text": "Onevent"
},
{
"code": null,
"e": 54293,
"s": 54208,
"text": "The name of a JavaScript callback function that will be invoked to handle UI events."
},
{
"code": null,
"e": 54300,
"s": 54293,
"text": "Render"
},
{
"code": null,
"e": 54389,
"s": 54300,
"text": "A space-separated list of IDs for components that will be updated after an Ajax request."
},
{
"code": null,
"e": 54463,
"s": 54389,
"text": "Let us create a test JSF application to test the custom component in JSF."
},
{
"code": null,
"e": 54994,
"s": 54463,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n private String name;\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n\n public String getWelcomeMessage() {\n return \"Hello \" + name;\n }\n}"
},
{
"code": null,
"e": 55919,
"s": 54994,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:f = \"http://java.sun.com/jsf/core\"\n xmlns:tp = \"http://java.sun.com/jsf/composite/tutorialspoint\">\n \n <h:head>\n <title>JSF tutorial</title>\n </h:head>\n \n <h:body>\n <h2>Ajax Example</h2>\n \n <h:form>\n <h:inputText id = \"inputName\" value = \"#{userData.name}\"></h:inputText>\n <h:commandButton value = \"Show Message\">\n <f:ajax execute = \"inputName\" render = \"outputMessage\" />\n </h:commandButton>\n <h2><h:outputText id = \"outputMessage\"\n value = \"#{userData.welcomeMessage != null ?\n userData.welcomeMessage : ''}\"\n /></h2>\n </h:form>\n </h:body>\n</html>"
},
{
"code": null,
"e": 56135,
"s": 55919,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 56253,
"s": 56135,
"text": "Enter the name and press the Show Message button. You will see the following result without page refresh/form submit."
},
{
"code": null,
"e": 56516,
"s": 56253,
"text": "When a user clicks a JSF button or link or changes any value in the text field, JSF UI component fires an event, which will be handled by the application code. To handle such an event, an event handler is to be registered in the application code or managed bean."
},
{
"code": null,
"e": 56812,
"s": 56516,
"text": "When a UI component checks that a user event has occured, it creates an instance of the corresponding event class and adds it to an event list. Then, Component fires the event, i.e., checks the list of listeners for that event and calls the event notification method on each listener or handler."
},
{
"code": null,
"e": 56942,
"s": 56812,
"text": "JSF also provide system level event handlers, which can be used to perform some tasks when the application starts or is stopping."
},
{
"code": null,
"e": 56998,
"s": 56942,
"text": "Following are some important Event Handler in JSF 2.0 −"
},
{
"code": null,
"e": 57076,
"s": 56998,
"text": "Value change events get fired when the user make changes in input components."
},
{
"code": null,
"e": 57149,
"s": 57076,
"text": "Action events get fired when the user clicks a button or link component."
},
{
"code": null,
"e": 57265,
"s": 57149,
"text": "Events firing during JSF lifecycle: PostConstructApplicationEvent, PreDestroyApplicationEvent , PreRenderViewEvent."
},
{
"code": null,
"e": 57345,
"s": 57265,
"text": "In this article, we'll demonstrate how to integrate database in JSF using JDBC."
},
{
"code": null,
"e": 57406,
"s": 57345,
"text": "Following are the database requirements to run this example."
},
{
"code": null,
"e": 57443,
"s": 57406,
"text": "Open Source and lightweight database"
},
{
"code": null,
"e": 57495,
"s": 57443,
"text": "JDBC driver for PostgreSQL 9.1 and JDK 1.5 or above"
},
{
"code": null,
"e": 57565,
"s": 57495,
"text": "Put PostgreSQL JDBC4 Driver jar in tomcat web server's lib directory."
},
{
"code": null,
"e": 58295,
"s": 57565,
"text": "create user user1;\ncreate database testdb with owner = user1;\n\nCREATE TABLE IF NOT EXISTS authors (\n id int PRIMARY KEY, \n name VARCHAR(25)\n);\n\nINSERT INTO authors(id, name) VALUES(1, 'Rob Bal');\nINSERT INTO authors(id, name) VALUES(2, 'John Carter');\nINSERT INTO authors(id, name) VALUES(3, 'Chris London');\nINSERT INTO authors(id, name) VALUES(4, 'Truman De Bal');\nINSERT INTO authors(id, name) VALUES(5, 'Emile Capote');\nINSERT INTO authors(id, name) VALUES(7, 'Breech Jabber');\nINSERT INTO authors(id, name) VALUES(8, 'Bob Carter');\nINSERT INTO authors(id, name) VALUES(9, 'Nelson Mand');\nINSERT INTO authors(id, name) VALUES(10, 'Tennant Mark');\n\nalter user user1 with password 'user1';\n\ngrant all on authors to user1;"
},
{
"code": null,
"e": 58358,
"s": 58295,
"text": "Let us create a test JSF application to test JDBC integration."
},
{
"code": null,
"e": 58807,
"s": 58358,
"text": ".authorTable { \n border-collapse:collapse;\n border-bottom:1px solid #000000;\n}\n\n.authorTableHeader {\n text-align:center;\n background:none repeat scroll 0 0 #B5B5B5;\n border-bottom:1px solid #000000;\n border-top:1px solid #000000;\n padding:2px;\n}\n\n.authorTableOddRow {\n text-align:center;\n background:none repeat scroll 0 0 #FFFFFFF;\t\n}\n\n.authorTableEvenRow {\n text-align:center;\n background:none repeat scroll 0 0 #D3D3D3;\n}"
},
{
"code": null,
"e": 61545,
"s": 58807,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/maven-v4_0_0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.test</groupId>\n <artifactId>helloworld</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>helloworld Maven Webapp</name>\n <url>http://maven.apache.org</url >\n \n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>javax.servlet</groupId>\n <artifactId>jstl</artifactId>\n <version>1.2</version>\n </dependency>\n \n <dependency>\n <groupId>postgresql</groupId>\n <artifactId>postgresql</artifactId>\n <version>9.1-901.jdbc4</version>\n </dependency>\n </dependencies>\n \n <build>\n <finalName>helloworld</finalName>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.1</version>\n <configuration>\n <source>1.6</source>\n <target>1.6</target>\n </configuration>\n </plugin>\n \n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <version>2.6</version>\n <executions>\n <execution>\n <id>copy-resources</id>\n <phase>validate</phase>\n <goals>\n <goal>copy-resources</goal>\n </goals>\n \n <configuration>\n <outputDirectory>${basedir}/target/helloworld/resources\n </outputDirectory>\n <resources> \n <resource>\n <directory>src/main/resources</directory>\n <filtering>true</filtering>\n </resource>\n </resources> \n </configuration> \n </execution>\n </executions>\n </plugin>\n \n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 61868,
"s": 61545,
"text": "package com.tutorialspoint.test;\n\npublic class Author {\n int id;\n String name;\n \n public String getName() {\n return name;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public int getId() {\n return id;\n }\n \n public void setId(int id) {\n this.id = id;\n }\n}"
},
{
"code": null,
"e": 63555,
"s": 61868,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.PreparedStatement;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\nimport javax.faces.event.ComponentSystemEvent;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n\n public List<Author> getAuthors() {\n ResultSet rs = null;\n PreparedStatement pst = null;\n Connection con = getConnection();\n String stm = \"Select * from authors\";\n List<Author> records = new ArrayList<Author>();\n \n try { \n pst = con.prepareStatement(stm);\n pst.execute();\n rs = pst.getResultSet();\n\n while(rs.next()) {\n Author author = new Author();\n author.setId(rs.getInt(1));\n author.setName(rs.getString(2));\n records.add(author);\t\t\t\t\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return records;\n }\n\n public Connection getConnection() {\n Connection con = null;\n String url = \"jdbc:postgresql://localhost/testdb\";\n String user = \"user1\";\n String password = \"user1\";\n \n try {\n con = DriverManager.getConnection(url, user, password);\n System.out.println(\"Connection completed.\");\n } catch (SQLException ex) {\n System.out.println(ex.getMessage());\n }\n \n finally {\n }\n return con;\n }\n}"
},
{
"code": null,
"e": 64524,
"s": 63555,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title>\n <h:outputStylesheet library = \"css\" name = \"styles.css\" /> \n </h:head>\n \n <h:body>\n <h2>JDBC Integration Example</h2>\n \n <h:dataTable value = \"#{userData.authors}\" var = \"c\"\n styleClass = \"authorTable\"\n headerClass = \"authorTableHeader\"\n rowClasses = \"authorTableOddRow,authorTableEvenRow\">\n \n <h:column><f:facet name = \"header\">Author ID</f:facet>\n #{c.id}\n </h:column>\n \n <h:column><f:facet name = \"header\">Name</f:facet>\n #{c.name}\n </h:column>\n </h:dataTable>\n </h:body>\n</html> "
},
{
"code": null,
"e": 64740,
"s": 64524,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 64856,
"s": 64740,
"text": "Spring provides special class DelegatingVariableResolver to integrate JSF and Spring together in a seamless manner."
},
{
"code": null,
"e": 64948,
"s": 64856,
"text": "Following steps are required to integrate Spring Dependency Injection (IOC) feature in JSF."
},
{
"code": null,
"e": 65051,
"s": 64948,
"text": "Add a variable-resolver entry in faces-config.xml to point to spring class DelegatingVariableResolver."
},
{
"code": null,
"e": 65214,
"s": 65051,
"text": "<faces-config>\n <application>\n <variable-resolver>\n org.springframework.web.jsf.DelegatingVariableResolver\n </variable-resolver>\n ...\n</faces-config>"
},
{
"code": null,
"e": 65317,
"s": 65214,
"text": "Add ContextLoaderListener and RequestContextListener listener provided by spring framework in web.xml."
},
{
"code": null,
"e": 65678,
"s": 65317,
"text": "<web-app>\n ...\n <!-- Add Support for Spring -->\n <listener>\n <listener-class>\n org.springframework.web.context.ContextLoaderListener\n </listener-class>\n </listener>\n \n <listener>\n <listener-class>\n org.springframework.web.context.request.RequestContextListener\n </listener-class>\n </listener>\n ...\n</web-app>"
},
{
"code": null,
"e": 65769,
"s": 65678,
"text": "Define bean(s) in applicationContext.xml which will be used as dependency in managed bean."
},
{
"code": null,
"e": 65956,
"s": 65769,
"text": "<beans>\n <bean id = \"messageService\" \n class = \"com.tutorialspoint.test.MessageServiceImpl\">\n <property name = \"message\" value = \"Hello World!\" /> \n </bean>\n</beans>"
},
{
"code": null,
"e": 66180,
"s": 65956,
"text": "DelegatingVariableResolver first delegates value lookups to the default resolver of the JSF and then to Spring's WebApplicationContext. This allows one to easily inject springbased dependencies into one's JSF-managed beans."
},
{
"code": null,
"e": 66243,
"s": 66180,
"text": "We've injected messageService as spring-based dependency here."
},
{
"code": null,
"e": 66663,
"s": 66243,
"text": "<faces-config>\n ...\n <managed-bean>\n <managed-bean-name>userData</managed-bean-name>\n <managed-bean-class>com.tutorialspoint.test.UserData</managed-bean-class>\n <managed-bean-scope>request</managed-bean-scope>\n \n <managed-property>\n <property-name>messageService</property-name>\n <value>#{messageService}</value>\n </managed-property>\n </managed-bean> \n</faces-config>"
},
{
"code": null,
"e": 66997,
"s": 66663,
"text": "//jsf managed bean\npublic class UserData {\n \n //spring managed dependency\n private MessageService messageService;\n\n public void setMessageService(MessageService messageService) {\n this.messageService = messageService;\n }\n\n public String getGreetingMessage() {\n return messageService.getGreetingMessage();\n }\n}"
},
{
"code": null,
"e": 67062,
"s": 66997,
"text": "Let us create a test JSF application to test spring integration."
},
{
"code": null,
"e": 70011,
"s": 67062,
"text": "<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0\n http://maven.apache.org/maven-v4_0_0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.test</groupId>\n <artifactId>helloworld</artifactId>\n <packaging>war</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>helloworld Maven Webapp</name>\n <url>http://maven.apache.org</url>\n \n <dependencies>\n <dependency>\n <groupId>junit</groupId>\n <artifactId>junit</artifactId>\n <version>3.8.1</version>\n <scope>test</scope>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-api</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>com.sun.faces</groupId>\n <artifactId>jsf-impl</artifactId>\n <version>2.1.7</version>\n </dependency>\n \n <dependency>\n <groupId>javax.servlet</groupId>\n <artifactId>jstl</artifactId>\n <version>1.2</version>\n </dependency>\n \n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-core</artifactId>\n <version>3.1.2.RELEASE</version>\n </dependency>\n \n <dependency>\n <groupId>org.springframework</groupId>\n <artifactId>spring-web</artifactId>\n <version>3.1.2.RELEASE</version> \n </dependency>\n </dependencies>\n \n <build>\n <finalName>helloworld</finalName>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>2.3.1</version>\n <configuration>\n <source>1.6</source>\n <target>1.6</target>\n </configuration>\n </plugin>\n \n <plugin>\n <artifactId>maven-resources-plugin</artifactId>\n <version>2.6</version>\n \n <executions>\n <execution>\n <id>copy-resources</id>\n <phase>validate</phase>\n <goals>\n <goal>copy-resources</goal>\n </goals>\n \n <configuration>\n <outputDirectory>${basedir}/target/helloworld/resources\n </outputDirectory>\n <resources> \n <resource>\n <directory>src/main/resources</directory>\n <filtering>true</filtering>\n </resource>\n </resources> \n </configuration> \n </execution>\n </executions>\n \n </plugin>\n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 70868,
"s": 70011,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<faces-config\n xmlns = \"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version = \"2.0\"> \n \n <application>\n <variable-resolver>\n org.springframework.web.jsf.DelegatingVariableResolver\n </variable-resolver>\n </application>\n \n <managed-bean>\n <managed-bean-name>userData</managed-bean-name>\n <managed-bean-class>com.tutorialspoint.test.UserData</managed-bean-class>\n <managed-bean-scope>request</managed-bean-scope>\n <managed-property>\n <property-name>messageService</property-name>\n <value>#{messageService}</value>\n </managed-property>\n </managed-bean> \n</faces-config>"
},
{
"code": null,
"e": 71846,
"s": 70868,
"text": "<!DOCTYPE web-app PUBLIC\n \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n \"http://java.sun.com/dtd/web-app_2_3.dtd\" >\n\n<web-app>\n <display-name>Archetype Created Web Application</display-name>\n\n <context-param>\n <param-name>javax.faces.PROJECT_STAGE</param-name>\n <param-value>Development</param-value>\n </context-param>\t\n \n <!-- Add Support for Spring -->\n <listener> \n <listener-class>\n org.springframework.web.context.ContextLoaderListener\n </listener-class>\n </listener>\n \n <listener>\n <listener-class>\n org.springframework.web.context.request.RequestContextListener\n </listener-class>\n </listener>\n \n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n</web-app>"
},
{
"code": null,
"e": 72193,
"s": 71846,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN 2.0//EN\" \n \"http://www.springframework.org/dtd/spring-beans-2.0.dtd\">\n\n<beans>\n <bean id = \"messageService\" \n class = \"com.tutorialspoint.test.MessageServiceImpl\">\n <property name = \"message\" value = \"Hello World!\" /> \n </bean>\n</beans>"
},
{
"code": null,
"e": 72295,
"s": 72193,
"text": "package com.tutorialspoint.test;\n\npublic interface MessageService {\n String getGreetingMessage();\n}"
},
{
"code": null,
"e": 72631,
"s": 72295,
"text": "package com.tutorialspoint.test;\n\npublic class MessageServiceImpl implements MessageService {\n private String message;\n \n public String getGreetingMessage() {\n return message;\n }\n \n public String getMessage() {\n return message;\n }\n public void setMessage(String message) {\n this.message = message;\n }\n}"
},
{
"code": null,
"e": 73132,
"s": 72631,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\npublic class UserData implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\tprivate MessageService messageService;\n\n public MessageService getMessageService() {\n return messageService;\n }\n\n public void setMessageService(MessageService messageService) {\n this.messageService = messageService;\n }\n\n public String getGreetingMessage() {\n return messageService.getGreetingMessage();\n }\n}"
},
{
"code": null,
"e": 73615,
"s": 73132,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title>\n </h:head>\n \n <h:body>\n <h2>Spring Integration Example</h2>\n #{userData.greetingMessage}\n </h:body>\n</html> "
},
{
"code": null,
"e": 73831,
"s": 73615,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 74009,
"s": 73831,
"text": "JSF provides a rich expression language. We can write normal operations using #{operation-expression} notation. Following are some of the advantages of JSF Expression languages."
},
{
"code": null,
"e": 74137,
"s": 74009,
"text": "Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean."
},
{
"code": null,
"e": 74265,
"s": 74137,
"text": "Can reference bean properties where bean can be an object stored in request, session or application scope or is a managed bean."
},
{
"code": null,
"e": 74352,
"s": 74265,
"text": "Provides easy access to elements of a collection which can be a list, map or an array."
},
{
"code": null,
"e": 74439,
"s": 74352,
"text": "Provides easy access to elements of a collection which can be a list, map or an array."
},
{
"code": null,
"e": 74501,
"s": 74439,
"text": "Provides easy access to predefined objects such as a request."
},
{
"code": null,
"e": 74563,
"s": 74501,
"text": "Provides easy access to predefined objects such as a request."
},
{
"code": null,
"e": 74648,
"s": 74563,
"text": "Arithmetic, logical and relational operations can be done using expression language."
},
{
"code": null,
"e": 74733,
"s": 74648,
"text": "Arithmetic, logical and relational operations can be done using expression language."
},
{
"code": null,
"e": 74760,
"s": 74733,
"text": "Automatic type conversion."
},
{
"code": null,
"e": 74787,
"s": 74760,
"text": "Automatic type conversion."
},
{
"code": null,
"e": 74858,
"s": 74787,
"text": "Shows missing values as empty strings instead of NullPointerException."
},
{
"code": null,
"e": 74929,
"s": 74858,
"text": "Shows missing values as empty strings instead of NullPointerException."
},
{
"code": null,
"e": 74995,
"s": 74929,
"text": "Let us create a test JSF application to test expression language."
},
{
"code": null,
"e": 75536,
"s": 74995,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\nimport java.util.Date;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n private Date createTime = new Date();\n private String message = \"Hello World!\";\n\n public Date getCreateTime() {\n return(createTime);\n }\n \n public String getMessage() {\n return(message);\n }\n}"
},
{
"code": null,
"e": 76148,
"s": 75536,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title>\n </h:head>\n \n <h:body>\n <h2>Expression Language Example</h2>\n Creation time: \n <h:outputText value = \"#{userData.createTime}\"/>\n <br/><br/>\n Message: \n <h:outputText value = \"#{userData.message}\"/>\n </h:body>\n</html> "
},
{
"code": null,
"e": 76364,
"s": 76148,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 76655,
"s": 76364,
"text": "Internationalization is a technique in which status messages, GUI component labels, currency, date are not hardcoded in the program. Instead, they are stored outside the source code in resource bundles and retrieved dynamically. JSF provides a very convenient way to handle resource bundle."
},
{
"code": null,
"e": 76718,
"s": 76655,
"text": "Following steps are required to internalize a JSF application."
},
{
"code": null,
"e": 76816,
"s": 76718,
"text": "Create properties file for each locale. Name should be in <file-name>_<locale>.properties format."
},
{
"code": null,
"e": 76860,
"s": 76816,
"text": "Default locale can be omitted in file name."
},
{
"code": null,
"e": 76885,
"s": 76860,
"text": "greeting = Hello World!\n"
},
{
"code": null,
"e": 76920,
"s": 76885,
"text": "greeting = Bonjour tout le monde!\n"
},
{
"code": null,
"e": 77201,
"s": 76920,
"text": "<application>\n <locale-config>\n <default-locale>en</default-locale>\n <supported-locale>fr</supported-locale>\n </locale-config>\n \n <resource-bundle>\n <base-name>com.tutorialspoint.messages</base-name>\n <var>msg</var>\n </resource-bundle>\n</application>"
},
{
"code": null,
"e": 77247,
"s": 77201,
"text": "<h:outputText value = \"#{msg['greeting']}\" />"
},
{
"code": null,
"e": 77321,
"s": 77247,
"text": "Let us create a test JSF application to test internationalization in JSF."
},
{
"code": null,
"e": 77346,
"s": 77321,
"text": "greeting = Hello World!\n"
},
{
"code": null,
"e": 77381,
"s": 77346,
"text": "greeting = Bonjour tout le monde!\n"
},
{
"code": null,
"e": 78020,
"s": 77381,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<faces-config\n xmlns = \"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://java.sun.com/xml/ns/javaee \n http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd\"\n version = \"2.0\">\n \n <application>\n <locale-config>\n <default-locale>en</default-locale>\n <supported-locale>fr</supported-locale>\n </locale-config>\n \n <resource-bundle>\n <base-name>com.tutorialspoint.messages</base-name>\n <var>msg</var>\n </resource-bundle>\n </application>\n</faces-config>"
},
{
"code": null,
"e": 79389,
"s": 78020,
"text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\nimport java.util.LinkedHashMap;\nimport java.util.Locale;\nimport java.util.Map;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\nimport javax.faces.context.FacesContext;\nimport javax.faces.event.ValueChangeEvent;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n private String locale;\n\n private static Map<String,Object> countries;\n static {\n \n countries = new LinkedHashMap<String,Object>();\n countries.put(\"English\", Locale.ENGLISH);\n countries.put(\"French\", Locale.FRENCH);\n }\n\n public Map<String, Object> getCountries() {\n return countries;\n }\n\n public String getLocale() {\n return locale;\n }\n\n public void setLocale(String locale) {\n this.locale = locale;\n }\n\n //value change event listener\n public void localeChanged(ValueChangeEvent e) {\n String newLocaleValue = e.getNewValue().toString();\n \n for (Map.Entry<String, Object> entry : countries.entrySet()) {\n \n if(entry.getValue().toString().equals(newLocaleValue)) {\n FacesContext.getCurrentInstance()\n .getViewRoot().setLocale((Locale)entry.getValue()); \n }\n }\n }\n}"
},
{
"code": null,
"e": 80289,
"s": 79389,
"text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \nxmlns:h = \"http://java.sun.com/jsf/html\"\nxmlns:f = \"http://java.sun.com/jsf/core\">\n \n <h:head>\n <title>JSF tutorial</title>\t \t\n </h:head>\n \n <h:body> \n <h2>Internalization Language Example</h2>\n \n <h:form>\n <h3><h:outputText value = \"#{msg['greeting']}\" /></h3>\n \n <h:panelGrid columns = \"2\"> \n Language : \n <h:selectOneMenu value = \"#{userData.locale}\" onchange = \"submit()\"\n valueChangeListener = \"#{userData.localeChanged}\">\n <f:selectItems value = \"#{userData.countries}\" /> \n </h:selectOneMenu> \n </h:panelGrid> \n \n </h:form>\n </h:body>\n</html>"
},
{
"code": null,
"e": 80505,
"s": 80289,
"text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result."
},
{
"code": null,
"e": 80571,
"s": 80505,
"text": "Change language from dropdown. You will see the following output."
},
{
"code": null,
"e": 80606,
"s": 80571,
"text": "\n 37 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 80621,
"s": 80606,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 80628,
"s": 80621,
"text": " Print"
},
{
"code": null,
"e": 80639,
"s": 80628,
"text": " Add Notes"
}
] |
Convert from any base to decimal and vice versa - GeeksforGeeks | 27 May, 2021
Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11 and so on. Write a function to convert the number to decimal.
Examples:
Input number is given as string and output is an integer.
Input: str = "1100", base = 2
Output: 12
Input: str = "11A", base = 16
Output: 282
Input: str = "123", base = 8
Output: 83
We strongly recommend you to minimize your browser and try this yourself first. We can always use the below formula to convert from any base to decimal.
"str" is input number as a string
"base" is the base of the input number.
Decimal Equivalent is,
1*str[len-1] + base*str[len-2] + (base)2*str[len-3] + ...
Below is implementation of above formula.
C
Java
Python3
C#
PHP
Javascript
// C program to convert a number from any base// to decimal#include <stdio.h>#include <string.h> // To return value of a char. For example, 2 is// returned for '2'. 10 is returned for 'A', 11// for 'B'int val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a number from given base 'b'// to decimalint toDeci(char *str, int base){ int len = strlen(str); int power = 1; // Initialize power of base int num = 0; // Initialize result int i; // Decimal equivalent is str[len-1]*1 + // str[len-2]*base + str[len-3]*(base^2) + ... for (i = len - 1; i >= 0; i--) { // A digit in input number must be // less than number's base if (val(str[i]) >= base) { printf("Invalid Number"); return -1; } num += val(str[i]) * power; power = power * base; } return num;} // Driver codeint main(){ char str[] = "11A"; int base = 16; printf("Decimal equivalent of %s in base %d is " " %d\n", str, base, toDeci(str, base)); return 0;}
// Java program to convert// a number from any base// to decimalimport java.io.*; class GFG{// To return value of a char.// For example, 2 is returned// for '2'. 10 is returned// for 'A', 11 for 'B'static int val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a// number from given base// 'b' to decimalstatic int toDeci(String str, int base){ int len = str.length(); int power = 1; // Initialize // power of base int num = 0; // Initialize result int i; // Decimal equivalent is // str[len-1]*1 + str[len-2] * // base + str[len-3]*(base^2) + ... for (i = len - 1; i >= 0; i--) { // A digit in input number // must be less than // number's base if (val(str.charAt(i)) >= base) { System.out.println("Invalid Number"); return -1; } num += val(str.charAt(i)) * power; power = power * base; } return num;} // Driver codepublic static void main (String[] args){ String str = "11A"; int base = 16; System.out.println("Decimal equivalent of "+ str + " in base "+ base + " is "+ " "+ toDeci(str, base));}} // This code is contributed// by anuj_67.
# Python program to convert a# number from any base to decimal # To return value of a char.# For example, 2 is returned# for '2'. 10 is returned for 'A',# 11 for 'B'def val(c): if c >= '0' and c <= '9': return ord(c) - ord('0') else: return ord(c) - ord('A') + 10; # Function to convert a number# from given base 'b' to decimaldef toDeci(str,base): llen = len(str) power = 1 #Initialize power of base num = 0 #Initialize result # Decimal equivalent is str[len-1]*1 + # str[len-2]*base + str[len-3]*(base^2) + ... for i in range(llen - 1, -1, -1): # A digit in input number must # be less than number's base if val(str[i]) >= base: print('Invalid Number') return -1 num += val(str[i]) * power power = power * base return num # Driver codestrr = "11A"base = 16print('Decimal equivalent of', strr, 'in base', base, 'is', toDeci(strr, base)) # This code is contributed# by Sahil shelangia
// C# program to convert// a number from any base// to decimalusing System; class GFG{// To return value of a char.// For example, 2 is returned// for '2'. 10 is returned// for 'A', 11 for 'B'static int val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a// number from given base// 'b' to decimalstatic int toDeci(string str, int b_ase){ int len = str.Length; int power = 1; // Initialize // power of base int num = 0; // Initialize result int i; // Decimal equivalent is // str[len-1]*1 + str[len-2] * // base + str[len-3]*(base^2) + ... for (i = len - 1; i >= 0; i--) { // A digit in input number // must be less than // number's base if (val(str[i]) >= b_ase) { Console.WriteLine("Invalid Number"); return -1; } num += val(str[i]) * power; power = power * b_ase; } return num;} // Driver codepublic static void Main (){ string str = "11A"; int b_ase = 16; Console.WriteLine("Decimal equivalent of "+ str + " in base "+ b_ase + " is " + toDeci(str, b_ase));}} // This code is contributed// by anuj_67.
<?php// PHP program to convert a number from// any base to decimal // To return value of a char. For example,// 2 is returned for '2'. 10 is returned// for 'A', 11 for 'B'function val($c){ if ($c >= '0' && $c <= '9') return ord($c) - ord('0'); else return ord($c) - ord('A') + 10;} // Function to convert a number from given// base 'b' to decimalfunction toDeci($str, $base){ $len = strlen($str); $power = 1; // Initialize power of base $num = 0; // Initialize result // Decimal equivalent is str[len-1]*1 + // str[len-2]*base + str[len-3]*(base^2) + ... for ($i = $len - 1; $i >= 0; $i--) { // A digit in input number must be // less than number's base if (val($str[$i]) >= $base) { print("Invalid Number"); return -1; } $num += val($str[$i]) * $power; $power = $power * $base; } return $num;} // Driver code$str = "11A";$base = 16;print("Decimal equivalent of $str " . "in base $base is " . toDeci($str, $base)); // This code is contributed by mits?>
<script> // Javascript program to convert// a number from any base// to decimal // To return value of a char.// For example, 2 is returned// for '2'. 10 is returned// for 'A', 11 for 'B'function val(c){ if (c >= '0'.charCodeAt() && c <= '9'.charCodeAt()) return (c - '0'.charCodeAt()); else return (c - 'A'.charCodeAt() + 10);} // Function to convert a// number from given base// 'b' to decimalfunction toDeci(str, b_ase){ let len = str.length; // Initialize // power of base let power = 1; // Initialize result let num = 0; let i; // Decimal equivalent is // str[len-1]*1 + str[len-2] * // base + str[len-3]*(base^2) + ... for(i = len - 1; i >= 0; i--) { // A digit in input number // must be less than // number's base if (val(str[i].charCodeAt()) >= b_ase) { document.write("Invalid Number"); return -1; } num += val(str[i].charCodeAt()) * power; power = power * b_ase; } return num;} // Driver codelet str = "11A";let b_ase = 16; document.write("Decimal equivalent of "+ str + " in base "+ b_ase + " is " + toDeci(str, b_ase)); // This code is contributed by divyesh072019 </script>
Output :
Decimal equivalent of 11A in base 16 is 282
How to do reverse? Let the given input decimal number be “inputNum” and target base be “base”. We repeatedly divide inputNum by base and store the remainder. We finally reverse the obtained string. Below is C implementation.
C
Java
Python3
C#
PHP
Javascript
// C Program to convert decimal to any given base#include <stdio.h>#include <string.h> // To return char for a value. For example '2'// is returned for 2. 'A' is returned for 10. 'B'// for 11char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + '0'); else return (char)(num - 10 + 'A');} // Utility function to reverse a stringvoid strev(char *str){ int len = strlen(str); int i; for (i = 0; i < len/2; i++) { char temp = str[i]; str[i] = str[len-i-1]; str[len-i-1] = temp; }} // Function to convert a given decimal number// to a base 'base' andchar* fromDeci(char res[], int base, int inputNum){ int index = 0; // Initialize index of result // Convert input number is given base by repeatedly // dividing it by base and taking remainder while (inputNum > 0) { res[index++] = reVal(inputNum % base); inputNum /= base; } res[index] = '\0'; // Reverse the result strev(res); return res;} // Driver programint main(){ int inputNum = 282, base = 16; char res[100]; printf("Equivalent of %d in base %d is " " %s\n", inputNum, base, fromDeci(res, base, inputNum)); return 0;}
// Java Program to convert decimal to any given baseimport java.lang.*;import java.io.*;import java.util.*; class GFG{ // To return char for a value. For// example '2' is returned for 2.// 'A' is returned for 10. 'B' for 11static char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65);} // Function to convert a given decimal number// to a base 'base' andstatic String fromDeci(int base1, int inputNum){ String s = ""; // Convert input number is given // base by repeatedly dividing it // by base and taking remainder while (inputNum > 0) { s += reVal(inputNum % base1); inputNum /= base1; } StringBuilder ix = new StringBuilder(); // append a string into StringBuilder input1 ix.append(s); // Reverse the result return new String(ix.reverse());} // Driver codepublic static void main (String[] args){ int inputNum = 282, base1 = 16; System.out.println("Equivalent of " + inputNum + " in base "+base1+" is " + fromDeci(base1, inputNum));}} // This code is contributed by mits
# Python3 Program to convert decimal to# any given base # To return char for a value. For example# '2' is returned for 2. 'A' is returned# for 10. 'B' for 11def reVal(num): if (num >= 0 and num <= 9): return chr(num + ord('0')); else: return chr(num - 10 + ord('A')); # Utility function to reverse a stringdef strev(str): len = len(str); for i in range(int(len / 2)): temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; # Function to convert a given decimal# number to a base 'base' anddef fromDeci(res, base, inputNum): index = 0; # Initialize index of result # Convert input number is given base # by repeatedly dividing it by base # and taking remainder while (inputNum > 0): res+= reVal(inputNum % base); inputNum = int(inputNum / base); # Reverse the result res = res[::-1]; return res; # Driver CodeinputNum = 282;base = 16;res = "";print("Equivalent of", inputNum, "in base", base, "is", fromDeci(res, base, inputNum)); # This code is contributed by mits
// C# Program to convert decimal to any given baseusing System;using System.Collections; class GFG{ // To return char for a value. For// example '2' is returned for 2.// 'A' is returned for 10. 'B' for 11static char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65);} // Function to convert a given decimal number// to a base 'base' andstatic string fromDeci(int base1, int inputNum){ string s = ""; // Convert input number is given // base by repeatedly dividing it // by base and taking remainder while (inputNum > 0) { s += reVal(inputNum % base1); inputNum /= base1; } char[] res = s.ToCharArray(); // Reverse the result Array.Reverse(res); return new String(res);} // Driver codestatic void Main(){ int inputNum = 282, base1 = 16; Console.WriteLine("Equivalent of " + inputNum + " in base "+base1+" is " + fromDeci(base1, inputNum));}} // This code is contributed by mits
<?php// PHP Program to convert decimal to// any given base // To return char for a value. For example '2'// is returned for 2. 'A' is returned for 10.// 'B' for 11function reVal($num){ if ($num >= 0 && $num <= 9) return chr($num + ord('0')); else return chr($num - 10 + ord('A'));} // Utility function to reverse a stringfunction strev($str){ $len = strlen($str); for ($i = 0; $i < $len / 2; $i++) { $temp = $str[$i]; $str[$i] = $str[$len - $i - 1]; $str[$len - $i - 1] = $temp; }} // Function to convert a given decimal// number to a base 'base' andfunction fromDeci($res, $base, $inputNum){ $index = 0; // Initialize index of result // Convert input number is given base // by repeatedly dividing it by base // and taking remainder while ($inputNum > 0) { $res.= reVal($inputNum % $base); $inputNum = (int)($inputNum / $base); } // Reverse the result $res = strrev($res); return $res;} // Driver Code$inputNum = 282;$base = 16;$res = "";print("Equivalent of $inputNum in base $base is " . fromDeci($res, $base, $inputNum)); // This code is contributed by mits?>
<script> // Javascript Program to convert decimal to any given base // To return char for a value. For // example '2' is returned for 2. // 'A' is returned for 10. 'B' for 11 function reVal(num) { if (num >= 0 && num <= 9) return String.fromCharCode(num + 48); else return String.fromCharCode(num - 10 + 65); } // Function to convert a given decimal number // to a base 'base' and function fromDeci(base1, inputNum) { let s = ""; // Convert input number is given // base by repeatedly dividing it // by base and taking remainder while (inputNum > 0) { s += reVal(inputNum % base1); inputNum = parseInt(inputNum / base1, 10); } let res = s.split(''); // Reverse the result res.reverse(); return res.join(""); } let inputNum = 282, base1 = 16; document.write("Equivalent of " + inputNum + " in base "+base1+" is " + fromDeci(base1, inputNum)); // This code is contributed by rameshtravel07.</script>
Output :
Equivalent of 282 in base 16 is 11A
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vt_m
sahilshelangia
Mithun Kumar
anshuunstoppable
divyesh072019
rameshtravel07
base-conversion
Motlay
Mathematical
Motlay
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Operators in C / C++
Euclidean algorithms (Basic and Extended)
Algorithm to solve Rubik's Cube
The Knight's tour problem | Backtracking-1
Write a program to calculate pow(x,n)
Print all possible combinations of r elements in a given array of size n
How to swap two numbers without using a temporary variable?
Find minimum number of coins that make a given value
Write a program to reverse digits of a number | [
{
"code": null,
"e": 24668,
"s": 24640,
"text": "\n27 May, 2021"
},
{
"code": null,
"e": 24925,
"s": 24668,
"text": "Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11 and so on. Write a function to convert the number to decimal."
},
{
"code": null,
"e": 24936,
"s": 24925,
"text": "Examples: "
},
{
"code": null,
"e": 25123,
"s": 24936,
"text": "Input number is given as string and output is an integer.\n\nInput: str = \"1100\", base = 2 \nOutput: 12\n\nInput: str = \"11A\", base = 16\nOutput: 282\n\nInput: str = \"123\", base = 8\nOutput: 83 "
},
{
"code": null,
"e": 25276,
"s": 25123,
"text": "We strongly recommend you to minimize your browser and try this yourself first. We can always use the below formula to convert from any base to decimal."
},
{
"code": null,
"e": 25435,
"s": 25276,
"text": "\"str\" is input number as a string \n\"base\" is the base of the input number.\n\nDecimal Equivalent is,\n 1*str[len-1] + base*str[len-2] + (base)2*str[len-3] + ..."
},
{
"code": null,
"e": 25479,
"s": 25435,
"text": "Below is implementation of above formula. "
},
{
"code": null,
"e": 25481,
"s": 25479,
"text": "C"
},
{
"code": null,
"e": 25486,
"s": 25481,
"text": "Java"
},
{
"code": null,
"e": 25494,
"s": 25486,
"text": "Python3"
},
{
"code": null,
"e": 25497,
"s": 25494,
"text": "C#"
},
{
"code": null,
"e": 25501,
"s": 25497,
"text": "PHP"
},
{
"code": null,
"e": 25512,
"s": 25501,
"text": "Javascript"
},
{
"code": "// C program to convert a number from any base// to decimal#include <stdio.h>#include <string.h> // To return value of a char. For example, 2 is// returned for '2'. 10 is returned for 'A', 11// for 'B'int val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a number from given base 'b'// to decimalint toDeci(char *str, int base){ int len = strlen(str); int power = 1; // Initialize power of base int num = 0; // Initialize result int i; // Decimal equivalent is str[len-1]*1 + // str[len-2]*base + str[len-3]*(base^2) + ... for (i = len - 1; i >= 0; i--) { // A digit in input number must be // less than number's base if (val(str[i]) >= base) { printf(\"Invalid Number\"); return -1; } num += val(str[i]) * power; power = power * base; } return num;} // Driver codeint main(){ char str[] = \"11A\"; int base = 16; printf(\"Decimal equivalent of %s in base %d is \" \" %d\\n\", str, base, toDeci(str, base)); return 0;}",
"e": 26633,
"s": 25512,
"text": null
},
{
"code": "// Java program to convert// a number from any base// to decimalimport java.io.*; class GFG{// To return value of a char.// For example, 2 is returned// for '2'. 10 is returned// for 'A', 11 for 'B'static int val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a// number from given base// 'b' to decimalstatic int toDeci(String str, int base){ int len = str.length(); int power = 1; // Initialize // power of base int num = 0; // Initialize result int i; // Decimal equivalent is // str[len-1]*1 + str[len-2] * // base + str[len-3]*(base^2) + ... for (i = len - 1; i >= 0; i--) { // A digit in input number // must be less than // number's base if (val(str.charAt(i)) >= base) { System.out.println(\"Invalid Number\"); return -1; } num += val(str.charAt(i)) * power; power = power * base; } return num;} // Driver codepublic static void main (String[] args){ String str = \"11A\"; int base = 16; System.out.println(\"Decimal equivalent of \"+ str + \" in base \"+ base + \" is \"+ \" \"+ toDeci(str, base));}} // This code is contributed// by anuj_67.",
"e": 27995,
"s": 26633,
"text": null
},
{
"code": "# Python program to convert a# number from any base to decimal # To return value of a char.# For example, 2 is returned# for '2'. 10 is returned for 'A',# 11 for 'B'def val(c): if c >= '0' and c <= '9': return ord(c) - ord('0') else: return ord(c) - ord('A') + 10; # Function to convert a number# from given base 'b' to decimaldef toDeci(str,base): llen = len(str) power = 1 #Initialize power of base num = 0 #Initialize result # Decimal equivalent is str[len-1]*1 + # str[len-2]*base + str[len-3]*(base^2) + ... for i in range(llen - 1, -1, -1): # A digit in input number must # be less than number's base if val(str[i]) >= base: print('Invalid Number') return -1 num += val(str[i]) * power power = power * base return num # Driver codestrr = \"11A\"base = 16print('Decimal equivalent of', strr, 'in base', base, 'is', toDeci(strr, base)) # This code is contributed# by Sahil shelangia",
"e": 29025,
"s": 27995,
"text": null
},
{
"code": "// C# program to convert// a number from any base// to decimalusing System; class GFG{// To return value of a char.// For example, 2 is returned// for '2'. 10 is returned// for 'A', 11 for 'B'static int val(char c){ if (c >= '0' && c <= '9') return (int)c - '0'; else return (int)c - 'A' + 10;} // Function to convert a// number from given base// 'b' to decimalstatic int toDeci(string str, int b_ase){ int len = str.Length; int power = 1; // Initialize // power of base int num = 0; // Initialize result int i; // Decimal equivalent is // str[len-1]*1 + str[len-2] * // base + str[len-3]*(base^2) + ... for (i = len - 1; i >= 0; i--) { // A digit in input number // must be less than // number's base if (val(str[i]) >= b_ase) { Console.WriteLine(\"Invalid Number\"); return -1; } num += val(str[i]) * power; power = power * b_ase; } return num;} // Driver codepublic static void Main (){ string str = \"11A\"; int b_ase = 16; Console.WriteLine(\"Decimal equivalent of \"+ str + \" in base \"+ b_ase + \" is \" + toDeci(str, b_ase));}} // This code is contributed// by anuj_67.",
"e": 30301,
"s": 29025,
"text": null
},
{
"code": "<?php// PHP program to convert a number from// any base to decimal // To return value of a char. For example,// 2 is returned for '2'. 10 is returned// for 'A', 11 for 'B'function val($c){ if ($c >= '0' && $c <= '9') return ord($c) - ord('0'); else return ord($c) - ord('A') + 10;} // Function to convert a number from given// base 'b' to decimalfunction toDeci($str, $base){ $len = strlen($str); $power = 1; // Initialize power of base $num = 0; // Initialize result // Decimal equivalent is str[len-1]*1 + // str[len-2]*base + str[len-3]*(base^2) + ... for ($i = $len - 1; $i >= 0; $i--) { // A digit in input number must be // less than number's base if (val($str[$i]) >= $base) { print(\"Invalid Number\"); return -1; } $num += val($str[$i]) * $power; $power = $power * $base; } return $num;} // Driver code$str = \"11A\";$base = 16;print(\"Decimal equivalent of $str \" . \"in base $base is \" . toDeci($str, $base)); // This code is contributed by mits?>",
"e": 31380,
"s": 30301,
"text": null
},
{
"code": "<script> // Javascript program to convert// a number from any base// to decimal // To return value of a char.// For example, 2 is returned// for '2'. 10 is returned// for 'A', 11 for 'B'function val(c){ if (c >= '0'.charCodeAt() && c <= '9'.charCodeAt()) return (c - '0'.charCodeAt()); else return (c - 'A'.charCodeAt() + 10);} // Function to convert a// number from given base// 'b' to decimalfunction toDeci(str, b_ase){ let len = str.length; // Initialize // power of base let power = 1; // Initialize result let num = 0; let i; // Decimal equivalent is // str[len-1]*1 + str[len-2] * // base + str[len-3]*(base^2) + ... for(i = len - 1; i >= 0; i--) { // A digit in input number // must be less than // number's base if (val(str[i].charCodeAt()) >= b_ase) { document.write(\"Invalid Number\"); return -1; } num += val(str[i].charCodeAt()) * power; power = power * b_ase; } return num;} // Driver codelet str = \"11A\";let b_ase = 16; document.write(\"Decimal equivalent of \"+ str + \" in base \"+ b_ase + \" is \" + toDeci(str, b_ase)); // This code is contributed by divyesh072019 </script>",
"e": 32678,
"s": 31380,
"text": null
},
{
"code": null,
"e": 32688,
"s": 32678,
"text": "Output : "
},
{
"code": null,
"e": 32732,
"s": 32688,
"text": "Decimal equivalent of 11A in base 16 is 282"
},
{
"code": null,
"e": 32957,
"s": 32732,
"text": "How to do reverse? Let the given input decimal number be “inputNum” and target base be “base”. We repeatedly divide inputNum by base and store the remainder. We finally reverse the obtained string. Below is C implementation."
},
{
"code": null,
"e": 32959,
"s": 32957,
"text": "C"
},
{
"code": null,
"e": 32964,
"s": 32959,
"text": "Java"
},
{
"code": null,
"e": 32972,
"s": 32964,
"text": "Python3"
},
{
"code": null,
"e": 32975,
"s": 32972,
"text": "C#"
},
{
"code": null,
"e": 32979,
"s": 32975,
"text": "PHP"
},
{
"code": null,
"e": 32990,
"s": 32979,
"text": "Javascript"
},
{
"code": "// C Program to convert decimal to any given base#include <stdio.h>#include <string.h> // To return char for a value. For example '2'// is returned for 2. 'A' is returned for 10. 'B'// for 11char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + '0'); else return (char)(num - 10 + 'A');} // Utility function to reverse a stringvoid strev(char *str){ int len = strlen(str); int i; for (i = 0; i < len/2; i++) { char temp = str[i]; str[i] = str[len-i-1]; str[len-i-1] = temp; }} // Function to convert a given decimal number// to a base 'base' andchar* fromDeci(char res[], int base, int inputNum){ int index = 0; // Initialize index of result // Convert input number is given base by repeatedly // dividing it by base and taking remainder while (inputNum > 0) { res[index++] = reVal(inputNum % base); inputNum /= base; } res[index] = '\\0'; // Reverse the result strev(res); return res;} // Driver programint main(){ int inputNum = 282, base = 16; char res[100]; printf(\"Equivalent of %d in base %d is \" \" %s\\n\", inputNum, base, fromDeci(res, base, inputNum)); return 0;}",
"e": 34199,
"s": 32990,
"text": null
},
{
"code": "// Java Program to convert decimal to any given baseimport java.lang.*;import java.io.*;import java.util.*; class GFG{ // To return char for a value. For// example '2' is returned for 2.// 'A' is returned for 10. 'B' for 11static char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65);} // Function to convert a given decimal number// to a base 'base' andstatic String fromDeci(int base1, int inputNum){ String s = \"\"; // Convert input number is given // base by repeatedly dividing it // by base and taking remainder while (inputNum > 0) { s += reVal(inputNum % base1); inputNum /= base1; } StringBuilder ix = new StringBuilder(); // append a string into StringBuilder input1 ix.append(s); // Reverse the result return new String(ix.reverse());} // Driver codepublic static void main (String[] args){ int inputNum = 282, base1 = 16; System.out.println(\"Equivalent of \" + inputNum + \" in base \"+base1+\" is \" + fromDeci(base1, inputNum));}} // This code is contributed by mits",
"e": 35371,
"s": 34199,
"text": null
},
{
"code": "# Python3 Program to convert decimal to# any given base # To return char for a value. For example# '2' is returned for 2. 'A' is returned# for 10. 'B' for 11def reVal(num): if (num >= 0 and num <= 9): return chr(num + ord('0')); else: return chr(num - 10 + ord('A')); # Utility function to reverse a stringdef strev(str): len = len(str); for i in range(int(len / 2)): temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; # Function to convert a given decimal# number to a base 'base' anddef fromDeci(res, base, inputNum): index = 0; # Initialize index of result # Convert input number is given base # by repeatedly dividing it by base # and taking remainder while (inputNum > 0): res+= reVal(inputNum % base); inputNum = int(inputNum / base); # Reverse the result res = res[::-1]; return res; # Driver CodeinputNum = 282;base = 16;res = \"\";print(\"Equivalent of\", inputNum, \"in base\", base, \"is\", fromDeci(res, base, inputNum)); # This code is contributed by mits",
"e": 36445,
"s": 35371,
"text": null
},
{
"code": "// C# Program to convert decimal to any given baseusing System;using System.Collections; class GFG{ // To return char for a value. For// example '2' is returned for 2.// 'A' is returned for 10. 'B' for 11static char reVal(int num){ if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65);} // Function to convert a given decimal number// to a base 'base' andstatic string fromDeci(int base1, int inputNum){ string s = \"\"; // Convert input number is given // base by repeatedly dividing it // by base and taking remainder while (inputNum > 0) { s += reVal(inputNum % base1); inputNum /= base1; } char[] res = s.ToCharArray(); // Reverse the result Array.Reverse(res); return new String(res);} // Driver codestatic void Main(){ int inputNum = 282, base1 = 16; Console.WriteLine(\"Equivalent of \" + inputNum + \" in base \"+base1+\" is \" + fromDeci(base1, inputNum));}} // This code is contributed by mits",
"e": 37506,
"s": 36445,
"text": null
},
{
"code": "<?php// PHP Program to convert decimal to// any given base // To return char for a value. For example '2'// is returned for 2. 'A' is returned for 10.// 'B' for 11function reVal($num){ if ($num >= 0 && $num <= 9) return chr($num + ord('0')); else return chr($num - 10 + ord('A'));} // Utility function to reverse a stringfunction strev($str){ $len = strlen($str); for ($i = 0; $i < $len / 2; $i++) { $temp = $str[$i]; $str[$i] = $str[$len - $i - 1]; $str[$len - $i - 1] = $temp; }} // Function to convert a given decimal// number to a base 'base' andfunction fromDeci($res, $base, $inputNum){ $index = 0; // Initialize index of result // Convert input number is given base // by repeatedly dividing it by base // and taking remainder while ($inputNum > 0) { $res.= reVal($inputNum % $base); $inputNum = (int)($inputNum / $base); } // Reverse the result $res = strrev($res); return $res;} // Driver Code$inputNum = 282;$base = 16;$res = \"\";print(\"Equivalent of $inputNum in base $base is \" . fromDeci($res, $base, $inputNum)); // This code is contributed by mits?>",
"e": 38686,
"s": 37506,
"text": null
},
{
"code": "<script> // Javascript Program to convert decimal to any given base // To return char for a value. For // example '2' is returned for 2. // 'A' is returned for 10. 'B' for 11 function reVal(num) { if (num >= 0 && num <= 9) return String.fromCharCode(num + 48); else return String.fromCharCode(num - 10 + 65); } // Function to convert a given decimal number // to a base 'base' and function fromDeci(base1, inputNum) { let s = \"\"; // Convert input number is given // base by repeatedly dividing it // by base and taking remainder while (inputNum > 0) { s += reVal(inputNum % base1); inputNum = parseInt(inputNum / base1, 10); } let res = s.split(''); // Reverse the result res.reverse(); return res.join(\"\"); } let inputNum = 282, base1 = 16; document.write(\"Equivalent of \" + inputNum + \" in base \"+base1+\" is \" + fromDeci(base1, inputNum)); // This code is contributed by rameshtravel07.</script>",
"e": 39828,
"s": 38686,
"text": null
},
{
"code": null,
"e": 39837,
"s": 39828,
"text": "Output :"
},
{
"code": null,
"e": 39874,
"s": 39837,
"text": "Equivalent of 282 in base 16 is 11A"
},
{
"code": null,
"e": 39999,
"s": 39874,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 40004,
"s": 39999,
"text": "vt_m"
},
{
"code": null,
"e": 40019,
"s": 40004,
"text": "sahilshelangia"
},
{
"code": null,
"e": 40032,
"s": 40019,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 40049,
"s": 40032,
"text": "anshuunstoppable"
},
{
"code": null,
"e": 40063,
"s": 40049,
"text": "divyesh072019"
},
{
"code": null,
"e": 40078,
"s": 40063,
"text": "rameshtravel07"
},
{
"code": null,
"e": 40094,
"s": 40078,
"text": "base-conversion"
},
{
"code": null,
"e": 40101,
"s": 40094,
"text": "Motlay"
},
{
"code": null,
"e": 40114,
"s": 40101,
"text": "Mathematical"
},
{
"code": null,
"e": 40121,
"s": 40114,
"text": "Motlay"
},
{
"code": null,
"e": 40134,
"s": 40121,
"text": "Mathematical"
},
{
"code": null,
"e": 40232,
"s": 40134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40241,
"s": 40232,
"text": "Comments"
},
{
"code": null,
"e": 40254,
"s": 40241,
"text": "Old Comments"
},
{
"code": null,
"e": 40303,
"s": 40254,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 40324,
"s": 40303,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 40366,
"s": 40324,
"text": "Euclidean algorithms (Basic and Extended)"
},
{
"code": null,
"e": 40398,
"s": 40366,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 40441,
"s": 40398,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 40479,
"s": 40441,
"text": "Write a program to calculate pow(x,n)"
},
{
"code": null,
"e": 40552,
"s": 40479,
"text": "Print all possible combinations of r elements in a given array of size n"
},
{
"code": null,
"e": 40612,
"s": 40552,
"text": "How to swap two numbers without using a temporary variable?"
},
{
"code": null,
"e": 40665,
"s": 40612,
"text": "Find minimum number of coins that make a given value"
}
] |
Using Python to Connect to a GraphQL API | by Melvynn Fernandez | Towards Data Science | Let’s automate and remove the margin for error, trying to get rid of the front end one step at a time.
What exactly is GraphQL?GraphQL in its simplest terms a query language used for the front end. We send a request and retrieve certain data back. GraphQL is also advanced enough to make changes in the data called mutations. But that requires a whole new article to explain.
So the main reason I wanted to connect to GraphQL directly is because we have a web application where we must manually fill in fields one by one. Not the most effective use of my time if we know it’s repetitive.
The old method I used was thru Selenium, which also caused room for error whenever front end engineers made some changes. So I did some research and decided why not just send the data directly thru GraphQL. I still grab data from SalesForce, I have an article showing you how to do that here. I would then process all that data and send to the GraphQL endpoint.
But I am getting sidetracked, let’s connect to GraphQL using Python and get some data back!
Getting StartedAssuming you already have Python installed the main modules you need are:1. requests (used to connect to GraphQL)2. json (used to parse GraphQL data)3. pandas (used for visibility of our data)
Let’s import these modules into a new Python script.
import requestsimport jsonimport pandas as pd
For tutorial purposes, we will connect to a GraphQL endpoint that does not require authentication. We will connect to a Rick and Morty GraphQL API!
Let’s start with something simple, a dataset of characters will do. The information I want from each of them is the name, status, species, type and gender. We can set this GraphQL query as a string and set it as a variable like this:
query = """query { characters { results { name status species type gender } }}"""
The people who made this made it really easy for us to connect. We get a limit of 10000 requests per day, so use them sparingly. The next few lines of code we set the URL, send the request to them aka the query. If successful we should get a status_code of 200 and text in the format of a string.
url = 'https://rickandmortyapi.com/graphql/'r = requests.post(url, json={'query': query})print(r.status_code)print(r.text)
The r.text is in the format of a string. This is where the module json comes in. Let’s transform this string to a JSON format so we can move it to a DataFrame.
json_data = json.loads(r.text)
We only want name, status, species, type, and gender. So before we push it to a DataFrame, since it is a nested JSON we want to move further into the nest. Now we can send it to be translated to a DataFrame. We can do that with the following code:
df_data = json_data[‘data’][‘characters’][‘results’]df = pd.DataFrame(df_data)
Our DataFrame should now look like this.
Now that is has been transferred to a pandas DataFrame the possibilities are endless!
Access to my code here!
I also have tutoring and career guidance available here!
Don’t forget to connect with me on LinkedIn if you guys have any questions, comments or concerns! | [
{
"code": null,
"e": 275,
"s": 172,
"text": "Let’s automate and remove the margin for error, trying to get rid of the front end one step at a time."
},
{
"code": null,
"e": 548,
"s": 275,
"text": "What exactly is GraphQL?GraphQL in its simplest terms a query language used for the front end. We send a request and retrieve certain data back. GraphQL is also advanced enough to make changes in the data called mutations. But that requires a whole new article to explain."
},
{
"code": null,
"e": 760,
"s": 548,
"text": "So the main reason I wanted to connect to GraphQL directly is because we have a web application where we must manually fill in fields one by one. Not the most effective use of my time if we know it’s repetitive."
},
{
"code": null,
"e": 1122,
"s": 760,
"text": "The old method I used was thru Selenium, which also caused room for error whenever front end engineers made some changes. So I did some research and decided why not just send the data directly thru GraphQL. I still grab data from SalesForce, I have an article showing you how to do that here. I would then process all that data and send to the GraphQL endpoint."
},
{
"code": null,
"e": 1214,
"s": 1122,
"text": "But I am getting sidetracked, let’s connect to GraphQL using Python and get some data back!"
},
{
"code": null,
"e": 1422,
"s": 1214,
"text": "Getting StartedAssuming you already have Python installed the main modules you need are:1. requests (used to connect to GraphQL)2. json (used to parse GraphQL data)3. pandas (used for visibility of our data)"
},
{
"code": null,
"e": 1475,
"s": 1422,
"text": "Let’s import these modules into a new Python script."
},
{
"code": null,
"e": 1521,
"s": 1475,
"text": "import requestsimport jsonimport pandas as pd"
},
{
"code": null,
"e": 1669,
"s": 1521,
"text": "For tutorial purposes, we will connect to a GraphQL endpoint that does not require authentication. We will connect to a Rick and Morty GraphQL API!"
},
{
"code": null,
"e": 1903,
"s": 1669,
"text": "Let’s start with something simple, a dataset of characters will do. The information I want from each of them is the name, status, species, type and gender. We can set this GraphQL query as a string and set it as a variable like this:"
},
{
"code": null,
"e": 2020,
"s": 1903,
"text": "query = \"\"\"query { characters { results { name status species type gender } }}\"\"\""
},
{
"code": null,
"e": 2317,
"s": 2020,
"text": "The people who made this made it really easy for us to connect. We get a limit of 10000 requests per day, so use them sparingly. The next few lines of code we set the URL, send the request to them aka the query. If successful we should get a status_code of 200 and text in the format of a string."
},
{
"code": null,
"e": 2440,
"s": 2317,
"text": "url = 'https://rickandmortyapi.com/graphql/'r = requests.post(url, json={'query': query})print(r.status_code)print(r.text)"
},
{
"code": null,
"e": 2600,
"s": 2440,
"text": "The r.text is in the format of a string. This is where the module json comes in. Let’s transform this string to a JSON format so we can move it to a DataFrame."
},
{
"code": null,
"e": 2631,
"s": 2600,
"text": "json_data = json.loads(r.text)"
},
{
"code": null,
"e": 2879,
"s": 2631,
"text": "We only want name, status, species, type, and gender. So before we push it to a DataFrame, since it is a nested JSON we want to move further into the nest. Now we can send it to be translated to a DataFrame. We can do that with the following code:"
},
{
"code": null,
"e": 2958,
"s": 2879,
"text": "df_data = json_data[‘data’][‘characters’][‘results’]df = pd.DataFrame(df_data)"
},
{
"code": null,
"e": 2999,
"s": 2958,
"text": "Our DataFrame should now look like this."
},
{
"code": null,
"e": 3085,
"s": 2999,
"text": "Now that is has been transferred to a pandas DataFrame the possibilities are endless!"
},
{
"code": null,
"e": 3109,
"s": 3085,
"text": "Access to my code here!"
},
{
"code": null,
"e": 3166,
"s": 3109,
"text": "I also have tutoring and career guidance available here!"
}
] |
How to remove all non-printable characters in a string in PHP? - GeeksforGeeks | 07 May, 2019
Given a string which contains printable and not-printable characters. The task is to remove all non-printable characters from the string. Space ( ) is first printable char and tilde (~) is last printable ASCII characters. So the task is to replace all characters which do fall in that range means to take only those char which occur in range(32-127). This task is done by only differents type regex expression.
Example:
Input: str = "\n\nGeeks \n\n\n\tfor Geeks\n\t"
Output: Geeks for Geeks
Note: Newline (\n) and tab (\t) are commands not printable character.
Method 1: Using general regular expression: There are many regex available. The best solution is to strip all non-ASCII characters from the input string, that can be done with this preg_replace.
Example:
<?PHP// PHP program to remove all non-printable// character from string // String with non printable characters$str = "Geeks šžfor ÂGee\tks\n"; // Using preg_replace method to remove all // non-printable character from string$str = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $str); // Display the modify stringecho($str); ?>
Geeks for Geeks
Method 2: Use the ‘print’ regex: Other possible solution is to use the print regular expression. The [:print:] regular expression stands for “any printable character”.
Example:
<?PHP// PHP program to remove all non-printable// character from string // String with non printable char$str = "Geeks šžfor ÂGee\tks\n"; // Using preg_replace method to remove all // non-printable character from string$str = preg_replace('/[[:^print:]]/', '', $str); // Display modify stringecho($str); ?>
Geeks for Geeks
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
How to receive JSON POST with PHP ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP | [
{
"code": null,
"e": 25186,
"s": 25158,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 25597,
"s": 25186,
"text": "Given a string which contains printable and not-printable characters. The task is to remove all non-printable characters from the string. Space ( ) is first printable char and tilde (~) is last printable ASCII characters. So the task is to replace all characters which do fall in that range means to take only those char which occur in range(32-127). This task is done by only differents type regex expression."
},
{
"code": null,
"e": 25606,
"s": 25597,
"text": "Example:"
},
{
"code": null,
"e": 25678,
"s": 25606,
"text": "Input: str = \"\\n\\nGeeks \\n\\n\\n\\tfor Geeks\\n\\t\"\nOutput: Geeks for Geeks\n"
},
{
"code": null,
"e": 25748,
"s": 25678,
"text": "Note: Newline (\\n) and tab (\\t) are commands not printable character."
},
{
"code": null,
"e": 25943,
"s": 25748,
"text": "Method 1: Using general regular expression: There are many regex available. The best solution is to strip all non-ASCII characters from the input string, that can be done with this preg_replace."
},
{
"code": null,
"e": 25952,
"s": 25943,
"text": "Example:"
},
{
"code": "<?PHP// PHP program to remove all non-printable// character from string // String with non printable characters$str = \"Geeks šžfor ÂGee\\tks\\n\"; // Using preg_replace method to remove all // non-printable character from string$str = preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $str); // Display the modify stringecho($str); ?>",
"e": 26284,
"s": 25952,
"text": null
},
{
"code": null,
"e": 26301,
"s": 26284,
"text": "Geeks for Geeks\n"
},
{
"code": null,
"e": 26469,
"s": 26301,
"text": "Method 2: Use the ‘print’ regex: Other possible solution is to use the print regular expression. The [:print:] regular expression stands for “any printable character”."
},
{
"code": null,
"e": 26478,
"s": 26469,
"text": "Example:"
},
{
"code": " <?PHP// PHP program to remove all non-printable// character from string // String with non printable char$str = \"Geeks šžfor ÂGee\\tks\\n\"; // Using preg_replace method to remove all // non-printable character from string$str = preg_replace('/[[:^print:]]/', '', $str); // Display modify stringecho($str); ?>",
"e": 26795,
"s": 26478,
"text": null
},
{
"code": null,
"e": 26812,
"s": 26795,
"text": "Geeks for Geeks\n"
},
{
"code": null,
"e": 26819,
"s": 26812,
"text": "Picked"
},
{
"code": null,
"e": 26823,
"s": 26819,
"text": "PHP"
},
{
"code": null,
"e": 26836,
"s": 26823,
"text": "PHP Programs"
},
{
"code": null,
"e": 26853,
"s": 26836,
"text": "Web Technologies"
},
{
"code": null,
"e": 26880,
"s": 26853,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26884,
"s": 26880,
"text": "PHP"
},
{
"code": null,
"e": 26982,
"s": 26884,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26991,
"s": 26982,
"text": "Comments"
},
{
"code": null,
"e": 27004,
"s": 26991,
"text": "Old Comments"
},
{
"code": null,
"e": 27054,
"s": 27004,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27094,
"s": 27054,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27144,
"s": 27094,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 27171,
"s": 27144,
"text": "Comparing two dates in PHP"
},
{
"code": null,
"e": 27207,
"s": 27171,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 27257,
"s": 27207,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 27297,
"s": 27257,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 27349,
"s": 27297,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 27399,
"s": 27349,
"text": "How to check whether an array is empty using PHP?"
}
] |
GATE | GATE CS 1996 | Question 13 | 20 May, 2019
An advantage of chained hash table (external hashing) over the open addressing scheme is
(A) Worst case complexity of search operations is less(B) Space used is less(C) Deletion is easier(D) None of the aboveAnswer: (C)Explanation:
In Open Addressing scheme sometimes though element is present we can't delete it if empty bucket comes in between while searching for that element.
External hashing scheme is free from this limitations .
Hence, Option c is correct answer.
Quiz of this Question
GATE CS 1996
GATE-GATE CS 1996
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE CS 2008 | Question 40
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31 | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 May, 2019"
},
{
"code": null,
"e": 117,
"s": 28,
"text": "An advantage of chained hash table (external hashing) over the open addressing scheme is"
},
{
"code": null,
"e": 260,
"s": 117,
"text": "(A) Worst case complexity of search operations is less(B) Space used is less(C) Deletion is easier(D) None of the aboveAnswer: (C)Explanation:"
},
{
"code": null,
"e": 500,
"s": 260,
"text": "In Open Addressing scheme sometimes though element is present we can't delete it if empty bucket comes in between while searching for that element.\nExternal hashing scheme is free from this limitations .\nHence, Option c is correct answer. "
},
{
"code": null,
"e": 522,
"s": 500,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 535,
"s": 522,
"text": "GATE CS 1996"
},
{
"code": null,
"e": 553,
"s": 535,
"text": "GATE-GATE CS 1996"
},
{
"code": null,
"e": 558,
"s": 553,
"text": "GATE"
},
{
"code": null,
"e": 656,
"s": 558,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 698,
"s": 656,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
},
{
"code": null,
"e": 760,
"s": 698,
"text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33"
},
{
"code": null,
"e": 802,
"s": 760,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 20"
},
{
"code": null,
"e": 836,
"s": 802,
"text": "GATE | GATE CS 2008 | Question 46"
},
{
"code": null,
"e": 878,
"s": 836,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 51"
},
{
"code": null,
"e": 920,
"s": 878,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 962,
"s": 920,
"text": "GATE | GATE-CS-2015 (Set 2) | Question 55"
},
{
"code": null,
"e": 996,
"s": 962,
"text": "GATE | GATE CS 2008 | Question 40"
},
{
"code": null,
"e": 1030,
"s": 996,
"text": "GATE | GATE-CS-2001 | Question 50"
}
] |
SQL Interview Questions | Set 2 | 14 Jun, 2022
Difference between Locking, Blocking and DeadlockingLocking: Locking occurs when a connection needs access to a piece of data in a database and it locks it for certain use so that no other transaction is able to access it.Blocking: Blocking occurs when a transaction tries to acquire an incompatible lock on a resource that another transaction has already locked. The blocked transaction remains blocked until the blocking transaction releases the lock.Deadlocking: Deadlocking occurs when two or more transactions have a resource locked, and each transaction requests a lock on the resource that another transaction has already locked. Neither of the transactions here can move forward, as each one is waiting for the other to release the lock.Delete duplicate data from table so that only first data remains constantManagersIdNameSalary1Harpreet200002Ravi300003Vinay100004Ravi300005Harpreet200006Vinay100007Rajeev400008Vinay100009Ravi3000010Sanjay50000Query:DELETE M1 from managers M1, managers M2 where M2.Name=M1.Name AND M1.Id>M2.Id;
Output:IdNameSalary1Harpreet200002Ravi300003Vinay100007Rajeev4000010Sanjay50000Find the Name of Employees where First Name, Second Name, and Last Name is given in the table. Some Name is missing such as First Name, Second Name and maybe Last Name. Here we will use COALESCE() function which will return first Non Null values.EmployeesIDFNameSNameLNameSalary1HarpreetSingh300002AshuNULLRana500003NULLVinayThakur400004NULLVinayNULL100005NULLNULLRajveer600006ManjeetSinghNULL60000Query :SELECT ID, COALESCE(FName, SName, LName) as Name FROM employees;
Output:Find the Employees who were hired in the Last n monthsFinding the Employees who have been hire in the last n months. Here we get desired output by using TIMESTAMPDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:Select *, TIMESTAMPDIFF(month, Hiredate, current_date()) as
DiffMonth from employees
where TIMESTAMPDIFF(month, Hiredate, current_date()) between
1 and 5 order by Hiredate desc;
Note: Here in query 1 and 5 are indicates 1 to n months which show the Employees who have hired last 1 to 5 months. In this query, DiffMonth is an extra column for our understanding which shows the Nth months.Output:Find the Employees who hired in the Last n daysFinding the Employees who have been hired in the last n days. Here we get desired output by using DATEDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:select *, DATEDIFF(current_date(), Hiredate)as
DiffDay from employees
where DATEDIFF(current_date(), Hiredate) between
1 and 100 order by Hiredate desc;
Note : Here in query 1 and 100 indicates 1 to n days which show the Employees who have hired last 1 to 100 days. In this query DiffDay is an extra column for our understanding which shows the Nth days.Output:Find the Employees who were hired in the Last n yearsFinding the Employees who have been hired in the last n years. Here we get desired output by using TIMESTAMPDIFF() MySQL functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *, TIMESTAMPDIFF(year, Hiredate, current_date()) as
DiffYear from employees
where TIMESTAMPDIFF(year, Hiredate, current_date())
between 1 and 4 order by Hiredate desc;
Note: Here in query 1 and 4 are indicates 1 to n years which shows the Employees who have hired last 1 to 4 years. In this query, DiffYear is a extra column for our understanding which show the Nth years.Output:Select all names that start with a given letterHere we get desired output by using three different queriesEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *from employees where Fname like 'A%';
select *from employees where left(FName, 1)='A';
select *from employees where substring(FName, 1, 1)='A';
Note: Here every query will give same output and the list of Employees who’s FName start with letter A.
Difference between Locking, Blocking and DeadlockingLocking: Locking occurs when a connection needs access to a piece of data in a database and it locks it for certain use so that no other transaction is able to access it.Blocking: Blocking occurs when a transaction tries to acquire an incompatible lock on a resource that another transaction has already locked. The blocked transaction remains blocked until the blocking transaction releases the lock.Deadlocking: Deadlocking occurs when two or more transactions have a resource locked, and each transaction requests a lock on the resource that another transaction has already locked. Neither of the transactions here can move forward, as each one is waiting for the other to release the lock.
Locking: Locking occurs when a connection needs access to a piece of data in a database and it locks it for certain use so that no other transaction is able to access it.
Blocking: Blocking occurs when a transaction tries to acquire an incompatible lock on a resource that another transaction has already locked. The blocked transaction remains blocked until the blocking transaction releases the lock.
Deadlocking: Deadlocking occurs when two or more transactions have a resource locked, and each transaction requests a lock on the resource that another transaction has already locked. Neither of the transactions here can move forward, as each one is waiting for the other to release the lock.
Delete duplicate data from table so that only first data remains constantManagersIdNameSalary1Harpreet200002Ravi300003Vinay100004Ravi300005Harpreet200006Vinay100007Rajeev400008Vinay100009Ravi3000010Sanjay50000Query:DELETE M1 from managers M1, managers M2 where M2.Name=M1.Name AND M1.Id>M2.Id;
Output:IdNameSalary1Harpreet200002Ravi300003Vinay100007Rajeev4000010Sanjay50000
Managers
Query:
DELETE M1 from managers M1, managers M2 where M2.Name=M1.Name AND M1.Id>M2.Id;
Output:
Find the Name of Employees where First Name, Second Name, and Last Name is given in the table. Some Name is missing such as First Name, Second Name and maybe Last Name. Here we will use COALESCE() function which will return first Non Null values.EmployeesIDFNameSNameLNameSalary1HarpreetSingh300002AshuNULLRana500003NULLVinayThakur400004NULLVinayNULL100005NULLNULLRajveer600006ManjeetSinghNULL60000Query :SELECT ID, COALESCE(FName, SName, LName) as Name FROM employees;
Output:
Employees
Query :
SELECT ID, COALESCE(FName, SName, LName) as Name FROM employees;
Output:
Find the Employees who were hired in the Last n monthsFinding the Employees who have been hire in the last n months. Here we get desired output by using TIMESTAMPDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:Select *, TIMESTAMPDIFF(month, Hiredate, current_date()) as
DiffMonth from employees
where TIMESTAMPDIFF(month, Hiredate, current_date()) between
1 and 5 order by Hiredate desc;
Note: Here in query 1 and 5 are indicates 1 to n months which show the Employees who have hired last 1 to 5 months. In this query, DiffMonth is an extra column for our understanding which shows the Nth months.Output:
Query:
Select *, TIMESTAMPDIFF(month, Hiredate, current_date()) as
DiffMonth from employees
where TIMESTAMPDIFF(month, Hiredate, current_date()) between
1 and 5 order by Hiredate desc;
Note: Here in query 1 and 5 are indicates 1 to n months which show the Employees who have hired last 1 to 5 months. In this query, DiffMonth is an extra column for our understanding which shows the Nth months.
Output:
Find the Employees who hired in the Last n daysFinding the Employees who have been hired in the last n days. Here we get desired output by using DATEDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:select *, DATEDIFF(current_date(), Hiredate)as
DiffDay from employees
where DATEDIFF(current_date(), Hiredate) between
1 and 100 order by Hiredate desc;
Note : Here in query 1 and 100 indicates 1 to n days which show the Employees who have hired last 1 to 100 days. In this query DiffDay is an extra column for our understanding which shows the Nth days.Output:
Employees
Query:
select *, DATEDIFF(current_date(), Hiredate)as
DiffDay from employees
where DATEDIFF(current_date(), Hiredate) between
1 and 100 order by Hiredate desc;
Note : Here in query 1 and 100 indicates 1 to n days which show the Employees who have hired last 1 to 100 days. In this query DiffDay is an extra column for our understanding which shows the Nth days.
Output:
Find the Employees who were hired in the Last n yearsFinding the Employees who have been hired in the last n years. Here we get desired output by using TIMESTAMPDIFF() MySQL functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *, TIMESTAMPDIFF(year, Hiredate, current_date()) as
DiffYear from employees
where TIMESTAMPDIFF(year, Hiredate, current_date())
between 1 and 4 order by Hiredate desc;
Note: Here in query 1 and 4 are indicates 1 to n years which shows the Employees who have hired last 1 to 4 years. In this query, DiffYear is a extra column for our understanding which show the Nth years.Output:
Employees
Query:
select *, TIMESTAMPDIFF(year, Hiredate, current_date()) as
DiffYear from employees
where TIMESTAMPDIFF(year, Hiredate, current_date())
between 1 and 4 order by Hiredate desc;
Note: Here in query 1 and 4 are indicates 1 to n years which shows the Employees who have hired last 1 to 4 years. In this query, DiffYear is a extra column for our understanding which show the Nth years.
Output:
Select all names that start with a given letterHere we get desired output by using three different queriesEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *from employees where Fname like 'A%';
select *from employees where left(FName, 1)='A';
select *from employees where substring(FName, 1, 1)='A';
Note: Here every query will give same output and the list of Employees who’s FName start with letter A.
Employees
Query:
select *from employees where Fname like 'A%';
select *from employees where left(FName, 1)='A';
select *from employees where substring(FName, 1, 1)='A';
Note: Here every query will give same output and the list of Employees who’s FName start with letter A.
Related articles :
SQL Interview Questions | Set 1Commonly asked DBMS Questions Set 1Commonly asked DBMS Questions Set 2
SQL Interview Questions | Set 1
Commonly asked DBMS Questions Set 1
Commonly asked DBMS Questions Set 2
zeto
vinayedula
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Data Preprocessing in Data Mining
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
SQL | DDL, DQL, DML, DCL and TCL Commands
How to find Nth highest salary from a table
CTE in SQL
SQL | ALTER (RENAME)
How to Update Multiple Columns in Single Update Statement in SQL? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 5165,
"s": 52,
"text": "Difference between Locking, Blocking and DeadlockingLocking: Locking occurs when a connection needs access to a piece of data in a database and it locks it for certain use so that no other transaction is able to access it.Blocking: Blocking occurs when a transaction tries to acquire an incompatible lock on a resource that another transaction has already locked. The blocked transaction remains blocked until the blocking transaction releases the lock.Deadlocking: Deadlocking occurs when two or more transactions have a resource locked, and each transaction requests a lock on the resource that another transaction has already locked. Neither of the transactions here can move forward, as each one is waiting for the other to release the lock.Delete duplicate data from table so that only first data remains constantManagersIdNameSalary1Harpreet200002Ravi300003Vinay100004Ravi300005Harpreet200006Vinay100007Rajeev400008Vinay100009Ravi3000010Sanjay50000Query:DELETE M1 from managers M1, managers M2 where M2.Name=M1.Name AND M1.Id>M2.Id;\nOutput:IdNameSalary1Harpreet200002Ravi300003Vinay100007Rajeev4000010Sanjay50000Find the Name of Employees where First Name, Second Name, and Last Name is given in the table. Some Name is missing such as First Name, Second Name and maybe Last Name. Here we will use COALESCE() function which will return first Non Null values.EmployeesIDFNameSNameLNameSalary1HarpreetSingh300002AshuNULLRana500003NULLVinayThakur400004NULLVinayNULL100005NULLNULLRajveer600006ManjeetSinghNULL60000Query :SELECT ID, COALESCE(FName, SName, LName) as Name FROM employees;\nOutput:Find the Employees who were hired in the Last n monthsFinding the Employees who have been hire in the last n months. Here we get desired output by using TIMESTAMPDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:Select *, TIMESTAMPDIFF(month, Hiredate, current_date()) as \nDiffMonth from employees\nwhere TIMESTAMPDIFF(month, Hiredate, current_date()) between \n1 and 5 order by Hiredate desc;\nNote: Here in query 1 and 5 are indicates 1 to n months which show the Employees who have hired last 1 to 5 months. In this query, DiffMonth is an extra column for our understanding which shows the Nth months.Output:Find the Employees who hired in the Last n daysFinding the Employees who have been hired in the last n days. Here we get desired output by using DATEDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:select *, DATEDIFF(current_date(), Hiredate)as \nDiffDay from employees\nwhere DATEDIFF(current_date(), Hiredate) between\n1 and 100 order by Hiredate desc; \nNote : Here in query 1 and 100 indicates 1 to n days which show the Employees who have hired last 1 to 100 days. In this query DiffDay is an extra column for our understanding which shows the Nth days.Output:Find the Employees who were hired in the Last n yearsFinding the Employees who have been hired in the last n years. Here we get desired output by using TIMESTAMPDIFF() MySQL functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *, TIMESTAMPDIFF(year, Hiredate, current_date()) as \nDiffYear from employees\nwhere TIMESTAMPDIFF(year, Hiredate, current_date()) \nbetween 1 and 4 order by Hiredate desc;\nNote: Here in query 1 and 4 are indicates 1 to n years which shows the Employees who have hired last 1 to 4 years. In this query, DiffYear is a extra column for our understanding which show the Nth years.Output:Select all names that start with a given letterHere we get desired output by using three different queriesEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *from employees where Fname like 'A%';\n\nselect *from employees where left(FName, 1)='A';\n\nselect *from employees where substring(FName, 1, 1)='A';\nNote: Here every query will give same output and the list of Employees who’s FName start with letter A."
},
{
"code": null,
"e": 5911,
"s": 5165,
"text": "Difference between Locking, Blocking and DeadlockingLocking: Locking occurs when a connection needs access to a piece of data in a database and it locks it for certain use so that no other transaction is able to access it.Blocking: Blocking occurs when a transaction tries to acquire an incompatible lock on a resource that another transaction has already locked. The blocked transaction remains blocked until the blocking transaction releases the lock.Deadlocking: Deadlocking occurs when two or more transactions have a resource locked, and each transaction requests a lock on the resource that another transaction has already locked. Neither of the transactions here can move forward, as each one is waiting for the other to release the lock."
},
{
"code": null,
"e": 6082,
"s": 5911,
"text": "Locking: Locking occurs when a connection needs access to a piece of data in a database and it locks it for certain use so that no other transaction is able to access it."
},
{
"code": null,
"e": 6314,
"s": 6082,
"text": "Blocking: Blocking occurs when a transaction tries to acquire an incompatible lock on a resource that another transaction has already locked. The blocked transaction remains blocked until the blocking transaction releases the lock."
},
{
"code": null,
"e": 6607,
"s": 6314,
"text": "Deadlocking: Deadlocking occurs when two or more transactions have a resource locked, and each transaction requests a lock on the resource that another transaction has already locked. Neither of the transactions here can move forward, as each one is waiting for the other to release the lock."
},
{
"code": null,
"e": 6981,
"s": 6607,
"text": "Delete duplicate data from table so that only first data remains constantManagersIdNameSalary1Harpreet200002Ravi300003Vinay100004Ravi300005Harpreet200006Vinay100007Rajeev400008Vinay100009Ravi3000010Sanjay50000Query:DELETE M1 from managers M1, managers M2 where M2.Name=M1.Name AND M1.Id>M2.Id;\nOutput:IdNameSalary1Harpreet200002Ravi300003Vinay100007Rajeev4000010Sanjay50000"
},
{
"code": null,
"e": 6990,
"s": 6981,
"text": "Managers"
},
{
"code": null,
"e": 6997,
"s": 6990,
"text": "Query:"
},
{
"code": null,
"e": 7077,
"s": 6997,
"text": "DELETE M1 from managers M1, managers M2 where M2.Name=M1.Name AND M1.Id>M2.Id;\n"
},
{
"code": null,
"e": 7085,
"s": 7077,
"text": "Output:"
},
{
"code": null,
"e": 7563,
"s": 7085,
"text": "Find the Name of Employees where First Name, Second Name, and Last Name is given in the table. Some Name is missing such as First Name, Second Name and maybe Last Name. Here we will use COALESCE() function which will return first Non Null values.EmployeesIDFNameSNameLNameSalary1HarpreetSingh300002AshuNULLRana500003NULLVinayThakur400004NULLVinayNULL100005NULLNULLRajveer600006ManjeetSinghNULL60000Query :SELECT ID, COALESCE(FName, SName, LName) as Name FROM employees;\nOutput:"
},
{
"code": null,
"e": 7573,
"s": 7563,
"text": "Employees"
},
{
"code": null,
"e": 7581,
"s": 7573,
"text": "Query :"
},
{
"code": null,
"e": 7647,
"s": 7581,
"text": "SELECT ID, COALESCE(FName, SName, LName) as Name FROM employees;\n"
},
{
"code": null,
"e": 7655,
"s": 7647,
"text": "Output:"
},
{
"code": null,
"e": 8603,
"s": 7655,
"text": "Find the Employees who were hired in the Last n monthsFinding the Employees who have been hire in the last n months. Here we get desired output by using TIMESTAMPDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:Select *, TIMESTAMPDIFF(month, Hiredate, current_date()) as \nDiffMonth from employees\nwhere TIMESTAMPDIFF(month, Hiredate, current_date()) between \n1 and 5 order by Hiredate desc;\nNote: Here in query 1 and 5 are indicates 1 to n months which show the Employees who have hired last 1 to 5 months. In this query, DiffMonth is an extra column for our understanding which shows the Nth months.Output:"
},
{
"code": null,
"e": 8610,
"s": 8603,
"text": "Query:"
},
{
"code": null,
"e": 8791,
"s": 8610,
"text": "Select *, TIMESTAMPDIFF(month, Hiredate, current_date()) as \nDiffMonth from employees\nwhere TIMESTAMPDIFF(month, Hiredate, current_date()) between \n1 and 5 order by Hiredate desc;\n"
},
{
"code": null,
"e": 9001,
"s": 8791,
"text": "Note: Here in query 1 and 5 are indicates 1 to n months which show the Employees who have hired last 1 to 5 months. In this query, DiffMonth is an extra column for our understanding which shows the Nth months."
},
{
"code": null,
"e": 9009,
"s": 9001,
"text": "Output:"
},
{
"code": null,
"e": 9911,
"s": 9009,
"text": "Find the Employees who hired in the Last n daysFinding the Employees who have been hired in the last n days. Here we get desired output by using DATEDIFF() mysql functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002017/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002017/12/124AnkitaSharmaFemale450002017/12/155VijayKumarMale500002018/01/126DilipYadavMale250002018/02/267JayvijaySinghMale300002018/02/188ReenuKumariFemale400002017/09/199AnkitVermaMale250002018/04/0410HarpreetSinghMale500002017/10/10Query:select *, DATEDIFF(current_date(), Hiredate)as \nDiffDay from employees\nwhere DATEDIFF(current_date(), Hiredate) between\n1 and 100 order by Hiredate desc; \nNote : Here in query 1 and 100 indicates 1 to n days which show the Employees who have hired last 1 to 100 days. In this query DiffDay is an extra column for our understanding which shows the Nth days.Output:"
},
{
"code": null,
"e": 9921,
"s": 9911,
"text": "Employees"
},
{
"code": null,
"e": 9928,
"s": 9921,
"text": "Query:"
},
{
"code": null,
"e": 10084,
"s": 9928,
"text": "select *, DATEDIFF(current_date(), Hiredate)as \nDiffDay from employees\nwhere DATEDIFF(current_date(), Hiredate) between\n1 and 100 order by Hiredate desc; \n"
},
{
"code": null,
"e": 10286,
"s": 10084,
"text": "Note : Here in query 1 and 100 indicates 1 to n days which show the Employees who have hired last 1 to 100 days. In this query DiffDay is an extra column for our understanding which shows the Nth days."
},
{
"code": null,
"e": 10294,
"s": 10286,
"text": "Output:"
},
{
"code": null,
"e": 11233,
"s": 10294,
"text": "Find the Employees who were hired in the Last n yearsFinding the Employees who have been hired in the last n years. Here we get desired output by using TIMESTAMPDIFF() MySQL functionEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *, TIMESTAMPDIFF(year, Hiredate, current_date()) as \nDiffYear from employees\nwhere TIMESTAMPDIFF(year, Hiredate, current_date()) \nbetween 1 and 4 order by Hiredate desc;\nNote: Here in query 1 and 4 are indicates 1 to n years which shows the Employees who have hired last 1 to 4 years. In this query, DiffYear is a extra column for our understanding which show the Nth years.Output:"
},
{
"code": null,
"e": 11243,
"s": 11233,
"text": "Employees"
},
{
"code": null,
"e": 11250,
"s": 11243,
"text": "Query:"
},
{
"code": null,
"e": 11428,
"s": 11250,
"text": "select *, TIMESTAMPDIFF(year, Hiredate, current_date()) as \nDiffYear from employees\nwhere TIMESTAMPDIFF(year, Hiredate, current_date()) \nbetween 1 and 4 order by Hiredate desc;\n"
},
{
"code": null,
"e": 11633,
"s": 11428,
"text": "Note: Here in query 1 and 4 are indicates 1 to n years which shows the Employees who have hired last 1 to 4 years. In this query, DiffYear is a extra column for our understanding which show the Nth years."
},
{
"code": null,
"e": 11641,
"s": 11633,
"text": "Output:"
},
{
"code": null,
"e": 12373,
"s": 11641,
"text": "Select all names that start with a given letterHere we get desired output by using three different queriesEmployeesIDFNameLNameGenderSalaryHiredate1RajveerSinghMale300002010/11/052ManveerSinghMale500002017/11/053AshutoshKumarMale400002015/12/124AnkitaSharmaFemale450002016/12/155VijayKumarMale500002017/01/126DilipYadavMale250002011/02/267JayvijaySinghMale300002012/02/188ReenuKumariFemale400002013/09/199AnkitVermaMale250002017/04/0410HarpreetSinghMale500002017/10/10Query:select *from employees where Fname like 'A%';\n\nselect *from employees where left(FName, 1)='A';\n\nselect *from employees where substring(FName, 1, 1)='A';\nNote: Here every query will give same output and the list of Employees who’s FName start with letter A."
},
{
"code": null,
"e": 12383,
"s": 12373,
"text": "Employees"
},
{
"code": null,
"e": 12390,
"s": 12383,
"text": "Query:"
},
{
"code": null,
"e": 12545,
"s": 12390,
"text": "select *from employees where Fname like 'A%';\n\nselect *from employees where left(FName, 1)='A';\n\nselect *from employees where substring(FName, 1, 1)='A';\n"
},
{
"code": null,
"e": 12649,
"s": 12545,
"text": "Note: Here every query will give same output and the list of Employees who’s FName start with letter A."
},
{
"code": null,
"e": 12668,
"s": 12649,
"text": "Related articles :"
},
{
"code": null,
"e": 12770,
"s": 12668,
"text": "SQL Interview Questions | Set 1Commonly asked DBMS Questions Set 1Commonly asked DBMS Questions Set 2"
},
{
"code": null,
"e": 12802,
"s": 12770,
"text": "SQL Interview Questions | Set 1"
},
{
"code": null,
"e": 12838,
"s": 12802,
"text": "Commonly asked DBMS Questions Set 1"
},
{
"code": null,
"e": 12874,
"s": 12838,
"text": "Commonly asked DBMS Questions Set 2"
},
{
"code": null,
"e": 12879,
"s": 12874,
"text": "zeto"
},
{
"code": null,
"e": 12890,
"s": 12879,
"text": "vinayedula"
},
{
"code": null,
"e": 12895,
"s": 12890,
"text": "DBMS"
},
{
"code": null,
"e": 12899,
"s": 12895,
"text": "SQL"
},
{
"code": null,
"e": 12904,
"s": 12899,
"text": "DBMS"
},
{
"code": null,
"e": 12908,
"s": 12904,
"text": "SQL"
},
{
"code": null,
"e": 13006,
"s": 12908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13017,
"s": 13006,
"text": "CTE in SQL"
},
{
"code": null,
"e": 13070,
"s": 13017,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 13104,
"s": 13070,
"text": "Data Preprocessing in Data Mining"
},
{
"code": null,
"e": 13149,
"s": 13104,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 13182,
"s": 13149,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 13224,
"s": 13182,
"text": "SQL | DDL, DQL, DML, DCL and TCL Commands"
},
{
"code": null,
"e": 13268,
"s": 13224,
"text": "How to find Nth highest salary from a table"
},
{
"code": null,
"e": 13279,
"s": 13268,
"text": "CTE in SQL"
},
{
"code": null,
"e": 13300,
"s": 13279,
"text": "SQL | ALTER (RENAME)"
}
] |
How to create timeline using CSS? | 15 Sep, 2020
We can easily create a timeline using some basic HTML and CSS. HTML Code is used to create a basic structure of the timeline and CSS code is used to set the style.
HTML Code: In this section, we will create a structure of our timeline. Our structure will include four events.
Steps:
Create a div element with class main-container.
Inside our main container create four more div with class text-wrapper.
Inside each div with class text-wrapper include another div with class content and include one h3 and p tag within it.
Example: HTML code
<!DOCTYPE html><html><body> <!-- container which will contain our timeline --> <div class="main-container"> <!-- event 1st of timeline --> <div class="text-wrapper left"> <!-- all text content of timeline --> <div class="content"> <h3>one</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class="text-wrapper right"> <!-- all text content of timeline --> <div class="content"> <h3>two</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class="text-wrapper left"> <!-- all text content of timeline --> <div class="content"> <h3>three</h3> <p>Some Stuff</p> </div> </div> <!-- event 1st of timeline --> <div class="text-wrapper right"> <!-- all text content of timeline --> <div class="content"> <h3>four</h3> <p>Some stuff</p> </div> </div> </div></body></html>
CSS code: We will use CSS to give our timeline some structure and set position of events.
<style> .main-container{ position: relative; width: 500px;}/*creating line for timeline*/.main-container::after{ content: ''; position: absolute; width: 10px; background-color: #FFC0CB; top:0; bottom: 0; left: 50%; margin-left: -3px;}/*Adjusting box of all content*/.text-wrapper{ padding: 10px 40px; position: relative; width:51%; box-sizing: border-box; margin: 50px 0;}.text-wrapper::after{ content: ''; position: absolute; width: 30px; height: 25px; right: -10px; background-color:#FF69B4; top:15px; border-radius: 50%; z-index: 1;}/*for left events*/.left{ left: 0;}/*for right events*/.right{ left:50%;}.right::after{ left:-10px;}/*content box colour padding and radius for circular corner*/.content{ padding: 15px 15px 15px 17px; background-color: #FFC0CB; border-radius: 4px;}/*setting text property of event heading*/.content h3{ text-transform: uppercase; font-size: 14px; color: #212121; letter-spacing:1px;}/*setting text property of event content*/.content p{ color: #616161; font-weight: 300; font-size: 18px; margin-top: 2px;} </style>
Complete Code:
<!DOCTYPE html><html><head> <style> .main-container{ position: relative; width: 500px;}/*creating line for timeline*/.main-container::after{ content: ''; position: absolute; width: 10px; background-color: #FFC0CB; top:0; bottom: 0; left: 50%; margin-left: -3px;}/*Adjusting box of all content*/.text-wrapper{ padding: 10px 40px; position: relative; width:51%; box-sizing: border-box; margin: 50px 0;}.text-wrapper::after{ content: ''; position: absolute; width: 30px; height: 25px; right: -10px; background-color:#FF69B4; top:15px; border-radius: 50%; z-index: 1;}/*for left events*/.left{ left: 0;}/*for right events*/.right{ left:50%;}.right::after{ left:-10px;}/*content box colour padding and radius for circular corner*/.content{ padding: 15px 15px 15px 17px; background-color: #FFC0CB; border-radius: 4px;}/*setting text property of event heading*/.content h3{ text-transform: uppercase; font-size: 14px; color: #212121; letter-spacing:1px;}/*setting text property of event content*/.content p{ color: #616161; font-weight: 300; font-size: 18px; margin-top: 2px;} </style></head><body> <!-- container which will contain our timeline --> <div class="main-container"> <!-- event 1st of timeline --> <div class="text-wrapper left"> <!-- all text content of timeline --> <div class="content"> <h3>one</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class="text-wrapper right"> <!-- all text content of timeline --> <div class="content"> <h3>two</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class="text-wrapper left"> <!-- all text content of timeline --> <div class="content"> <h3>three</h3> <p>Some Stuff</p> </div> </div> <!-- event 1st of timeline --> <div class="text-wrapper right"> <!-- all text content of timeline --> <div class="content"> <h3>four</h3> <p>Some stuff</p> </div> </div> </div></body></html>
Output:
CSS-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Sep, 2020"
},
{
"code": null,
"e": 216,
"s": 52,
"text": "We can easily create a timeline using some basic HTML and CSS. HTML Code is used to create a basic structure of the timeline and CSS code is used to set the style."
},
{
"code": null,
"e": 328,
"s": 216,
"text": "HTML Code: In this section, we will create a structure of our timeline. Our structure will include four events."
},
{
"code": null,
"e": 335,
"s": 328,
"text": "Steps:"
},
{
"code": null,
"e": 383,
"s": 335,
"text": "Create a div element with class main-container."
},
{
"code": null,
"e": 455,
"s": 383,
"text": "Inside our main container create four more div with class text-wrapper."
},
{
"code": null,
"e": 574,
"s": 455,
"text": "Inside each div with class text-wrapper include another div with class content and include one h3 and p tag within it."
},
{
"code": null,
"e": 593,
"s": 574,
"text": "Example: HTML code"
},
{
"code": "<!DOCTYPE html><html><body> <!-- container which will contain our timeline --> <div class=\"main-container\"> <!-- event 1st of timeline --> <div class=\"text-wrapper left\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>one</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class=\"text-wrapper right\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>two</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class=\"text-wrapper left\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>three</h3> <p>Some Stuff</p> </div> </div> <!-- event 1st of timeline --> <div class=\"text-wrapper right\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>four</h3> <p>Some stuff</p> </div> </div> </div></body></html>",
"e": 1741,
"s": 593,
"text": null
},
{
"code": null,
"e": 1831,
"s": 1741,
"text": "CSS code: We will use CSS to give our timeline some structure and set position of events."
},
{
"code": "<style> .main-container{ position: relative; width: 500px;}/*creating line for timeline*/.main-container::after{ content: ''; position: absolute; width: 10px; background-color: #FFC0CB; top:0; bottom: 0; left: 50%; margin-left: -3px;}/*Adjusting box of all content*/.text-wrapper{ padding: 10px 40px; position: relative; width:51%; box-sizing: border-box; margin: 50px 0;}.text-wrapper::after{ content: ''; position: absolute; width: 30px; height: 25px; right: -10px; background-color:#FF69B4; top:15px; border-radius: 50%; z-index: 1;}/*for left events*/.left{ left: 0;}/*for right events*/.right{ left:50%;}.right::after{ left:-10px;}/*content box colour padding and radius for circular corner*/.content{ padding: 15px 15px 15px 17px; background-color: #FFC0CB; border-radius: 4px;}/*setting text property of event heading*/.content h3{ text-transform: uppercase; font-size: 14px; color: #212121; letter-spacing:1px;}/*setting text property of event content*/.content p{ color: #616161; font-weight: 300; font-size: 18px; margin-top: 2px;} </style>",
"e": 2998,
"s": 1831,
"text": null
},
{
"code": null,
"e": 3013,
"s": 2998,
"text": "Complete Code:"
},
{
"code": "<!DOCTYPE html><html><head> <style> .main-container{ position: relative; width: 500px;}/*creating line for timeline*/.main-container::after{ content: ''; position: absolute; width: 10px; background-color: #FFC0CB; top:0; bottom: 0; left: 50%; margin-left: -3px;}/*Adjusting box of all content*/.text-wrapper{ padding: 10px 40px; position: relative; width:51%; box-sizing: border-box; margin: 50px 0;}.text-wrapper::after{ content: ''; position: absolute; width: 30px; height: 25px; right: -10px; background-color:#FF69B4; top:15px; border-radius: 50%; z-index: 1;}/*for left events*/.left{ left: 0;}/*for right events*/.right{ left:50%;}.right::after{ left:-10px;}/*content box colour padding and radius for circular corner*/.content{ padding: 15px 15px 15px 17px; background-color: #FFC0CB; border-radius: 4px;}/*setting text property of event heading*/.content h3{ text-transform: uppercase; font-size: 14px; color: #212121; letter-spacing:1px;}/*setting text property of event content*/.content p{ color: #616161; font-weight: 300; font-size: 18px; margin-top: 2px;} </style></head><body> <!-- container which will contain our timeline --> <div class=\"main-container\"> <!-- event 1st of timeline --> <div class=\"text-wrapper left\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>one</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class=\"text-wrapper right\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>two</h3> <p>Some stuff</p> </div> </div> <!-- event 1st of timeline --> <div class=\"text-wrapper left\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>three</h3> <p>Some Stuff</p> </div> </div> <!-- event 1st of timeline --> <div class=\"text-wrapper right\"> <!-- all text content of timeline --> <div class=\"content\"> <h3>four</h3> <p>Some stuff</p> </div> </div> </div></body></html>",
"e": 5342,
"s": 3013,
"text": null
},
{
"code": null,
"e": 5350,
"s": 5342,
"text": "Output:"
},
{
"code": null,
"e": 5359,
"s": 5350,
"text": "CSS-Misc"
},
{
"code": null,
"e": 5363,
"s": 5359,
"text": "CSS"
},
{
"code": null,
"e": 5368,
"s": 5363,
"text": "HTML"
},
{
"code": null,
"e": 5385,
"s": 5368,
"text": "Web Technologies"
},
{
"code": null,
"e": 5390,
"s": 5385,
"text": "HTML"
},
{
"code": null,
"e": 5488,
"s": 5390,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5527,
"s": 5488,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 5566,
"s": 5527,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 5605,
"s": 5566,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 5642,
"s": 5605,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 5671,
"s": 5642,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 5695,
"s": 5671,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5748,
"s": 5695,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 5808,
"s": 5748,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 5869,
"s": 5808,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Python Program to check Armstrong Number | 29 Jun, 2022
Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.
abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....
Example:
Input : 153
Output : Yes
153 is an Armstrong number.
1*1*1 + 5*5*5 + 3*3*3 = 153
Input : 120
Output : No
120 is not a Armstrong number.
1*1*1 + 2*2*2 + 0*0*0 = 9
Input : 1253
Output : No
1253 is not a Armstrong Number
1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723
Input : 1634
Output : Yes
1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634
Python
# Python program to determine whether# the number is Armstrong number or not # Function to calculate x raised to# the power ydef power(x, y): if y == 0: return 1 if y % 2 == 0: return power(x, y // 2) * power(x, y // 2) return x * power(x, y // 2) * power(x, y // 2) # Function to calculate order of the numberdef order(x): # Variable to store of the number n = 0 while (x != 0): n = n + 1 x = x // 10 return n # Function to check whether the given# number is Armstrong number or notdef isArmstrong(x): n = order(x) temp = x sum1 = 0 while (temp != 0): r = temp % 10 sum1 = sum1 + power(r, n) temp = temp // 10 # If condition satisfies return (sum1 == x) # Driver codex = 153print(isArmstrong(x)) x = 1253print(isArmstrong(x))
True
False
Time complexity: O((logn)2)
Auxiliary Space: O(1)
Method: A positive integer is called an Armstrong number if an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because 153 = 1*1*1 + 5*5*5 + 3*3*3 The while loop iterates like first, it checks if the number is not equal to zero or not. if it is not equal to zero then enter into the loop and find the reminder of number ex: 153%10 gives reminder 3. In the next step add the cube of a number to the sum1(3*3*3). Then the step gives the quotient of the number (153//10=15). this loop will continue till the given number is equal to zero.
Python3
# python 3 program# to check whether the given number is armstrong or not# without using power function n = 153 # or n=int(input()) -> taking input from users = n # assigning input value to the s variableb = len(str(n))sum1 = 0while n != 0: r = n % 10 sum1 = sum1+(r**b) n = n//10if s == sum1: print("The given number", s, "is armstrong number")else: print("The given number", s, "is not armstrong number") # This code is contributed by Gangarajula Laxmi
The given number 153 is armstrong number
Please refer complete article on Program for Armstrong Numbers for more details!
Time complexity: O(logn)
Auxiliary Space: O(1)
akash_1998
laxmigangarajula03
hasani
rajsan250
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Jun, 2022"
},
{
"code": null,
"e": 239,
"s": 54,
"text": "Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if."
},
{
"code": null,
"e": 299,
"s": 239,
"text": "abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... "
},
{
"code": null,
"e": 308,
"s": 299,
"text": "Example:"
},
{
"code": null,
"e": 644,
"s": 308,
"text": "Input : 153\nOutput : Yes\n153 is an Armstrong number.\n1*1*1 + 5*5*5 + 3*3*3 = 153\n\nInput : 120\nOutput : No\n120 is not a Armstrong number.\n1*1*1 + 2*2*2 + 0*0*0 = 9\n\nInput : 1253\nOutput : No\n1253 is not a Armstrong Number\n1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723\n\nInput : 1634\nOutput : Yes\n1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634"
},
{
"code": null,
"e": 651,
"s": 644,
"text": "Python"
},
{
"code": "# Python program to determine whether# the number is Armstrong number or not # Function to calculate x raised to# the power ydef power(x, y): if y == 0: return 1 if y % 2 == 0: return power(x, y // 2) * power(x, y // 2) return x * power(x, y // 2) * power(x, y // 2) # Function to calculate order of the numberdef order(x): # Variable to store of the number n = 0 while (x != 0): n = n + 1 x = x // 10 return n # Function to check whether the given# number is Armstrong number or notdef isArmstrong(x): n = order(x) temp = x sum1 = 0 while (temp != 0): r = temp % 10 sum1 = sum1 + power(r, n) temp = temp // 10 # If condition satisfies return (sum1 == x) # Driver codex = 153print(isArmstrong(x)) x = 1253print(isArmstrong(x))",
"e": 1501,
"s": 651,
"text": null
},
{
"code": null,
"e": 1512,
"s": 1501,
"text": "True\nFalse"
},
{
"code": null,
"e": 1540,
"s": 1512,
"text": "Time complexity: O((logn)2)"
},
{
"code": null,
"e": 1562,
"s": 1540,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2188,
"s": 1562,
"text": "Method: A positive integer is called an Armstrong number if an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the number itself. For example, 153 is an Armstrong number because 153 = 1*1*1 + 5*5*5 + 3*3*3 The while loop iterates like first, it checks if the number is not equal to zero or not. if it is not equal to zero then enter into the loop and find the reminder of number ex: 153%10 gives reminder 3. In the next step add the cube of a number to the sum1(3*3*3). Then the step gives the quotient of the number (153//10=15). this loop will continue till the given number is equal to zero. "
},
{
"code": null,
"e": 2196,
"s": 2188,
"text": "Python3"
},
{
"code": "# python 3 program# to check whether the given number is armstrong or not# without using power function n = 153 # or n=int(input()) -> taking input from users = n # assigning input value to the s variableb = len(str(n))sum1 = 0while n != 0: r = n % 10 sum1 = sum1+(r**b) n = n//10if s == sum1: print(\"The given number\", s, \"is armstrong number\")else: print(\"The given number\", s, \"is not armstrong number\") # This code is contributed by Gangarajula Laxmi",
"e": 2668,
"s": 2196,
"text": null
},
{
"code": null,
"e": 2709,
"s": 2668,
"text": "The given number 153 is armstrong number"
},
{
"code": null,
"e": 2790,
"s": 2709,
"text": "Please refer complete article on Program for Armstrong Numbers for more details!"
},
{
"code": null,
"e": 2815,
"s": 2790,
"text": "Time complexity: O(logn)"
},
{
"code": null,
"e": 2837,
"s": 2815,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2848,
"s": 2837,
"text": "akash_1998"
},
{
"code": null,
"e": 2867,
"s": 2848,
"text": "laxmigangarajula03"
},
{
"code": null,
"e": 2874,
"s": 2867,
"text": "hasani"
},
{
"code": null,
"e": 2884,
"s": 2874,
"text": "rajsan250"
},
{
"code": null,
"e": 2900,
"s": 2884,
"text": "Python Programs"
}
] |
Java Program to Create Directories Recursively | 12 May, 2022
A directory/folder is a File System used in computing that acts as a named memory location for storing related files or even subfolders. This allows better management of files and folders and is premised on the concept of real-world folders used for storing files. This system is the implementation of compartmentalization of the memory and makes the working space more organized. The Directory File System allows hierarchical arrangement as well as nesting of directories inside other directories.
Recursion is the process through which a function calls itself. It is a very useful approach to break down complex problems into smaller subparts.
Approaches:
Using the mkdir() methodUsing the createDirectory() method of the java.nio package
Using the mkdir() method
Using the createDirectory() method of the java.nio package
The first approach is to import the java.io.File class and define a method named file() which internally makes use of the mkdir() function to recursively create directories. The algorithm used inside the file() method is described below.
Algorithm:
Create the file() method with the return type as void.This method takes three parameters :String md which stands for Main Directory.String path which stands for the directory structure to be made where each character means a new directoryInt depth represents the number of directories to be made.Declare the terminating condition as if (depth == 0) return.Decrement the depth for each recursive call.Check if the path string is 0 in length and display the message accordingly.Append the md with the first character of the path string and remove the first character from the path string for each recursive call.Create an object of the File class with md as a parameter.Check if the directory already exists using the exists() method and display the message.Else create the directory using the mkdir()method.Make the recursive call.
Create the file() method with the return type as void.
This method takes three parameters :String md which stands for Main Directory.String path which stands for the directory structure to be made where each character means a new directoryInt depth represents the number of directories to be made.
String md which stands for Main Directory.
String path which stands for the directory structure to be made where each character means a new directory
Int depth represents the number of directories to be made.
Declare the terminating condition as if (depth == 0) return.
Decrement the depth for each recursive call.
Check if the path string is 0 in length and display the message accordingly.
Append the md with the first character of the path string and remove the first character from the path string for each recursive call.
Create an object of the File class with md as a parameter.
Check if the directory already exists using the exists() method and display the message.
Else create the directory using the mkdir()method.
Make the recursive call.
Implementation: Below is the implementation of the above program.
Java
// Java Program to Create Directories Recursively // Importing required classesimport java.io.File; // Main classclass GFG { // Method // To create directories static void file(String md, String path, int depth) { // md stores the starting path each character in // path represents new directory depth stores // the number of directories to be created // terminating condition if (depth == 0) return; // Decrementing the depth by 1 depth -= 1; // Checking if the path exists if (path.length() == 0) System.out.println("Path does not exist"); // execute if the path has more directories else { // appending the next directory // would be md = md + "\\" + // path.charAt(0) for windows md = md + "/" + path.charAt(0); // removing the first character // from path string path = path.substring(1); // creating File object File f = new File(md); // if the directory already exists if (f.exists()) { System.out.println("The Directory " + "already exists"); } else { // creating the directory boolean val = f.mkdir(); if (val) System.out.println(md + " created" + " successfully"); else System.out.println( "Unable to " + "create Directory"); } } // recursive call file(md, path, depth); } // Driver method public static void main(String[] args) { // creating class object GFG ob = new GFG(); // path for windows -> "C:\\Users\\ // harshit\\Desktop" ob.file("/home/mayur/Desktop", "abcd", 4); }}
Output:
This approach makes use of java.nio package to implement the code. We deploy the createDirectories() method here to create new directories. We also make use of the try-catch block to catch IO Errors. The Algorithm can be found below.
Algorithm:
Repeat steps through 1-6 as mentioned in the algorithm in approach 1.Now, convert the string md to Path Instance using Path.gets() method.Again, check if the Directory already exists using the exists() method.If the Directory is not present, open a try-catch block, and create a new directory using createDirectories() method.Else, display that the Directory already exists.Make the recursive call
Repeat steps through 1-6 as mentioned in the algorithm in approach 1.
Now, convert the string md to Path Instance using Path.gets() method.
Again, check if the Directory already exists using the exists() method.
If the Directory is not present, open a try-catch block, and create a new directory using createDirectories() method.
Else, display that the Directory already exists.
Make the recursive call
Below is the implementation of the above program.
Java
// Java code to create directories recursively // importing the packagesimport java.nio.file.Paths;import java.nio.file.Path;import java.nio.file.Files;import java.io.IOException; class GFG { // defining the recursive method static void file(String md, String path, int depth) { // base case if (depth == 0) return; // decrement the depth depth -= 1; // check if the path is empty if (path.length() == 0) System.out.println("Path does not exist"); else { // appending the first character from // path string md = md + "/" + path.charAt(0); // removing the first character from // path string path = path.substring(1); // creating the path instance from // path string Path p = Paths.get(md); // if the directory already exists if (!Files.exists(p)) { try { // creating directory Files.createDirectories(p); System.out.println(md + " created" + " successfully"); } catch (IOException err) { err.printStackTrace(); } } else System.out.println("The directory " + "already exists"); } // recursive call file(md, path, depth); } // Driver Code public static void main(String[] args) { // creating the object of the class GFG ob = new GFG(); // md would be -> "C:\\Users\\harshit\\ // Desktop for windows ob.file("/home/mayur/Desktop", "klm", 5); }}
Output:
sumitgumber28
solankimayank
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": 28,
"s": 0,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 529,
"s": 28,
"text": "A directory/folder is a File System used in computing that acts as a named memory location for storing related files or even subfolders. This allows better management of files and folders and is premised on the concept of real-world folders used for storing files. This system is the implementation of compartmentalization of the memory and makes the working space more organized. The Directory File System allows hierarchical arrangement as well as nesting of directories inside other directories. "
},
{
"code": null,
"e": 676,
"s": 529,
"text": "Recursion is the process through which a function calls itself. It is a very useful approach to break down complex problems into smaller subparts."
},
{
"code": null,
"e": 688,
"s": 676,
"text": "Approaches:"
},
{
"code": null,
"e": 771,
"s": 688,
"text": "Using the mkdir() methodUsing the createDirectory() method of the java.nio package"
},
{
"code": null,
"e": 796,
"s": 771,
"text": "Using the mkdir() method"
},
{
"code": null,
"e": 855,
"s": 796,
"text": "Using the createDirectory() method of the java.nio package"
},
{
"code": null,
"e": 1093,
"s": 855,
"text": "The first approach is to import the java.io.File class and define a method named file() which internally makes use of the mkdir() function to recursively create directories. The algorithm used inside the file() method is described below."
},
{
"code": null,
"e": 1104,
"s": 1093,
"text": "Algorithm:"
},
{
"code": null,
"e": 1935,
"s": 1104,
"text": "Create the file() method with the return type as void.This method takes three parameters :String md which stands for Main Directory.String path which stands for the directory structure to be made where each character means a new directoryInt depth represents the number of directories to be made.Declare the terminating condition as if (depth == 0) return.Decrement the depth for each recursive call.Check if the path string is 0 in length and display the message accordingly.Append the md with the first character of the path string and remove the first character from the path string for each recursive call.Create an object of the File class with md as a parameter.Check if the directory already exists using the exists() method and display the message.Else create the directory using the mkdir()method.Make the recursive call."
},
{
"code": null,
"e": 1990,
"s": 1935,
"text": "Create the file() method with the return type as void."
},
{
"code": null,
"e": 2233,
"s": 1990,
"text": "This method takes three parameters :String md which stands for Main Directory.String path which stands for the directory structure to be made where each character means a new directoryInt depth represents the number of directories to be made."
},
{
"code": null,
"e": 2276,
"s": 2233,
"text": "String md which stands for Main Directory."
},
{
"code": null,
"e": 2383,
"s": 2276,
"text": "String path which stands for the directory structure to be made where each character means a new directory"
},
{
"code": null,
"e": 2442,
"s": 2383,
"text": "Int depth represents the number of directories to be made."
},
{
"code": null,
"e": 2503,
"s": 2442,
"text": "Declare the terminating condition as if (depth == 0) return."
},
{
"code": null,
"e": 2548,
"s": 2503,
"text": "Decrement the depth for each recursive call."
},
{
"code": null,
"e": 2625,
"s": 2548,
"text": "Check if the path string is 0 in length and display the message accordingly."
},
{
"code": null,
"e": 2760,
"s": 2625,
"text": "Append the md with the first character of the path string and remove the first character from the path string for each recursive call."
},
{
"code": null,
"e": 2819,
"s": 2760,
"text": "Create an object of the File class with md as a parameter."
},
{
"code": null,
"e": 2908,
"s": 2819,
"text": "Check if the directory already exists using the exists() method and display the message."
},
{
"code": null,
"e": 2959,
"s": 2908,
"text": "Else create the directory using the mkdir()method."
},
{
"code": null,
"e": 2984,
"s": 2959,
"text": "Make the recursive call."
},
{
"code": null,
"e": 3050,
"s": 2984,
"text": "Implementation: Below is the implementation of the above program."
},
{
"code": null,
"e": 3055,
"s": 3050,
"text": "Java"
},
{
"code": "// Java Program to Create Directories Recursively // Importing required classesimport java.io.File; // Main classclass GFG { // Method // To create directories static void file(String md, String path, int depth) { // md stores the starting path each character in // path represents new directory depth stores // the number of directories to be created // terminating condition if (depth == 0) return; // Decrementing the depth by 1 depth -= 1; // Checking if the path exists if (path.length() == 0) System.out.println(\"Path does not exist\"); // execute if the path has more directories else { // appending the next directory // would be md = md + \"\\\\\" + // path.charAt(0) for windows md = md + \"/\" + path.charAt(0); // removing the first character // from path string path = path.substring(1); // creating File object File f = new File(md); // if the directory already exists if (f.exists()) { System.out.println(\"The Directory \" + \"already exists\"); } else { // creating the directory boolean val = f.mkdir(); if (val) System.out.println(md + \" created\" + \" successfully\"); else System.out.println( \"Unable to \" + \"create Directory\"); } } // recursive call file(md, path, depth); } // Driver method public static void main(String[] args) { // creating class object GFG ob = new GFG(); // path for windows -> \"C:\\\\Users\\\\ // harshit\\\\Desktop\" ob.file(\"/home/mayur/Desktop\", \"abcd\", 4); }}",
"e": 5026,
"s": 3055,
"text": null
},
{
"code": null,
"e": 5034,
"s": 5026,
"text": "Output:"
},
{
"code": null,
"e": 5268,
"s": 5034,
"text": "This approach makes use of java.nio package to implement the code. We deploy the createDirectories() method here to create new directories. We also make use of the try-catch block to catch IO Errors. The Algorithm can be found below."
},
{
"code": null,
"e": 5279,
"s": 5268,
"text": "Algorithm:"
},
{
"code": null,
"e": 5677,
"s": 5279,
"text": "Repeat steps through 1-6 as mentioned in the algorithm in approach 1.Now, convert the string md to Path Instance using Path.gets() method.Again, check if the Directory already exists using the exists() method.If the Directory is not present, open a try-catch block, and create a new directory using createDirectories() method.Else, display that the Directory already exists.Make the recursive call"
},
{
"code": null,
"e": 5747,
"s": 5677,
"text": "Repeat steps through 1-6 as mentioned in the algorithm in approach 1."
},
{
"code": null,
"e": 5817,
"s": 5747,
"text": "Now, convert the string md to Path Instance using Path.gets() method."
},
{
"code": null,
"e": 5889,
"s": 5817,
"text": "Again, check if the Directory already exists using the exists() method."
},
{
"code": null,
"e": 6007,
"s": 5889,
"text": "If the Directory is not present, open a try-catch block, and create a new directory using createDirectories() method."
},
{
"code": null,
"e": 6056,
"s": 6007,
"text": "Else, display that the Directory already exists."
},
{
"code": null,
"e": 6080,
"s": 6056,
"text": "Make the recursive call"
},
{
"code": null,
"e": 6130,
"s": 6080,
"text": "Below is the implementation of the above program."
},
{
"code": null,
"e": 6135,
"s": 6130,
"text": "Java"
},
{
"code": "// Java code to create directories recursively // importing the packagesimport java.nio.file.Paths;import java.nio.file.Path;import java.nio.file.Files;import java.io.IOException; class GFG { // defining the recursive method static void file(String md, String path, int depth) { // base case if (depth == 0) return; // decrement the depth depth -= 1; // check if the path is empty if (path.length() == 0) System.out.println(\"Path does not exist\"); else { // appending the first character from // path string md = md + \"/\" + path.charAt(0); // removing the first character from // path string path = path.substring(1); // creating the path instance from // path string Path p = Paths.get(md); // if the directory already exists if (!Files.exists(p)) { try { // creating directory Files.createDirectories(p); System.out.println(md + \" created\" + \" successfully\"); } catch (IOException err) { err.printStackTrace(); } } else System.out.println(\"The directory \" + \"already exists\"); } // recursive call file(md, path, depth); } // Driver Code public static void main(String[] args) { // creating the object of the class GFG ob = new GFG(); // md would be -> \"C:\\\\Users\\\\harshit\\\\ // Desktop for windows ob.file(\"/home/mayur/Desktop\", \"klm\", 5); }}",
"e": 7909,
"s": 6135,
"text": null
},
{
"code": null,
"e": 7917,
"s": 7909,
"text": "Output:"
},
{
"code": null,
"e": 7931,
"s": 7917,
"text": "sumitgumber28"
},
{
"code": null,
"e": 7945,
"s": 7931,
"text": "solankimayank"
},
{
"code": null,
"e": 7950,
"s": 7945,
"text": "Java"
},
{
"code": null,
"e": 7964,
"s": 7950,
"text": "Java Programs"
},
{
"code": null,
"e": 7969,
"s": 7964,
"text": "Java"
},
{
"code": null,
"e": 8067,
"s": 7969,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8082,
"s": 8067,
"text": "Stream In Java"
},
{
"code": null,
"e": 8103,
"s": 8082,
"text": "Introduction to Java"
},
{
"code": null,
"e": 8124,
"s": 8103,
"text": "Constructors in Java"
},
{
"code": null,
"e": 8143,
"s": 8124,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 8160,
"s": 8143,
"text": "Generics in Java"
},
{
"code": null,
"e": 8186,
"s": 8160,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 8220,
"s": 8186,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 8267,
"s": 8220,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 8305,
"s": 8267,
"text": "Factory method design pattern in Java"
}
] |
Augmented Faces with ARCore in Android | 17 Feb, 2022
Augmented Faces permit the application to naturally distinguish various regions of an individual’s face, and utilize those areas to overlay resources, for example, surfaces and models in a way that appropriately matches the contours and regions of an individual face. ARCore is a stage for building Augmented reality applications on Android. Augmented Face is a subsystem of ARCore that permits your application to:
Naturally, recognize various areas of any individual’s identified face, and utilize those regions to overlay resources, for example, surfaces and models in a way that appropriately matches the contours and regions of an individual face.
Utilize the 468-point face mesh that is given by ARCore to apply a custom texture over a distinguished face.
For example, we can create effects like animated masks, glasses, virtual hats, perform skin retouching, or the next Snapchat App.
Augmented faces don’t require uncommon or special hardware, such as a depth sensor. Rather, it uses the phone’s camera and machine learning to provide three snippets of data:
Generates a Face Mesh: a 468 points dense 3D face mesh, which allows you to pan detailed textures that accurately follow facial moments.Recognizes the Pose: points on a person’s face, anchored based on the generated Face Mesh, which is useful for placing effects on or close to the temple and nose.Overlays and position textures and 3D models based on the face mesh generated and recognized regions.
Generates a Face Mesh: a 468 points dense 3D face mesh, which allows you to pan detailed textures that accurately follow facial moments.
Recognizes the Pose: points on a person’s face, anchored based on the generated Face Mesh, which is useful for placing effects on or close to the temple and nose.
Overlays and position textures and 3D models based on the face mesh generated and recognized regions.
It uses machine learning models that are built on top of the TensorFlow Lite platform to achieve this and the crossing pipeline is optimized to run on the device in real-time. It uses a technique called transfer learning wherein we train the neural network for two objectives, one, to predict 3D vertices and to predict 2D contours. To predict 3D vertices, we train it with a synthetic 3D data set and use this neural network as a starting point for the next stage of training.
In this next stage, it uses the annotated data set, annotated real-world data set to train the model for 2D contour prediction. The resulting network not only predicts 3D vertices from a synthetic data set but can also perform well from 2D images. To make sure the solution works for everyone ARCore developers train the network with geographically diverse data sets so that it works for all types of faces, wider faces, taller faces, and all types of skin colors.
And to enable these complex algorithms on mobile devices, we have multiple adaptive algorithms built into the ARCore. These algorithms sense dynamically how much time it has taken to process previous images and adjust accordingly various parameters of the pipeline. It uses multiple ML models, one optimized for higher quality and one optimized for higher performance when computing the resources is really challenging. It also adjusts pipeline parameters such as inference rates so that it skips a few images, and instead replace that with interpolation data. With all these techniques, what you get is a full-frame rate experience for your user. So it provides face mesh and region poses at full camera frame rate while handling all these techniques internal to the ARCore.
To appropriately overlay textures and 3D models on an identified face, ARCore provides detected regions and an augmented face mesh. This mesh is a virtual depiction of the face and comprises the vertices, facial regions, and the focal point of the user’s head. At the point when a user’s face is identified by the camera, ARCore performs the following steps to generate the augmented face mesh, as well as center and region poses:
It distinguishes the center pose and a face mesh.The center pose, situated behind the nose, is the actual center point of the user’s head (in other words, inside the skull).The face mesh comprises of many vertices that make up the face and is characterized relative to the center pose.
The center pose, situated behind the nose, is the actual center point of the user’s head (in other words, inside the skull).
The face mesh comprises of many vertices that make up the face and is characterized relative to the center pose.
The AugmentedFace class utilizes the face mesh and center pose to distinguish face regions present on the client’s face. These regions are:Right brow (RIGHT_FOREHEAD)Left temple (LEFT_FOREHEAD)Tip of the nose (NOSE_TIP)
Right brow (RIGHT_FOREHEAD)
Left temple (LEFT_FOREHEAD)
Tip of the nose (NOSE_TIP)
The Face mesh, center pose, and face region poses are utilized by AugmentedFace APIs as positioning points and regions to place the resources in your app.
468 point face texture mesh
Trackable: A Trackable is an interface which can be followed by ARCore and something from which Anchors can be connected to.
Anchor: It describes a fixed location and orientation in the real world. To stay at a fixed location in physical space, the numerical description of this position will update as ARCore’s understanding of the space improves. Anchors are hashable and may for example be used as keys in HashMaps.
Pose: At the point when you need to state wherein the scene you need to put the object and you need to specify the location in terms of the scene’s coordinates. The Pose is the means by which you state this.
Session: Deals with the AR framework state and handles the session lifecycle. This class offers the primary passage to the ARCore API. This class permits the user to make a session, configure it, start or stop it and, above all, receive frames that allow access to the camera image and device pose.
Textures: Textures are especially helpful for Augmented Faces. This permits you to make a light overlay that lines up with the locales of the identified face(s) to add to your experience.
ArFragment: ARCore utilizes an ArFragment that provides a lot of features, for example, plane finding, permission handling, and camera set up. You can utilize the fragment legitimately in your activity, however at whatever point you need custom features, for example, Augmented Faces, you should extend the ArFragment and set the proper settings. This fragment is the layer that conceals all the compound stuff (like OpenGL, rendering models, etc) and gives high-level APIs to load and render 3D models.
ModelRenderable: ModelRenderable renders a 3D Model by attaching it to a Node.
Sceneform SDK: Sceneform SDK is another library for Android that empowers the quick creation and mix of AR experiences in your application. It joins ARCore and an amazing physically-based 3D renderer.
We are going to create Snapchat, Instagram, and TikTok like face filters. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding the assets file used in this example
Add any 3D model in sampledata/models folder. We can do this by creating a new folder in the project file directory or directly from the Android Studio. The allowed 3D model extensions are .fbx, .OBJ, .glTF. There are many free models available on the internet. You can visit, here or more. You can download the assets used in this example from here. Please refer to this article to create a raw folder in android studio. Then just copy and paste the fox_face.sfb file to the raw folder. Similarly, copy and paste the fox_face_mesh_texture.png file to the drawable folder.
Step 3: Adding dependencies to the build.gradle(:app) file
Add the following dependencies to the build.gradle(:app) file.
// Provides ARCore Session and related resources.
implementation ‘com.google.ar:core:1.16.0’
// Provides ArFragment, and other UX resources.
implementation ‘com.google.ar.sceneform.ux:sceneform-ux:1.15.0’
// Alternatively, use ArSceneView without the UX dependency.
implementation ‘com.google.ar.sceneform:core:1.8.0’
Add the following code snippet to the build.gradle file. This is required(only once) to convert .fbx asset into .sfb and save that in the raw folder. Or you can add them by yourself as done in step 2.
// required(only once) to convert .fbx asset into .sfb
// and save that in raw folder
sceneform.asset(‘sampledata/models/fox_face.fbx’,
‘default’,
‘sampleData/models/fox_face.sfa’,
‘src/main/res/raw/fox_face’)
Step 4: Adding dependencies to the build.gradle(:project) file
Add the following dependencies to the build.gradle(:project) file.
// Add Sceneform plugin classpath to Project
// level build.gradle file
classpath ‘com.google.ar.sceneform:plugin:1.15.0’
Step 5: Working with the AndroidManifest.xml file
Add the following line to the AndroidManifest.xml file.
// Both “AR Optional” and “AR Required” apps require CAMERA permission.
<uses-permission android:name=”android.permission.CAMERA” />
// Indicates that app requires ARCore (“AR Required”). Ensures app is only
// visible in the Google Play Store on devices that support ARCore.
// For “AR Optional” apps remove this line. →
<uses-feature android:name=”android.hardware.camera.ar” android:required=”true”/>
<application>
...
// Indicates that app requires ARCore (“AR Required”). Causes Google
// Play Store to download and install ARCore along with the app.
// For an “AR Optional” app, specify “optional” instead of “required”.
<meta-data android:name=”com.google.ar.core” android:value=”required” />
...
</application>
Below is the complete code for the AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.arsnapchat"> <uses-feature android:name="android.hardware.camera" android:required="true" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-feature android:name="android.hardware.camera.ar" android:required="true" /> <uses-feature android:name="android.hardware.camera.autofocus" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <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"> <meta-data android:name="com.google.ar.core" android:value="required" /> <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>
Step 6: Modify the activity_main.xml file
We have added a fragment to the activity_main.xml file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout 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"> <fragment android:id="@+id/arFragment" android:name="com.example.arsnapchat.CustomArFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Note:
Please add your package name to this attribute.
android:name=”com.example.arsnapchat.CustomArFragment”
Step 7: Create a new Java class
Create a new class and name the file as CustomArFragment that extends ArFragment. Below is the code for the CustomArFragment.java file.
Java
import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.FrameLayout;import androidx.annotation.Nullable;import com.google.ar.core.Config;import com.google.ar.core.Session;import com.google.ar.sceneform.ux.ArFragment;import java.util.EnumSet;import java.util.Set; public class CustomArFragment extends ArFragment { @Override protected Config getSessionConfiguration(Session session) { Config config = new Config(session); // Configure 3D Face Mesh config.setAugmentedFaceMode(Config.AugmentedFaceMode.MESH3D); this.getArSceneView().setupSession(session); return config; } @Override protected Set<Session.Feature> getSessionFeatures() { // Configure Front Camera return EnumSet.of(Session.Feature.FRONT_CAMERA); } // Override to turn off planeDiscoveryController. // Plane traceable are not supported with the front camera. @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { FrameLayout frameLayout = (FrameLayout) super.onCreateView(inflater, container, savedInstanceState); getPlaneDiscoveryController().hide(); getPlaneDiscoveryController().setInstructionView(null); return frameLayout; }}
Step 8: Modify the MainActivity.java file
Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.ar.core.AugmentedFace;import com.google.ar.core.Frame;import com.google.ar.core.TrackingState;import com.google.ar.sceneform.rendering.ModelRenderable;import com.google.ar.sceneform.rendering.Renderable;import com.google.ar.sceneform.rendering.Texture;import com.google.ar.sceneform.ux.AugmentedFaceNode;import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map; public class MainActivity extends AppCompatActivity { private ModelRenderable modelRenderable; private Texture texture; private boolean isAdded = false; private final HashMap<AugmentedFace, AugmentedFaceNode> faceNodeMap = new HashMap<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CustomArFragment customArFragment = (CustomArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment); // Use ModelRenderable.Builder to load the *.sfb // models at runtime. // Load the face regions renderable. // To ensure that the asset doesn't cast or receive // shadows in the scene, ensure that setShadowCaster // and setShadowReceiver are both set to false. ModelRenderable.builder() .setSource(this, R.raw.fox_face) .build() .thenAccept(rendarable -> { this.modelRenderable = rendarable; this.modelRenderable.setShadowCaster(false); this.modelRenderable.setShadowReceiver(false); }) .exceptionally(throwable -> { Toast.makeText(this, "error loading model", Toast.LENGTH_SHORT).show(); return null; }); // Load the face mesh texture.(2D texture on face) // Save the texture(.png file) in drawable folder. Texture.builder() .setSource(this, R.drawable.fox_face_mesh_texture) .build() .thenAccept(textureModel -> this.texture = textureModel) .exceptionally(throwable -> { Toast.makeText(this, "cannot load texture", Toast.LENGTH_SHORT).show(); return null; }); assert customArFragment != null; // This is important to make sure that the camera // stream renders first so that the face mesh // occlusion works correctly. customArFragment.getArSceneView().setCameraStreamRenderPriority(Renderable.RENDER_PRIORITY_FIRST); customArFragment.getArSceneView().getScene().addOnUpdateListener(frameTime -> { if (modelRenderable == null || texture == null) { return; } Frame frame = customArFragment.getArSceneView().getArFrame(); assert frame != null; // Render the effect for the face Rendering the effect involves these steps: // 1.Create the Sceneform face node. // 2.Add the face node to the Sceneform scene. // 3.Set the face region Renderable. Extracting the face mesh and // rendering the face effect is added to a listener on // the scene that gets called on every processed camera frame. Collection<AugmentedFace> augmentedFaces = frame.getUpdatedTrackables(AugmentedFace.class); // Make new AugmentedFaceNodes for any new faces. for (AugmentedFace augmentedFace : augmentedFaces) { if (isAdded) return; AugmentedFaceNode augmentedFaceMode = new AugmentedFaceNode(augmentedFace); augmentedFaceMode.setParent(customArFragment.getArSceneView().getScene()); augmentedFaceMode.setFaceRegionsRenderable(modelRenderable); augmentedFaceMode.setFaceMeshTexture(texture); faceNodeMap.put(augmentedFace, augmentedFaceMode); isAdded = true; // Remove any AugmentedFaceNodes associated with // an AugmentedFace that stopped tracking. Iterator<Map.Entry<AugmentedFace, AugmentedFaceNode>> iterator = faceNodeMap.entrySet().iterator(); Map.Entry<AugmentedFace, AugmentedFaceNode> entry = iterator.next(); AugmentedFace face = entry.getKey(); while (face.getTrackingState() == TrackingState.STOPPED) { AugmentedFaceNode node = entry.getValue(); node.setParent(null); iterator.remove(); } } }); }}
Github Project Link: https://github.com/raghavtilak/AugmentedFaces
Augmented Faces only works with the Front Camera.Not all devices support ARCore. There’s still a small fraction of devices which doesn’t come with AR Core support. You can check out the list of ARCore supported devices at https://developers.google.com/ar/discover/supported-devices.For AR Optional App minSdkVersion should be 14 and for AR Required App minSdkVersion should be 24.If your app falls in the category of AR Required app then the device using it should have AR Core installed on it.
Augmented Faces only works with the Front Camera.
Not all devices support ARCore. There’s still a small fraction of devices which doesn’t come with AR Core support. You can check out the list of ARCore supported devices at https://developers.google.com/ar/discover/supported-devices.
For AR Optional App minSdkVersion should be 14 and for AR Required App minSdkVersion should be 24.
If your app falls in the category of AR Required app then the device using it should have AR Core installed on it.
Notes:
Prior to making a Session, it must be verified beforehand that ARCore is installed and up to date. If ARCore isn’t installed, then session creation might fail and any later installation or upgrade of ARCore would require restarting of the app, and might cause the app to be killed.The orientation of the face mesh is different for Unreal, Android and Unity.Calling Trackable.createAnchor(Pose) would result in an IllegalStateException because Augmented Faces supports only front-facing (selfie) camera, and does not support attaching anchors.
Prior to making a Session, it must be verified beforehand that ARCore is installed and up to date. If ARCore isn’t installed, then session creation might fail and any later installation or upgrade of ARCore would require restarting of the app, and might cause the app to be killed.
The orientation of the face mesh is different for Unreal, Android and Unity.
Calling Trackable.createAnchor(Pose) would result in an IllegalStateException because Augmented Faces supports only front-facing (selfie) camera, and does not support attaching anchors.
adnanirshad158
sumitgumber28
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Feb, 2022"
},
{
"code": null,
"e": 472,
"s": 54,
"text": "Augmented Faces permit the application to naturally distinguish various regions of an individual’s face, and utilize those areas to overlay resources, for example, surfaces and models in a way that appropriately matches the contours and regions of an individual face. ARCore is a stage for building Augmented reality applications on Android. Augmented Face is a subsystem of ARCore that permits your application to: "
},
{
"code": null,
"e": 709,
"s": 472,
"text": "Naturally, recognize various areas of any individual’s identified face, and utilize those regions to overlay resources, for example, surfaces and models in a way that appropriately matches the contours and regions of an individual face."
},
{
"code": null,
"e": 818,
"s": 709,
"text": "Utilize the 468-point face mesh that is given by ARCore to apply a custom texture over a distinguished face."
},
{
"code": null,
"e": 948,
"s": 818,
"text": "For example, we can create effects like animated masks, glasses, virtual hats, perform skin retouching, or the next Snapchat App."
},
{
"code": null,
"e": 1123,
"s": 948,
"text": "Augmented faces don’t require uncommon or special hardware, such as a depth sensor. Rather, it uses the phone’s camera and machine learning to provide three snippets of data:"
},
{
"code": null,
"e": 1523,
"s": 1123,
"text": "Generates a Face Mesh: a 468 points dense 3D face mesh, which allows you to pan detailed textures that accurately follow facial moments.Recognizes the Pose: points on a person’s face, anchored based on the generated Face Mesh, which is useful for placing effects on or close to the temple and nose.Overlays and position textures and 3D models based on the face mesh generated and recognized regions."
},
{
"code": null,
"e": 1660,
"s": 1523,
"text": "Generates a Face Mesh: a 468 points dense 3D face mesh, which allows you to pan detailed textures that accurately follow facial moments."
},
{
"code": null,
"e": 1823,
"s": 1660,
"text": "Recognizes the Pose: points on a person’s face, anchored based on the generated Face Mesh, which is useful for placing effects on or close to the temple and nose."
},
{
"code": null,
"e": 1925,
"s": 1823,
"text": "Overlays and position textures and 3D models based on the face mesh generated and recognized regions."
},
{
"code": null,
"e": 2403,
"s": 1925,
"text": "It uses machine learning models that are built on top of the TensorFlow Lite platform to achieve this and the crossing pipeline is optimized to run on the device in real-time. It uses a technique called transfer learning wherein we train the neural network for two objectives, one, to predict 3D vertices and to predict 2D contours. To predict 3D vertices, we train it with a synthetic 3D data set and use this neural network as a starting point for the next stage of training."
},
{
"code": null,
"e": 2869,
"s": 2403,
"text": "In this next stage, it uses the annotated data set, annotated real-world data set to train the model for 2D contour prediction. The resulting network not only predicts 3D vertices from a synthetic data set but can also perform well from 2D images. To make sure the solution works for everyone ARCore developers train the network with geographically diverse data sets so that it works for all types of faces, wider faces, taller faces, and all types of skin colors. "
},
{
"code": null,
"e": 3645,
"s": 2869,
"text": "And to enable these complex algorithms on mobile devices, we have multiple adaptive algorithms built into the ARCore. These algorithms sense dynamically how much time it has taken to process previous images and adjust accordingly various parameters of the pipeline. It uses multiple ML models, one optimized for higher quality and one optimized for higher performance when computing the resources is really challenging. It also adjusts pipeline parameters such as inference rates so that it skips a few images, and instead replace that with interpolation data. With all these techniques, what you get is a full-frame rate experience for your user. So it provides face mesh and region poses at full camera frame rate while handling all these techniques internal to the ARCore."
},
{
"code": null,
"e": 4076,
"s": 3645,
"text": "To appropriately overlay textures and 3D models on an identified face, ARCore provides detected regions and an augmented face mesh. This mesh is a virtual depiction of the face and comprises the vertices, facial regions, and the focal point of the user’s head. At the point when a user’s face is identified by the camera, ARCore performs the following steps to generate the augmented face mesh, as well as center and region poses:"
},
{
"code": null,
"e": 4362,
"s": 4076,
"text": "It distinguishes the center pose and a face mesh.The center pose, situated behind the nose, is the actual center point of the user’s head (in other words, inside the skull).The face mesh comprises of many vertices that make up the face and is characterized relative to the center pose."
},
{
"code": null,
"e": 4487,
"s": 4362,
"text": "The center pose, situated behind the nose, is the actual center point of the user’s head (in other words, inside the skull)."
},
{
"code": null,
"e": 4600,
"s": 4487,
"text": "The face mesh comprises of many vertices that make up the face and is characterized relative to the center pose."
},
{
"code": null,
"e": 4820,
"s": 4600,
"text": "The AugmentedFace class utilizes the face mesh and center pose to distinguish face regions present on the client’s face. These regions are:Right brow (RIGHT_FOREHEAD)Left temple (LEFT_FOREHEAD)Tip of the nose (NOSE_TIP)"
},
{
"code": null,
"e": 4848,
"s": 4820,
"text": "Right brow (RIGHT_FOREHEAD)"
},
{
"code": null,
"e": 4876,
"s": 4848,
"text": "Left temple (LEFT_FOREHEAD)"
},
{
"code": null,
"e": 4903,
"s": 4876,
"text": "Tip of the nose (NOSE_TIP)"
},
{
"code": null,
"e": 5058,
"s": 4903,
"text": "The Face mesh, center pose, and face region poses are utilized by AugmentedFace APIs as positioning points and regions to place the resources in your app."
},
{
"code": null,
"e": 5086,
"s": 5058,
"text": "468 point face texture mesh"
},
{
"code": null,
"e": 5211,
"s": 5086,
"text": "Trackable: A Trackable is an interface which can be followed by ARCore and something from which Anchors can be connected to."
},
{
"code": null,
"e": 5506,
"s": 5211,
"text": "Anchor: It describes a fixed location and orientation in the real world. To stay at a fixed location in physical space, the numerical description of this position will update as ARCore’s understanding of the space improves. Anchors are hashable and may for example be used as keys in HashMaps."
},
{
"code": null,
"e": 5714,
"s": 5506,
"text": "Pose: At the point when you need to state wherein the scene you need to put the object and you need to specify the location in terms of the scene’s coordinates. The Pose is the means by which you state this."
},
{
"code": null,
"e": 6013,
"s": 5714,
"text": "Session: Deals with the AR framework state and handles the session lifecycle. This class offers the primary passage to the ARCore API. This class permits the user to make a session, configure it, start or stop it and, above all, receive frames that allow access to the camera image and device pose."
},
{
"code": null,
"e": 6201,
"s": 6013,
"text": "Textures: Textures are especially helpful for Augmented Faces. This permits you to make a light overlay that lines up with the locales of the identified face(s) to add to your experience."
},
{
"code": null,
"e": 6705,
"s": 6201,
"text": "ArFragment: ARCore utilizes an ArFragment that provides a lot of features, for example, plane finding, permission handling, and camera set up. You can utilize the fragment legitimately in your activity, however at whatever point you need custom features, for example, Augmented Faces, you should extend the ArFragment and set the proper settings. This fragment is the layer that conceals all the compound stuff (like OpenGL, rendering models, etc) and gives high-level APIs to load and render 3D models."
},
{
"code": null,
"e": 6784,
"s": 6705,
"text": "ModelRenderable: ModelRenderable renders a 3D Model by attaching it to a Node."
},
{
"code": null,
"e": 6985,
"s": 6784,
"text": "Sceneform SDK: Sceneform SDK is another library for Android that empowers the quick creation and mix of AR experiences in your application. It joins ARCore and an amazing physically-based 3D renderer."
},
{
"code": null,
"e": 7224,
"s": 6985,
"text": "We are going to create Snapchat, Instagram, and TikTok like face filters. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 7253,
"s": 7224,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 7415,
"s": 7253,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 7467,
"s": 7415,
"text": "Step 2: Adding the assets file used in this example"
},
{
"code": null,
"e": 8041,
"s": 7467,
"text": "Add any 3D model in sampledata/models folder. We can do this by creating a new folder in the project file directory or directly from the Android Studio. The allowed 3D model extensions are .fbx, .OBJ, .glTF. There are many free models available on the internet. You can visit, here or more. You can download the assets used in this example from here. Please refer to this article to create a raw folder in android studio. Then just copy and paste the fox_face.sfb file to the raw folder. Similarly, copy and paste the fox_face_mesh_texture.png file to the drawable folder. "
},
{
"code": null,
"e": 8100,
"s": 8041,
"text": "Step 3: Adding dependencies to the build.gradle(:app) file"
},
{
"code": null,
"e": 8164,
"s": 8100,
"text": "Add the following dependencies to the build.gradle(:app) file. "
},
{
"code": null,
"e": 8214,
"s": 8164,
"text": "// Provides ARCore Session and related resources."
},
{
"code": null,
"e": 8257,
"s": 8214,
"text": "implementation ‘com.google.ar:core:1.16.0’"
},
{
"code": null,
"e": 8305,
"s": 8257,
"text": "// Provides ArFragment, and other UX resources."
},
{
"code": null,
"e": 8369,
"s": 8305,
"text": "implementation ‘com.google.ar.sceneform.ux:sceneform-ux:1.15.0’"
},
{
"code": null,
"e": 8430,
"s": 8369,
"text": "// Alternatively, use ArSceneView without the UX dependency."
},
{
"code": null,
"e": 8482,
"s": 8430,
"text": "implementation ‘com.google.ar.sceneform:core:1.8.0’"
},
{
"code": null,
"e": 8683,
"s": 8482,
"text": "Add the following code snippet to the build.gradle file. This is required(only once) to convert .fbx asset into .sfb and save that in the raw folder. Or you can add them by yourself as done in step 2."
},
{
"code": null,
"e": 8738,
"s": 8683,
"text": "// required(only once) to convert .fbx asset into .sfb"
},
{
"code": null,
"e": 8769,
"s": 8738,
"text": "// and save that in raw folder"
},
{
"code": null,
"e": 8819,
"s": 8769,
"text": "sceneform.asset(‘sampledata/models/fox_face.fbx’,"
},
{
"code": null,
"e": 8854,
"s": 8819,
"text": " ‘default’,"
},
{
"code": null,
"e": 8912,
"s": 8854,
"text": " ‘sampleData/models/fox_face.sfa’,"
},
{
"code": null,
"e": 8965,
"s": 8912,
"text": " ‘src/main/res/raw/fox_face’)"
},
{
"code": null,
"e": 9028,
"s": 8965,
"text": "Step 4: Adding dependencies to the build.gradle(:project) file"
},
{
"code": null,
"e": 9096,
"s": 9028,
"text": "Add the following dependencies to the build.gradle(:project) file. "
},
{
"code": null,
"e": 9141,
"s": 9096,
"text": "// Add Sceneform plugin classpath to Project"
},
{
"code": null,
"e": 9168,
"s": 9141,
"text": "// level build.gradle file"
},
{
"code": null,
"e": 9218,
"s": 9168,
"text": "classpath ‘com.google.ar.sceneform:plugin:1.15.0’"
},
{
"code": null,
"e": 9268,
"s": 9218,
"text": "Step 5: Working with the AndroidManifest.xml file"
},
{
"code": null,
"e": 9324,
"s": 9268,
"text": "Add the following line to the AndroidManifest.xml file."
},
{
"code": null,
"e": 9396,
"s": 9324,
"text": "// Both “AR Optional” and “AR Required” apps require CAMERA permission."
},
{
"code": null,
"e": 9457,
"s": 9396,
"text": "<uses-permission android:name=”android.permission.CAMERA” />"
},
{
"code": null,
"e": 9532,
"s": 9457,
"text": "// Indicates that app requires ARCore (“AR Required”). Ensures app is only"
},
{
"code": null,
"e": 9600,
"s": 9532,
"text": "// visible in the Google Play Store on devices that support ARCore."
},
{
"code": null,
"e": 9646,
"s": 9600,
"text": "// For “AR Optional” apps remove this line. →"
},
{
"code": null,
"e": 9729,
"s": 9646,
"text": "<uses-feature android:name=”android.hardware.camera.ar” android:required=”true”/>"
},
{
"code": null,
"e": 9743,
"s": 9729,
"text": "<application>"
},
{
"code": null,
"e": 9750,
"s": 9743,
"text": " ..."
},
{
"code": null,
"e": 9822,
"s": 9750,
"text": " // Indicates that app requires ARCore (“AR Required”). Causes Google"
},
{
"code": null,
"e": 9890,
"s": 9822,
"text": " // Play Store to download and install ARCore along with the app."
},
{
"code": null,
"e": 9964,
"s": 9890,
"text": " // For an “AR Optional” app, specify “optional” instead of “required”."
},
{
"code": null,
"e": 10040,
"s": 9964,
"text": " <meta-data android:name=”com.google.ar.core” android:value=”required” />"
},
{
"code": null,
"e": 10048,
"s": 10040,
"text": " ..."
},
{
"code": null,
"e": 10064,
"s": 10048,
"text": " </application>"
},
{
"code": null,
"e": 10125,
"s": 10064,
"text": "Below is the complete code for the AndroidManifest.xml file."
},
{
"code": null,
"e": 10129,
"s": 10125,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.arsnapchat\"> <uses-feature android:name=\"android.hardware.camera\" android:required=\"true\" /> <uses-permission android:name=\"android.permission.CAMERA\" /> <uses-permission android:name=\"android.permission.INTERNET\" /> <uses-feature android:name=\"android.hardware.camera.ar\" android:required=\"true\" /> <uses-feature android:name=\"android.hardware.camera.autofocus\" /> <uses-feature android:glEsVersion=\"0x00020000\" android:required=\"true\" /> <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\"> <meta-data android:name=\"com.google.ar.core\" android:value=\"required\" /> <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>",
"e": 11426,
"s": 10129,
"text": null
},
{
"code": null,
"e": 11469,
"s": 11426,
"text": " Step 6: Modify the activity_main.xml file"
},
{
"code": null,
"e": 11576,
"s": 11469,
"text": "We have added a fragment to the activity_main.xml file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 11580,
"s": 11576,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout 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\"> <fragment android:id=\"@+id/arFragment\" android:name=\"com.example.arsnapchat.CustomArFragment\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 12149,
"s": 11580,
"text": null
},
{
"code": null,
"e": 12156,
"s": 12149,
"text": "Note: "
},
{
"code": null,
"e": 12204,
"s": 12156,
"text": "Please add your package name to this attribute."
},
{
"code": null,
"e": 12259,
"s": 12204,
"text": "android:name=”com.example.arsnapchat.CustomArFragment”"
},
{
"code": null,
"e": 12291,
"s": 12259,
"text": "Step 7: Create a new Java class"
},
{
"code": null,
"e": 12427,
"s": 12291,
"text": "Create a new class and name the file as CustomArFragment that extends ArFragment. Below is the code for the CustomArFragment.java file."
},
{
"code": null,
"e": 12432,
"s": 12427,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.FrameLayout;import androidx.annotation.Nullable;import com.google.ar.core.Config;import com.google.ar.core.Session;import com.google.ar.sceneform.ux.ArFragment;import java.util.EnumSet;import java.util.Set; public class CustomArFragment extends ArFragment { @Override protected Config getSessionConfiguration(Session session) { Config config = new Config(session); // Configure 3D Face Mesh config.setAugmentedFaceMode(Config.AugmentedFaceMode.MESH3D); this.getArSceneView().setupSession(session); return config; } @Override protected Set<Session.Feature> getSessionFeatures() { // Configure Front Camera return EnumSet.of(Session.Feature.FRONT_CAMERA); } // Override to turn off planeDiscoveryController. // Plane traceable are not supported with the front camera. @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { FrameLayout frameLayout = (FrameLayout) super.onCreateView(inflater, container, savedInstanceState); getPlaneDiscoveryController().hide(); getPlaneDiscoveryController().setInstructionView(null); return frameLayout; }}",
"e": 13796,
"s": 12432,
"text": null
},
{
"code": null,
"e": 13838,
"s": 13796,
"text": "Step 8: Modify the MainActivity.java file"
},
{
"code": null,
"e": 13963,
"s": 13838,
"text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 13968,
"s": 13963,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import com.google.ar.core.AugmentedFace;import com.google.ar.core.Frame;import com.google.ar.core.TrackingState;import com.google.ar.sceneform.rendering.ModelRenderable;import com.google.ar.sceneform.rendering.Renderable;import com.google.ar.sceneform.rendering.Texture;import com.google.ar.sceneform.ux.AugmentedFaceNode;import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map; public class MainActivity extends AppCompatActivity { private ModelRenderable modelRenderable; private Texture texture; private boolean isAdded = false; private final HashMap<AugmentedFace, AugmentedFaceNode> faceNodeMap = new HashMap<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CustomArFragment customArFragment = (CustomArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment); // Use ModelRenderable.Builder to load the *.sfb // models at runtime. // Load the face regions renderable. // To ensure that the asset doesn't cast or receive // shadows in the scene, ensure that setShadowCaster // and setShadowReceiver are both set to false. ModelRenderable.builder() .setSource(this, R.raw.fox_face) .build() .thenAccept(rendarable -> { this.modelRenderable = rendarable; this.modelRenderable.setShadowCaster(false); this.modelRenderable.setShadowReceiver(false); }) .exceptionally(throwable -> { Toast.makeText(this, \"error loading model\", Toast.LENGTH_SHORT).show(); return null; }); // Load the face mesh texture.(2D texture on face) // Save the texture(.png file) in drawable folder. Texture.builder() .setSource(this, R.drawable.fox_face_mesh_texture) .build() .thenAccept(textureModel -> this.texture = textureModel) .exceptionally(throwable -> { Toast.makeText(this, \"cannot load texture\", Toast.LENGTH_SHORT).show(); return null; }); assert customArFragment != null; // This is important to make sure that the camera // stream renders first so that the face mesh // occlusion works correctly. customArFragment.getArSceneView().setCameraStreamRenderPriority(Renderable.RENDER_PRIORITY_FIRST); customArFragment.getArSceneView().getScene().addOnUpdateListener(frameTime -> { if (modelRenderable == null || texture == null) { return; } Frame frame = customArFragment.getArSceneView().getArFrame(); assert frame != null; // Render the effect for the face Rendering the effect involves these steps: // 1.Create the Sceneform face node. // 2.Add the face node to the Sceneform scene. // 3.Set the face region Renderable. Extracting the face mesh and // rendering the face effect is added to a listener on // the scene that gets called on every processed camera frame. Collection<AugmentedFace> augmentedFaces = frame.getUpdatedTrackables(AugmentedFace.class); // Make new AugmentedFaceNodes for any new faces. for (AugmentedFace augmentedFace : augmentedFaces) { if (isAdded) return; AugmentedFaceNode augmentedFaceMode = new AugmentedFaceNode(augmentedFace); augmentedFaceMode.setParent(customArFragment.getArSceneView().getScene()); augmentedFaceMode.setFaceRegionsRenderable(modelRenderable); augmentedFaceMode.setFaceMeshTexture(texture); faceNodeMap.put(augmentedFace, augmentedFaceMode); isAdded = true; // Remove any AugmentedFaceNodes associated with // an AugmentedFace that stopped tracking. Iterator<Map.Entry<AugmentedFace, AugmentedFaceNode>> iterator = faceNodeMap.entrySet().iterator(); Map.Entry<AugmentedFace, AugmentedFaceNode> entry = iterator.next(); AugmentedFace face = entry.getKey(); while (face.getTrackingState() == TrackingState.STOPPED) { AugmentedFaceNode node = entry.getValue(); node.setParent(null); iterator.remove(); } } }); }}",
"e": 18678,
"s": 13968,
"text": null
},
{
"code": null,
"e": 18745,
"s": 18678,
"text": "Github Project Link: https://github.com/raghavtilak/AugmentedFaces"
},
{
"code": null,
"e": 19240,
"s": 18745,
"text": "Augmented Faces only works with the Front Camera.Not all devices support ARCore. There’s still a small fraction of devices which doesn’t come with AR Core support. You can check out the list of ARCore supported devices at https://developers.google.com/ar/discover/supported-devices.For AR Optional App minSdkVersion should be 14 and for AR Required App minSdkVersion should be 24.If your app falls in the category of AR Required app then the device using it should have AR Core installed on it."
},
{
"code": null,
"e": 19290,
"s": 19240,
"text": "Augmented Faces only works with the Front Camera."
},
{
"code": null,
"e": 19524,
"s": 19290,
"text": "Not all devices support ARCore. There’s still a small fraction of devices which doesn’t come with AR Core support. You can check out the list of ARCore supported devices at https://developers.google.com/ar/discover/supported-devices."
},
{
"code": null,
"e": 19623,
"s": 19524,
"text": "For AR Optional App minSdkVersion should be 14 and for AR Required App minSdkVersion should be 24."
},
{
"code": null,
"e": 19738,
"s": 19623,
"text": "If your app falls in the category of AR Required app then the device using it should have AR Core installed on it."
},
{
"code": null,
"e": 19745,
"s": 19738,
"text": "Notes:"
},
{
"code": null,
"e": 20288,
"s": 19745,
"text": "Prior to making a Session, it must be verified beforehand that ARCore is installed and up to date. If ARCore isn’t installed, then session creation might fail and any later installation or upgrade of ARCore would require restarting of the app, and might cause the app to be killed.The orientation of the face mesh is different for Unreal, Android and Unity.Calling Trackable.createAnchor(Pose) would result in an IllegalStateException because Augmented Faces supports only front-facing (selfie) camera, and does not support attaching anchors."
},
{
"code": null,
"e": 20570,
"s": 20288,
"text": "Prior to making a Session, it must be verified beforehand that ARCore is installed and up to date. If ARCore isn’t installed, then session creation might fail and any later installation or upgrade of ARCore would require restarting of the app, and might cause the app to be killed."
},
{
"code": null,
"e": 20647,
"s": 20570,
"text": "The orientation of the face mesh is different for Unreal, Android and Unity."
},
{
"code": null,
"e": 20833,
"s": 20647,
"text": "Calling Trackable.createAnchor(Pose) would result in an IllegalStateException because Augmented Faces supports only front-facing (selfie) camera, and does not support attaching anchors."
},
{
"code": null,
"e": 20848,
"s": 20833,
"text": "adnanirshad158"
},
{
"code": null,
"e": 20862,
"s": 20848,
"text": "sumitgumber28"
},
{
"code": null,
"e": 20870,
"s": 20862,
"text": "android"
},
{
"code": null,
"e": 20894,
"s": 20870,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 20902,
"s": 20894,
"text": "Android"
},
{
"code": null,
"e": 20907,
"s": 20902,
"text": "Java"
},
{
"code": null,
"e": 20926,
"s": 20907,
"text": "Technical Scripter"
},
{
"code": null,
"e": 20931,
"s": 20926,
"text": "Java"
},
{
"code": null,
"e": 20939,
"s": 20931,
"text": "Android"
}
] |
BufferedReader ready() method in Java with Examples - GeeksforGeeks | 28 May, 2020
The ready() method of BufferedReader class in Java is used to verify whether the buffer stream is ready to be read or not. A buffer stream is said to be ready in two cases either the buffer is not empty or the main stream is ready.
Syntax:
public boolean ready()
throws IOException
Overrides: This method overrides ready() method of Reader class.
Parameters: This method does not accept any parameter.
Return value: This method returns true if the stream is ready to be read otherwise it returns false.
Exceptions: This method throws IOException if an I/O error occurs.
Below programs illustrate ready() method in BufferedReader class in IO package:
Program 1: Assume the existence of the file “c:/demo.txt”.
// Java program to illustrate// BufferedReader ready() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text "GEEKS" FileReader fileReader = new FileReader( "c:/demo.txt"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); boolean b = buffReader.ready(); System.out.println(b); while (b) { System.out.println( (char)buffReader.read()); b = buffReader.ready(); } System.out.println(b); }}
Program 2: Assume the existence of the file “c:/demo.txt”.
// Java program to illustrate// BufferedReader ready() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text "GEEKSFORGEEKS" FileReader fileReader = new FileReader( "c:/demo.txt"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); boolean b = buffreader.ready(); System.out.println(b); while (b) { System.out.println( (char)buffReader.read()); b = buffReader.ready(); } System.out.println(b); }}
References: https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#ready()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Set in Java
LinkedList in Java
Overriding in Java
Queue Interface In Java | [
{
"code": null,
"e": 24530,
"s": 24502,
"text": "\n28 May, 2020"
},
{
"code": null,
"e": 24762,
"s": 24530,
"text": "The ready() method of BufferedReader class in Java is used to verify whether the buffer stream is ready to be read or not. A buffer stream is said to be ready in two cases either the buffer is not empty or the main stream is ready."
},
{
"code": null,
"e": 24770,
"s": 24762,
"text": "Syntax:"
},
{
"code": null,
"e": 24824,
"s": 24770,
"text": "public boolean ready() \n throws IOException\n"
},
{
"code": null,
"e": 24889,
"s": 24824,
"text": "Overrides: This method overrides ready() method of Reader class."
},
{
"code": null,
"e": 24944,
"s": 24889,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 25045,
"s": 24944,
"text": "Return value: This method returns true if the stream is ready to be read otherwise it returns false."
},
{
"code": null,
"e": 25112,
"s": 25045,
"text": "Exceptions: This method throws IOException if an I/O error occurs."
},
{
"code": null,
"e": 25192,
"s": 25112,
"text": "Below programs illustrate ready() method in BufferedReader class in IO package:"
},
{
"code": null,
"e": 25251,
"s": 25192,
"text": "Program 1: Assume the existence of the file “c:/demo.txt”."
},
{
"code": "// Java program to illustrate// BufferedReader ready() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text \"GEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); boolean b = buffReader.ready(); System.out.println(b); while (b) { System.out.println( (char)buffReader.read()); b = buffReader.ready(); } System.out.println(b); }}",
"e": 25962,
"s": 25251,
"text": null
},
{
"code": null,
"e": 26021,
"s": 25962,
"text": "Program 2: Assume the existence of the file “c:/demo.txt”."
},
{
"code": "// Java program to illustrate// BufferedReader ready() method import java.io.*; public class GFG { public static void main(String[] args) { // Read the stream 'demo.txt' // containing text \"GEEKSFORGEEKS\" FileReader fileReader = new FileReader( \"c:/demo.txt\"); // Convert fileReader to // bufferedReader BufferedReader buffReader = new BufferedReader( fileReader); boolean b = buffreader.ready(); System.out.println(b); while (b) { System.out.println( (char)buffReader.read()); b = buffReader.ready(); } System.out.println(b); }}",
"e": 26740,
"s": 26021,
"text": null
},
{
"code": null,
"e": 26831,
"s": 26740,
"text": "References: https://docs.oracle.com/javase/10/docs/api/java/io/BufferedReader.html#ready()"
},
{
"code": null,
"e": 26846,
"s": 26831,
"text": "Java-Functions"
},
{
"code": null,
"e": 26862,
"s": 26846,
"text": "Java-IO package"
},
{
"code": null,
"e": 26867,
"s": 26862,
"text": "Java"
},
{
"code": null,
"e": 26872,
"s": 26867,
"text": "Java"
},
{
"code": null,
"e": 26970,
"s": 26872,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26989,
"s": 26970,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27007,
"s": 26989,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27039,
"s": 27007,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27059,
"s": 27039,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27074,
"s": 27059,
"text": "Stream In Java"
},
{
"code": null,
"e": 27098,
"s": 27074,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 27110,
"s": 27098,
"text": "Set in Java"
},
{
"code": null,
"e": 27129,
"s": 27110,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 27148,
"s": 27129,
"text": "Overriding in Java"
}
] |
Let’s Build a Streaming Data Pipeline | by Daniel Foley | Towards Data Science | Today's post is based on a project I recently did in work. I was really excited to implement it and to write it up as a blog post as it gave me a chance to do some data engineering and also do something that was quite valuable for my team. Not too long ago, I discovered that we had a relatively large amount of user log data relating to one of our data products stored on our systems. As it turns out nobody was really using this data so I immediately became interested in what we could learn if we started to regularly analyze it. There was a couple of problems, however. The first issue was that the data was stored in many different text files which were not immediately accessible for analysis. The second issue was that it was stored in a locked down system so I couldn't use any of my favorite tools to analyze the data.
I considered how I could make this easier to access for us and really create some value by building this data source into some of our user engagement work. After thinking about this for a while I decided I would build a pipeline to feed this data into a cloud database so that I and the wider team could access it and start generating some insights. After having recently completed the GCP Data Engineering specialization on Coursera I was keen to start a project using some of the tools in the course.
Right so putting the data into a cloud database seems like a reasonable way to deal with my first problem but what could I do about problem number 2? Well luckily, there was a way to transfer this data to an environment where I could access tools like Python and Google Cloud Platform (GCP). This was, however going to be a long process so I needed to do something that would allow me to develop while I waited for the data transfer. The solution I arrived at was to create some fake data using the Faker library in Python. I had never used the library before but quickly realized how useful it was. Taking this approach allowed me to start writing code and testing the pipeline without having the actual data.
With that said, In this post, I will walk through how I built the pipeline described above using some of the technologies available on GCP. In particular, I will be using Apache Beam (python version), Dataflow, Pub/Sub, and Big Query to collect user logs, transform the data and feed it into a database for further analysis. For my use case, I only needed the batch functionality of beam since my data was not coming in real-time so Pub/Sub was not required. I will, however, focus on the streaming version since this is what you might commonly come across in practice.
Google Cloud Platform provides a bunch of really useful tools for big data processing. Some of the tools I will be using include:
Pub/Sub is a messaging service that uses a Publisher-Subscriber model allowing us to ingest data in real-time.
DataFlow is a service that simplifies creating data pipelines and automatically handles things like scaling up the infrastructure which means we can just concentrate on writing the code for our pipeline.
BigQuery is a cloud data warehouse. If you are familiar with other SQL style databases then BigQuery should be pretty straightforward.
Finally, we will be using Apache Beam and in particular, we will focus on the Python version to create our pipeline. This tool will allow us to create a pipeline for streaming or batch processing that integrates with GCP. It is particularly useful for parallel processing and is suited to Extract, Transform, and Load (ETL) type tasks so if we need to move data from one place to another while performing transformations or calculations Beam is a good choice.
There is a wide variety of tools available on GCP so it can be difficult to keep track of them all and what their purpose is but here is a summary of them for reference.
Let’s visualize the components of our pipeline using figure 1. At a high level, what we want to do is collect the user-generated data in real time, process it and feed it into BigQuery. The logs are generated when users interact with the product sending requests to the server which is then logged. This data can be particularly useful in understanding how users engage with our product and whether things are working correctly. In general, the pipeline will have the following steps:
Our user log data is published to a Pub/Sub topic.We will connect to Pub/Sub and transform the data into the appropriate format using Python and Beam (step 3 and 4 in Figure 1).After transforming the data, Beam will then connect to BigQuery and append the data to our table(step 4 and 5 in Figure 1).To carry out analysis we can connect to BigQuery using a variety of tools such as Tableau and Python.
Our user log data is published to a Pub/Sub topic.
We will connect to Pub/Sub and transform the data into the appropriate format using Python and Beam (step 3 and 4 in Figure 1).
After transforming the data, Beam will then connect to BigQuery and append the data to our table(step 4 and 5 in Figure 1).
To carry out analysis we can connect to BigQuery using a variety of tools such as Tableau and Python.
Beam makes this process very easy to do whether we have a streaming data source or if we have a CSV file and want to do a batch job. You will see later that there are only minimal changes to the code required to switch between the two. This is one of the advantages of using Beam.
As I mentioned before, due to limited access to the data I decided to create fake data that was the same format as the actual data. This was a really useful exercise as I could develop the code and test the pipeline while I waited for the data. I suggest taking a look at the Faker documentation if you want to see what else the library has to offer. Our user data will in general look similar to the example below. Based on this format we can generate data line by line to simulate real-time data. These logs give us information such as the date, the type of request, the response from the server, the IP address, etc.
192.52.197.161 - - [30/Apr/2019:21:11:42] "PUT /tag/category/tag HTTP/1.1" [401] 155 "https://harris-lopez.com/categories/about/" "Mozilla/5.0 (Macintosh; PPC Mac OS X 10_11_2) AppleWebKit/5312 (KHTML, like Gecko) Chrome/34.0.855.0 Safari/5312"
Based on the line above we want to create our LINE variable using the 7 variables in the curly brackets below. We will also use these as variable names in our table schema a little later as well.
LINE = """\{remote_addr} - - [{time_local}] "{request_type} {request_path} HTTP/1.1" [{status}] {body_bytes_sent} "{http_referer}" "{http_user_agent}"\"""
If we were doing a batch job the code would be quite similar although we would need to create a bunch of samples over some time range. To use faker we just create an object and call the methods we need. In particular, faker was useful for generating IP addresses as well as websites. I used the following methods:
fake.ipv4()fake.uri_path()fake.uri()fake.user_agent()
Note: To run the pipeline and publish the user log data I used the google cloud shell as I was having problems running the pipeline using Python 3. Google cloud shell uses Python 2 which plays a bit nicer with Apache Beam.
To be able to run the pipeline we need to do a bit of setup. For those of you who haven't used GCP before you will need to go through the 6 steps outlined on this page.
After this, we will need to upload our scripts to Google cloud storage and copy them to over to our Google cloud shell. Uploading to cloud storage is pretty straightforward and explained here. To copy our files, we can open up the Google Cloud shell in the toolbar by clicking the first icon on the left in Figure 2 below.
The commands we need to copy over the files and install the necessary libraries are listed below.
# Copy file from cloud storagegsutil cp gs://<YOUR-BUCKET>/ * .sudo pip install apache-beam[gcp] oauth2client==3.0.0 sudo pip install -U pipsudo pip install Faker==1.0.2# Environment variablesBUCKET=<YOUR-BUCKET>PROJECT=<YOUR-PROJECT>
After we have completed the set-up steps, the next thing we need to do is create a dataset and a table in BigQuery. There are a few different ways to do this but the easiest is to just use the google cloud console and first create a dataset. You can follow the steps in the following link to create a table and a schema. Our table will have 7 columns corresponding to the components of each user log. For ease, we will define all columns as strings apart from the timelocal variable and name them according to the variables we generated previously. Our table schema should look like figure 3.
Pub/Sub is a vital component of our pipeline as it allows multiple independent applications to interact with each other. In particular, it acts as a middle man allowing us to send and receive messages between applications. The first thing we need to do is create a topic. This is pretty simple to do by going to Pub/Sub in the console and clicking CREATE TOPIC.
The code below calls our script to generate log data defined above and then connects to and sends the logs to Pub/Sub. The only things we need to do are create a PublisherClient object, add the path to the topic using the topic_path method and call the publish function while passing the topic_path and data. Notice that we are importing generate_log_line from our stream_logs script so make sure these files are in the same folder or you will get an import error. We can then run this in our google console using:
python publish.py
Once the file is running we should be able to see log data printing to the console like the figure below. This script will keep running until we use CTRL+C to kill it.
Now that we have the initial set up out of the way we can get to the fun stuff and code up our pipeline using Beam and Python. To create a Beam pipeline we need to create a pipeline object (p). Once we have created the pipeline object we can apply multiple functions one after the other using the pipe (|) operator. In general, the workflow looks like the image below.
[Final Output PCollection] = ([Initial Input PCollection] | [First Transform] | [Second Transform] | [Third Transform])
In our code, we create two custom functions. The regex_clean function which searches the data and extracts the appropriate string based on the PATTERNS list using the re.search function. The function returns a comma-separated string. If you are not a regex expert I recommend looking at this tutorial and playing around in a notebook to test the code. After this, we define a custom ParDo function called Split which is a type of Beam transform for doing parallel processing. There is a specific way of doing this in Python where we have to create a class which inherits from the DoFn Beam class. The Split function takes the parsed string from the previous function and returns a list of dictionaries with keys equal to the column names in our BigQuery table. The one thing to note about this function is that I had to import datetime within the function for it to work. I was getting an error when I imported at the top of the file which was odd. This list then gets passed to the WriteToBigQuery function which just appends our data to the table. The code for both the Batch DataFlow job and the Streaming DataFlow job are provided below. The only difference between the batch and streaming code is that in the batch job we are reading a CSV from src_path using the ReadFromText function in Beam.
We can execute the pipeline a few different ways. If we wanted to we could just run it locally from the terminal provided we have remotely logged in to GCP.
python -m main_pipeline_stream.py \ --input_topic "projects/user-logs-237110/topics/userlogs" \ --streaming
We are going to be running it using DataFlow, however. We can do this using the command below while also setting the following mandatory options.
project - The ID of your GCP project.
runner - The pipeline runner that will parse your program and construct your pipeline. For cloud execution, this must be DataflowRunner.
staging_location - A Cloud Storage path for Cloud Dataflow to stage code packages needed by workers executing the job.
temp_location - A Cloud Storage path for Cloud Dataflow to stage temporary job files created during the execution of the pipeline.
streaming
python main_pipeline_stream.py \--runner DataFlow \--project $PROJECT \--temp_location $BUCKET/tmp \--staging_location $BUCKET/staging--streaming
While this command is running we can head over to the DataFlow tab in the google console and view our pipeline. When we click into the pipeline we should something like Figure 4. For debugging purposes, it can be quite helpful to go into the logs and then Stackdriver to view detailed logs. This has helped me figure out issues with the pipeline on a number of occasions.
Right we should have our pipeline up and running with data flowing into our table. To confirm this, we can go over to BigQuery and view the data. After using the command below you should see the first few rows of the dataset. Now that we have our data stored in BigQuery we can do further analysis as well as share the data with colleagues and start answering and addressing business questions.
SELECT * FROM `user-logs-237110.userlogs.logdata` LIMIT 10;
Hopefully, this provides a useful example of creating a streaming data pipeline and also of finding ways of making data more accessible. Having the data in this format provides many benefits to us. We can now start answering useful questions like how many people use our product? Is the user base growing over time? What aspects of the product are people interacting with the most? and are there any errors happening when there shouldn't be? These are the types of questions that an organization will be interested in and based on these insights we can drive improvements to the product and improve user engagement.
Beam is really useful for this type of exercise and there are a number of other interesting use cases as well. For example, you may want to analyze stock tick data in real-time and make trades based on the analysis, maybe you have sensor data coming in from vehicles and you want to figure out calculate the level of traffic. You could also, for example, be a games company collecting data on users and using this to create dashboards to track key metrics. Ok guys, so that’s it for another post, thanks for reading and for those who want to see the full code, below is a link to my GitHub.
Recommended Course: Data Engineering, Big Data, and Machine Learning on GCP
github.com
Note some of the links in this post are affiliate links. | [
{
"code": null,
"e": 999,
"s": 171,
"text": "Today's post is based on a project I recently did in work. I was really excited to implement it and to write it up as a blog post as it gave me a chance to do some data engineering and also do something that was quite valuable for my team. Not too long ago, I discovered that we had a relatively large amount of user log data relating to one of our data products stored on our systems. As it turns out nobody was really using this data so I immediately became interested in what we could learn if we started to regularly analyze it. There was a couple of problems, however. The first issue was that the data was stored in many different text files which were not immediately accessible for analysis. The second issue was that it was stored in a locked down system so I couldn't use any of my favorite tools to analyze the data."
},
{
"code": null,
"e": 1502,
"s": 999,
"text": "I considered how I could make this easier to access for us and really create some value by building this data source into some of our user engagement work. After thinking about this for a while I decided I would build a pipeline to feed this data into a cloud database so that I and the wider team could access it and start generating some insights. After having recently completed the GCP Data Engineering specialization on Coursera I was keen to start a project using some of the tools in the course."
},
{
"code": null,
"e": 2213,
"s": 1502,
"text": "Right so putting the data into a cloud database seems like a reasonable way to deal with my first problem but what could I do about problem number 2? Well luckily, there was a way to transfer this data to an environment where I could access tools like Python and Google Cloud Platform (GCP). This was, however going to be a long process so I needed to do something that would allow me to develop while I waited for the data transfer. The solution I arrived at was to create some fake data using the Faker library in Python. I had never used the library before but quickly realized how useful it was. Taking this approach allowed me to start writing code and testing the pipeline without having the actual data."
},
{
"code": null,
"e": 2783,
"s": 2213,
"text": "With that said, In this post, I will walk through how I built the pipeline described above using some of the technologies available on GCP. In particular, I will be using Apache Beam (python version), Dataflow, Pub/Sub, and Big Query to collect user logs, transform the data and feed it into a database for further analysis. For my use case, I only needed the batch functionality of beam since my data was not coming in real-time so Pub/Sub was not required. I will, however, focus on the streaming version since this is what you might commonly come across in practice."
},
{
"code": null,
"e": 2913,
"s": 2783,
"text": "Google Cloud Platform provides a bunch of really useful tools for big data processing. Some of the tools I will be using include:"
},
{
"code": null,
"e": 3024,
"s": 2913,
"text": "Pub/Sub is a messaging service that uses a Publisher-Subscriber model allowing us to ingest data in real-time."
},
{
"code": null,
"e": 3228,
"s": 3024,
"text": "DataFlow is a service that simplifies creating data pipelines and automatically handles things like scaling up the infrastructure which means we can just concentrate on writing the code for our pipeline."
},
{
"code": null,
"e": 3363,
"s": 3228,
"text": "BigQuery is a cloud data warehouse. If you are familiar with other SQL style databases then BigQuery should be pretty straightforward."
},
{
"code": null,
"e": 3823,
"s": 3363,
"text": "Finally, we will be using Apache Beam and in particular, we will focus on the Python version to create our pipeline. This tool will allow us to create a pipeline for streaming or batch processing that integrates with GCP. It is particularly useful for parallel processing and is suited to Extract, Transform, and Load (ETL) type tasks so if we need to move data from one place to another while performing transformations or calculations Beam is a good choice."
},
{
"code": null,
"e": 3993,
"s": 3823,
"text": "There is a wide variety of tools available on GCP so it can be difficult to keep track of them all and what their purpose is but here is a summary of them for reference."
},
{
"code": null,
"e": 4478,
"s": 3993,
"text": "Let’s visualize the components of our pipeline using figure 1. At a high level, what we want to do is collect the user-generated data in real time, process it and feed it into BigQuery. The logs are generated when users interact with the product sending requests to the server which is then logged. This data can be particularly useful in understanding how users engage with our product and whether things are working correctly. In general, the pipeline will have the following steps:"
},
{
"code": null,
"e": 4880,
"s": 4478,
"text": "Our user log data is published to a Pub/Sub topic.We will connect to Pub/Sub and transform the data into the appropriate format using Python and Beam (step 3 and 4 in Figure 1).After transforming the data, Beam will then connect to BigQuery and append the data to our table(step 4 and 5 in Figure 1).To carry out analysis we can connect to BigQuery using a variety of tools such as Tableau and Python."
},
{
"code": null,
"e": 4931,
"s": 4880,
"text": "Our user log data is published to a Pub/Sub topic."
},
{
"code": null,
"e": 5059,
"s": 4931,
"text": "We will connect to Pub/Sub and transform the data into the appropriate format using Python and Beam (step 3 and 4 in Figure 1)."
},
{
"code": null,
"e": 5183,
"s": 5059,
"text": "After transforming the data, Beam will then connect to BigQuery and append the data to our table(step 4 and 5 in Figure 1)."
},
{
"code": null,
"e": 5285,
"s": 5183,
"text": "To carry out analysis we can connect to BigQuery using a variety of tools such as Tableau and Python."
},
{
"code": null,
"e": 5566,
"s": 5285,
"text": "Beam makes this process very easy to do whether we have a streaming data source or if we have a CSV file and want to do a batch job. You will see later that there are only minimal changes to the code required to switch between the two. This is one of the advantages of using Beam."
},
{
"code": null,
"e": 6186,
"s": 5566,
"text": "As I mentioned before, due to limited access to the data I decided to create fake data that was the same format as the actual data. This was a really useful exercise as I could develop the code and test the pipeline while I waited for the data. I suggest taking a look at the Faker documentation if you want to see what else the library has to offer. Our user data will in general look similar to the example below. Based on this format we can generate data line by line to simulate real-time data. These logs give us information such as the date, the type of request, the response from the server, the IP address, etc."
},
{
"code": null,
"e": 6431,
"s": 6186,
"text": "192.52.197.161 - - [30/Apr/2019:21:11:42] \"PUT /tag/category/tag HTTP/1.1\" [401] 155 \"https://harris-lopez.com/categories/about/\" \"Mozilla/5.0 (Macintosh; PPC Mac OS X 10_11_2) AppleWebKit/5312 (KHTML, like Gecko) Chrome/34.0.855.0 Safari/5312\""
},
{
"code": null,
"e": 6627,
"s": 6431,
"text": "Based on the line above we want to create our LINE variable using the 7 variables in the curly brackets below. We will also use these as variable names in our table schema a little later as well."
},
{
"code": null,
"e": 6782,
"s": 6627,
"text": "LINE = \"\"\"\\{remote_addr} - - [{time_local}] \"{request_type} {request_path} HTTP/1.1\" [{status}] {body_bytes_sent} \"{http_referer}\" \"{http_user_agent}\"\\\"\"\""
},
{
"code": null,
"e": 7096,
"s": 6782,
"text": "If we were doing a batch job the code would be quite similar although we would need to create a bunch of samples over some time range. To use faker we just create an object and call the methods we need. In particular, faker was useful for generating IP addresses as well as websites. I used the following methods:"
},
{
"code": null,
"e": 7150,
"s": 7096,
"text": "fake.ipv4()fake.uri_path()fake.uri()fake.user_agent()"
},
{
"code": null,
"e": 7373,
"s": 7150,
"text": "Note: To run the pipeline and publish the user log data I used the google cloud shell as I was having problems running the pipeline using Python 3. Google cloud shell uses Python 2 which plays a bit nicer with Apache Beam."
},
{
"code": null,
"e": 7542,
"s": 7373,
"text": "To be able to run the pipeline we need to do a bit of setup. For those of you who haven't used GCP before you will need to go through the 6 steps outlined on this page."
},
{
"code": null,
"e": 7865,
"s": 7542,
"text": "After this, we will need to upload our scripts to Google cloud storage and copy them to over to our Google cloud shell. Uploading to cloud storage is pretty straightforward and explained here. To copy our files, we can open up the Google Cloud shell in the toolbar by clicking the first icon on the left in Figure 2 below."
},
{
"code": null,
"e": 7963,
"s": 7865,
"text": "The commands we need to copy over the files and install the necessary libraries are listed below."
},
{
"code": null,
"e": 8198,
"s": 7963,
"text": "# Copy file from cloud storagegsutil cp gs://<YOUR-BUCKET>/ * .sudo pip install apache-beam[gcp] oauth2client==3.0.0 sudo pip install -U pipsudo pip install Faker==1.0.2# Environment variablesBUCKET=<YOUR-BUCKET>PROJECT=<YOUR-PROJECT>"
},
{
"code": null,
"e": 8791,
"s": 8198,
"text": "After we have completed the set-up steps, the next thing we need to do is create a dataset and a table in BigQuery. There are a few different ways to do this but the easiest is to just use the google cloud console and first create a dataset. You can follow the steps in the following link to create a table and a schema. Our table will have 7 columns corresponding to the components of each user log. For ease, we will define all columns as strings apart from the timelocal variable and name them according to the variables we generated previously. Our table schema should look like figure 3."
},
{
"code": null,
"e": 9153,
"s": 8791,
"text": "Pub/Sub is a vital component of our pipeline as it allows multiple independent applications to interact with each other. In particular, it acts as a middle man allowing us to send and receive messages between applications. The first thing we need to do is create a topic. This is pretty simple to do by going to Pub/Sub in the console and clicking CREATE TOPIC."
},
{
"code": null,
"e": 9668,
"s": 9153,
"text": "The code below calls our script to generate log data defined above and then connects to and sends the logs to Pub/Sub. The only things we need to do are create a PublisherClient object, add the path to the topic using the topic_path method and call the publish function while passing the topic_path and data. Notice that we are importing generate_log_line from our stream_logs script so make sure these files are in the same folder or you will get an import error. We can then run this in our google console using:"
},
{
"code": null,
"e": 9686,
"s": 9668,
"text": "python publish.py"
},
{
"code": null,
"e": 9854,
"s": 9686,
"text": "Once the file is running we should be able to see log data printing to the console like the figure below. This script will keep running until we use CTRL+C to kill it."
},
{
"code": null,
"e": 10223,
"s": 9854,
"text": "Now that we have the initial set up out of the way we can get to the fun stuff and code up our pipeline using Beam and Python. To create a Beam pipeline we need to create a pipeline object (p). Once we have created the pipeline object we can apply multiple functions one after the other using the pipe (|) operator. In general, the workflow looks like the image below."
},
{
"code": null,
"e": 10369,
"s": 10223,
"text": "[Final Output PCollection] = ([Initial Input PCollection] | [First Transform] | [Second Transform] | [Third Transform])"
},
{
"code": null,
"e": 11669,
"s": 10369,
"text": "In our code, we create two custom functions. The regex_clean function which searches the data and extracts the appropriate string based on the PATTERNS list using the re.search function. The function returns a comma-separated string. If you are not a regex expert I recommend looking at this tutorial and playing around in a notebook to test the code. After this, we define a custom ParDo function called Split which is a type of Beam transform for doing parallel processing. There is a specific way of doing this in Python where we have to create a class which inherits from the DoFn Beam class. The Split function takes the parsed string from the previous function and returns a list of dictionaries with keys equal to the column names in our BigQuery table. The one thing to note about this function is that I had to import datetime within the function for it to work. I was getting an error when I imported at the top of the file which was odd. This list then gets passed to the WriteToBigQuery function which just appends our data to the table. The code for both the Batch DataFlow job and the Streaming DataFlow job are provided below. The only difference between the batch and streaming code is that in the batch job we are reading a CSV from src_path using the ReadFromText function in Beam."
},
{
"code": null,
"e": 11826,
"s": 11669,
"text": "We can execute the pipeline a few different ways. If we wanted to we could just run it locally from the terminal provided we have remotely logged in to GCP."
},
{
"code": null,
"e": 11936,
"s": 11826,
"text": "python -m main_pipeline_stream.py \\ --input_topic \"projects/user-logs-237110/topics/userlogs\" \\ --streaming"
},
{
"code": null,
"e": 12082,
"s": 11936,
"text": "We are going to be running it using DataFlow, however. We can do this using the command below while also setting the following mandatory options."
},
{
"code": null,
"e": 12120,
"s": 12082,
"text": "project - The ID of your GCP project."
},
{
"code": null,
"e": 12257,
"s": 12120,
"text": "runner - The pipeline runner that will parse your program and construct your pipeline. For cloud execution, this must be DataflowRunner."
},
{
"code": null,
"e": 12376,
"s": 12257,
"text": "staging_location - A Cloud Storage path for Cloud Dataflow to stage code packages needed by workers executing the job."
},
{
"code": null,
"e": 12507,
"s": 12376,
"text": "temp_location - A Cloud Storage path for Cloud Dataflow to stage temporary job files created during the execution of the pipeline."
},
{
"code": null,
"e": 12517,
"s": 12507,
"text": "streaming"
},
{
"code": null,
"e": 12663,
"s": 12517,
"text": "python main_pipeline_stream.py \\--runner DataFlow \\--project $PROJECT \\--temp_location $BUCKET/tmp \\--staging_location $BUCKET/staging--streaming"
},
{
"code": null,
"e": 13035,
"s": 12663,
"text": "While this command is running we can head over to the DataFlow tab in the google console and view our pipeline. When we click into the pipeline we should something like Figure 4. For debugging purposes, it can be quite helpful to go into the logs and then Stackdriver to view detailed logs. This has helped me figure out issues with the pipeline on a number of occasions."
},
{
"code": null,
"e": 13430,
"s": 13035,
"text": "Right we should have our pipeline up and running with data flowing into our table. To confirm this, we can go over to BigQuery and view the data. After using the command below you should see the first few rows of the dataset. Now that we have our data stored in BigQuery we can do further analysis as well as share the data with colleagues and start answering and addressing business questions."
},
{
"code": null,
"e": 13490,
"s": 13430,
"text": "SELECT * FROM `user-logs-237110.userlogs.logdata` LIMIT 10;"
},
{
"code": null,
"e": 14106,
"s": 13490,
"text": "Hopefully, this provides a useful example of creating a streaming data pipeline and also of finding ways of making data more accessible. Having the data in this format provides many benefits to us. We can now start answering useful questions like how many people use our product? Is the user base growing over time? What aspects of the product are people interacting with the most? and are there any errors happening when there shouldn't be? These are the types of questions that an organization will be interested in and based on these insights we can drive improvements to the product and improve user engagement."
},
{
"code": null,
"e": 14697,
"s": 14106,
"text": "Beam is really useful for this type of exercise and there are a number of other interesting use cases as well. For example, you may want to analyze stock tick data in real-time and make trades based on the analysis, maybe you have sensor data coming in from vehicles and you want to figure out calculate the level of traffic. You could also, for example, be a games company collecting data on users and using this to create dashboards to track key metrics. Ok guys, so that’s it for another post, thanks for reading and for those who want to see the full code, below is a link to my GitHub."
},
{
"code": null,
"e": 14773,
"s": 14697,
"text": "Recommended Course: Data Engineering, Big Data, and Machine Learning on GCP"
},
{
"code": null,
"e": 14784,
"s": 14773,
"text": "github.com"
}
] |
Different way to create a thread in Python - GeeksforGeeks | 01 Oct, 2020
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an Operating System.
1) Create a Thread without using an Explicit function:
By importing the module and creating the Thread class object separately we can easily create a thread. It is a function-oriented way of creating a thread.
Python3
# Import required modulesfrom threading import * # Explicit functiondef display() : for i in range(10) : print("Child Thread") # Driver Code # Create object of thread class Thread_obj = Thread(target=display) # Executing child threadThread_obj.start() # Executing main threadfor i in range(10): print('Main Thread')
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
In the above example, we have created an explicit function display() which prints Child Thread 10 times. Then we created a Thread class object named Thread_obj using the threading module. The first Thread is targeting the display() method i.e. display() method will be executed by this Thread object and the main thread(the second one) is targeting the for loop and will be responsible for executing by the Main Thread 10 times.
NOTE: Here which thread will get chance first (Main Thread or Child Thread) depends on the Thread Scheduler present in Python Virtual Machine (PVM), so we can’t predict the output.
2) Create Thread by extending Thread Class :
In this method, we will extend the thread class from the threading module. This approach of creating a thread is also known as Object-Oriented Way.
Python3
# Import required modulefrom threading import * # Extending Thread classclass Mythread(Thread): # Target function for thread def run(self): for i in range(10): print('Child Thread') # Driver Code # Creating thread class objectt = Mythread() # Execution of target functiont.start() # Executed by main threadfor i in range(10): print('Main Thread')
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
In the above example, we create a class that extends the Thread class, inside this class, we must override the run() method which will be the target function of our Child Thread, when the start() method is called it initiates the execution of the run() method(Target Function) of the thread.
3. Create Thread without extending Thread Class :
Another Object-Oriented Way of creating Thread is by not extending any thread class to create Thread.
Python3
# Import required modulesfrom threading import * # Creating classclass Gfg: # Creating instance method def method1(self): for i in range(10): print('Child Thread') # Driver Code # Creating object of Gfg classobj = Gfg() # Creating object of thread by# targeting instance method of Gfg classthread_obj = Thread(target=obj.method1) # Call the target function of threathread_obj.start() # for loop executed by main threadfor i in range(10): print('Main Thread')
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
In the above program, we separately create an object of thread class and Gfg class, and whenever we create an object of thread class that time we have to mention the target function as well. The thread class object targets the instance method of the Gfg class. To start the execution of the target function we must call the start() method.
Python-threading
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25579,
"s": 25551,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25746,
"s": 25579,
"text": "A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an Operating System. "
},
{
"code": null,
"e": 25802,
"s": 25746,
"text": "1) Create a Thread without using an Explicit function: "
},
{
"code": null,
"e": 25958,
"s": 25802,
"text": "By importing the module and creating the Thread class object separately we can easily create a thread. It is a function-oriented way of creating a thread. "
},
{
"code": null,
"e": 25966,
"s": 25958,
"text": "Python3"
},
{
"code": "# Import required modulesfrom threading import * # Explicit functiondef display() : for i in range(10) : print(\"Child Thread\") # Driver Code # Create object of thread class Thread_obj = Thread(target=display) # Executing child threadThread_obj.start() # Executing main threadfor i in range(10): print('Main Thread')",
"e": 26359,
"s": 25966,
"text": null
},
{
"code": null,
"e": 26612,
"s": 26359,
"text": "Child Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread \n"
},
{
"code": null,
"e": 27041,
"s": 26612,
"text": "In the above example, we have created an explicit function display() which prints Child Thread 10 times. Then we created a Thread class object named Thread_obj using the threading module. The first Thread is targeting the display() method i.e. display() method will be executed by this Thread object and the main thread(the second one) is targeting the for loop and will be responsible for executing by the Main Thread 10 times."
},
{
"code": null,
"e": 27223,
"s": 27041,
"text": "NOTE: Here which thread will get chance first (Main Thread or Child Thread) depends on the Thread Scheduler present in Python Virtual Machine (PVM), so we can’t predict the output. "
},
{
"code": null,
"e": 27269,
"s": 27223,
"text": "2) Create Thread by extending Thread Class : "
},
{
"code": null,
"e": 27419,
"s": 27269,
"text": "In this method, we will extend the thread class from the threading module. This approach of creating a thread is also known as Object-Oriented Way. "
},
{
"code": null,
"e": 27427,
"s": 27419,
"text": "Python3"
},
{
"code": "# Import required modulefrom threading import * # Extending Thread classclass Mythread(Thread): # Target function for thread def run(self): for i in range(10): print('Child Thread') # Driver Code # Creating thread class objectt = Mythread() # Execution of target functiont.start() # Executed by main threadfor i in range(10): print('Main Thread')",
"e": 27824,
"s": 27427,
"text": null
},
{
"code": null,
"e": 28075,
"s": 27824,
"text": "Child Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\n"
},
{
"code": null,
"e": 28368,
"s": 28075,
"text": "In the above example, we create a class that extends the Thread class, inside this class, we must override the run() method which will be the target function of our Child Thread, when the start() method is called it initiates the execution of the run() method(Target Function) of the thread. "
},
{
"code": null,
"e": 28419,
"s": 28368,
"text": "3. Create Thread without extending Thread Class : "
},
{
"code": null,
"e": 28521,
"s": 28419,
"text": "Another Object-Oriented Way of creating Thread is by not extending any thread class to create Thread."
},
{
"code": null,
"e": 28529,
"s": 28521,
"text": "Python3"
},
{
"code": "# Import required modulesfrom threading import * # Creating classclass Gfg: # Creating instance method def method1(self): for i in range(10): print('Child Thread') # Driver Code # Creating object of Gfg classobj = Gfg() # Creating object of thread by# targeting instance method of Gfg classthread_obj = Thread(target=obj.method1) # Call the target function of threathread_obj.start() # for loop executed by main threadfor i in range(10): print('Main Thread')",
"e": 29039,
"s": 28529,
"text": null
},
{
"code": null,
"e": 29290,
"s": 29039,
"text": "Child Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nChild Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\nMain Thread\n"
},
{
"code": null,
"e": 29630,
"s": 29290,
"text": "In the above program, we separately create an object of thread class and Gfg class, and whenever we create an object of thread class that time we have to mention the target function as well. The thread class object targets the instance method of the Gfg class. To start the execution of the target function we must call the start() method."
},
{
"code": null,
"e": 29647,
"s": 29630,
"text": "Python-threading"
},
{
"code": null,
"e": 29654,
"s": 29647,
"text": "Python"
},
{
"code": null,
"e": 29752,
"s": 29654,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29784,
"s": 29752,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29826,
"s": 29784,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29868,
"s": 29826,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29924,
"s": 29868,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29951,
"s": 29924,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29982,
"s": 29951,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30011,
"s": 29982,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 30033,
"s": 30011,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30072,
"s": 30033,
"text": "Python | Get unique values from a list"
}
] |
Angular PrimeNG MegaMenu Component - GeeksforGeeks | 08 Sep, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the MegaMenu component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code.
MegaMenu component: It is a navigation component that is used to make a component with multiple numbers of the menu.
Properties:
model: It is an array of menuitems. It accepts the array data type as input & the default value is null.
orientation: It is used to define the orientation. It is of string data type & the default value is horizontal.
style: It is used to set the Inline style of the component. It is of string data type & the default value is null.
styleClass: It is used to set the style class of the component. It is of string data type & the default value is null.
baseZIndex: It is used to set the base zIndex value to use in layering. It accepts the number data type as input & the default value is 0.
autoZIndex: It is used to specify whether to automatically manage the layering. It is of boolean data type & the default value is true.
Styling:
p-megamenu: It is a container element.
p-menu-list: It is a list element.
p-menuitem: It is a menuitem element.
p-menuitem-text: It is a label of a menuitem.
p-menuitem-icon: It is an icon of a menuitem.
p-submenu-icon: It is the arrow icon of a submenu.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following:
Example 1: This is the basic example that illustrates how to use the MegaMenu component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG MegaMenu Component</h5><p-megaMenu [model]="gfg"></p-megaMenu>
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MegaMenuModule } from 'primeng/megamenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MegaMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
app.component.ts
import { Component } from '@angular/core';import { MegaMenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MegaMenuItem[]; ngOnInit() { this.gfg = [ { label: 'GeeksforGeeks', items: [ [ { label: 'AngularJS', items: [{ label: 'AngularJS 1' }, { label: 'AngularJS 2' }] }, { label: 'ReactJS', items: [{ label: 'ReactJS 1' }, { label: 'ReactJS 2' }] } ], [ { label: 'HTML', items: [{ label: 'HTML 1' }, { label: 'HTML 2' }] }, { label: 'PrimeNG', items: [{ label: 'PriemNG 1' }, { label: 'PrimeNG 2' }] } ] ] } ]; }}
Output:
Example 2: In this example, we will know how to use the orientation property in the MegaMenu component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG MegaMenu Component</h5><p-megaMenu [model]="gfg" orientation='vertical'></p-megaMenu>
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MegaMenuModule } from 'primeng/megamenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MegaMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
app.component.ts
import { Component } from '@angular/core';import { MegaMenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MegaMenuItem[]; ngOnInit() { this.gfg = [ { label: 'GeeksforGeeks', items: [ [ { label: 'AngularJS', items: [{ label: 'AngularJS 1' }, { label: 'AngularJS 2' }] }, { label: 'ReactJS', items: [{ label: 'ReactJS 1' }, { label: 'ReactJS 2' }] } ], [ { label: 'HTML', items: [{ label: 'HTML 1' }, { label: 'HTML 2' }] }, { label: 'PrimeNG', items: [{ label: 'PriemNG 1' }, { label: 'PrimeNG 2' }] } ] ] } ]; }}
Output:
Reference: https://primefaces.org/primeng/showcase/#/megamenu
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular PrimeNG Messages Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
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": 26464,
"s": 26436,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 26855,
"s": 26464,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the MegaMenu component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. "
},
{
"code": null,
"e": 26972,
"s": 26855,
"text": "MegaMenu component: It is a navigation component that is used to make a component with multiple numbers of the menu."
},
{
"code": null,
"e": 26984,
"s": 26972,
"text": "Properties:"
},
{
"code": null,
"e": 27089,
"s": 26984,
"text": "model: It is an array of menuitems. It accepts the array data type as input & the default value is null."
},
{
"code": null,
"e": 27201,
"s": 27089,
"text": "orientation: It is used to define the orientation. It is of string data type & the default value is horizontal."
},
{
"code": null,
"e": 27316,
"s": 27201,
"text": "style: It is used to set the Inline style of the component. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27435,
"s": 27316,
"text": "styleClass: It is used to set the style class of the component. It is of string data type & the default value is null."
},
{
"code": null,
"e": 27574,
"s": 27435,
"text": "baseZIndex: It is used to set the base zIndex value to use in layering. It accepts the number data type as input & the default value is 0."
},
{
"code": null,
"e": 27710,
"s": 27574,
"text": "autoZIndex: It is used to specify whether to automatically manage the layering. It is of boolean data type & the default value is true."
},
{
"code": null,
"e": 27719,
"s": 27710,
"text": "Styling:"
},
{
"code": null,
"e": 27758,
"s": 27719,
"text": "p-megamenu: It is a container element."
},
{
"code": null,
"e": 27793,
"s": 27758,
"text": "p-menu-list: It is a list element."
},
{
"code": null,
"e": 27831,
"s": 27793,
"text": "p-menuitem: It is a menuitem element."
},
{
"code": null,
"e": 27877,
"s": 27831,
"text": "p-menuitem-text: It is a label of a menuitem."
},
{
"code": null,
"e": 27923,
"s": 27877,
"text": "p-menuitem-icon: It is an icon of a menuitem."
},
{
"code": null,
"e": 27974,
"s": 27923,
"text": "p-submenu-icon: It is the arrow icon of a submenu."
},
{
"code": null,
"e": 28028,
"s": 27976,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 28095,
"s": 28028,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 28110,
"s": 28095,
"text": "ng new appname"
},
{
"code": null,
"e": 28207,
"s": 28110,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 28218,
"s": 28207,
"text": "cd appname"
},
{
"code": null,
"e": 28267,
"s": 28218,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 28324,
"s": 28267,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 28376,
"s": 28324,
"text": "Project Structure: It will look like the following:"
},
{
"code": null,
"e": 28465,
"s": 28376,
"text": "Example 1: This is the basic example that illustrates how to use the MegaMenu component."
},
{
"code": null,
"e": 28484,
"s": 28465,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG MegaMenu Component</h5><p-megaMenu [model]=\"gfg\"></p-megaMenu>",
"e": 28581,
"s": 28484,
"text": null
},
{
"code": null,
"e": 28595,
"s": 28581,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MegaMenuModule } from 'primeng/megamenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MegaMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 29069,
"s": 28595,
"text": null
},
{
"code": null,
"e": 29086,
"s": 29069,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import { MegaMenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MegaMenuItem[]; ngOnInit() { this.gfg = [ { label: 'GeeksforGeeks', items: [ [ { label: 'AngularJS', items: [{ label: 'AngularJS 1' }, { label: 'AngularJS 2' }] }, { label: 'ReactJS', items: [{ label: 'ReactJS 1' }, { label: 'ReactJS 2' }] } ], [ { label: 'HTML', items: [{ label: 'HTML 1' }, { label: 'HTML 2' }] }, { label: 'PrimeNG', items: [{ label: 'PriemNG 1' }, { label: 'PrimeNG 2' }] } ] ] } ]; }}",
"e": 29955,
"s": 29086,
"text": null
},
{
"code": null,
"e": 29965,
"s": 29957,
"text": "Output:"
},
{
"code": null,
"e": 30069,
"s": 29965,
"text": "Example 2: In this example, we will know how to use the orientation property in the MegaMenu component."
},
{
"code": null,
"e": 30088,
"s": 30069,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG MegaMenu Component</h5><p-megaMenu [model]=\"gfg\" orientation='vertical'></p-megaMenu>",
"e": 30208,
"s": 30088,
"text": null
},
{
"code": null,
"e": 30222,
"s": 30208,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { MegaMenuModule } from 'primeng/megamenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, MegaMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 30696,
"s": 30222,
"text": null
},
{
"code": null,
"e": 30713,
"s": 30696,
"text": "app.component.ts"
},
{
"code": "import { Component } from '@angular/core';import { MegaMenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MegaMenuItem[]; ngOnInit() { this.gfg = [ { label: 'GeeksforGeeks', items: [ [ { label: 'AngularJS', items: [{ label: 'AngularJS 1' }, { label: 'AngularJS 2' }] }, { label: 'ReactJS', items: [{ label: 'ReactJS 1' }, { label: 'ReactJS 2' }] } ], [ { label: 'HTML', items: [{ label: 'HTML 1' }, { label: 'HTML 2' }] }, { label: 'PrimeNG', items: [{ label: 'PriemNG 1' }, { label: 'PrimeNG 2' }] } ] ] } ]; }}",
"e": 31582,
"s": 30713,
"text": null
},
{
"code": null,
"e": 31590,
"s": 31582,
"text": "Output:"
},
{
"code": null,
"e": 31652,
"s": 31590,
"text": "Reference: https://primefaces.org/primeng/showcase/#/megamenu"
},
{
"code": null,
"e": 31668,
"s": 31652,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 31678,
"s": 31668,
"text": "AngularJS"
},
{
"code": null,
"e": 31695,
"s": 31678,
"text": "Web Technologies"
},
{
"code": null,
"e": 31793,
"s": 31695,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31828,
"s": 31793,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31863,
"s": 31828,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 31898,
"s": 31863,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 31922,
"s": 31898,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 31975,
"s": 31922,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 32015,
"s": 31975,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32048,
"s": 32015,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32093,
"s": 32048,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32136,
"s": 32093,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Compressed Tries - GeeksforGeeks | 24 Nov, 2021
A trie is a data structure that stores strings like a tree data structure. The maximum number of children in a node is equal to the size of the alphabet. One can easily print letters in alphabetical order which isn’t possible with hashing.
Properties of Trie:
It’s a multi-way tree.
Each node has from 1 to N children.
Each leaf node corresponds to the stored string, which is a chain of characters on a path from the root to its side.
Types of Trie:
Standard Trie
Suffix Trie
Compressed Trie
Compressed Trie:
Tries with nodes of degree at least 2. It is accomplished by compressing the nodes of the standard trie. It is also known as Radix Tries. It is used to achieve space optimization
Since the nodes are compressed. Let’s visually compare the structure of the Standard tree and the compressed tree for a better approach. In terms of memory, a compressed trie tree uses very few amounts of nodes which gives a huge memory advantage(especially for long) strings with long common prefixes. In terms of speed, a regular trie tree would be slightly faster because its operations don’t involve any string operations, they are simple loops.
In the below image, the left tree is a Standard trie, the right tree is a compressed trie.
Implementation:
A standard trie node looks like this:
Java
Python3
class node { node[] children = new node[26]; boolean isWordEnd;}
class node: def __init__(self): self.node = [None]*26 self.isWordEnd=False
But for a compressed trie, redesigning of the tree will be as follows, in the general trie, an edge ‘a’ is denoted by this particular element in the array of references, but in the compressed trie, “An edge ‘face’ is denoted by this particular element in the array of references”. The code is-:
Java
Python3
class node { node[] children = new node[26]; StringBuilder[] edgeLabel = new StringBuilder[26]; boolean isEnd;}
class node: def __init__(self): self.children = [None]*26 sefl.edgeLabel = [None]*26 self.isEnd=False
Node in Compressed Trie:
Java
Python3
class CompressedNode { int bitNumber; int data; CompressedNode leftChild, rightChild;}
class node: def __init__(self): self.bitNumber=0 self.data=None self.leftChild, self.rightChild=None,None
Class Compressed trie:
Java
Python3
class CompressedNode { // Root Node private CompressedNode root; private static final int MaxBits = 10; // Constructor public CompressedNode() { root = null; } // Function to check if empty public boolean isEmpty() { return root == null; } // Function to clear public void makeEmpty() { root = null; }}
class CompressedNode { #Root Node root=CompressedNode() MaxBits = 10 #Constructor def __init__(self): self.root = None #Function to check if empty def isEmpty(self): return self.root == None #Function to clear def makeEmpty(self): self.root = None
Searching in Compressed Trie:
Searching in a compressed Trie tree is much like searching. Here, instead of comparing a single character, we compare strings.
Java
Python3
// Function to search a key k// in the triepublic boolean search(int k){ // Find the number of bits int numOfBits = (int)(Math.log(k) / Math.log(2)) + 1; // If error occurs if (numOfBits > MaxBits) { System.out.println("Error : Number too large"); return false; } // Search Node CompressedNode searchNode = search(root, k); // If the data matches if (searchNode.data == k) return true; // Else return false else return false;}
# Function to search a key k# in the trieimport mathdef search(k): # Find the number of bits numOfBits = int(math.log2(k)) + 1 # If error occurs if (numOfBits > MaxBits) : print("Error : Number too large") return False # Search Node searchNode = search(root, k) # If the data matches if (searchNode.data == k): return True # Else return false else: return False
Inserting an element in Compressed Trie:
Java
Python3
// Function to implement the insert// functionality in the trieprivate CompressedNode insert( CompressedNode t, int ele){ CompressedNode current, parent; CompressedNode lastNode, newNode; int i; // If Node is NULL if (t == null) { t = new CompressedNode(); t.bitNumber = 0; t.data = ele; t.leftChild = t; t.rightChild = null; return t; } // Search the key ele lastNode = search(t, ele); // If already present key if (ele == lastNode.data) { System.out.println( "Error : key is already present\n"); return t; } for (i = 1; bit(ele, i) == bit(lastNode.data, i); i++) ; current = t.leftChild; parent = t; while (current.bitNumber > parent.bitNumber && current.bitNumber < i) { parent = current; current = (bit(ele, current.bitNumber)) ? current.rightChild : current.leftChild; } newNode = new CompressedNode(); newNode.bitNumber = i; newNode.data = ele; newNode.leftChild = bit(ele, i) ? current : newNode; newNode.rightChild = bit(ele, i) ? newNode : current; if (current == parent.leftChild) parent.leftChild = newNode; else parent.rightChild = newNode; return t;}
# Function to implement the insert# functionality in the triedef insert( t, ele): # If Node is None if (t == None) : t = CompressedNode() t.bitNumber = 0 t.data = ele t.leftChild = t t.rightChild = None return t # Search the key ele lastNode = search(t, ele) # If already present key if (ele == lastNode.data) : print( "Error : key is already present") return t i=1 while(bit(ele, i) == bit(lastNode.data, i)): i+=1 current = t.leftChild parent = t while (current.bitNumber > parent.bitNumber and current.bitNumber < i) : parent = current current = current.rightChild if (bit(ele, current.bitNumber)) else current.leftChild newNode = CompressedNode() newNode.bitNumber = i newNode.data = ele newNode.leftChild = current if bit(ele, i) else newNode newNode.rightChild = newNode if bit(ele, i) else current if (current == parent.leftChild): parent.leftChild = newNode else: parent.rightChild = newNode return t
Below is the program to implement all functionality of the compressed Trie:
Java
Python3
// Java program to implement the// Compressed Trie class Trie { // Root Node private final Node root = new Node(false); // 'a' for lower, 'A' for upper private final char CASE; // Default case public Trie() { CASE = 'a'; } // Constructor accepting the // starting symbol public Trie(char CASE) { this.CASE = CASE; } // Function to insert a word in // the compressed trie public void insert(String word) { // Store the root Node trav = root; int i = 0; // Iterate i less than word // length while (i < word.length() && trav.edgeLabel[word.charAt(i) - CASE] != null) { // Find the index int index = word.charAt(i) - CASE, j = 0; StringBuilder label = trav.edgeLabel[index]; // Iterate till j is less // than label length while (j < label.length() && i < word.length() && label.charAt(j) == word.charAt(i)) { ++i; ++j; } // If is the same as the // label length if (j == label.length()) { trav = trav.children[index]; } else { // Inserting a prefix of // the existing word if (i == word.length()) { Node existingChild = trav.children[index]; Node newChild = new Node(true); StringBuilder remainingLabel = strCopy(label, j); // Making "facebook" // as "face" label.setLength(j); // New node for "face" trav.children[index] = newChild; newChild .children[remainingLabel.charAt(0) - CASE] = existingChild; newChild .edgeLabel[remainingLabel.charAt(0) - CASE] = remainingLabel; } else { // Inserting word which has // a partial match with // existing word StringBuilder remainingLabel = strCopy(label, j); Node newChild = new Node(false); StringBuilder remainingWord = strCopy(word, i); // Store the trav in // temp node Node temp = trav.children[index]; label.setLength(j); trav.children[index] = newChild; newChild .edgeLabel[remainingLabel.charAt(0) - CASE] = remainingLabel; newChild .children[remainingLabel.charAt(0) - CASE] = temp; newChild .edgeLabel[remainingWord.charAt(0) - CASE] = remainingWord; newChild .children[remainingWord.charAt(0) - CASE] = new Node(true); } return; } } // Insert new node for new word if (i < word.length()) { trav.edgeLabel[word.charAt(i) - CASE] = strCopy(word, i); trav.children[word.charAt(i) - CASE] = new Node(true); } else { // Insert "there" when "therein" // and "thereafter" are existing trav.isEnd = true; } } // Function that creates new String // from an existing string starting // from the given index private StringBuilder strCopy( CharSequence str, int index) { StringBuilder result = new StringBuilder(100); while (index != str.length()) { result.append(str.charAt(index++)); } return result; } // Function to print the Trie public void print() { printUtil(root, new StringBuilder()); } // Function to print the word // starting from the given node private void printUtil( Node node, StringBuilder str) { if (node.isEnd) { System.out.println(str); } for (int i = 0; i < node.edgeLabel.length; ++i) { // If edgeLabel is not // NULL if (node.edgeLabel[i] != null) { int length = str.length(); str = str.append(node.edgeLabel[i]); printUtil(node.children[i], str); str = str.delete(length, str.length()); } } } // Function to search a word public boolean search(String word) { int i = 0; // Stores the root Node trav = root; while (i < word.length() && trav.edgeLabel[word.charAt(i) - CASE] != null) { int index = word.charAt(i) - CASE; StringBuilder label = trav.edgeLabel[index]; int j = 0; while (i < word.length() && j < label.length()) { // Character mismatch if (word.charAt(i) != label.charAt(j)) { return false; } ++i; ++j; } if (j == label.length() && i <= word.length()) { // Traverse further trav = trav.children[index]; } else { // Edge label is larger // than target word // searching for "face" // when tree has "facebook" return false; } } // Target word fully traversed // and current node is word return i == word.length() && trav.isEnd; } // Function to search the prefix public boolean startsWith(String prefix) { int i = 0; // Stores the root Node trav = root; while (i < prefix.length() && trav.edgeLabel[prefix.charAt(i) - CASE] != null) { int index = prefix.charAt(i) - CASE; StringBuilder label = trav.edgeLabel[index]; int j = 0; while (i < prefix.length() && j < label.length()) { // Character mismatch if (prefix.charAt(i) != label.charAt(j)) { return false; } ++i; ++j; } if (j == label.length() && i <= prefix.length()) { // Traverse further trav = trav.children[index]; } else { // Edge label is larger // than target word, // which is fine return true; } } return i == prefix.length(); }} // Node classclass Node { // Number of symbols private final static int SYMBOLS = 26; Node[] children = new Node[SYMBOLS]; StringBuilder[] edgeLabel = new StringBuilder[SYMBOLS]; boolean isEnd; // Function to check if the end // of the string is reached public Node(boolean isEnd) { this.isEnd = isEnd; }} class GFG { // Driver Code public static void main(String[] args) { Trie trie = new Trie(); // Insert words trie.insert("facebook"); trie.insert("face"); trie.insert("this"); trie.insert("there"); trie.insert("then"); // Print inserted words trie.print(); // Check if these words // are present or not System.out.println( trie.search("there")); System.out.println( trie.search("therein")); System.out.println( trie.startsWith("th")); System.out.println( trie.startsWith("fab")); }}
# Java program to implement the# Compressed Trie class Trie: # Root Node root = Node(False) CASE='' # Default self.CASE def Trie(self, CASE='a') : self.CASE = CASE # Function to insert a word in # the compressed trie def insert(self,word): # Store the root trav = root i = 0 # Iterate i less than word # length while (i < word.length() and trav.edgeLabel[word.charAt(i) - self.CASE] is not None) : # Find the index index = ord(word[i]) - ord(self.CASE); j = 0 label = trav.edgeLabel[index] # Iterate till j is less # than label length while (j < len(label) and i < len(word) and label[j] == word[i]) : i+=1 j+=1 # If is the same as the # label length if (j == label.length()) : trav = trav.children[index] else : # Inserting a prefix of # the existing word if (i == word.length()) : existingChild = trav.children[index] newChild = Node(True) remainingLabel = strCopy(label, j) # Making "facebook" # as "face" label.setLength(j) # New node for "face" trav.children[index] = newChild newChild.children[ord(remainingLabel[0])-ord(self.CASE)] = existingChild newChild.edgeLabel[ord(remainingLabel.charAt(0))- ord(self.CASE)] = remainingLabel else : # Inserting word which has # a partial match with # existing word remainingLabel = strCopy(label, j) newChild = Node(False) remainingWord = strCopy(word, i) # Store the trav in # temp node temp = trav.children[index] trav.children[index] = newChild newChild.edgeLabel[ord(remainingLabel.charAt(0)) - ord(self.CASE)]=remainingLabel newChild.children[ord(remainingLabel.charAt(0)) - ord(self.CASE)]=temp newChild.edgeLabel[ord(remainingWord.charAt(0)) - ord(self.CASE)] = remainingWord newChild.children[ord(remainingWord.charAt(0)) - ord(self.CASE)] = Node(True) return # Insert new node for new word if (i < len(word)): trav.edgeLabel[ord(word.charAt(i)) - ord(self.CASE)] = strCopy(word, i) trav.children[ord(word.charAt(i)) - ord(self.CASE)] = Node(True) else : # Insert "there" when "therein" # and "thereafter" are existing trav.isEnd = True # Function that creates new String # from an existing string starting # from the given index def strCopy(self, str, index): result = '' while (index != len(str)) : result+=str.charAt(index) index+=1 return result # Function to print the word # starting from the given node def printUtil(self,node, str): if (node.isEnd) : print(str) for i in range(node.edgeLabel.length): # If edgeLabel is not # None if (node.edgeLabel[i] != None) : length = len(str) str = str.append(node.edgeLabel[i]) printUtil(node.children[i], str) str = str.delete(length, str.length()) # Function to search a word def search(self,word): i = 0 # Stores the root trav = root while (i < len(word) and trav.edgeLabel[ord(word.charAt(i)) - ord(self.CASE)] != None) : index = ord(word.charAt(i)) - ord(self.CASE) label = trav.edgeLabel[index] j = 0 while (i < word.length() and j < label.length()) : # Character mismatch if (word.charAt(i) != label.charAt(j)) : return False i+=1 j+=1 if (j == len(label) and i <= len(word)) : # Traverse further trav = trav.children[index] else : # Edge label is larger # than target word # searching for "face" # when tree has "facebook" return False # Target word fully traversed # and current node is word return i == len(word) and trav.isEnd # Function to search the prefix def startsWith(self,prefix): i = 0 # Stores the root trav = root while (i < prefix.length() and trav.edgeLabel[prefix.charAt(i) - self.CASE]is not None) : index = ord(prefix.charAt(i)) - ord(self.CASE) label = trav.edgeLabel[index] j = 0 while (i < prefix.length() and j < label.length()) : # Character mismatch if (prefix.charAt(i) != label.charAt(j)) : return False i+=1 j+=1 if (j == len(label) and j<= len(prefix)) : # Traverse further trav = trav.children[index] else : # Edge label is larger # than target word, # which is fine return True return i == prefix.length() # Node classclass Node : def __init__(self): # Number of symbols self.SYMBOLS = 26 self.children = [None]*26 self.edgeLabel = [None]*SYMBOLS self.isEnd=False # Function to check if the end # of the string is reached def Node(self,isEnd): self.isEnd = isEnd class GFG : # Driver Code if __name__ == '__main__': trie = Trie() # Insert words trie.insert("facebook") trie.insert("face") trie.insert("this") trie.insert("there") trie.insert("then") # Print inserted words trie.print() # Check if these words # are present or not print( trie.search("there")) print( trie.search("therein")) print( trie.startsWith("th")) print( trie.startsWith("fab"))
face
facebook
then
there
this
true
false
true
false
bunnyram19
sagartomar9927
amartyaghoshgfg
Picked
Technical Scripter 2020
Trie
Advanced Data Structure
Data Structures
Technical Scripter
Tree
Data Structures
Tree
Trie
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Proof that Dominant Set of a Graph is NP-Complete
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Cartesian Tree
Advantages of Trie Data Structure
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 24406,
"s": 24378,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 24646,
"s": 24406,
"text": "A trie is a data structure that stores strings like a tree data structure. The maximum number of children in a node is equal to the size of the alphabet. One can easily print letters in alphabetical order which isn’t possible with hashing."
},
{
"code": null,
"e": 24666,
"s": 24646,
"text": "Properties of Trie:"
},
{
"code": null,
"e": 24689,
"s": 24666,
"text": "It’s a multi-way tree."
},
{
"code": null,
"e": 24725,
"s": 24689,
"text": "Each node has from 1 to N children."
},
{
"code": null,
"e": 24842,
"s": 24725,
"text": "Each leaf node corresponds to the stored string, which is a chain of characters on a path from the root to its side."
},
{
"code": null,
"e": 24857,
"s": 24842,
"text": "Types of Trie:"
},
{
"code": null,
"e": 24871,
"s": 24857,
"text": "Standard Trie"
},
{
"code": null,
"e": 24883,
"s": 24871,
"text": "Suffix Trie"
},
{
"code": null,
"e": 24899,
"s": 24883,
"text": "Compressed Trie"
},
{
"code": null,
"e": 24916,
"s": 24899,
"text": "Compressed Trie:"
},
{
"code": null,
"e": 25095,
"s": 24916,
"text": "Tries with nodes of degree at least 2. It is accomplished by compressing the nodes of the standard trie. It is also known as Radix Tries. It is used to achieve space optimization"
},
{
"code": null,
"e": 25545,
"s": 25095,
"text": "Since the nodes are compressed. Let’s visually compare the structure of the Standard tree and the compressed tree for a better approach. In terms of memory, a compressed trie tree uses very few amounts of nodes which gives a huge memory advantage(especially for long) strings with long common prefixes. In terms of speed, a regular trie tree would be slightly faster because its operations don’t involve any string operations, they are simple loops."
},
{
"code": null,
"e": 25636,
"s": 25545,
"text": "In the below image, the left tree is a Standard trie, the right tree is a compressed trie."
},
{
"code": null,
"e": 25652,
"s": 25636,
"text": "Implementation:"
},
{
"code": null,
"e": 25690,
"s": 25652,
"text": "A standard trie node looks like this:"
},
{
"code": null,
"e": 25695,
"s": 25690,
"text": "Java"
},
{
"code": null,
"e": 25703,
"s": 25695,
"text": "Python3"
},
{
"code": "class node { node[] children = new node[26]; boolean isWordEnd;}",
"e": 25774,
"s": 25703,
"text": null
},
{
"code": "class node: def __init__(self): self.node = [None]*26 self.isWordEnd=False",
"e": 25858,
"s": 25774,
"text": null
},
{
"code": null,
"e": 26156,
"s": 25861,
"text": "But for a compressed trie, redesigning of the tree will be as follows, in the general trie, an edge ‘a’ is denoted by this particular element in the array of references, but in the compressed trie, “An edge ‘face’ is denoted by this particular element in the array of references”. The code is-:"
},
{
"code": null,
"e": 26163,
"s": 26158,
"text": "Java"
},
{
"code": null,
"e": 26171,
"s": 26163,
"text": "Python3"
},
{
"code": "class node { node[] children = new node[26]; StringBuilder[] edgeLabel = new StringBuilder[26]; boolean isEnd;}",
"e": 26292,
"s": 26171,
"text": null
},
{
"code": "class node: def __init__(self): self.children = [None]*26 sefl.edgeLabel = [None]*26 self.isEnd=False",
"e": 26412,
"s": 26292,
"text": null
},
{
"code": null,
"e": 26440,
"s": 26415,
"text": "Node in Compressed Trie:"
},
{
"code": null,
"e": 26447,
"s": 26442,
"text": "Java"
},
{
"code": null,
"e": 26455,
"s": 26447,
"text": "Python3"
},
{
"code": "class CompressedNode { int bitNumber; int data; CompressedNode leftChild, rightChild;}",
"e": 26551,
"s": 26455,
"text": null
},
{
"code": "class node: def __init__(self): self.bitNumber=0 self.data=None self.leftChild, self.rightChild=None,None",
"e": 26675,
"s": 26551,
"text": null
},
{
"code": null,
"e": 26701,
"s": 26678,
"text": "Class Compressed trie:"
},
{
"code": null,
"e": 26708,
"s": 26703,
"text": "Java"
},
{
"code": null,
"e": 26716,
"s": 26708,
"text": "Python3"
},
{
"code": "class CompressedNode { // Root Node private CompressedNode root; private static final int MaxBits = 10; // Constructor public CompressedNode() { root = null; } // Function to check if empty public boolean isEmpty() { return root == null; } // Function to clear public void makeEmpty() { root = null; }}",
"e": 27051,
"s": 26716,
"text": null
},
{
"code": "class CompressedNode { #Root Node root=CompressedNode() MaxBits = 10 #Constructor def __init__(self): self.root = None #Function to check if empty def isEmpty(self): return self.root == None #Function to clear def makeEmpty(self): self.root = None",
"e": 27361,
"s": 27051,
"text": null
},
{
"code": null,
"e": 27394,
"s": 27364,
"text": "Searching in Compressed Trie:"
},
{
"code": null,
"e": 27524,
"s": 27396,
"text": "Searching in a compressed Trie tree is much like searching. Here, instead of comparing a single character, we compare strings. "
},
{
"code": null,
"e": 27531,
"s": 27526,
"text": "Java"
},
{
"code": null,
"e": 27539,
"s": 27531,
"text": "Python3"
},
{
"code": "// Function to search a key k// in the triepublic boolean search(int k){ // Find the number of bits int numOfBits = (int)(Math.log(k) / Math.log(2)) + 1; // If error occurs if (numOfBits > MaxBits) { System.out.println(\"Error : Number too large\"); return false; } // Search Node CompressedNode searchNode = search(root, k); // If the data matches if (searchNode.data == k) return true; // Else return false else return false;}",
"e": 28031,
"s": 27539,
"text": null
},
{
"code": "# Function to search a key k# in the trieimport mathdef search(k): # Find the number of bits numOfBits = int(math.log2(k)) + 1 # If error occurs if (numOfBits > MaxBits) : print(\"Error : Number too large\") return False # Search Node searchNode = search(root, k) # If the data matches if (searchNode.data == k): return True # Else return false else: return False",
"e": 28461,
"s": 28031,
"text": null
},
{
"code": null,
"e": 28505,
"s": 28464,
"text": "Inserting an element in Compressed Trie:"
},
{
"code": null,
"e": 28512,
"s": 28507,
"text": "Java"
},
{
"code": null,
"e": 28520,
"s": 28512,
"text": "Python3"
},
{
"code": "// Function to implement the insert// functionality in the trieprivate CompressedNode insert( CompressedNode t, int ele){ CompressedNode current, parent; CompressedNode lastNode, newNode; int i; // If Node is NULL if (t == null) { t = new CompressedNode(); t.bitNumber = 0; t.data = ele; t.leftChild = t; t.rightChild = null; return t; } // Search the key ele lastNode = search(t, ele); // If already present key if (ele == lastNode.data) { System.out.println( \"Error : key is already present\\n\"); return t; } for (i = 1; bit(ele, i) == bit(lastNode.data, i); i++) ; current = t.leftChild; parent = t; while (current.bitNumber > parent.bitNumber && current.bitNumber < i) { parent = current; current = (bit(ele, current.bitNumber)) ? current.rightChild : current.leftChild; } newNode = new CompressedNode(); newNode.bitNumber = i; newNode.data = ele; newNode.leftChild = bit(ele, i) ? current : newNode; newNode.rightChild = bit(ele, i) ? newNode : current; if (current == parent.leftChild) parent.leftChild = newNode; else parent.rightChild = newNode; return t;}",
"e": 29821,
"s": 28520,
"text": null
},
{
"code": "# Function to implement the insert# functionality in the triedef insert( t, ele): # If Node is None if (t == None) : t = CompressedNode() t.bitNumber = 0 t.data = ele t.leftChild = t t.rightChild = None return t # Search the key ele lastNode = search(t, ele) # If already present key if (ele == lastNode.data) : print( \"Error : key is already present\") return t i=1 while(bit(ele, i) == bit(lastNode.data, i)): i+=1 current = t.leftChild parent = t while (current.bitNumber > parent.bitNumber and current.bitNumber < i) : parent = current current = current.rightChild if (bit(ele, current.bitNumber)) else current.leftChild newNode = CompressedNode() newNode.bitNumber = i newNode.data = ele newNode.leftChild = current if bit(ele, i) else newNode newNode.rightChild = newNode if bit(ele, i) else current if (current == parent.leftChild): parent.leftChild = newNode else: parent.rightChild = newNode return t",
"e": 30914,
"s": 29821,
"text": null
},
{
"code": null,
"e": 30993,
"s": 30917,
"text": "Below is the program to implement all functionality of the compressed Trie:"
},
{
"code": null,
"e": 31000,
"s": 30995,
"text": "Java"
},
{
"code": null,
"e": 31008,
"s": 31000,
"text": "Python3"
},
{
"code": "// Java program to implement the// Compressed Trie class Trie { // Root Node private final Node root = new Node(false); // 'a' for lower, 'A' for upper private final char CASE; // Default case public Trie() { CASE = 'a'; } // Constructor accepting the // starting symbol public Trie(char CASE) { this.CASE = CASE; } // Function to insert a word in // the compressed trie public void insert(String word) { // Store the root Node trav = root; int i = 0; // Iterate i less than word // length while (i < word.length() && trav.edgeLabel[word.charAt(i) - CASE] != null) { // Find the index int index = word.charAt(i) - CASE, j = 0; StringBuilder label = trav.edgeLabel[index]; // Iterate till j is less // than label length while (j < label.length() && i < word.length() && label.charAt(j) == word.charAt(i)) { ++i; ++j; } // If is the same as the // label length if (j == label.length()) { trav = trav.children[index]; } else { // Inserting a prefix of // the existing word if (i == word.length()) { Node existingChild = trav.children[index]; Node newChild = new Node(true); StringBuilder remainingLabel = strCopy(label, j); // Making \"facebook\" // as \"face\" label.setLength(j); // New node for \"face\" trav.children[index] = newChild; newChild .children[remainingLabel.charAt(0) - CASE] = existingChild; newChild .edgeLabel[remainingLabel.charAt(0) - CASE] = remainingLabel; } else { // Inserting word which has // a partial match with // existing word StringBuilder remainingLabel = strCopy(label, j); Node newChild = new Node(false); StringBuilder remainingWord = strCopy(word, i); // Store the trav in // temp node Node temp = trav.children[index]; label.setLength(j); trav.children[index] = newChild; newChild .edgeLabel[remainingLabel.charAt(0) - CASE] = remainingLabel; newChild .children[remainingLabel.charAt(0) - CASE] = temp; newChild .edgeLabel[remainingWord.charAt(0) - CASE] = remainingWord; newChild .children[remainingWord.charAt(0) - CASE] = new Node(true); } return; } } // Insert new node for new word if (i < word.length()) { trav.edgeLabel[word.charAt(i) - CASE] = strCopy(word, i); trav.children[word.charAt(i) - CASE] = new Node(true); } else { // Insert \"there\" when \"therein\" // and \"thereafter\" are existing trav.isEnd = true; } } // Function that creates new String // from an existing string starting // from the given index private StringBuilder strCopy( CharSequence str, int index) { StringBuilder result = new StringBuilder(100); while (index != str.length()) { result.append(str.charAt(index++)); } return result; } // Function to print the Trie public void print() { printUtil(root, new StringBuilder()); } // Function to print the word // starting from the given node private void printUtil( Node node, StringBuilder str) { if (node.isEnd) { System.out.println(str); } for (int i = 0; i < node.edgeLabel.length; ++i) { // If edgeLabel is not // NULL if (node.edgeLabel[i] != null) { int length = str.length(); str = str.append(node.edgeLabel[i]); printUtil(node.children[i], str); str = str.delete(length, str.length()); } } } // Function to search a word public boolean search(String word) { int i = 0; // Stores the root Node trav = root; while (i < word.length() && trav.edgeLabel[word.charAt(i) - CASE] != null) { int index = word.charAt(i) - CASE; StringBuilder label = trav.edgeLabel[index]; int j = 0; while (i < word.length() && j < label.length()) { // Character mismatch if (word.charAt(i) != label.charAt(j)) { return false; } ++i; ++j; } if (j == label.length() && i <= word.length()) { // Traverse further trav = trav.children[index]; } else { // Edge label is larger // than target word // searching for \"face\" // when tree has \"facebook\" return false; } } // Target word fully traversed // and current node is word return i == word.length() && trav.isEnd; } // Function to search the prefix public boolean startsWith(String prefix) { int i = 0; // Stores the root Node trav = root; while (i < prefix.length() && trav.edgeLabel[prefix.charAt(i) - CASE] != null) { int index = prefix.charAt(i) - CASE; StringBuilder label = trav.edgeLabel[index]; int j = 0; while (i < prefix.length() && j < label.length()) { // Character mismatch if (prefix.charAt(i) != label.charAt(j)) { return false; } ++i; ++j; } if (j == label.length() && i <= prefix.length()) { // Traverse further trav = trav.children[index]; } else { // Edge label is larger // than target word, // which is fine return true; } } return i == prefix.length(); }} // Node classclass Node { // Number of symbols private final static int SYMBOLS = 26; Node[] children = new Node[SYMBOLS]; StringBuilder[] edgeLabel = new StringBuilder[SYMBOLS]; boolean isEnd; // Function to check if the end // of the string is reached public Node(boolean isEnd) { this.isEnd = isEnd; }} class GFG { // Driver Code public static void main(String[] args) { Trie trie = new Trie(); // Insert words trie.insert(\"facebook\"); trie.insert(\"face\"); trie.insert(\"this\"); trie.insert(\"there\"); trie.insert(\"then\"); // Print inserted words trie.print(); // Check if these words // are present or not System.out.println( trie.search(\"there\")); System.out.println( trie.search(\"therein\")); System.out.println( trie.startsWith(\"th\")); System.out.println( trie.startsWith(\"fab\")); }}",
"e": 39222,
"s": 31008,
"text": null
},
{
"code": "# Java program to implement the# Compressed Trie class Trie: # Root Node root = Node(False) CASE='' # Default self.CASE def Trie(self, CASE='a') : self.CASE = CASE # Function to insert a word in # the compressed trie def insert(self,word): # Store the root trav = root i = 0 # Iterate i less than word # length while (i < word.length() and trav.edgeLabel[word.charAt(i) - self.CASE] is not None) : # Find the index index = ord(word[i]) - ord(self.CASE); j = 0 label = trav.edgeLabel[index] # Iterate till j is less # than label length while (j < len(label) and i < len(word) and label[j] == word[i]) : i+=1 j+=1 # If is the same as the # label length if (j == label.length()) : trav = trav.children[index] else : # Inserting a prefix of # the existing word if (i == word.length()) : existingChild = trav.children[index] newChild = Node(True) remainingLabel = strCopy(label, j) # Making \"facebook\" # as \"face\" label.setLength(j) # New node for \"face\" trav.children[index] = newChild newChild.children[ord(remainingLabel[0])-ord(self.CASE)] = existingChild newChild.edgeLabel[ord(remainingLabel.charAt(0))- ord(self.CASE)] = remainingLabel else : # Inserting word which has # a partial match with # existing word remainingLabel = strCopy(label, j) newChild = Node(False) remainingWord = strCopy(word, i) # Store the trav in # temp node temp = trav.children[index] trav.children[index] = newChild newChild.edgeLabel[ord(remainingLabel.charAt(0)) - ord(self.CASE)]=remainingLabel newChild.children[ord(remainingLabel.charAt(0)) - ord(self.CASE)]=temp newChild.edgeLabel[ord(remainingWord.charAt(0)) - ord(self.CASE)] = remainingWord newChild.children[ord(remainingWord.charAt(0)) - ord(self.CASE)] = Node(True) return # Insert new node for new word if (i < len(word)): trav.edgeLabel[ord(word.charAt(i)) - ord(self.CASE)] = strCopy(word, i) trav.children[ord(word.charAt(i)) - ord(self.CASE)] = Node(True) else : # Insert \"there\" when \"therein\" # and \"thereafter\" are existing trav.isEnd = True # Function that creates new String # from an existing string starting # from the given index def strCopy(self, str, index): result = '' while (index != len(str)) : result+=str.charAt(index) index+=1 return result # Function to print the word # starting from the given node def printUtil(self,node, str): if (node.isEnd) : print(str) for i in range(node.edgeLabel.length): # If edgeLabel is not # None if (node.edgeLabel[i] != None) : length = len(str) str = str.append(node.edgeLabel[i]) printUtil(node.children[i], str) str = str.delete(length, str.length()) # Function to search a word def search(self,word): i = 0 # Stores the root trav = root while (i < len(word) and trav.edgeLabel[ord(word.charAt(i)) - ord(self.CASE)] != None) : index = ord(word.charAt(i)) - ord(self.CASE) label = trav.edgeLabel[index] j = 0 while (i < word.length() and j < label.length()) : # Character mismatch if (word.charAt(i) != label.charAt(j)) : return False i+=1 j+=1 if (j == len(label) and i <= len(word)) : # Traverse further trav = trav.children[index] else : # Edge label is larger # than target word # searching for \"face\" # when tree has \"facebook\" return False # Target word fully traversed # and current node is word return i == len(word) and trav.isEnd # Function to search the prefix def startsWith(self,prefix): i = 0 # Stores the root trav = root while (i < prefix.length() and trav.edgeLabel[prefix.charAt(i) - self.CASE]is not None) : index = ord(prefix.charAt(i)) - ord(self.CASE) label = trav.edgeLabel[index] j = 0 while (i < prefix.length() and j < label.length()) : # Character mismatch if (prefix.charAt(i) != label.charAt(j)) : return False i+=1 j+=1 if (j == len(label) and j<= len(prefix)) : # Traverse further trav = trav.children[index] else : # Edge label is larger # than target word, # which is fine return True return i == prefix.length() # Node classclass Node : def __init__(self): # Number of symbols self.SYMBOLS = 26 self.children = [None]*26 self.edgeLabel = [None]*SYMBOLS self.isEnd=False # Function to check if the end # of the string is reached def Node(self,isEnd): self.isEnd = isEnd class GFG : # Driver Code if __name__ == '__main__': trie = Trie() # Insert words trie.insert(\"facebook\") trie.insert(\"face\") trie.insert(\"this\") trie.insert(\"there\") trie.insert(\"then\") # Print inserted words trie.print() # Check if these words # are present or not print( trie.search(\"there\")) print( trie.search(\"therein\")) print( trie.startsWith(\"th\")) print( trie.startsWith(\"fab\"))",
"e": 45872,
"s": 39222,
"text": null
},
{
"code": null,
"e": 45927,
"s": 45875,
"text": "face\nfacebook\nthen\nthere\nthis\ntrue\nfalse\ntrue\nfalse"
},
{
"code": null,
"e": 45942,
"s": 45931,
"text": "bunnyram19"
},
{
"code": null,
"e": 45957,
"s": 45942,
"text": "sagartomar9927"
},
{
"code": null,
"e": 45973,
"s": 45957,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 45980,
"s": 45973,
"text": "Picked"
},
{
"code": null,
"e": 46004,
"s": 45980,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 46009,
"s": 46004,
"text": "Trie"
},
{
"code": null,
"e": 46033,
"s": 46009,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 46049,
"s": 46033,
"text": "Data Structures"
},
{
"code": null,
"e": 46068,
"s": 46049,
"text": "Technical Scripter"
},
{
"code": null,
"e": 46073,
"s": 46068,
"text": "Tree"
},
{
"code": null,
"e": 46089,
"s": 46073,
"text": "Data Structures"
},
{
"code": null,
"e": 46094,
"s": 46089,
"text": "Tree"
},
{
"code": null,
"e": 46099,
"s": 46094,
"text": "Trie"
},
{
"code": null,
"e": 46197,
"s": 46099,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46206,
"s": 46197,
"text": "Comments"
},
{
"code": null,
"e": 46219,
"s": 46206,
"text": "Old Comments"
},
{
"code": null,
"e": 46269,
"s": 46219,
"text": "Proof that Dominant Set of a Graph is NP-Complete"
},
{
"code": null,
"e": 46311,
"s": 46269,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 46357,
"s": 46311,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 46372,
"s": 46357,
"text": "Cartesian Tree"
},
{
"code": null,
"e": 46406,
"s": 46372,
"text": "Advantages of Trie Data Structure"
},
{
"code": null,
"e": 46455,
"s": 46406,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 46499,
"s": 46455,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 46524,
"s": 46499,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 46580,
"s": 46524,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
How data compression works: exploring LZ77 | by Dhanesh Budhrani | Towards Data Science | In this post we are going to explore LZ77, a lossless data-compression algorithm created by Lempel and Ziv in 1977. This algorithm is widely spread in our current systems since, for instance, ZIP and GZIP are based on LZ77.
LZ77 iterates sequentially through the input string and stores any new match into a search buffer. The process of compression can be divided in 3 steps:
Find the longest match of a string that starts at the current position with a pattern available in the search buffer.Output a triple (o, l, c) where,
Find the longest match of a string that starts at the current position with a pattern available in the search buffer.
Output a triple (o, l, c) where,
o: offset, represents the number of positions that we would need to move backwards in order to find the start of the matching string.
l: length, represents the length of the match.
c: character, represents the character that is found after the match.
Move the cursor l+1 positions to the right.
Move the cursor l+1 positions to the right.
Let’s get a deeper insight with an example:
a b a b c b a b a b a a
Initially, our search buffer is empty and we start from the left, where we find an ‘a’. Given that there are not any matching patterns in our search buffer, we output the triple (0, 0, a), since we are not moving backwards (o = 0) and there is not a matching pattern in the search buffer (hence “matching” an empty string: l = 0). After this (non-)match, we find the character ‘a’, so c = a. We move l+1 positions to the right and find ourselves in the second position. We’ll be indicating the position of the cursor using the square brackets [].
a [b] a b c b a b a b a aLZ77 encoding: (0,0,a)
So far, we do not have any pattern in our search buffer that starts with ‘b’. Therefore, the encoding process is similar to the previous step: (0,0,b). At this point, things start to get interesting:
a b [a] b c b a b a b a aLZ77 encoding: (0,0,a), (0,0,b)
We’ve previously found an ‘a’ and even ‘ab’, but not ‘abc’ so we need to move 2 positions to the left (o = 2) and read 2 characters (l = 2). The next character that we can find is a ‘c’, therefore the output triple would be (2,2,c). We move our cursor l+1 positions to the right and find ourselves in the character ‘b’.
a b a b c [b] a b a b a aLZ77 encoding: (0,0,a), (0,0,b), (2,2,c)
We’ve already found a ‘b’, even ‘ba’ and even ‘bab’ but not ‘baba’, so we’ll be moving 4 positions to the left (o = 4) and read 3 characters (l = 3). The next character that we can find is an ‘a’, and hence the output triple would be (4,3,a). We move our cursor l+1 positions to the right and find ourselves in the character ‘b’.
a b a b c b a b a [b] a aLZ77 encoding: (0,0,a), (0,0,b), (2,2,c), (4,3,a)
We’re almost done! We’ve already seen a ‘b’ and a ba’, but not a ‘baa’. We need to move 2 positions to the left (o = 2) and read 2 characters (l = 2). After this match, we find an ‘a’, so the last output triple would be (2,2,a).
a b a b c b a b a b a aLZ77 encoding: (0,0,a), (0,0,b), (2,2,c), (4,3,a), (2,2,a)
You may have noticed that the time complexity in the compression phase does not seem to be too good considering that, in the worst case, we need to go back to the beginning of the input string to find a matching pattern (if any). This means that, in a 0-index position p, we need to move p positions to the left in the worst case. Thinking of an edge case in which every character of the string is different (and hence we do not take advantage of data compression), we would need to process 0 characters for the first position + 1 for the second + 2 for the third... + n-1 for the last position = n(n-1) / 2 = O(n2) time complexity. This is one of the reasons why it is common to predefine a limit on the size of the search buffer, allowing us to reuse the content of up to, for instance, 6 positions to the left of the cursor. The following example may help you illustrate this concept, where the parentheses indicate the content inside the search buffer.
a b a b c (b a b a b a) [c] b a a a
In this case, we would not find the ‘c’ in the search buffer and, hence, the output triple would be (0,0,c) instead of (7,3,a). However, we would not have to potentially pay the price in every processed character to find a match, in the worst case, at the beginning of the string. All in all, selecting the size of the search buffer becomes a tradeoff between the compression time and the required memory: a small search buffer will generally allow us to complete the compression phase faster, but the resulting encoding will require more memory; on the opposite side, a large search buffer will generally take longer to compress our data, but it will be more effective in terms of memory usage.
It is also common to limit the size of the lookahead buffer, which is the substring that starts at the cursor. Let’s illustrate this concept with an example, where the lookahead buffer is represented between two * symbols.
a b a b c (b a b a c a) *[b] a b a* c a a
In this case, we have a search buffer of size 6 and a lookahead buffer of size 4. Given that the content of our lookahead buffer is ‘baba’ and it is contained in the search buffer, the LZ77 encoding at this position would be (6,4,c). Note that, in this example, if our lookahead buffer was bigger, the output triple in this position would be different. For instance, if our lookahead buffer also had a size of 6 it would contain the string ‘babaca’, which is fully contained in the search buffer and, hence, the output triple would be (6,6,a).
It is worth mentioning that this algorithm is also known as the “sliding windows” algorithm, given that both the search buffer and the lookahead buffer get updated as the cursor “slides” through the input text.
Let’s see how LZ77 uses its encoded form to reproduce the original string. LZ77 is categorized as a lossless data-compression algorithm, which means that we should be able to fully recover the original string. It is also worth mentioning that, in the case of LZ77, we cannot start decompressing from a random LZ77 triple: instead, we need to start decompressing from the initial triple. The reason is, simply, that the encoded triples are based on the search buffer.
In order to illustrate the decompression process, let’s attempt to decompress the obtained encoding in the previous section, aiming to obtain the original string. Therefore, our encoding in this example would be the following:
(0,0,a), (0,0,b), (2,2,c), (4,3,a), (2,2,a)
Starting with (0,0,a), we need to move o = 0 positions to the left and read l = 0 characters (that is just an empty string). After that, write c = ‘a’. Hence, the decompressed value of this triple is ‘a’. At this point, our decompression string looks like this:
Current string: aRemaining LZ77 encoding: (0,0,b), (2,2,c), (4,3,a), (2,2,a)
The next triple that we find is (0,0,b) which means the following: move o = 0 positions to the left and read l = 0 characters (empty string). After that, write c = ‘b’. Hence, the decompressed value of this triple is ‘b’. Our decompression string now looks like this:
Current string: a bRemaining LZ77 encoding: (2,2,c), (4,3,a), (2,2,a)
The next triple that we find is (2,2,c), which is a bit more interesting. Now it means the following: move o = 2 positions to the left and read l = 2 characters (‘ab’). After that, write c = ‘c’. Hence, the decompressed value of this triple is ‘abc’. Our decompression string now looks like this:
Current string: a b a b cRemaining LZ77 encoding: (4,3,a), (2,2,a)
The next triple that we find is (4,3,a), which means the following: move o = 4 positions to the left and read l = 3 characters (‘bab’). After that, write c = ‘a’. Hence, the decompressed value of this triple is ‘baba’. Our decompression string now looks like this:
Current string: a b a b c b a b aRemaining LZ77 encoding: (2,2,a)
The last triple that we find is (2,2,a), which means the following: move o = 2 positions to the left and read l = 2 characters (‘ba’). After that, write c = ‘a’. Hence, the decompressed value of this triple is ‘baa’. Our decompression string now looks like this:
Fully decompressed string: a b a b c b a b a b a a
If you check the original to-be-compressed string in the previous section, you will see that they are the same! | [
{
"code": null,
"e": 396,
"s": 172,
"text": "In this post we are going to explore LZ77, a lossless data-compression algorithm created by Lempel and Ziv in 1977. This algorithm is widely spread in our current systems since, for instance, ZIP and GZIP are based on LZ77."
},
{
"code": null,
"e": 549,
"s": 396,
"text": "LZ77 iterates sequentially through the input string and stores any new match into a search buffer. The process of compression can be divided in 3 steps:"
},
{
"code": null,
"e": 699,
"s": 549,
"text": "Find the longest match of a string that starts at the current position with a pattern available in the search buffer.Output a triple (o, l, c) where,"
},
{
"code": null,
"e": 817,
"s": 699,
"text": "Find the longest match of a string that starts at the current position with a pattern available in the search buffer."
},
{
"code": null,
"e": 850,
"s": 817,
"text": "Output a triple (o, l, c) where,"
},
{
"code": null,
"e": 984,
"s": 850,
"text": "o: offset, represents the number of positions that we would need to move backwards in order to find the start of the matching string."
},
{
"code": null,
"e": 1031,
"s": 984,
"text": "l: length, represents the length of the match."
},
{
"code": null,
"e": 1101,
"s": 1031,
"text": "c: character, represents the character that is found after the match."
},
{
"code": null,
"e": 1145,
"s": 1101,
"text": "Move the cursor l+1 positions to the right."
},
{
"code": null,
"e": 1189,
"s": 1145,
"text": "Move the cursor l+1 positions to the right."
},
{
"code": null,
"e": 1233,
"s": 1189,
"text": "Let’s get a deeper insight with an example:"
},
{
"code": null,
"e": 1257,
"s": 1233,
"text": "a b a b c b a b a b a a"
},
{
"code": null,
"e": 1804,
"s": 1257,
"text": "Initially, our search buffer is empty and we start from the left, where we find an ‘a’. Given that there are not any matching patterns in our search buffer, we output the triple (0, 0, a), since we are not moving backwards (o = 0) and there is not a matching pattern in the search buffer (hence “matching” an empty string: l = 0). After this (non-)match, we find the character ‘a’, so c = a. We move l+1 positions to the right and find ourselves in the second position. We’ll be indicating the position of the cursor using the square brackets []."
},
{
"code": null,
"e": 1852,
"s": 1804,
"text": "a [b] a b c b a b a b a aLZ77 encoding: (0,0,a)"
},
{
"code": null,
"e": 2052,
"s": 1852,
"text": "So far, we do not have any pattern in our search buffer that starts with ‘b’. Therefore, the encoding process is similar to the previous step: (0,0,b). At this point, things start to get interesting:"
},
{
"code": null,
"e": 2109,
"s": 2052,
"text": "a b [a] b c b a b a b a aLZ77 encoding: (0,0,a), (0,0,b)"
},
{
"code": null,
"e": 2429,
"s": 2109,
"text": "We’ve previously found an ‘a’ and even ‘ab’, but not ‘abc’ so we need to move 2 positions to the left (o = 2) and read 2 characters (l = 2). The next character that we can find is a ‘c’, therefore the output triple would be (2,2,c). We move our cursor l+1 positions to the right and find ourselves in the character ‘b’."
},
{
"code": null,
"e": 2495,
"s": 2429,
"text": "a b a b c [b] a b a b a aLZ77 encoding: (0,0,a), (0,0,b), (2,2,c)"
},
{
"code": null,
"e": 2825,
"s": 2495,
"text": "We’ve already found a ‘b’, even ‘ba’ and even ‘bab’ but not ‘baba’, so we’ll be moving 4 positions to the left (o = 4) and read 3 characters (l = 3). The next character that we can find is an ‘a’, and hence the output triple would be (4,3,a). We move our cursor l+1 positions to the right and find ourselves in the character ‘b’."
},
{
"code": null,
"e": 2901,
"s": 2825,
"text": "a b a b c b a b a [b] a aLZ77 encoding: (0,0,a), (0,0,b), (2,2,c), (4,3,a)"
},
{
"code": null,
"e": 3130,
"s": 2901,
"text": "We’re almost done! We’ve already seen a ‘b’ and a ba’, but not a ‘baa’. We need to move 2 positions to the left (o = 2) and read 2 characters (l = 2). After this match, we find an ‘a’, so the last output triple would be (2,2,a)."
},
{
"code": null,
"e": 3212,
"s": 3130,
"text": "a b a b c b a b a b a aLZ77 encoding: (0,0,a), (0,0,b), (2,2,c), (4,3,a), (2,2,a)"
},
{
"code": null,
"e": 4169,
"s": 3212,
"text": "You may have noticed that the time complexity in the compression phase does not seem to be too good considering that, in the worst case, we need to go back to the beginning of the input string to find a matching pattern (if any). This means that, in a 0-index position p, we need to move p positions to the left in the worst case. Thinking of an edge case in which every character of the string is different (and hence we do not take advantage of data compression), we would need to process 0 characters for the first position + 1 for the second + 2 for the third... + n-1 for the last position = n(n-1) / 2 = O(n2) time complexity. This is one of the reasons why it is common to predefine a limit on the size of the search buffer, allowing us to reuse the content of up to, for instance, 6 positions to the left of the cursor. The following example may help you illustrate this concept, where the parentheses indicate the content inside the search buffer."
},
{
"code": null,
"e": 4205,
"s": 4169,
"text": "a b a b c (b a b a b a) [c] b a a a"
},
{
"code": null,
"e": 4901,
"s": 4205,
"text": "In this case, we would not find the ‘c’ in the search buffer and, hence, the output triple would be (0,0,c) instead of (7,3,a). However, we would not have to potentially pay the price in every processed character to find a match, in the worst case, at the beginning of the string. All in all, selecting the size of the search buffer becomes a tradeoff between the compression time and the required memory: a small search buffer will generally allow us to complete the compression phase faster, but the resulting encoding will require more memory; on the opposite side, a large search buffer will generally take longer to compress our data, but it will be more effective in terms of memory usage."
},
{
"code": null,
"e": 5124,
"s": 4901,
"text": "It is also common to limit the size of the lookahead buffer, which is the substring that starts at the cursor. Let’s illustrate this concept with an example, where the lookahead buffer is represented between two * symbols."
},
{
"code": null,
"e": 5166,
"s": 5124,
"text": "a b a b c (b a b a c a) *[b] a b a* c a a"
},
{
"code": null,
"e": 5710,
"s": 5166,
"text": "In this case, we have a search buffer of size 6 and a lookahead buffer of size 4. Given that the content of our lookahead buffer is ‘baba’ and it is contained in the search buffer, the LZ77 encoding at this position would be (6,4,c). Note that, in this example, if our lookahead buffer was bigger, the output triple in this position would be different. For instance, if our lookahead buffer also had a size of 6 it would contain the string ‘babaca’, which is fully contained in the search buffer and, hence, the output triple would be (6,6,a)."
},
{
"code": null,
"e": 5921,
"s": 5710,
"text": "It is worth mentioning that this algorithm is also known as the “sliding windows” algorithm, given that both the search buffer and the lookahead buffer get updated as the cursor “slides” through the input text."
},
{
"code": null,
"e": 6388,
"s": 5921,
"text": "Let’s see how LZ77 uses its encoded form to reproduce the original string. LZ77 is categorized as a lossless data-compression algorithm, which means that we should be able to fully recover the original string. It is also worth mentioning that, in the case of LZ77, we cannot start decompressing from a random LZ77 triple: instead, we need to start decompressing from the initial triple. The reason is, simply, that the encoded triples are based on the search buffer."
},
{
"code": null,
"e": 6615,
"s": 6388,
"text": "In order to illustrate the decompression process, let’s attempt to decompress the obtained encoding in the previous section, aiming to obtain the original string. Therefore, our encoding in this example would be the following:"
},
{
"code": null,
"e": 6659,
"s": 6615,
"text": "(0,0,a), (0,0,b), (2,2,c), (4,3,a), (2,2,a)"
},
{
"code": null,
"e": 6921,
"s": 6659,
"text": "Starting with (0,0,a), we need to move o = 0 positions to the left and read l = 0 characters (that is just an empty string). After that, write c = ‘a’. Hence, the decompressed value of this triple is ‘a’. At this point, our decompression string looks like this:"
},
{
"code": null,
"e": 6998,
"s": 6921,
"text": "Current string: aRemaining LZ77 encoding: (0,0,b), (2,2,c), (4,3,a), (2,2,a)"
},
{
"code": null,
"e": 7266,
"s": 6998,
"text": "The next triple that we find is (0,0,b) which means the following: move o = 0 positions to the left and read l = 0 characters (empty string). After that, write c = ‘b’. Hence, the decompressed value of this triple is ‘b’. Our decompression string now looks like this:"
},
{
"code": null,
"e": 7336,
"s": 7266,
"text": "Current string: a bRemaining LZ77 encoding: (2,2,c), (4,3,a), (2,2,a)"
},
{
"code": null,
"e": 7633,
"s": 7336,
"text": "The next triple that we find is (2,2,c), which is a bit more interesting. Now it means the following: move o = 2 positions to the left and read l = 2 characters (‘ab’). After that, write c = ‘c’. Hence, the decompressed value of this triple is ‘abc’. Our decompression string now looks like this:"
},
{
"code": null,
"e": 7700,
"s": 7633,
"text": "Current string: a b a b cRemaining LZ77 encoding: (4,3,a), (2,2,a)"
},
{
"code": null,
"e": 7965,
"s": 7700,
"text": "The next triple that we find is (4,3,a), which means the following: move o = 4 positions to the left and read l = 3 characters (‘bab’). After that, write c = ‘a’. Hence, the decompressed value of this triple is ‘baba’. Our decompression string now looks like this:"
},
{
"code": null,
"e": 8031,
"s": 7965,
"text": "Current string: a b a b c b a b aRemaining LZ77 encoding: (2,2,a)"
},
{
"code": null,
"e": 8294,
"s": 8031,
"text": "The last triple that we find is (2,2,a), which means the following: move o = 2 positions to the left and read l = 2 characters (‘ba’). After that, write c = ‘a’. Hence, the decompressed value of this triple is ‘baa’. Our decompression string now looks like this:"
},
{
"code": null,
"e": 8345,
"s": 8294,
"text": "Fully decompressed string: a b a b c b a b a b a a"
}
] |
Kth Ancestor in a Tree | Practice | GeeksforGeeks | Given a binary tree of size N, a node and a positive integer k., Your task is to complete the function kthAncestor(), the function should return the kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then return -1.
Example 1:
Input:
K = 2
Node = 4
Output: 1
Explanation:
Since, K is 2 and node is 4, so we
first need to locate the node and
look k times its ancestors.
Here in this Case node 4 has 1 as his
2nd Ancestor aka the Root of the tree.
Example 2:
Input:
k=1
node=3
1
/ \
2 3
Output:
1
Explanation:
K=1 and node=3 ,Kth ancestor of node 3 is 1.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1<=N<=104
1<= K <= 100
0
mayank2000j1 month ago
bool isPossible(Node *root,int node, vector <Node*> &arr){ if(root==NULL) return false; arr.push_back(root); if(root->data==node) return true; if(isPossible(root->left,node,arr) or isPossible(root->right,node,arr)) return true; arr.pop_back(); return false;}int kthAncestor(Node *root, int k, int node){ // Code here vector <Node*> arr; if(isPossible(root,node,arr)){ // return arr[arr.size()-1-k]->data; return k<arr.size() ? arr[arr.size()-1-k]->data : -1; } return -1;}
0
akshaydoodwal1 month ago
Node* solve(Node* root,int &k,int node){
// 1st base case
if(root==NULL){ return NULL; } // 2nd base case if(root->data==node){ return root; } Node* leftans=solve(root->left,k,node); Node* rightans=solve(root->right,k,node); if(leftans != NULL && rightans == NULL) { k--; if(k <= 0) { k=INT_MAX; return root; } return leftans; } if(leftans==NULL && rightans!=NULL){ k--; if(k<=0){ k=INT_MAX; return root; } else{ return rightans; } } return NULL;}
int kthAncestor(Node *root, int k, int node){ Node* ans= solve(root,k,node); if(ans==NULL|| ans->data==node) { return -1; } else{ return ans->data; }}
+1
priyanshugupta1231232 months ago
EASY JAVA SOLUTION WITHOUT EXTRA SPACE:
class Tree
{
int count =-1;
int res = -1;
public int kthAncestor(Node root, int k, int node)
{
utilFunc(root, k, node);
return res;
}
public boolean utilFunc(Node root, int k, int node){
if(root==null){
return false;
}
if(root.data == node){
count++;
if(count==k){
res = root.data;
}
return true;
}
boolean left = utilFunc(root.left , k , node);
if(left){
count++;
if(count==k){
res = root.data;
}
return true;
}
boolean right = utilFunc(root.right , k , node);
if(right){
count++;
if(count==k){
res = root.data;
}
return true;
}
return false;
}
}
0
roysayantanblr992 months ago
class Tree{ int ans=0; public int kthAncestor(Node root, int k, int node) { //Write your code here ArrayList<Integer> al = new ArrayList<>();
find_path(root,node,al,k); //System.out.println(al); return ans; } void find_path(Node root, int node, ArrayList<Integer> al, int k) { if(root!=null) { al.add(root.data); if(root.data == node) { //System.out.println(al); int index= al.size()-1-k; if(index>=0 && index<=al.size()-1) { ans= al.get(index); }else{ ans=-1; } return;
} find_path(root.left,node,al,k); find_path(root.right,node,al,k);
if(al.size()>0) { al.remove(al.size()-1); } } }}
0
vishalja77192 months ago
Node* solve(Node*root,int &k,int node)
{
if(root == NULL)
{
return NULL;
}
if(root->data == node)
{
return root;
}
Node* leftans=solve(root->left,k,node);
Node* rightans=solve(root->right,k,node);
if(leftans != NULL && rightans == NULL)
{
k--;
if(k <= 0)
{
k=INT_MAX;
return root;
}
return leftans;
}
if(leftans == NULL && rightans != NULL)
{
k--;
if(k <= 0)
{
k=INT_MAX;
return root;
}
return rightans;
}
}
int kthAncestor(Node *root, int k, int node)
{
// Code here
Node* ans=solve(root,k,node);
if(ans == NULL || ans->data == node)
{
return -1;
}
else{
return ans->data;
}
}
0
janvijindal052 months ago
Node* solve(Node *root, int &k, int node){ if(root==NULL) return NULL; if(root->data==node){ return root; } Node* leftAns=solve(root->left,k,node); Node* rightAns=solve(root->right,k,node); if(leftAns!=NULL && rightAns==NULL){ k--; if(k<=0){ k=INT_MAX; return root; } return leftAns; } if(rightAns!=NULL && leftAns==NULL){ k--; if(k<=0){ k=INT_MAX; return root; } return rightAns;} return NULL;
}
int kthAncestor(Node *root, int k, int node){ Node* ans=solve(root,k,node); if(ans==NULL || ans->data==node) return -1; else return ans->data;}
0
sangamchoudhary72 months ago
int solve(Node* root,int k,int node,int &ans){
if(!root) return 0;
else if(root->data == node) return 1;
int ld = solve(root->left,k,node,ans);
int rd = solve(root->right,k,node,ans);
if(ld == k or rd == k){
ans = root->data;
return ans;
}
if(ld) return ld+1;
else if(rd) return rd+1;
return 0;
}
int kthAncestor(Node *root, int k, int node){
int ans = -1;
solve(root,k,node,ans);
return ans;
}
0
bidishapandit032 months ago
//Java BFS solution
public void generateAncestor(Node root,HashMap<Integer,Integer>anc)
{
anc.put(root.data,-1);
Queue<Node> q=new LinkedList<>();
q.add(root);
while(!q.isEmpty())
{
Node curr=q.poll();
if(curr.left!=null)
{
anc.put(curr.left.data,curr.data);
q.add(curr.left);
}
if(curr.right!=null)
{
anc.put(curr.right.data,curr.data);
q.add(curr.right);
}
}
}
public int kthAncestor(Node root, int k, int node)
{
//Write your code here
HashMap<Integer,Integer>anc=new HashMap<>();
generateAncestor(root,anc);
while(k>0&&node!=-1)
{
node=anc.get(node);
k--;
}
return node;
}
0
dipsaili20193 months ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
struct Node{ int data; struct Node *left; struct Node *right;};Node* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL; return temp;}Node* buildTree(string str){ // Corner Case if(str.length() == 0 || str[0] == 'N') return NULL; // Creating vector of strings from input // string after spliting by space vector<string> ip; istringstream iss(str); for(string str; iss >> str; ) ip.push_back(str); // Create the root of the tree Node* root = newNode(stoi(ip[0])); // Push the root to the queue queue<Node*> queue; queue.push(root); // Starting from the second element int i = 1; while(!queue.empty() && i < ip.size()) { // Get and remove the front of the queue Node* currNode = queue.front(); queue.pop(); // Get the current node's value from the string string currVal = ip[i]; // If the left child is not null if(currVal != "N") { // Create the left child for the current node currNode->left = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->left); } // For the right child i++; if(i >= ip.size()) break; currVal = ip[i]; // If the right child is not null if(currVal != "N") { // Create the right child for the current node currNode->right = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->right); } i++; } return root;}int kthAncestor(Node *root, int k, int node);
int main(){ int t;scanf("%d ",&t); while(t--) { int k , node; scanf("%d ",&k); scanf("%d ",&node); string s; getline(cin,s); Node* root = buildTree(s); cout<<kthAncestor(root,k,node)<<endl; } return 0;}// } Driver Code Ends
//User function Template for C++/*Structure of the node of the binary tree is asstruct Node{int data;struct Node *left, *right;};*/// your task is to complete this functionNode* n;int ans = -1;void pmp(Node *root, unordered_map<Node*, Node*> &mp, int node){ queue<Node*> q; q.push(root); while(!q.empty()){ root = q.front(); if(root->data == node) n = root; q.pop(); if(root->left){ mp[root->left] = root; q.push(root->left); } if(root->right){ mp[root->right] = root; q.push(root->right); } }}void upr(Node* n, unordered_map<Node*, Node*> &mp, int k){ if(k == 0){ //cout<<n->data; ans = n->data; return; } if(mp[n] == NULL) return; upr(mp[n], mp, k-1);} int kthAncestor(Node *root, int k, int node){ unordered_map<Node*, Node*>mp; pmp(root, mp, node); upr(n, mp, k); return ans;}
+6
sangamchoudhary74 months ago
2 Approach
Time - O(n) , Space - O(n + h + h) where h → height of tree
Time - O(n) , Space - O(n + h + h) where h → height of tree
vector<int> ans;
void nodeToroot(Node* root,int node,vector<int> temp){
if(!root) return;
if(root->data == node){
ans = temp;
return;
}
temp.push_back(root->data);
nodeToroot(root->left,node,temp);
nodeToroot(root->right,node,temp);
temp.pop_back();
}
int kthAncestor(Node *root, int k, int node){
vector<int> temp;
nodeToroot(root,node,temp);
if(ans.empty()) return -1;
else if(ans.size() < k) return -1;
return ans[ans.size() - k];
}
2. Time - O(n) , Space - O(n)
int dfs(Node* root,int node,int k,int &ans){
if(!root) return 0;
if(root->data == node) return 1;
int lf = dfs(root->left,node,k,ans);
int rf = dfs(root->right,node,k,ans);
if(lf == k or rf == k){
ans = root->data;
}
if(lf) return lf+1;
else if(rf) return rf+1;
else return 0;
}
int kthAncestor(Node *root, int k, int node){
int ans = -1;
dfs(root,node,k,ans);
return ans;
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 497,
"s": 238,
"text": "Given a binary tree of size N, a node and a positive integer k., Your task is to complete the function kthAncestor(), the function should return the kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then return -1."
},
{
"code": null,
"e": 509,
"s": 497,
"text": "\nExample 1:"
},
{
"code": null,
"e": 740,
"s": 509,
"text": "\n\nInput:\n K = 2\n Node = 4\nOutput: 1\nExplanation:\nSince, K is 2 and node is 4, so we\nfirst need to locate the node and\nlook k times its ancestors.\nHere in this Case node 4 has 1 as his\n2nd Ancestor aka the Root of the tree."
},
{
"code": null,
"e": 753,
"s": 742,
"text": "Example 2:"
},
{
"code": null,
"e": 873,
"s": 753,
"text": "Input:\nk=1 \nnode=3\n 1\n / \\\n 2 3\n\nOutput:\n1\nExplanation:\nK=1 and node=3 ,Kth ancestor of node 3 is 1.\n\n"
},
{
"code": null,
"e": 935,
"s": 873,
"text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)"
},
{
"code": null,
"e": 973,
"s": 937,
"text": "Constraints:\n1<=N<=104\n1<= K <= 100"
},
{
"code": null,
"e": 975,
"s": 973,
"text": "0"
},
{
"code": null,
"e": 998,
"s": 975,
"text": "mayank2000j1 month ago"
},
{
"code": null,
"e": 1524,
"s": 998,
"text": "bool isPossible(Node *root,int node, vector <Node*> &arr){ if(root==NULL) return false; arr.push_back(root); if(root->data==node) return true; if(isPossible(root->left,node,arr) or isPossible(root->right,node,arr)) return true; arr.pop_back(); return false;}int kthAncestor(Node *root, int k, int node){ // Code here vector <Node*> arr; if(isPossible(root,node,arr)){ // return arr[arr.size()-1-k]->data; return k<arr.size() ? arr[arr.size()-1-k]->data : -1; } return -1;} "
},
{
"code": null,
"e": 1526,
"s": 1524,
"text": "0"
},
{
"code": null,
"e": 1551,
"s": 1526,
"text": "akshaydoodwal1 month ago"
},
{
"code": null,
"e": 1592,
"s": 1551,
"text": "Node* solve(Node* root,int &k,int node){"
},
{
"code": null,
"e": 1611,
"s": 1592,
"text": " // 1st base case"
},
{
"code": null,
"e": 2183,
"s": 1611,
"text": " if(root==NULL){ return NULL; } // 2nd base case if(root->data==node){ return root; } Node* leftans=solve(root->left,k,node); Node* rightans=solve(root->right,k,node); if(leftans != NULL && rightans == NULL) { k--; if(k <= 0) { k=INT_MAX; return root; } return leftans; } if(leftans==NULL && rightans!=NULL){ k--; if(k<=0){ k=INT_MAX; return root; } else{ return rightans; } } return NULL;}"
},
{
"code": null,
"e": 2352,
"s": 2183,
"text": "int kthAncestor(Node *root, int k, int node){ Node* ans= solve(root,k,node); if(ans==NULL|| ans->data==node) { return -1; } else{ return ans->data; }}"
},
{
"code": null,
"e": 2355,
"s": 2352,
"text": "+1"
},
{
"code": null,
"e": 2388,
"s": 2355,
"text": "priyanshugupta1231232 months ago"
},
{
"code": null,
"e": 2428,
"s": 2388,
"text": "EASY JAVA SOLUTION WITHOUT EXTRA SPACE:"
},
{
"code": null,
"e": 3319,
"s": 2430,
"text": "class Tree\n{\n int count =-1;\n int res = -1;\n public int kthAncestor(Node root, int k, int node)\n {\n utilFunc(root, k, node);\n return res;\n }\n \n public boolean utilFunc(Node root, int k, int node){\n if(root==null){\n return false;\n }\n if(root.data == node){\n count++;\n if(count==k){\n res = root.data;\n }\n return true;\n }\n boolean left = utilFunc(root.left , k , node);\n if(left){\n count++;\n if(count==k){\n res = root.data;\n }\n return true;\n }\n boolean right = utilFunc(root.right , k , node);\n if(right){\n count++;\n if(count==k){\n res = root.data;\n }\n return true;\n }\n return false;\n }\n}"
},
{
"code": null,
"e": 3321,
"s": 3319,
"text": "0"
},
{
"code": null,
"e": 3350,
"s": 3321,
"text": "roysayantanblr992 months ago"
},
{
"code": null,
"e": 3517,
"s": 3350,
"text": "class Tree{ int ans=0; public int kthAncestor(Node root, int k, int node) { //Write your code here ArrayList<Integer> al = new ArrayList<>();"
},
{
"code": null,
"e": 4090,
"s": 3517,
"text": " find_path(root,node,al,k); //System.out.println(al); return ans; } void find_path(Node root, int node, ArrayList<Integer> al, int k) { if(root!=null) { al.add(root.data); if(root.data == node) { //System.out.println(al); int index= al.size()-1-k; if(index>=0 && index<=al.size()-1) { ans= al.get(index); }else{ ans=-1; } return;"
},
{
"code": null,
"e": 4214,
"s": 4090,
"text": " } find_path(root.left,node,al,k); find_path(root.right,node,al,k);"
},
{
"code": null,
"e": 4316,
"s": 4214,
"text": " if(al.size()>0) { al.remove(al.size()-1); } } }}"
},
{
"code": null,
"e": 4318,
"s": 4316,
"text": "0"
},
{
"code": null,
"e": 4343,
"s": 4318,
"text": "vishalja77192 months ago"
},
{
"code": null,
"e": 5175,
"s": 4343,
"text": "Node* solve(Node*root,int &k,int node)\n{\n if(root == NULL)\n {\n return NULL;\n }\n if(root->data == node)\n {\n return root;\n }\n Node* leftans=solve(root->left,k,node);\n Node* rightans=solve(root->right,k,node);\n \n if(leftans != NULL && rightans == NULL)\n {\n k--;\n if(k <= 0)\n {\n k=INT_MAX;\n return root;\n }\n return leftans;\n }\n if(leftans == NULL && rightans != NULL)\n {\n k--;\n if(k <= 0)\n {\n k=INT_MAX;\n return root;\n }\n return rightans;\n }\n \n}\nint kthAncestor(Node *root, int k, int node)\n{\n // Code here\n Node* ans=solve(root,k,node);\n if(ans == NULL || ans->data == node)\n {\n return -1;\n }\n else{\n return ans->data;\n }\n}"
},
{
"code": null,
"e": 5177,
"s": 5175,
"text": "0"
},
{
"code": null,
"e": 5203,
"s": 5177,
"text": "janvijindal052 months ago"
},
{
"code": null,
"e": 5700,
"s": 5203,
"text": "Node* solve(Node *root, int &k, int node){ if(root==NULL) return NULL; if(root->data==node){ return root; } Node* leftAns=solve(root->left,k,node); Node* rightAns=solve(root->right,k,node); if(leftAns!=NULL && rightAns==NULL){ k--; if(k<=0){ k=INT_MAX; return root; } return leftAns; } if(rightAns!=NULL && leftAns==NULL){ k--; if(k<=0){ k=INT_MAX; return root; } return rightAns;} return NULL;"
},
{
"code": null,
"e": 5702,
"s": 5700,
"text": "}"
},
{
"code": null,
"e": 5857,
"s": 5702,
"text": "int kthAncestor(Node *root, int k, int node){ Node* ans=solve(root,k,node); if(ans==NULL || ans->data==node) return -1; else return ans->data;} "
},
{
"code": null,
"e": 5859,
"s": 5857,
"text": "0"
},
{
"code": null,
"e": 5888,
"s": 5859,
"text": "sangamchoudhary72 months ago"
},
{
"code": null,
"e": 6371,
"s": 5888,
"text": "int solve(Node* root,int k,int node,int &ans){\n if(!root) return 0;\n else if(root->data == node) return 1;\n \n int ld = solve(root->left,k,node,ans); \n int rd = solve(root->right,k,node,ans); \n \n if(ld == k or rd == k){\n ans = root->data; \n return ans;\n }\n \n if(ld) return ld+1;\n else if(rd) return rd+1;\n \n return 0;\n}\n\nint kthAncestor(Node *root, int k, int node){\n int ans = -1;\n solve(root,k,node,ans);\n return ans;\n}"
},
{
"code": null,
"e": 6373,
"s": 6371,
"text": "0"
},
{
"code": null,
"e": 6401,
"s": 6373,
"text": "bidishapandit032 months ago"
},
{
"code": null,
"e": 7282,
"s": 6401,
"text": "//Java BFS solution\npublic void generateAncestor(Node root,HashMap<Integer,Integer>anc)\n {\n anc.put(root.data,-1);\n Queue<Node> q=new LinkedList<>();\n q.add(root);\n while(!q.isEmpty())\n {\n Node curr=q.poll();\n if(curr.left!=null)\n {\n anc.put(curr.left.data,curr.data);\n q.add(curr.left);\n }\n if(curr.right!=null)\n {\n anc.put(curr.right.data,curr.data);\n q.add(curr.right);\n }\n }\n }\n public int kthAncestor(Node root, int k, int node)\n {\n //Write your code here\n \n HashMap<Integer,Integer>anc=new HashMap<>();\n generateAncestor(root,anc);\n while(k>0&&node!=-1)\n {\n node=anc.get(node);\n k--;\n \n }\n return node;\n }"
},
{
"code": null,
"e": 7284,
"s": 7282,
"text": "0"
},
{
"code": null,
"e": 7309,
"s": 7284,
"text": "dipsaili20193 months ago"
},
{
"code": null,
"e": 7377,
"s": 7309,
"text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 9135,
"s": 7377,
"text": "struct Node{ int data; struct Node *left; struct Node *right;};Node* newNode(int val){ Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL; return temp;}Node* buildTree(string str){ // Corner Case if(str.length() == 0 || str[0] == 'N') return NULL; // Creating vector of strings from input // string after spliting by space vector<string> ip; istringstream iss(str); for(string str; iss >> str; ) ip.push_back(str); // Create the root of the tree Node* root = newNode(stoi(ip[0])); // Push the root to the queue queue<Node*> queue; queue.push(root); // Starting from the second element int i = 1; while(!queue.empty() && i < ip.size()) { // Get and remove the front of the queue Node* currNode = queue.front(); queue.pop(); // Get the current node's value from the string string currVal = ip[i]; // If the left child is not null if(currVal != \"N\") { // Create the left child for the current node currNode->left = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->left); } // For the right child i++; if(i >= ip.size()) break; currVal = ip[i]; // If the right child is not null if(currVal != \"N\") { // Create the right child for the current node currNode->right = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->right); } i++; } return root;}int kthAncestor(Node *root, int k, int node);"
},
{
"code": null,
"e": 9393,
"s": 9135,
"text": "int main(){ int t;scanf(\"%d \",&t); while(t--) { int k , node; scanf(\"%d \",&k); scanf(\"%d \",&node); string s; getline(cin,s); Node* root = buildTree(s); cout<<kthAncestor(root,k,node)<<endl; } return 0;}// } Driver Code Ends"
},
{
"code": null,
"e": 10300,
"s": 9393,
"text": "//User function Template for C++/*Structure of the node of the binary tree is asstruct Node{int data;struct Node *left, *right;};*/// your task is to complete this functionNode* n;int ans = -1;void pmp(Node *root, unordered_map<Node*, Node*> &mp, int node){ queue<Node*> q; q.push(root); while(!q.empty()){ root = q.front(); if(root->data == node) n = root; q.pop(); if(root->left){ mp[root->left] = root; q.push(root->left); } if(root->right){ mp[root->right] = root; q.push(root->right); } }}void upr(Node* n, unordered_map<Node*, Node*> &mp, int k){ if(k == 0){ //cout<<n->data; ans = n->data; return; } if(mp[n] == NULL) return; upr(mp[n], mp, k-1);} int kthAncestor(Node *root, int k, int node){ unordered_map<Node*, Node*>mp; pmp(root, mp, node); upr(n, mp, k); return ans;} "
},
{
"code": null,
"e": 10303,
"s": 10300,
"text": "+6"
},
{
"code": null,
"e": 10332,
"s": 10303,
"text": "sangamchoudhary74 months ago"
},
{
"code": null,
"e": 10343,
"s": 10332,
"text": "2 Approach"
},
{
"code": null,
"e": 10405,
"s": 10345,
"text": "Time - O(n) , Space - O(n + h + h) where h → height of tree"
},
{
"code": null,
"e": 10465,
"s": 10405,
"text": "Time - O(n) , Space - O(n + h + h) where h → height of tree"
},
{
"code": null,
"e": 10966,
"s": 10465,
"text": "vector<int> ans;\nvoid nodeToroot(Node* root,int node,vector<int> temp){\n if(!root) return;\n if(root->data == node){\n ans = temp;\n return;\n }\n temp.push_back(root->data);\n nodeToroot(root->left,node,temp);\n nodeToroot(root->right,node,temp);\n temp.pop_back();\n}\n\nint kthAncestor(Node *root, int k, int node){\n vector<int> temp;\n nodeToroot(root,node,temp);\n if(ans.empty()) return -1;\n else if(ans.size() < k) return -1;\n return ans[ans.size() - k];\n}"
},
{
"code": null,
"e": 10996,
"s": 10966,
"text": "2. Time - O(n) , Space - O(n)"
},
{
"code": null,
"e": 11445,
"s": 10998,
"text": "int dfs(Node* root,int node,int k,int &ans){\n if(!root) return 0;\n if(root->data == node) return 1;\n \n int lf = dfs(root->left,node,k,ans);\n int rf = dfs(root->right,node,k,ans);\n \n if(lf == k or rf == k){\n ans = root->data;\n }\n \n if(lf) return lf+1;\n else if(rf) return rf+1;\n else return 0;\n}\n\nint kthAncestor(Node *root, int k, int node){\n int ans = -1;\n dfs(root,node,k,ans);\n return ans;\n}"
},
{
"code": null,
"e": 11593,
"s": 11447,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 11629,
"s": 11593,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11639,
"s": 11629,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11649,
"s": 11639,
"text": "\nContest\n"
},
{
"code": null,
"e": 11712,
"s": 11649,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11860,
"s": 11712,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 12068,
"s": 11860,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 12174,
"s": 12068,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Python Design Patterns - State | It provides a module for state machines, which are implemented using subclasses, derived from a specified state machine class. The methods are state independent and cause transitions declared using decorators.
The basic implementation of state pattern is shown below −
class ComputerState(object):
name = "state"
allowed = []
def switch(self, state):
""" Switch to new state """
if state.name in self.allowed:
print 'Current:',self,' => switched to new state',state.name
self.__class__ = state
else:
print 'Current:',self,' => switching to',state.name,'not possible.'
def __str__(self):
return self.name
class Off(ComputerState):
name = "off"
allowed = ['on']
class On(ComputerState):
""" State of being powered on and working """
name = "on"
allowed = ['off','suspend','hibernate']
class Suspend(ComputerState):
""" State of being in suspended mode after switched on """
name = "suspend"
allowed = ['on']
class Hibernate(ComputerState):
""" State of being in hibernation after powered on """
name = "hibernate"
allowed = ['on']
class Computer(object):
""" A class representing a computer """
def __init__(self, model='HP'):
self.model = model
# State of the computer - default is off.
self.state = Off()
def change(self, state):
""" Change state """
self.state.switch(state)
if __name__ == "__main__":
comp = Computer()
comp.change(On)
comp.change(Off)
comp.change(On)
comp.change(Suspend)
comp.change(Hibernate)
comp.change(On)
comp.change(Off)
The above program generates the following output −
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": 2689,
"s": 2479,
"text": "It provides a module for state machines, which are implemented using subclasses, derived from a specified state machine class. The methods are state independent and cause transitions declared using decorators."
},
{
"code": null,
"e": 2748,
"s": 2689,
"text": "The basic implementation of state pattern is shown below −"
},
{
"code": null,
"e": 4102,
"s": 2748,
"text": "class ComputerState(object):\n\n name = \"state\"\n allowed = []\n\n def switch(self, state):\n \"\"\" Switch to new state \"\"\"\n if state.name in self.allowed:\n print 'Current:',self,' => switched to new state',state.name\n self.__class__ = state\n else:\n print 'Current:',self,' => switching to',state.name,'not possible.'\n\n def __str__(self):\n return self.name\n\nclass Off(ComputerState):\n name = \"off\"\n allowed = ['on']\n\nclass On(ComputerState):\n \"\"\" State of being powered on and working \"\"\"\n name = \"on\"\n allowed = ['off','suspend','hibernate']\n\nclass Suspend(ComputerState):\n \"\"\" State of being in suspended mode after switched on \"\"\"\n name = \"suspend\"\n allowed = ['on']\n\nclass Hibernate(ComputerState):\n \"\"\" State of being in hibernation after powered on \"\"\"\n name = \"hibernate\"\n allowed = ['on']\n\nclass Computer(object):\n \"\"\" A class representing a computer \"\"\"\n \n def __init__(self, model='HP'):\n self.model = model\n # State of the computer - default is off.\n self.state = Off()\n \n def change(self, state):\n \"\"\" Change state \"\"\"\n self.state.switch(state)\n\nif __name__ == \"__main__\":\n comp = Computer()\n comp.change(On)\n comp.change(Off)\n comp.change(On)\n comp.change(Suspend)\n comp.change(Hibernate)\n comp.change(On)\n comp.change(Off)"
},
{
"code": null,
"e": 4153,
"s": 4102,
"text": "The above program generates the following output −"
},
{
"code": null,
"e": 4190,
"s": 4153,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4206,
"s": 4190,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4239,
"s": 4206,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4258,
"s": 4239,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4293,
"s": 4258,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4315,
"s": 4293,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4349,
"s": 4315,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4377,
"s": 4349,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4412,
"s": 4377,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4426,
"s": 4412,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4459,
"s": 4426,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4476,
"s": 4459,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4483,
"s": 4476,
"text": " Print"
},
{
"code": null,
"e": 4494,
"s": 4483,
"text": " Add Notes"
}
] |
C Program to find two’s complement for a given number | The two’s complement for a given binary number can be calculated in two methods, which are as follows −
Method 1 − Convert the given binary number into one’s complement and then, add 1.
Method 1 − Convert the given binary number into one’s complement and then, add 1.
Method 2 − The trailing zero’s after the first bit set from the Least Significant Bit (LSB) including one that remains unchanged and remaining all should be complementing.
Method 2 − The trailing zero’s after the first bit set from the Least Significant Bit (LSB) including one that remains unchanged and remaining all should be complementing.
The logic to find two’s complement for a given binary number is as follows −
for(i = SIZE - 1; i >= 0; i--){
if(one[i] == '1' && carry == 1){
two[i] = '0';
}
else if(one[i] == '0' && carry == 1){
two[i] = '1';
carry = 0;
} else {
two[i] = one[i];
}
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s\n",num, two);
The logic for finding one’s complement from a given binary number is −
for(i = 0; i < SIZE; i++){
if(num[i] == '0'){
one[i] = '1';
}
else if(num[i] == '1'){
one[i] = '0';
}
}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s\n",num, one);
Following is the C program to find two’s complement for a given number −
Live Demo
#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main(){
int i, carry = 1;
char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
printf("Enter the binary number\n");
gets(num);
for(i = 0; i < SIZE; i++){
if(num[i] == '0'){
one[i] = '1';
}
else if(num[i] == '1'){
one[i] = '0';
}
}
one[SIZE] = '\0';
printf("Ones' complement of binary number %s is %s\n",num, one);
for(i = SIZE - 1; i >= 0; i--){
if(one[i] == '1' && carry == 1){
two[i] = '0';
}
else if(one[i] == '0' && carry == 1){
two[i] = '1';
carry = 0;
}
else{
two[i] = one[i];
}
}
two[SIZE] = '\0';
printf("Two's complement of binary number %s is %s\n",num, two);
return 0;
}
When the above program is executed, it produces the following result −
Enter the binary number
1000010
Ones' complement of binary number 1000010 is 0111101
Two's complement of binary number 1000010 is 0111110 | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "The two’s complement for a given binary number can be calculated in two methods, which are as follows −"
},
{
"code": null,
"e": 1248,
"s": 1166,
"text": "Method 1 − Convert the given binary number into one’s complement and then, add 1."
},
{
"code": null,
"e": 1330,
"s": 1248,
"text": "Method 1 − Convert the given binary number into one’s complement and then, add 1."
},
{
"code": null,
"e": 1502,
"s": 1330,
"text": "Method 2 − The trailing zero’s after the first bit set from the Least Significant Bit (LSB) including one that remains unchanged and remaining all should be complementing."
},
{
"code": null,
"e": 1674,
"s": 1502,
"text": "Method 2 − The trailing zero’s after the first bit set from the Least Significant Bit (LSB) including one that remains unchanged and remaining all should be complementing."
},
{
"code": null,
"e": 1751,
"s": 1674,
"text": "The logic to find two’s complement for a given binary number is as follows −"
},
{
"code": null,
"e": 2047,
"s": 1751,
"text": "for(i = SIZE - 1; i >= 0; i--){\n if(one[i] == '1' && carry == 1){\n two[i] = '0';\n }\n else if(one[i] == '0' && carry == 1){\n two[i] = '1';\n carry = 0;\n } else {\n two[i] = one[i];\n }\n}\ntwo[SIZE] = '\\0';\nprintf(\"Two's complement of binary number %s is %s\\n\",num, two);"
},
{
"code": null,
"e": 2118,
"s": 2047,
"text": "The logic for finding one’s complement from a given binary number is −"
},
{
"code": null,
"e": 2329,
"s": 2118,
"text": "for(i = 0; i < SIZE; i++){\n if(num[i] == '0'){\n one[i] = '1';\n }\n else if(num[i] == '1'){\n one[i] = '0';\n }\n}\none[SIZE] = '\\0';\nprintf(\"Ones' complement of binary number %s is %s\\n\",num, one);"
},
{
"code": null,
"e": 2402,
"s": 2329,
"text": "Following is the C program to find two’s complement for a given number −"
},
{
"code": null,
"e": 2413,
"s": 2402,
"text": " Live Demo"
},
{
"code": null,
"e": 3201,
"s": 2413,
"text": "#include<stdio.h>\n#include<stdlib.h>\n#define SIZE 8\nint main(){\n int i, carry = 1;\n char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];\n printf(\"Enter the binary number\\n\");\n gets(num);\n for(i = 0; i < SIZE; i++){\n if(num[i] == '0'){\n one[i] = '1';\n }\n else if(num[i] == '1'){\n one[i] = '0';\n }\n }\n one[SIZE] = '\\0';\n printf(\"Ones' complement of binary number %s is %s\\n\",num, one);\n for(i = SIZE - 1; i >= 0; i--){\n if(one[i] == '1' && carry == 1){\n two[i] = '0';\n }\n else if(one[i] == '0' && carry == 1){\n two[i] = '1';\n carry = 0;\n }\n else{\n two[i] = one[i];\n }\n }\n two[SIZE] = '\\0';\n printf(\"Two's complement of binary number %s is %s\\n\",num, two);\n return 0;\n}"
},
{
"code": null,
"e": 3272,
"s": 3201,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 3410,
"s": 3272,
"text": "Enter the binary number\n1000010\nOnes' complement of binary number 1000010 is 0111101\nTwo's complement of binary number 1000010 is 0111110"
}
] |
Python PIL | Image.getdata() - GeeksforGeeks | 02 Aug, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.
getdata() Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.
Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).
Syntax: Image.getdata(band=None)
Parameters:
band – What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the “R” band from an “RGB” image).
Returns type: A sequence-like object.
Image Used:
# importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r"C:\Users\System-Pc\Desktop\lion.png").convert("L") # getting colors # multiband images (RBG) im1 = Image.Image.getdata(im) print(im1)
Output:
ImagingCore object at 0x0000026E11CD52D0
Another example:Here we change image.Image Used
# importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r"C:\Users\System-Pc\Desktop\tree.jpg").convert("L") # getting colors # multiband images (RBG) im1 = Image.Image.getdata(im) print(im1)
Output:
ImagingCore object at 0x0000029BA596C230
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python | [
{
"code": null,
"e": 24510,
"s": 24482,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 24837,
"s": 24510,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images."
},
{
"code": null,
"e": 25048,
"s": 24837,
"text": "getdata() Returns the contents of this image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on."
},
{
"code": null,
"e": 25264,
"s": 25048,
"text": "Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata())."
},
{
"code": null,
"e": 25297,
"s": 25264,
"text": "Syntax: Image.getdata(band=None)"
},
{
"code": null,
"e": 25309,
"s": 25297,
"text": "Parameters:"
},
{
"code": null,
"e": 25472,
"s": 25309,
"text": "band – What band to return. The default is to return all bands. To return a single band, pass in the index value (e.g. 0 to get the “R” band from an “RGB” image)."
},
{
"code": null,
"e": 25510,
"s": 25472,
"text": "Returns type: A sequence-like object."
},
{
"code": null,
"e": 25522,
"s": 25510,
"text": "Image Used:"
},
{
"code": " # importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\lion.png\").convert(\"L\") # getting colors # multiband images (RBG) im1 = Image.Image.getdata(im) print(im1) ",
"e": 25772,
"s": 25522,
"text": null
},
{
"code": null,
"e": 25780,
"s": 25772,
"text": "Output:"
},
{
"code": null,
"e": 25822,
"s": 25780,
"text": "ImagingCore object at 0x0000026E11CD52D0\n"
},
{
"code": null,
"e": 25870,
"s": 25822,
"text": "Another example:Here we change image.Image Used"
},
{
"code": "# importing Image module from PIL package from PIL import Image # opening a image im = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\tree.jpg\").convert(\"L\") # getting colors # multiband images (RBG) im1 = Image.Image.getdata(im) print(im1) ",
"e": 26115,
"s": 25870,
"text": null
},
{
"code": null,
"e": 26123,
"s": 26115,
"text": "Output:"
},
{
"code": null,
"e": 26165,
"s": 26123,
"text": "ImagingCore object at 0x0000029BA596C230\n"
},
{
"code": null,
"e": 26176,
"s": 26165,
"text": "Python-pil"
},
{
"code": null,
"e": 26183,
"s": 26176,
"text": "Python"
},
{
"code": null,
"e": 26281,
"s": 26183,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26299,
"s": 26281,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26334,
"s": 26299,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26366,
"s": 26334,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26408,
"s": 26366,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26430,
"s": 26408,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26460,
"s": 26430,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26486,
"s": 26460,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26530,
"s": 26486,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26567,
"s": 26530,
"text": "Create a Pandas DataFrame from Lists"
}
] |
How to exclude specific extension in Get-ChildItem in PowerShell? | To exclude specific extensions, you need to use –Exclude parameter in Get-ChildItem.
For example, as shown below when we run command, it will exclude .html files and display the rest.
Get-ChildItem D:\Temp\ -Recurse -Exclude *.html
Directory: D:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 24-11-2018 11:31 LGPO
Directory: D:\Temp\LGPO
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 01-06-2017 03:22 410088 LGPO.exe
-a---- 01-06-2017 02:25 638115 LGPO.pdf
Directory: D:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 07-05-2018 23:00 301 cars.xml
-a---- 08-12-2017 10:16 393 style.css
-a---- 08-12-2017 11:29 7974 Test.xlsx
-a---- 25-10-2017 08:13 104 testcsv.csv
You can exclude multiple extensions as well.
In the below example, we will exclude html and xml extensions.
Get-ChildItem D:\Temp\ -Recurse -Exclude *.html,*.xml
Directory: D:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 24-11-2018 11:31 LGPO
Directory: D:\Temp\LGPO
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 01-06-2017 03:22 410088 LGPO.exe
-a---- 01-06-2017 02:25 638115 LGPO.pdf
Directory: D:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 08-12-2017 10:16 393 style.css
-a---- 08-12-2017 11:29 7974 Test.xlsx
-a---- 25-10-2017 08:13 104 testcsv.csv | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "To exclude specific extensions, you need to use –Exclude parameter in Get-ChildItem."
},
{
"code": null,
"e": 1246,
"s": 1147,
"text": "For example, as shown below when we run command, it will exclude .html files and display the rest."
},
{
"code": null,
"e": 1294,
"s": 1246,
"text": "Get-ChildItem D:\\Temp\\ -Recurse -Exclude *.html"
},
{
"code": null,
"e": 2095,
"s": 1294,
"text": "Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\nd----- 24-11-2018 11:31 LGPO\n Directory: D:\\Temp\\LGPO\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 01-06-2017 03:22 410088 LGPO.exe\n-a---- 01-06-2017 02:25 638115 LGPO.pdf\n Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 07-05-2018 23:00 301 cars.xml\n-a---- 08-12-2017 10:16 393 style.css\n-a---- 08-12-2017 11:29 7974 Test.xlsx\n-a---- 25-10-2017 08:13 104 testcsv.csv"
},
{
"code": null,
"e": 2140,
"s": 2095,
"text": "You can exclude multiple extensions as well."
},
{
"code": null,
"e": 2203,
"s": 2140,
"text": "In the below example, we will exclude html and xml extensions."
},
{
"code": null,
"e": 2258,
"s": 2203,
"text": "Get-ChildItem D:\\Temp\\ -Recurse -Exclude *.html,*.xml\n"
},
{
"code": null,
"e": 3001,
"s": 2258,
"text": "Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\nd----- 24-11-2018 11:31 LGPO\n Directory: D:\\Temp\\LGPO\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 01-06-2017 03:22 410088 LGPO.exe\n-a---- 01-06-2017 02:25 638115 LGPO.pdf\n Directory: D:\\Temp\nMode LastWriteTime Length Name\n---- ------------- ------ ----\n-a---- 08-12-2017 10:16 393 style.css\n-a---- 08-12-2017 11:29 7974 Test.xlsx\n-a---- 25-10-2017 08:13 104 testcsv.csv"
}
] |
Adding Borders to Tables in CSS | The CSS border property is used to define a border for an element. The syntax of CSS border property is as follows−
Selector {
border: /*value*/
}
The following examples illustrate CSS border property−
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
margin: 1em;
border: 3px double green;
border-right-style: dashed;
border-left-width: 17px;
border-bottom-color: orange;
}
td {
font-size: 24px;
border-right-style: dotted;
border-width: 3px;
border-right-color: red;
}
</style>
</head>
<body>
<table>
<tr>
<td>demo</td>
<td>text</td>
</tr>
<tr>
<td>goes</td>
<td>here</td>
</tr>
</table>
</body>
</html>
This gives the following output−
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
table {
margin: auto;
caption-side: bottom;
border: 2px dashed black;
}
td {
border: 2px solid midnightblue;
text-align: center;
}
td[colspan] {
box-shadow: inset 0 0 10px lightblue;
text-align: center;
}
caption {
font-size: 16px;
font-weight: bold;
}
</style>
</head>
<body>
<h2<Ranking</h2>
<table>
<caption>Men's ODI Player Ranking</caption>
<tr>
<th>Player</th>
<th>Rank</th>
</tr>
<tr>
<td>Virat Kohli</td>
<td>1</td>
</tr>
<tr>
<td>Rohit Sharma</td>
<td>2</td>
</tr>
<tr>
<td>Babar Azam</td>
<td>3</td>
</tr>
<tr>
<td>Ross Taylor</td>
<td>4</td>
</tr>
<tr>
<td colspan="2">Sept2019</td>
</tr>
</table>
</body>
</html>
This gives the following output− | [
{
"code": null,
"e": 1178,
"s": 1062,
"text": "The CSS border property is used to define a border for an element. The syntax of CSS border property is as follows−"
},
{
"code": null,
"e": 1212,
"s": 1178,
"text": "Selector {\n border: /*value*/\n}"
},
{
"code": null,
"e": 1267,
"s": 1212,
"text": "The following examples illustrate CSS border property−"
},
{
"code": null,
"e": 1278,
"s": 1267,
"text": " Live Demo"
},
{
"code": null,
"e": 1705,
"s": 1278,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n margin: 1em;\n border: 3px double green;\n border-right-style: dashed;\n border-left-width: 17px;\n border-bottom-color: orange;\n}\ntd {\n font-size: 24px;\n border-right-style: dotted;\n border-width: 3px;\n border-right-color: red;\n}\n</style>\n</head>\n<body>\n<table>\n<tr>\n<td>demo</td>\n<td>text</td>\n</tr>\n<tr>\n<td>goes</td>\n<td>here</td>\n</tr>\n</table>\n</body>\n</html>"
},
{
"code": null,
"e": 1738,
"s": 1705,
"text": "This gives the following output−"
},
{
"code": null,
"e": 1749,
"s": 1738,
"text": " Live Demo"
},
{
"code": null,
"e": 2439,
"s": 1749,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ntable {\n margin: auto;\n caption-side: bottom;\n border: 2px dashed black;\n}\ntd {\n border: 2px solid midnightblue;\n text-align: center;\n}\ntd[colspan] {\n box-shadow: inset 0 0 10px lightblue;\n text-align: center;\n}\ncaption {\n font-size: 16px;\n font-weight: bold;\n}\n</style>\n</head>\n<body>\n<h2<Ranking</h2>\n<table>\n<caption>Men's ODI Player Ranking</caption>\n<tr>\n<th>Player</th>\n<th>Rank</th>\n</tr>\n<tr>\n<td>Virat Kohli</td>\n<td>1</td>\n</tr>\n<tr>\n<td>Rohit Sharma</td>\n<td>2</td>\n</tr>\n<tr>\n<td>Babar Azam</td>\n<td>3</td>\n</tr>\n<tr>\n<td>Ross Taylor</td>\n<td>4</td>\n</tr>\n<tr>\n<td colspan=\"2\">Sept2019</td>\n</tr>\n</table>\n</body>\n</html>"
},
{
"code": null,
"e": 2472,
"s": 2439,
"text": "This gives the following output−"
}
] |
An Introduction to Scala. Welcome to the first article in my... | by Jake Huneycutt | Towards Data Science | Welcome to the first article in my multi-part series on Scala. This tutorial is designed to teach introductory Scala as a precursor to learning Apache Spark.
This first section is available on Medium, but the rest of this guide can be found on the project Github page in the link below:
An Intro to Scala
Scala is an object-oriented and functional programming language. It’s is most closely related to Java, so Java programmers should have a leg up on learning it. However, Scala is designed to be more concise and have features of functional programming languages.
Spark is an open-source cluster-computing framework designed for big data processing. It is written in Scala. Spark can be run in Python (PySpark) and R (SparkR and sparklyr); however, the best performance with Spark can be achieved in Scala.
I will offer some other sources as both alternatives and references. Jose Portilla’s Udemy courses are great and my blog will series will loosely follow the structure for his “Scala and Spark for Big Data and Machine Learning” course. If you learn better in video format, I highly recommend that course.
Marius Eriksen of Twitter has published “Effective Scala”, which is available online for free. That’s a great resource, as well.
If you’re coming from a Python background, you might also check out this Python to Scala e-book, written by Rob Story. It’s “short and sweet” and serves as a good quick reference for all you Pythoners and Pythonistas out there!
With that, let’s get started!
The first task is to download Scala. Admittedly, this can be one of the more challenging parts of the process. You’ll need to go through several steps. If you’re using Windows 10, I recommend the following tutorial on YouTube:
How to Install and Setup SBT + Scala on Windows 10
You can decide on your own whether you want to install SBT, as well, as there are other options for running Scala (such as IntelliJ).
If you are using a Linux-based OS, here is a similar video for you. I cannot vouch for this, but it’s by the same author.
How to Install and Setup SBT on Ubuntu
Finally, here are some Mac instructions.
How to Install Scala on Mac
While I found installing Scala to be more difficult than Python or R, there are plenty of resources out on the web if you’re struggling. The good news is this is probably the most challenging part for most people.
We’ll use the command prompt for our early exercises, but we’ll eventually need a code editor. I recommend VS Code and I’ll walk you through how to download.
You are obviously free to use other options, such as Atom or Sublime, as well. Alternatively, if you want to use a full IDE, IntelliJ is a good choice and there is a Scala plug-in for it.
If you want to use VS Code and do not have it yet, download it here.
Once you have VS Code on your computer, launch it. On the left hand side of the screen, you should see some icons. One of these icons is a square of sorts. If you hover it, it should say “Extensions.” Click on that.
In the search bar, enter “Scala”. You should see some plug-in options for Scala. Go to “Scala (sbt)” and install it. Screenshot below highlights the box and correct plug-in.
You might also consider some other Scala plug-ins. I haven’t messed around much with the others, but I did download the Scala Syntax plug-in, as well.
In any case, now you should be configured for running Scala files.
Once you have everything installed, you should be able to run Scala through your command prompt. If you follow the instructions successfully and you’re running Windows, you can open the command prompt (shortcut: enter “cmd” in the search box at the “Start” menu) and type in:
spark-shell
This will launch Spark in local mode, which is what we’ll use for learning the basics of Scala.
Let’s start with the simple print statement. Scala’s print statements look similar to Java, but a bit more concise.
println(“Hello world!”)
And voila! You’ve now run your first Scala program.
We won’t need a code editor till we’re a few lessons in, but if you also want to make sure Scala works properly in VS Code, then go to File -> New File. Save your file as “hello_world.scala”. Enter the correct code in the file and then save.
Now open your terminal: View -> Terminal. Enter “spark-shell” in the terminal just as we did in the command prompt. To run the program, enter:
:load hello_world.scala
With that, you should get your printout.
That’s it for this Part 1. Part 2 covers data types; check it out at the project Github repo. | [
{
"code": null,
"e": 330,
"s": 172,
"text": "Welcome to the first article in my multi-part series on Scala. This tutorial is designed to teach introductory Scala as a precursor to learning Apache Spark."
},
{
"code": null,
"e": 459,
"s": 330,
"text": "This first section is available on Medium, but the rest of this guide can be found on the project Github page in the link below:"
},
{
"code": null,
"e": 477,
"s": 459,
"text": "An Intro to Scala"
},
{
"code": null,
"e": 738,
"s": 477,
"text": "Scala is an object-oriented and functional programming language. It’s is most closely related to Java, so Java programmers should have a leg up on learning it. However, Scala is designed to be more concise and have features of functional programming languages."
},
{
"code": null,
"e": 981,
"s": 738,
"text": "Spark is an open-source cluster-computing framework designed for big data processing. It is written in Scala. Spark can be run in Python (PySpark) and R (SparkR and sparklyr); however, the best performance with Spark can be achieved in Scala."
},
{
"code": null,
"e": 1285,
"s": 981,
"text": "I will offer some other sources as both alternatives and references. Jose Portilla’s Udemy courses are great and my blog will series will loosely follow the structure for his “Scala and Spark for Big Data and Machine Learning” course. If you learn better in video format, I highly recommend that course."
},
{
"code": null,
"e": 1414,
"s": 1285,
"text": "Marius Eriksen of Twitter has published “Effective Scala”, which is available online for free. That’s a great resource, as well."
},
{
"code": null,
"e": 1642,
"s": 1414,
"text": "If you’re coming from a Python background, you might also check out this Python to Scala e-book, written by Rob Story. It’s “short and sweet” and serves as a good quick reference for all you Pythoners and Pythonistas out there!"
},
{
"code": null,
"e": 1672,
"s": 1642,
"text": "With that, let’s get started!"
},
{
"code": null,
"e": 1899,
"s": 1672,
"text": "The first task is to download Scala. Admittedly, this can be one of the more challenging parts of the process. You’ll need to go through several steps. If you’re using Windows 10, I recommend the following tutorial on YouTube:"
},
{
"code": null,
"e": 1950,
"s": 1899,
"text": "How to Install and Setup SBT + Scala on Windows 10"
},
{
"code": null,
"e": 2084,
"s": 1950,
"text": "You can decide on your own whether you want to install SBT, as well, as there are other options for running Scala (such as IntelliJ)."
},
{
"code": null,
"e": 2206,
"s": 2084,
"text": "If you are using a Linux-based OS, here is a similar video for you. I cannot vouch for this, but it’s by the same author."
},
{
"code": null,
"e": 2245,
"s": 2206,
"text": "How to Install and Setup SBT on Ubuntu"
},
{
"code": null,
"e": 2286,
"s": 2245,
"text": "Finally, here are some Mac instructions."
},
{
"code": null,
"e": 2314,
"s": 2286,
"text": "How to Install Scala on Mac"
},
{
"code": null,
"e": 2528,
"s": 2314,
"text": "While I found installing Scala to be more difficult than Python or R, there are plenty of resources out on the web if you’re struggling. The good news is this is probably the most challenging part for most people."
},
{
"code": null,
"e": 2686,
"s": 2528,
"text": "We’ll use the command prompt for our early exercises, but we’ll eventually need a code editor. I recommend VS Code and I’ll walk you through how to download."
},
{
"code": null,
"e": 2874,
"s": 2686,
"text": "You are obviously free to use other options, such as Atom or Sublime, as well. Alternatively, if you want to use a full IDE, IntelliJ is a good choice and there is a Scala plug-in for it."
},
{
"code": null,
"e": 2943,
"s": 2874,
"text": "If you want to use VS Code and do not have it yet, download it here."
},
{
"code": null,
"e": 3159,
"s": 2943,
"text": "Once you have VS Code on your computer, launch it. On the left hand side of the screen, you should see some icons. One of these icons is a square of sorts. If you hover it, it should say “Extensions.” Click on that."
},
{
"code": null,
"e": 3333,
"s": 3159,
"text": "In the search bar, enter “Scala”. You should see some plug-in options for Scala. Go to “Scala (sbt)” and install it. Screenshot below highlights the box and correct plug-in."
},
{
"code": null,
"e": 3484,
"s": 3333,
"text": "You might also consider some other Scala plug-ins. I haven’t messed around much with the others, but I did download the Scala Syntax plug-in, as well."
},
{
"code": null,
"e": 3551,
"s": 3484,
"text": "In any case, now you should be configured for running Scala files."
},
{
"code": null,
"e": 3827,
"s": 3551,
"text": "Once you have everything installed, you should be able to run Scala through your command prompt. If you follow the instructions successfully and you’re running Windows, you can open the command prompt (shortcut: enter “cmd” in the search box at the “Start” menu) and type in:"
},
{
"code": null,
"e": 3839,
"s": 3827,
"text": "spark-shell"
},
{
"code": null,
"e": 3935,
"s": 3839,
"text": "This will launch Spark in local mode, which is what we’ll use for learning the basics of Scala."
},
{
"code": null,
"e": 4051,
"s": 3935,
"text": "Let’s start with the simple print statement. Scala’s print statements look similar to Java, but a bit more concise."
},
{
"code": null,
"e": 4075,
"s": 4051,
"text": "println(“Hello world!”)"
},
{
"code": null,
"e": 4127,
"s": 4075,
"text": "And voila! You’ve now run your first Scala program."
},
{
"code": null,
"e": 4369,
"s": 4127,
"text": "We won’t need a code editor till we’re a few lessons in, but if you also want to make sure Scala works properly in VS Code, then go to File -> New File. Save your file as “hello_world.scala”. Enter the correct code in the file and then save."
},
{
"code": null,
"e": 4512,
"s": 4369,
"text": "Now open your terminal: View -> Terminal. Enter “spark-shell” in the terminal just as we did in the command prompt. To run the program, enter:"
},
{
"code": null,
"e": 4536,
"s": 4512,
"text": ":load hello_world.scala"
},
{
"code": null,
"e": 4577,
"s": 4536,
"text": "With that, you should get your printout."
}
] |
Pandas - Removing Duplicates | Duplicate rows are rows
that have been registered more than one time.
Duration Date Pulse Maxpulse Calories
0 60 '2020/12/01' 110 130 409.1
1 60 '2020/12/02' 117 145 479.0
2 60 '2020/12/03' 103 135 340.0
3 45 '2020/12/04' 109 175 282.4
4 45 '2020/12/05' 117 148 406.0
5 60 '2020/12/06' 102 127 300.0
6 60 '2020/12/07' 110 136 374.0
7 450 '2020/12/08' 104 134 253.3
8 30 '2020/12/09' 109 133 195.1
9 60 '2020/12/10' 98 124 269.0
10 60 '2020/12/11' 103 147 329.3
11 60 '2020/12/12' 100 120 250.7
12 60 '2020/12/12' 100 120 250.7
13 60 '2020/12/13' 106 128 345.3
14 60 '2020/12/14' 104 132 379.3
15 60 '2020/12/15' 98 123 275.0
16 60 '2020/12/16' 98 120 215.2
17 60 '2020/12/17' 100 120 300.0
18 45 '2020/12/18' 90 112 NaN
19 60 '2020/12/19' 103 123 323.0
20 45 '2020/12/20' 97 125 243.0
21 60 '2020/12/21' 108 131 364.2
22 45 NaN 100 119 282.0
23 60 '2020/12/23' 130 101 300.0
24 45 '2020/12/24' 105 132 246.0
25 60 '2020/12/25' 102 126 334.5
26 60 20201226 100 120 250.0
27 60 '2020/12/27' 92 118 241.0
28 60 '2020/12/28' 103 132 NaN
29 60 '2020/12/29' 100 132 280.0
30 60 '2020/12/30' 102 129 380.3
31 60 '2020/12/31' 92 115 243.0
By taking a look at our test data set, we can assume that row 11 and 12 are duplicates.
To discover duplicates, we can use the duplicated() method.
The duplicated() method returns a Boolean values for each row:
Returns True for every row that is a duplicate, othwerwise False:
To remove duplicates, use the drop_duplicates() method.
Remove all duplicates:
Remember: The (inplace = True) will
make sure that the method does NOT return a new DataFrame, but it will remove all
duplicates from the original DataFrame.
Insert the correct syntax for removing rows with empty cells.
df.()
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": 71,
"s": 0,
"text": "Duplicate rows are rows \nthat have been registered more than one time."
},
{
"code": null,
"e": 1922,
"s": 71,
"text": "\n Duration Date Pulse Maxpulse Calories\n 0 60 '2020/12/01' 110 130 409.1\n 1 60 '2020/12/02' 117 145 479.0\n 2 60 '2020/12/03' 103 135 340.0\n 3 45 '2020/12/04' 109 175 282.4\n 4 45 '2020/12/05' 117 148 406.0\n 5 60 '2020/12/06' 102 127 300.0\n 6 60 '2020/12/07' 110 136 374.0\n 7 450 '2020/12/08' 104 134 253.3\n 8 30 '2020/12/09' 109 133 195.1\n 9 60 '2020/12/10' 98 124 269.0\n 10 60 '2020/12/11' 103 147 329.3\n 11 60 '2020/12/12' 100 120 250.7\n 12 60 '2020/12/12' 100 120 250.7\n 13 60 '2020/12/13' 106 128 345.3\n 14 60 '2020/12/14' 104 132 379.3\n 15 60 '2020/12/15' 98 123 275.0\n 16 60 '2020/12/16' 98 120 215.2\n 17 60 '2020/12/17' 100 120 300.0\n 18 45 '2020/12/18' 90 112 NaN\n 19 60 '2020/12/19' 103 123 323.0\n 20 45 '2020/12/20' 97 125 243.0\n 21 60 '2020/12/21' 108 131 364.2\n 22 45 NaN 100 119 282.0\n 23 60 '2020/12/23' 130 101 300.0\n 24 45 '2020/12/24' 105 132 246.0\n 25 60 '2020/12/25' 102 126 334.5\n 26 60 20201226 100 120 250.0\n 27 60 '2020/12/27' 92 118 241.0\n 28 60 '2020/12/28' 103 132 NaN\n 29 60 '2020/12/29' 100 132 280.0\n 30 60 '2020/12/30' 102 129 380.3\n 31 60 '2020/12/31' 92 115 243.0\n\n"
},
{
"code": null,
"e": 2010,
"s": 1922,
"text": "By taking a look at our test data set, we can assume that row 11 and 12 are duplicates."
},
{
"code": null,
"e": 2070,
"s": 2010,
"text": "To discover duplicates, we can use the duplicated() method."
},
{
"code": null,
"e": 2133,
"s": 2070,
"text": "The duplicated() method returns a Boolean values for each row:"
},
{
"code": null,
"e": 2199,
"s": 2133,
"text": "Returns True for every row that is a duplicate, othwerwise False:"
},
{
"code": null,
"e": 2255,
"s": 2199,
"text": "To remove duplicates, use the drop_duplicates() method."
},
{
"code": null,
"e": 2278,
"s": 2255,
"text": "Remove all duplicates:"
},
{
"code": null,
"e": 2442,
"s": 2278,
"text": "Remember: The (inplace = True) will \n make sure that the method does NOT return a new DataFrame, but it will remove all \n duplicates from the original DataFrame."
},
{
"code": null,
"e": 2504,
"s": 2442,
"text": "Insert the correct syntax for removing rows with empty cells."
},
{
"code": null,
"e": 2511,
"s": 2504,
"text": "df.()\n"
},
{
"code": null,
"e": 2530,
"s": 2511,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2563,
"s": 2530,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2605,
"s": 2563,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2712,
"s": 2605,
"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": 2731,
"s": 2712,
"text": "[email protected]"
}
] |
Draw Histogram with Logarithmic Scale in R - GeeksforGeeks | 30 May, 2021
R is a programming language, mainly used for statistical computing and graphics. It implements various statistical techniques including linear modeling, classification, time series analysis, and clustering. A Histogram is commonly used to depict the frequency distribution of variables. It also is often used to summarize both continuous and discrete data. Unlike the bar chart where the frequency is indicated by the height of the bars, here the frequency is indicated by the area of the bar.
In this article, we will see how to draw a histogram with a Logarithmic scale in R Programming Language.
Method 1: Using Base R
The hist() function to create histograms.
Syntax:
Syntax : hist( v, main, xlab, xlim, ylim, breaks, col, border)
If we want to convert the values of our histogram to a logarithmic scale, we can use the log() function within the hist() function as shown below:
hist(log(v))
v : The vector containing the numeric values to be used in histogram.
Example 1: Creating a Normal Histogram
A vector ‘A’ is taken which contains the numerical values to be used by the histogram. The vector ‘A‘ is plotted using the hist() function, the title of the plot is set to “Histogram” using the main parameter.
R
# Code for Plotting A Normal Histogram# Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogramhist(A, main = "Histogram")
Output:
Example 2: Creating a Histogram with Logarithmic Scale in R
A vector ‘A‘ is taken which contains the numerical values to be used by the histogram, the vector ‘A‘ is plotted using the log() function inside the hist() function.
The title of the plot is set to “Histogram”, the color of the bar is set to “green”, border color of the bar is set to “red” and the xlabel is set to “Logarithmic Scale” using the main, col, border, xlab parameters respectively.
Code:
R
# Code for Plotting A Histogram in# the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 20, 20, 20, 20, 30, 30) # Plot the histogramhist(log(A), main = "Histogram", col = "green", border = "red", xlab = "Logarithmic Scale")
Output:
Method 2: Using ggplot2 Package
Install ggplot2 package using the install.packages() and Load the ggplot2 package using the library().
# Install & load ggplot2 package
install.packages("ggplot2")
library("ggplot2")
The ggplot2 is an R package dedicated to data visualization. With the ggplot2 package, we can plot almost any type of chart.
Syntax: ggplot(data.frame(x), aes(x)) + geom_histogram()
x is the vector which contains the numerical values to be used by the histogram.
data.frame(x) creates a data frame from the given data
aes(x) is often used within other graphing elements to specify the desired aesthetics
geom_histogram() is used to plot the histogram
Creating a Normal Histogram:
A vector “A” is taken which contains the numerical values to be used by the histogram.The histogram is plotted using the function ggplot() function and the geom_histogram() function
A vector “A” is taken which contains the numerical values to be used by the histogram.
The histogram is plotted using the function ggplot() function and the geom_histogram() function
Example:
R
library("ggplot2") # Code for Plotting A Histogram in # the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogram# The bins parameter divides the plot# into 5 parts/barsggplot(data.frame(A), aes(A)) + geom_histogram(bins = 5)
Output:
Method 3: Using ggplot2 Package and log() function.
If we want to convert the values of our histogram to a logarithmic scale, we can use the log() function within the ggplot() and geom_histogram() function as shown below:
Syntax: ggplot(data.frame(log(x)), aes(log(x))) + geom_histogram()
x is the vector which contains the numerical values to be used by the histogram.
data.frame(log(x)) creates a data frame from log(x)
aes(log(x)) is often used within other graphing elements to specify the desired aesthetics
geom_histogram() is used to plot the histogram
A vector ‘A‘ is taken which contains the numerical values to be used by the histogram. Transform x-axis to logarithmic scale using log() function, plot the vector ‘A‘ using the ggplot() function, log() function and geom_histogram() function. The color of the bars is set to green and the border color is set to red using fill and color respectively.
R
library("ggplot2") # Code for Plotting A Histogram in # the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogram# The bins parameter divides the plot # into 5 parts/barsggplot(data.frame(log(A)), aes(log(A))) + geom_histogram(bins = 5)
Output:
Method 4: Using ggplot2 Package and scale_x_log10() function.
If we want to convert the values of our histogram to a logarithmic scale, we can use the scale_x_log10() function along with the ggplot() and geom_histogram() function as shown below:
Syntax: ggplot(data.frame(x), aes(x)) + geom_histogram() + scale_x_log10()
Parameters:
x is the vector which contains the numerical values to be used by the histogram.
data.frame(x) creates a data frame from x.
aes(x) is often used within other graphing elements to specify the desired aesthetics
geom_histogram() is used to plot the histogram
scale_x_log10() is used to convert the x-axis to logarithmic scale
A vector ‘A‘ is taken which contains the numerical values to be used by the histogram. Plot the vector ‘A‘ using the ggplot() function, scale_x_log10() function and geom_histogram() function, The color of the bars is set to green and the border colour is set to red using fill and color respectively.
R
library("ggplot2") # Code for Plotting A Histogram in # the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogram# The bins parameter divides the# plot into 6 parts/barsggplot(data.frame(A), aes(A)) +geom_histogram(color = "red", fill = "green", bins = 6) +scale_x_log10()
Output:
Picked
R-Charts
R-ggplot
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Data Visualization in R
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 25656,
"s": 25162,
"text": "R is a programming language, mainly used for statistical computing and graphics. It implements various statistical techniques including linear modeling, classification, time series analysis, and clustering. A Histogram is commonly used to depict the frequency distribution of variables. It also is often used to summarize both continuous and discrete data. Unlike the bar chart where the frequency is indicated by the height of the bars, here the frequency is indicated by the area of the bar."
},
{
"code": null,
"e": 25761,
"s": 25656,
"text": "In this article, we will see how to draw a histogram with a Logarithmic scale in R Programming Language."
},
{
"code": null,
"e": 25784,
"s": 25761,
"text": "Method 1: Using Base R"
},
{
"code": null,
"e": 25827,
"s": 25784,
"text": "The hist() function to create histograms. "
},
{
"code": null,
"e": 25835,
"s": 25827,
"text": "Syntax:"
},
{
"code": null,
"e": 25898,
"s": 25835,
"text": "Syntax : hist( v, main, xlab, xlim, ylim, breaks, col, border)"
},
{
"code": null,
"e": 26045,
"s": 25898,
"text": "If we want to convert the values of our histogram to a logarithmic scale, we can use the log() function within the hist() function as shown below:"
},
{
"code": null,
"e": 26058,
"s": 26045,
"text": "hist(log(v))"
},
{
"code": null,
"e": 26128,
"s": 26058,
"text": "v : The vector containing the numeric values to be used in histogram."
},
{
"code": null,
"e": 26167,
"s": 26128,
"text": "Example 1: Creating a Normal Histogram"
},
{
"code": null,
"e": 26377,
"s": 26167,
"text": "A vector ‘A’ is taken which contains the numerical values to be used by the histogram. The vector ‘A‘ is plotted using the hist() function, the title of the plot is set to “Histogram” using the main parameter."
},
{
"code": null,
"e": 26379,
"s": 26377,
"text": "R"
},
{
"code": "# Code for Plotting A Normal Histogram# Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogramhist(A, main = \"Histogram\")",
"e": 26550,
"s": 26379,
"text": null
},
{
"code": null,
"e": 26558,
"s": 26550,
"text": "Output:"
},
{
"code": null,
"e": 26618,
"s": 26558,
"text": "Example 2: Creating a Histogram with Logarithmic Scale in R"
},
{
"code": null,
"e": 26784,
"s": 26618,
"text": "A vector ‘A‘ is taken which contains the numerical values to be used by the histogram, the vector ‘A‘ is plotted using the log() function inside the hist() function."
},
{
"code": null,
"e": 27013,
"s": 26784,
"text": "The title of the plot is set to “Histogram”, the color of the bar is set to “green”, border color of the bar is set to “red” and the xlabel is set to “Logarithmic Scale” using the main, col, border, xlab parameters respectively."
},
{
"code": null,
"e": 27019,
"s": 27013,
"text": "Code:"
},
{
"code": null,
"e": 27021,
"s": 27019,
"text": "R"
},
{
"code": "# Code for Plotting A Histogram in# the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 20, 20, 20, 20, 30, 30) # Plot the histogramhist(log(A), main = \"Histogram\", col = \"green\", border = \"red\", xlab = \"Logarithmic Scale\")",
"e": 27285,
"s": 27021,
"text": null
},
{
"code": null,
"e": 27293,
"s": 27285,
"text": "Output:"
},
{
"code": null,
"e": 27325,
"s": 27293,
"text": "Method 2: Using ggplot2 Package"
},
{
"code": null,
"e": 27428,
"s": 27325,
"text": "Install ggplot2 package using the install.packages() and Load the ggplot2 package using the library()."
},
{
"code": null,
"e": 27508,
"s": 27428,
"text": "# Install & load ggplot2 package\ninstall.packages(\"ggplot2\")\nlibrary(\"ggplot2\")"
},
{
"code": null,
"e": 27634,
"s": 27508,
"text": "The ggplot2 is an R package dedicated to data visualization. With the ggplot2 package, we can plot almost any type of chart. "
},
{
"code": null,
"e": 27691,
"s": 27634,
"text": "Syntax: ggplot(data.frame(x), aes(x)) + geom_histogram()"
},
{
"code": null,
"e": 27772,
"s": 27691,
"text": "x is the vector which contains the numerical values to be used by the histogram."
},
{
"code": null,
"e": 27827,
"s": 27772,
"text": "data.frame(x) creates a data frame from the given data"
},
{
"code": null,
"e": 27913,
"s": 27827,
"text": "aes(x) is often used within other graphing elements to specify the desired aesthetics"
},
{
"code": null,
"e": 27960,
"s": 27913,
"text": "geom_histogram() is used to plot the histogram"
},
{
"code": null,
"e": 27989,
"s": 27960,
"text": "Creating a Normal Histogram:"
},
{
"code": null,
"e": 28171,
"s": 27989,
"text": "A vector “A” is taken which contains the numerical values to be used by the histogram.The histogram is plotted using the function ggplot() function and the geom_histogram() function"
},
{
"code": null,
"e": 28258,
"s": 28171,
"text": "A vector “A” is taken which contains the numerical values to be used by the histogram."
},
{
"code": null,
"e": 28354,
"s": 28258,
"text": "The histogram is plotted using the function ggplot() function and the geom_histogram() function"
},
{
"code": null,
"e": 28363,
"s": 28354,
"text": "Example:"
},
{
"code": null,
"e": 28365,
"s": 28363,
"text": "R"
},
{
"code": "library(\"ggplot2\") # Code for Plotting A Histogram in # the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogram# The bins parameter divides the plot# into 5 parts/barsggplot(data.frame(A), aes(A)) + geom_histogram(bins = 5)",
"e": 28663,
"s": 28365,
"text": null
},
{
"code": null,
"e": 28671,
"s": 28663,
"text": "Output:"
},
{
"code": null,
"e": 28723,
"s": 28671,
"text": "Method 3: Using ggplot2 Package and log() function."
},
{
"code": null,
"e": 28893,
"s": 28723,
"text": "If we want to convert the values of our histogram to a logarithmic scale, we can use the log() function within the ggplot() and geom_histogram() function as shown below:"
},
{
"code": null,
"e": 28960,
"s": 28893,
"text": "Syntax: ggplot(data.frame(log(x)), aes(log(x))) + geom_histogram()"
},
{
"code": null,
"e": 29041,
"s": 28960,
"text": "x is the vector which contains the numerical values to be used by the histogram."
},
{
"code": null,
"e": 29093,
"s": 29041,
"text": "data.frame(log(x)) creates a data frame from log(x)"
},
{
"code": null,
"e": 29184,
"s": 29093,
"text": "aes(log(x)) is often used within other graphing elements to specify the desired aesthetics"
},
{
"code": null,
"e": 29231,
"s": 29184,
"text": "geom_histogram() is used to plot the histogram"
},
{
"code": null,
"e": 29581,
"s": 29231,
"text": "A vector ‘A‘ is taken which contains the numerical values to be used by the histogram. Transform x-axis to logarithmic scale using log() function, plot the vector ‘A‘ using the ggplot() function, log() function and geom_histogram() function. The color of the bars is set to green and the border color is set to red using fill and color respectively."
},
{
"code": null,
"e": 29583,
"s": 29581,
"text": "R"
},
{
"code": "library(\"ggplot2\") # Code for Plotting A Histogram in # the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogram# The bins parameter divides the plot # into 5 parts/barsggplot(data.frame(log(A)), aes(log(A))) + geom_histogram(bins = 5)",
"e": 29900,
"s": 29583,
"text": null
},
{
"code": null,
"e": 29908,
"s": 29900,
"text": "Output:"
},
{
"code": null,
"e": 29970,
"s": 29908,
"text": "Method 4: Using ggplot2 Package and scale_x_log10() function."
},
{
"code": null,
"e": 30154,
"s": 29970,
"text": "If we want to convert the values of our histogram to a logarithmic scale, we can use the scale_x_log10() function along with the ggplot() and geom_histogram() function as shown below:"
},
{
"code": null,
"e": 30229,
"s": 30154,
"text": "Syntax: ggplot(data.frame(x), aes(x)) + geom_histogram() + scale_x_log10()"
},
{
"code": null,
"e": 30241,
"s": 30229,
"text": "Parameters:"
},
{
"code": null,
"e": 30322,
"s": 30241,
"text": "x is the vector which contains the numerical values to be used by the histogram."
},
{
"code": null,
"e": 30365,
"s": 30322,
"text": "data.frame(x) creates a data frame from x."
},
{
"code": null,
"e": 30451,
"s": 30365,
"text": "aes(x) is often used within other graphing elements to specify the desired aesthetics"
},
{
"code": null,
"e": 30498,
"s": 30451,
"text": "geom_histogram() is used to plot the histogram"
},
{
"code": null,
"e": 30565,
"s": 30498,
"text": "scale_x_log10() is used to convert the x-axis to logarithmic scale"
},
{
"code": null,
"e": 30866,
"s": 30565,
"text": "A vector ‘A‘ is taken which contains the numerical values to be used by the histogram. Plot the vector ‘A‘ using the ggplot() function, scale_x_log10() function and geom_histogram() function, The color of the bars is set to green and the border colour is set to red using fill and color respectively."
},
{
"code": null,
"e": 30868,
"s": 30866,
"text": "R"
},
{
"code": "library(\"ggplot2\") # Code for Plotting A Histogram in # the Logarithmic Scale # Create data for the HistogramA <- c(10, 10, 10, 20, 15, 15, 20, 20, 20, 20) # Plot the histogram# The bins parameter divides the# plot into 6 parts/barsggplot(data.frame(A), aes(A)) +geom_histogram(color = \"red\", fill = \"green\", bins = 6) +scale_x_log10()",
"e": 31215,
"s": 30868,
"text": null
},
{
"code": null,
"e": 31223,
"s": 31215,
"text": "Output:"
},
{
"code": null,
"e": 31230,
"s": 31223,
"text": "Picked"
},
{
"code": null,
"e": 31239,
"s": 31230,
"text": "R-Charts"
},
{
"code": null,
"e": 31248,
"s": 31239,
"text": "R-ggplot"
},
{
"code": null,
"e": 31257,
"s": 31248,
"text": "R-Graphs"
},
{
"code": null,
"e": 31265,
"s": 31257,
"text": "R-plots"
},
{
"code": null,
"e": 31276,
"s": 31265,
"text": "R Language"
},
{
"code": null,
"e": 31374,
"s": 31276,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31383,
"s": 31374,
"text": "Comments"
},
{
"code": null,
"e": 31396,
"s": 31383,
"text": "Old Comments"
},
{
"code": null,
"e": 31448,
"s": 31396,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 31486,
"s": 31448,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 31521,
"s": 31486,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 31579,
"s": 31521,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 31603,
"s": 31579,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 31640,
"s": 31603,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 31683,
"s": 31640,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 31733,
"s": 31683,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 31770,
"s": 31733,
"text": "How to import an Excel File into R ?"
}
] |
PHP - Function scandir() | array scandir ( string $directory [, int $sorting_order [, resource $context]] );
It returns an array of files and directories from the passed directory.
directory(Required)
The directory that will be scanned.
sorting_order(Optional)
It specifies the sort order. Default is 0 (ascending). If set to 1, it indicates descending order.
context(Optional)
It specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream.
It returns an array of filenames on success, or FALSE on failure.
Following is the usage of this function −
<?php
$dir = '/newfolder';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
?>
This will produce the following result −
Array (
[0] => .
[1] => ..
[2] => abc.php
[3] => bbc.txt
[4] => somedir
)
Array (
[0] => somedir
[1] => indiabbc.txt
[2] => status999.php
[3] => ..
[4] => .
)
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2840,
"s": 2757,
"text": "array scandir ( string $directory [, int $sorting_order [, resource $context]] );\n"
},
{
"code": null,
"e": 2913,
"s": 2840,
"text": "It returns an array of files and directories from the passed directory."
},
{
"code": null,
"e": 2933,
"s": 2913,
"text": "directory(Required)"
},
{
"code": null,
"e": 2969,
"s": 2933,
"text": "The directory that will be scanned."
},
{
"code": null,
"e": 2993,
"s": 2969,
"text": "sorting_order(Optional)"
},
{
"code": null,
"e": 3092,
"s": 2993,
"text": "It specifies the sort order. Default is 0 (ascending). If set to 1, it indicates descending order."
},
{
"code": null,
"e": 3110,
"s": 3092,
"text": "context(Optional)"
},
{
"code": null,
"e": 3230,
"s": 3110,
"text": "It specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream."
},
{
"code": null,
"e": 3296,
"s": 3230,
"text": "It returns an array of filenames on success, or FALSE on failure."
},
{
"code": null,
"e": 3338,
"s": 3296,
"text": "Following is the usage of this function −"
},
{
"code": null,
"e": 3480,
"s": 3338,
"text": "<?php\n $dir = '/newfolder';\n $files1 = scandir($dir);\n $files2 = scandir($dir, 1);\n \n print_r($files1);\n print_r($files2);\n?> "
},
{
"code": null,
"e": 3521,
"s": 3480,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3711,
"s": 3521,
"text": "Array (\n [0] => .\n [1] => ..\n [2] => abc.php\n [3] => bbc.txt\n [4] => somedir\n)\nArray (\n [0] => somedir\n [1] => indiabbc.txt\n [2] => status999.php\n [3] => ..\n [4] => .\n)\n"
},
{
"code": null,
"e": 3744,
"s": 3711,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 3760,
"s": 3744,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3793,
"s": 3760,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3804,
"s": 3793,
"text": " Syed Raza"
},
{
"code": null,
"e": 3839,
"s": 3804,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3856,
"s": 3839,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3889,
"s": 3856,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3904,
"s": 3889,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 3939,
"s": 3904,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 3951,
"s": 3939,
"text": " Azaz Patel"
},
{
"code": null,
"e": 3986,
"s": 3951,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4014,
"s": 3986,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4021,
"s": 4014,
"text": " Print"
},
{
"code": null,
"e": 4032,
"s": 4021,
"text": " Add Notes"
}
] |
Performing total of a column in a temporary column in SAP | You need to perform select again on your query. Here is the sample
SELECT DATE, FUND_ID, PPT_ID, SOURCE_ID, AMOUNT, SUM (AMOUNT) as TOTAL
FROM (
SELECT
AD.CHV_DATE.DATE,
AD.CHV_FUND.FUND_ID,
AD.CHV_PARTICT.PPT_ID,
AD.CHV_PARTICT.SOURCE_ID,
SUM (AD.CHV_PARTICT.AMOUNT),
FROM
AD.CHV_DATE,
AD.CHV_FUND,
AD.CHV_PARTICT,
AD.CHV_SOURCE
WHERE
DC.CHV_SOURCE.FUND_ID=AD.CHV_FUND.FUND_ID
AND (DC.CHV_SOURCE.DATE=AD.CHV_DATE.DATE)
AND (DC.CHV_PARTICT.PPT_ID=AD.CHV_SOURCE.PPT_ID)
AND (
AD.CHV_DATE.DATE IN ('2017-08-02')
AND
AD.CHV_PARTICT.PPT_ID IN ('PPT0449')
)
GROUP BY
AD.CHV_DATE.DATE,
AD.CHV_FUND.FUND_ID,
AD.CHV_PARTICT.PPT_ID,
AD.CHV_SOURCE.SOURCE_ID)
GROUP by DATE, FUND_ID, PPT_ID, SOURCE_ID, AMOUNT | [
{
"code": null,
"e": 1129,
"s": 1062,
"text": "You need to perform select again on your query. Here is the sample"
},
{
"code": null,
"e": 1817,
"s": 1129,
"text": "SELECT DATE, FUND_ID, PPT_ID, SOURCE_ID, AMOUNT, SUM (AMOUNT) as TOTAL\nFROM (\n SELECT\n AD.CHV_DATE.DATE,\n AD.CHV_FUND.FUND_ID,\n AD.CHV_PARTICT.PPT_ID,\n AD.CHV_PARTICT.SOURCE_ID,\n SUM (AD.CHV_PARTICT.AMOUNT),\nFROM\n AD.CHV_DATE,\n AD.CHV_FUND,\n AD.CHV_PARTICT,\n AD.CHV_SOURCE\nWHERE\n DC.CHV_SOURCE.FUND_ID=AD.CHV_FUND.FUND_ID\nAND (DC.CHV_SOURCE.DATE=AD.CHV_DATE.DATE)\nAND (DC.CHV_PARTICT.PPT_ID=AD.CHV_SOURCE.PPT_ID)\nAND (\n AD.CHV_DATE.DATE IN ('2017-08-02') \n AND\n AD.CHV_PARTICT.PPT_ID IN ('PPT0449')\n)\nGROUP BY\n AD.CHV_DATE.DATE,\n AD.CHV_FUND.FUND_ID,\n AD.CHV_PARTICT.PPT_ID,\n AD.CHV_SOURCE.SOURCE_ID)\nGROUP by DATE, FUND_ID, PPT_ID, SOURCE_ID, AMOUNT"
}
] |
Java Program to get the count of child nodes of any node in JTree | Use the getChildCount() method in Java to get the count of child nosed of any node i.e. even if it’s a root node or not.
Let’s say we want the count of child nodes for node 1, which is not a root node, therefore −
node1.getChildCount()
The following is an example to get the count of child nodes of any node −
package my;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class SwingDemo {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Demo");
DefaultMutableTreeNode node = new DefaultMutableTreeNode("Website");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Videos");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Tutorials");
DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("QA");
DefaultMutableTreeNode node4 = new DefaultMutableTreeNode("Tools");
node.add(node1);
node.add(node2);
node.add(node3);
node.add(node4);
DefaultMutableTreeNode one = new DefaultMutableTreeNode("PHP Videos");
DefaultMutableTreeNode two = new DefaultMutableTreeNode("HTML5 Videos");
DefaultMutableTreeNode three = new DefaultMutableTreeNode("Blockchain Videos");
DefaultMutableTreeNode four = new DefaultMutableTreeNode("Java");
DefaultMutableTreeNode five = new DefaultMutableTreeNode("DBMS");
DefaultMutableTreeNode six = new DefaultMutableTreeNode("CSS");
DefaultMutableTreeNode seven = new DefaultMutableTreeNode("MongoDB");
DefaultMutableTreeNode eight = new DefaultMutableTreeNode("Python QA");
DefaultMutableTreeNode nine = new DefaultMutableTreeNode("jQuery QA");
DefaultMutableTreeNode ten = new DefaultMutableTreeNode("Photo Editing Tool");
node1.add(one);
node1.add(two);
node1.add(three);
node2.add(four);
node2.add(five);
node2.add(six);
node2.add(seven);
node3.add(eight);
node3.add(nine);
node4.add(ten);
JTree tree = new JTree(node);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.putClientProperty("JTree.lineStyle", "Angled");
System.out.println("Number of children of node1 (Videos) = " + node1.getChildCount());
System.out.println("Number of children of node2 (Tutorials) = " + node2.getChildCount());
System.out.println("Number of children of node3 (QA) = " + node3.getChildCount());
System.out.println("Number of children of node4 (Tools) = " + node4.getChildCount());
tree.setRowHeight(25);
frame.add(tree);
frame.setSize(600,450);
frame.setVisible(true);
}
}
The Console displays the count of each node −
The JTree is as follows | [
{
"code": null,
"e": 1183,
"s": 1062,
"text": "Use the getChildCount() method in Java to get the count of child nosed of any node i.e. even if it’s a root node or not."
},
{
"code": null,
"e": 1276,
"s": 1183,
"text": "Let’s say we want the count of child nodes for node 1, which is not a root node, therefore −"
},
{
"code": null,
"e": 1298,
"s": 1276,
"text": "node1.getChildCount()"
},
{
"code": null,
"e": 1372,
"s": 1298,
"text": "The following is an example to get the count of child nodes of any node −"
},
{
"code": null,
"e": 3751,
"s": 1372,
"text": "package my;\nimport javax.swing.JFrame;\nimport javax.swing.JTree;\nimport javax.swing.tree.DefaultMutableTreeNode;\npublic class SwingDemo {\n public static void main(String[] args) throws Exception {\n JFrame frame = new JFrame(\"Demo\");\n DefaultMutableTreeNode node = new DefaultMutableTreeNode(\"Website\");\n DefaultMutableTreeNode node1 = new DefaultMutableTreeNode(\"Videos\");\n DefaultMutableTreeNode node2 = new DefaultMutableTreeNode(\"Tutorials\");\n DefaultMutableTreeNode node3 = new DefaultMutableTreeNode(\"QA\");\n DefaultMutableTreeNode node4 = new DefaultMutableTreeNode(\"Tools\");\n node.add(node1);\n node.add(node2);\n node.add(node3);\n node.add(node4);\n DefaultMutableTreeNode one = new DefaultMutableTreeNode(\"PHP Videos\");\n DefaultMutableTreeNode two = new DefaultMutableTreeNode(\"HTML5 Videos\");\n DefaultMutableTreeNode three = new DefaultMutableTreeNode(\"Blockchain Videos\");\n DefaultMutableTreeNode four = new DefaultMutableTreeNode(\"Java\");\n DefaultMutableTreeNode five = new DefaultMutableTreeNode(\"DBMS\");\n DefaultMutableTreeNode six = new DefaultMutableTreeNode(\"CSS\");\n DefaultMutableTreeNode seven = new DefaultMutableTreeNode(\"MongoDB\");\n DefaultMutableTreeNode eight = new DefaultMutableTreeNode(\"Python QA\");\n DefaultMutableTreeNode nine = new DefaultMutableTreeNode(\"jQuery QA\");\n DefaultMutableTreeNode ten = new DefaultMutableTreeNode(\"Photo Editing Tool\");\n node1.add(one);\n node1.add(two);\n node1.add(three);\n node2.add(four);\n node2.add(five);\n node2.add(six);\n node2.add(seven);\n node3.add(eight);\n node3.add(nine);\n node4.add(ten);\n JTree tree = new JTree(node);\n for (int i = 0; i < tree.getRowCount(); i++) {\n tree.expandRow(i);\n }\n tree.putClientProperty(\"JTree.lineStyle\", \"Angled\");\n System.out.println(\"Number of children of node1 (Videos) = \" + node1.getChildCount());\n System.out.println(\"Number of children of node2 (Tutorials) = \" + node2.getChildCount());\n System.out.println(\"Number of children of node3 (QA) = \" + node3.getChildCount());\n System.out.println(\"Number of children of node4 (Tools) = \" + node4.getChildCount());\n tree.setRowHeight(25);\n frame.add(tree);\n frame.setSize(600,450);\n frame.setVisible(true);\n }\n}"
},
{
"code": null,
"e": 3797,
"s": 3751,
"text": "The Console displays the count of each node −"
},
{
"code": null,
"e": 3821,
"s": 3797,
"text": "The JTree is as follows"
}
] |
Set the width of an element to 75% in Bootstrap | To set the width of an element to 75%, use the .w-75 class in Bootstrap.
You can try to run the following code to set element’s width −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "container">
<h3>Set element width</h3>
<div class = "w-100 bg-danger">Normal width</div>
<div class = "w-75 bg-warning">Width is 75%</div>
</body>
</html> | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To set the width of an element to 75%, use the .w-75 class in Bootstrap."
},
{
"code": null,
"e": 1198,
"s": 1135,
"text": "You can try to run the following code to set element’s width −"
},
{
"code": null,
"e": 1208,
"s": 1198,
"text": "Live Demo"
},
{
"code": null,
"e": 1814,
"s": 1208,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <h3>Set element width</h3>\n <div class = \"w-100 bg-danger\">Normal width</div>\n <div class = \"w-75 bg-warning\">Width is 75%</div>\n </body>\n</html>"
}
] |
C++ Files and Streams | So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −
ofstream
This data type represents the output file stream and is used to create files and to write information to files.
ifstream
This data type represents the input file stream and is used to read information from files.
fstream
This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened.
ios::app
Append mode. All output to that file to be appended to the end.
ios::ate
Open a file for output and move the read/write control to the end of the file.
ios::in
Open a file for reading.
ios::out
Open a file for writing.
ios::trunc
If the file already exists, its contents will be truncated before opening the file.
You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile;
afile.open("file.dat", ios::out | ios::in );
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.
Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
When the above code is compiled and executed, it produces the following sample input and output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.
Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. Some examples of positioning the "get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
// position n bytes forward in fileObject
fileObject.seekg( n, ios::cur );
// position n bytes back from end of fileObject
fileObject.seekg( n, ios::end );
// position at end of fileObject
fileObject.seekg( 0, ios::end );
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2489,
"s": 2318,
"text": "So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively."
},
{
"code": null,
"e": 2649,
"s": 2489,
"text": "This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −"
},
{
"code": null,
"e": 2658,
"s": 2649,
"text": "ofstream"
},
{
"code": null,
"e": 2770,
"s": 2658,
"text": "This data type represents the output file stream and is used to create files and to write information to files."
},
{
"code": null,
"e": 2779,
"s": 2770,
"text": "ifstream"
},
{
"code": null,
"e": 2872,
"s": 2779,
"text": "This data type represents the input file stream and is used to read information from files."
},
{
"code": null,
"e": 2880,
"s": 2872,
"text": "fstream"
},
{
"code": null,
"e": 3082,
"s": 2880,
"text": "This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files."
},
{
"code": null,
"e": 3197,
"s": 3082,
"text": "To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file."
},
{
"code": null,
"e": 3406,
"s": 3197,
"text": "A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only."
},
{
"code": null,
"e": 3522,
"s": 3406,
"text": "Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects."
},
{
"code": null,
"e": 3576,
"s": 3522,
"text": "void open(const char *filename, ios::openmode mode);\n"
},
{
"code": null,
"e": 3765,
"s": 3576,
"text": "Here, the first argument specifies the name and location of the file to be opened and the second argument of the open() member function defines the mode in which the file should be opened."
},
{
"code": null,
"e": 3774,
"s": 3765,
"text": "ios::app"
},
{
"code": null,
"e": 3838,
"s": 3774,
"text": "Append mode. All output to that file to be appended to the end."
},
{
"code": null,
"e": 3847,
"s": 3838,
"text": "ios::ate"
},
{
"code": null,
"e": 3926,
"s": 3847,
"text": "Open a file for output and move the read/write control to the end of the file."
},
{
"code": null,
"e": 3934,
"s": 3926,
"text": "ios::in"
},
{
"code": null,
"e": 3959,
"s": 3934,
"text": "Open a file for reading."
},
{
"code": null,
"e": 3968,
"s": 3959,
"text": "ios::out"
},
{
"code": null,
"e": 3993,
"s": 3968,
"text": "Open a file for writing."
},
{
"code": null,
"e": 4004,
"s": 3993,
"text": "ios::trunc"
},
{
"code": null,
"e": 4088,
"s": 4004,
"text": "If the file already exists, its contents will be truncated before opening the file."
},
{
"code": null,
"e": 4293,
"s": 4088,
"text": "You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −"
},
{
"code": null,
"e": 4362,
"s": 4293,
"text": "ofstream outfile;\noutfile.open(\"file.dat\", ios::out | ios::trunc );\n"
},
{
"code": null,
"e": 4440,
"s": 4362,
"text": "Similar way, you can open a file for reading and writing purpose as follows −"
},
{
"code": null,
"e": 4502,
"s": 4440,
"text": "fstream afile;\nafile.open(\"file.dat\", ios::out | ios::in );\n"
},
{
"code": null,
"e": 4753,
"s": 4502,
"text": "When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination."
},
{
"code": null,
"e": 4870,
"s": 4753,
"text": "Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects."
},
{
"code": null,
"e": 4885,
"s": 4870,
"text": "void close();\n"
},
{
"code": null,
"e": 5166,
"s": 4885,
"text": "While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object."
},
{
"code": null,
"e": 5422,
"s": 5166,
"text": "You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object."
},
{
"code": null,
"e": 5649,
"s": 5422,
"text": "Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −"
},
{
"code": null,
"e": 6581,
"s": 5649,
"text": "#include <fstream>\n#include <iostream>\nusing namespace std;\n \nint main () {\n char data[100];\n\n // open a file in write mode.\n ofstream outfile;\n outfile.open(\"afile.dat\");\n\n cout << \"Writing to the file\" << endl;\n cout << \"Enter your name: \"; \n cin.getline(data, 100);\n\n // write inputted data into the file.\n outfile << data << endl;\n\n cout << \"Enter your age: \"; \n cin >> data;\n cin.ignore();\n \n // again write inputted data into the file.\n outfile << data << endl;\n\n // close the opened file.\n outfile.close();\n\n // open a file in read mode.\n ifstream infile; \n infile.open(\"afile.dat\"); \n \n cout << \"Reading from the file\" << endl; \n infile >> data; \n\n // write the data at the screen.\n cout << data << endl;\n \n // again read the data from the file and display it.\n infile >> data; \n cout << data << endl; \n\n // close the opened file.\n infile.close();\n\n return 0;\n}"
},
{
"code": null,
"e": 6679,
"s": 6581,
"text": "When the above code is compiled and executed, it produces the following sample input and output −"
},
{
"code": null,
"e": 6778,
"s": 6679,
"text": "$./a.out\nWriting to the file\nEnter your name: Zara\nEnter your age: 9\nReading from the file\nZara\n9\n"
},
{
"code": null,
"e": 6983,
"s": 6778,
"text": "Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement."
},
{
"code": null,
"e": 7172,
"s": 6983,
"text": "Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg (\"seek get\") for istream and seekp (\"seek put\") for ostream."
},
{
"code": null,
"e": 7534,
"s": 7172,
"text": "The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream."
},
{
"code": null,
"e": 7743,
"s": 7534,
"text": "The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. Some examples of positioning the \"get\" file-position pointer are −"
},
{
"code": null,
"e": 8053,
"s": 7743,
"text": "// position to the nth byte of fileObject (assumes ios::beg)\nfileObject.seekg( n );\n\n// position n bytes forward in fileObject\nfileObject.seekg( n, ios::cur );\n\n// position n bytes back from end of fileObject\nfileObject.seekg( n, ios::end );\n\n// position at end of fileObject\nfileObject.seekg( 0, ios::end );\n"
},
{
"code": null,
"e": 8090,
"s": 8053,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 8109,
"s": 8090,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8141,
"s": 8109,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 8164,
"s": 8141,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 8200,
"s": 8164,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 8217,
"s": 8200,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8252,
"s": 8217,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8269,
"s": 8252,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8304,
"s": 8269,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8321,
"s": 8304,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8356,
"s": 8321,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8373,
"s": 8356,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8380,
"s": 8373,
"text": " Print"
},
{
"code": null,
"e": 8391,
"s": 8380,
"text": " Add Notes"
}
] |
How to use a List as a key of a Dictionary in Python 3? | 17 May, 2020
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below .
If the Python dictionaries just iterate over their keys to check if the given keys are present or not it would take O(N) time. But python dictionaries take O(1) to check if the key is present or not. So, how dictionaries search the key, for every key it generates a hash value for the key and by this hash value, it can track its elements.
Lists are mutable objects which means that we can change values inside a list append or delete values of the list . So if a hash function is generated from a list and then the items of the lists changed the dictionary will generate a new hash value for this list and could not find it.
For example, If the list is a = [1, 2, 3, 4, 5] and supposes hash of a list is the sum of values inside the list. So hash(a) = 15. Now we append 6 to a . So a = [1, 2, 3, 4, 5, 6] hash(a) = 21. So hash value of a changed. Therefore it can not be found inside the dictionary.
Another problem is different lists with the same hash value. If b = [5, 5, 5] hash(b) = 15. So if a (From the above example with the same hash value) is present is inside the dictionary, and if we search for b. Then the dictionary may give us the wrong result.
We can change the list into immutable objects like string or tuple and then can use it as a key. Below is the implementation of the approach.
# Declaring a dictionaryd = {} # This is the list which we are # trying to use as a key to# the dictionarya =[1, 2, 3, 4, 5] # converting the list a to a stringp = str(a)d[p]= 1 # converting the list a to a tupleq = tuple(a) d[q]= 1 for key, value in d.items(): print(key, ':', value)
Output:
[1, 2, 3, 4, 5] : 1
(1, 2, 3, 4, 5) : 1
python-dict
Python
python-dict
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": "\n17 May, 2020"
},
{
"code": null,
"e": 337,
"s": 28,
"text": "In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below ."
},
{
"code": null,
"e": 677,
"s": 337,
"text": "If the Python dictionaries just iterate over their keys to check if the given keys are present or not it would take O(N) time. But python dictionaries take O(1) to check if the key is present or not. So, how dictionaries search the key, for every key it generates a hash value for the key and by this hash value, it can track its elements."
},
{
"code": null,
"e": 963,
"s": 677,
"text": "Lists are mutable objects which means that we can change values inside a list append or delete values of the list . So if a hash function is generated from a list and then the items of the lists changed the dictionary will generate a new hash value for this list and could not find it."
},
{
"code": null,
"e": 1238,
"s": 963,
"text": "For example, If the list is a = [1, 2, 3, 4, 5] and supposes hash of a list is the sum of values inside the list. So hash(a) = 15. Now we append 6 to a . So a = [1, 2, 3, 4, 5, 6] hash(a) = 21. So hash value of a changed. Therefore it can not be found inside the dictionary."
},
{
"code": null,
"e": 1499,
"s": 1238,
"text": "Another problem is different lists with the same hash value. If b = [5, 5, 5] hash(b) = 15. So if a (From the above example with the same hash value) is present is inside the dictionary, and if we search for b. Then the dictionary may give us the wrong result."
},
{
"code": null,
"e": 1643,
"s": 1499,
"text": "We can change the list into immutable objects like string or tuple and then can use it as a key. Below is the implementation of the approach. "
},
{
"code": "# Declaring a dictionaryd = {} # This is the list which we are # trying to use as a key to# the dictionarya =[1, 2, 3, 4, 5] # converting the list a to a stringp = str(a)d[p]= 1 # converting the list a to a tupleq = tuple(a) d[q]= 1 for key, value in d.items(): print(key, ':', value)",
"e": 1936,
"s": 1643,
"text": null
},
{
"code": null,
"e": 1945,
"s": 1936,
"text": " Output:"
},
{
"code": null,
"e": 1985,
"s": 1945,
"text": "[1, 2, 3, 4, 5] : 1\n(1, 2, 3, 4, 5) : 1"
},
{
"code": null,
"e": 1997,
"s": 1985,
"text": "python-dict"
},
{
"code": null,
"e": 2004,
"s": 1997,
"text": "Python"
},
{
"code": null,
"e": 2016,
"s": 2004,
"text": "python-dict"
},
{
"code": null,
"e": 2114,
"s": 2016,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2146,
"s": 2114,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2173,
"s": 2146,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2194,
"s": 2173,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2217,
"s": 2194,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2273,
"s": 2217,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2304,
"s": 2273,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2346,
"s": 2304,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2388,
"s": 2346,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2427,
"s": 2388,
"text": "Python | Get unique values from a list"
}
] |
Program to find Normal and Trace of a matrix | 07 Jul, 2022
Given a 2D matrix, the task is to find Trace and Normal of matrix.Normal of a matrix is defined as square root of sum of squares of matrix elements.Trace of a n x n square matrix is sum of diagonal elements.
Examples :
Input : mat[][] = {{7, 8, 9},
{6, 1, 2},
{5, 4, 3}};
Output : Normal = 16
Trace = 11
Explanation :
Normal = sqrt(7*7+ 8*8 + 9*9 + 6*6 +
1*1 + 2*2 + 5*5 + 4*4 + 3*3)
= 16
Trace = 7+1+3 = 11
Input :mat[][] = {{1, 2, 3},
{6, 4, 5},
{2, 1, 3}};
Output : Normal = 10
Trace = 8
Explanation :
Normal = sqrt(1*1 +2*2 + 3*3 + 6*6 + 4*4 +
5*5 + 2*2 + 1*1 + 3*3)
Trace = 8(1+4+3)
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find trace and normal// of given matrix#include<bits/stdc++.h>using namespace std; // Size of given matrixconst int MAX = 100; // Returns Normal of a matrix of size n x nint findNormal(int mat[][MAX], int n){ int sum = 0; for (int i=0; i<n; i++) for (int j=0; j<n; j++) sum += mat[i][j]*mat[i][j]; return sqrt(sum);} // Returns trace of a matrix of size n x nint findTrace(int mat[][MAX], int n){ int sum = 0; for (int i=0; i<n; i++) sum += mat[i][i]; return sum;} // Driven sourceint main(){ int mat[][MAX] = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; cout << "Trace of Matrix = " << findTrace(mat, 5) << endl; cout << "Normal of Matrix = " << findNormal(mat, 5) << endl; return 0;}
// Java program to find trace and normal// of given matrix import java.io.*; class GFG { // Size of given matrixstatic int MAX = 100; // Returns Normal of a matrix of size n x n static int findNormal(int mat[][], int n){ int sum = 0; for (int i=0; i<n; i++) for (int j=0; j<n; j++) sum += mat[i][j]*mat[i][j]; return (int)Math.sqrt(sum);} // Returns trace of a matrix of size n x n static int findTrace(int mat[][], int n){ int sum = 0; for (int i=0; i<n; i++) sum += mat[i][i]; return sum;} // Driven sourcepublic static void main (String[] args) { int mat[][] = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; System.out.println ("Trace of Matrix = " + findTrace(mat, 5)); System.out.println ("Normal of Matrix = " + findNormal(mat, 5)); }} // This code is contributed by vt_m.
# Python3 program to find trace and# normal of given matriximport math # Size of given matrixMAX = 100; # Returns Normal of a matrix# of size n x ndef findNormal(mat, n): sum = 0; for i in range(n): for j in range(n): sum += mat[i][j] * mat[i][j]; return math.floor(math.sqrt(sum)); # Returns trace of a matrix of# size n x ndef findTrace(mat, n): sum = 0; for i in range(n): sum += mat[i][i]; return sum; # Driver Codemat = [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]]; print("Trace of Matrix =", findTrace(mat, 5)); print("Normal of Matrix =", findNormal(mat, 5)); # This code is contributed by mits
// C# program to find trace and normal// of given matrixusing System; class GFG { // Returns Normal of a matrix of // size n x n static int findNormal(int [,]mat, int n) { int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += mat[i,j] * mat[i,j]; return (int)Math.Sqrt(sum); } // Returns trace of a matrix of size // n x n static int findTrace(int [,]mat, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += mat[i,i]; return sum; } // Driven source public static void Main () { int [,]mat = { {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; Console.Write ("Trace of Matrix = " + findTrace(mat, 5) + "\n"); Console.Write("Normal of Matrix = " + findNormal(mat, 5)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find trace and// normal of given matrix // Size of given matrix$MAX = 100; // Returns Normal of a// matrix of size n x nfunction findNormal($mat, $n){ $sum = 0; for ( $i = 0; $i < $n; $i++) for ( $j = 0; $j < $n; $j++) $sum += $mat[$i][$j] * $mat[$i][$j]; return floor(sqrt($sum));} // Returns trace of a// matrix of size n x nfunction findTrace( $mat, $n){ $sum = 0; for ( $i = 0; $i < $n; $i++) $sum += $mat[$i][$i]; return $sum;} // Driver Code$mat = array(array(1, 1, 1, 1, 1), array(2, 2, 2, 2, 2), array(3, 3, 3, 3, 3), array(4, 4, 4, 4, 4), array(5, 5, 5, 5, 5)); echo "Trace of Matrix = ", findTrace($mat, 5),"\n"; echo "Normal of Matrix = " , findNormal($mat, 5) ; // This code is contributed by anuj_67.?>
<script> // Javascript program to find trace// and normal of given matrix // Size of given matrixvar MAX = 100; // Returns Normal of a matrix of size n x nfunction findNormal(mat, n){ var sum = 0; for(var i = 0; i < n; i++) for(var j = 0; j < n; j++) sum += mat[i][j] * mat[i][j]; return parseInt(Math.sqrt(sum));} // Returns trace of a matrix of size n x nfunction findTrace(mat, n){ var sum = 0; for(var i = 0; i < n; i++) sum += mat[i][i]; return sum;} // Driver codevar mat = [ [ 1, 1, 1, 1, 1 ], [ 2, 2, 2, 2, 2 ], [ 3, 3, 3, 3, 3 ], [ 4, 4, 4, 4, 4 ], [ 5, 5, 5, 5, 5 ] ]; document.write("Trace of Matrix = " + findTrace(mat, 5) + "<br>");document.write("Normal of Matrix = " + findNormal(mat, 5)); // This code is contributed by Kirti </script>
Trace of Matrix = 15
Normal of Matrix = 16
Time Complexity : O(n*n) Space Complexity : O(1)
This article is contributed by DANISH_RAZA. 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.
nitin mittal
vt_m
Mithun Kumar
Kirti_Mangal
hardikkoriintern
Mathematical
Matrix
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 261,
"s": 53,
"text": "Given a 2D matrix, the task is to find Trace and Normal of matrix.Normal of a matrix is defined as square root of sum of squares of matrix elements.Trace of a n x n square matrix is sum of diagonal elements."
},
{
"code": null,
"e": 273,
"s": 261,
"text": "Examples : "
},
{
"code": null,
"e": 784,
"s": 273,
"text": "Input : mat[][] = {{7, 8, 9},\n {6, 1, 2},\n {5, 4, 3}};\nOutput : Normal = 16 \n Trace = 11\nExplanation : \nNormal = sqrt(7*7+ 8*8 + 9*9 + 6*6 +\n 1*1 + 2*2 + 5*5 + 4*4 + 3*3) \n = 16\nTrace = 7+1+3 = 11\n\nInput :mat[][] = {{1, 2, 3},\n {6, 4, 5},\n {2, 1, 3}};\nOutput : Normal = 10 \n Trace = 8\nExplanation : \nNormal = sqrt(1*1 +2*2 + 3*3 + 6*6 + 4*4 + \n 5*5 + 2*2 + 1*1 + 3*3) \nTrace = 8(1+4+3)"
},
{
"code": null,
"e": 800,
"s": 784,
"text": "Implementation:"
},
{
"code": null,
"e": 804,
"s": 800,
"text": "C++"
},
{
"code": null,
"e": 809,
"s": 804,
"text": "Java"
},
{
"code": null,
"e": 817,
"s": 809,
"text": "Python3"
},
{
"code": null,
"e": 820,
"s": 817,
"text": "C#"
},
{
"code": null,
"e": 824,
"s": 820,
"text": "PHP"
},
{
"code": null,
"e": 835,
"s": 824,
"text": "Javascript"
},
{
"code": "// C++ program to find trace and normal// of given matrix#include<bits/stdc++.h>using namespace std; // Size of given matrixconst int MAX = 100; // Returns Normal of a matrix of size n x nint findNormal(int mat[][MAX], int n){ int sum = 0; for (int i=0; i<n; i++) for (int j=0; j<n; j++) sum += mat[i][j]*mat[i][j]; return sqrt(sum);} // Returns trace of a matrix of size n x nint findTrace(int mat[][MAX], int n){ int sum = 0; for (int i=0; i<n; i++) sum += mat[i][i]; return sum;} // Driven sourceint main(){ int mat[][MAX] = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; cout << \"Trace of Matrix = \" << findTrace(mat, 5) << endl; cout << \"Normal of Matrix = \" << findNormal(mat, 5) << endl; return 0;}",
"e": 1686,
"s": 835,
"text": null
},
{
"code": "// Java program to find trace and normal// of given matrix import java.io.*; class GFG { // Size of given matrixstatic int MAX = 100; // Returns Normal of a matrix of size n x n static int findNormal(int mat[][], int n){ int sum = 0; for (int i=0; i<n; i++) for (int j=0; j<n; j++) sum += mat[i][j]*mat[i][j]; return (int)Math.sqrt(sum);} // Returns trace of a matrix of size n x n static int findTrace(int mat[][], int n){ int sum = 0; for (int i=0; i<n; i++) sum += mat[i][i]; return sum;} // Driven sourcepublic static void main (String[] args) { int mat[][] = {{1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; System.out.println (\"Trace of Matrix = \" + findTrace(mat, 5)); System.out.println (\"Normal of Matrix = \" + findNormal(mat, 5)); }} // This code is contributed by vt_m.",
"e": 2629,
"s": 1686,
"text": null
},
{
"code": "# Python3 program to find trace and# normal of given matriximport math # Size of given matrixMAX = 100; # Returns Normal of a matrix# of size n x ndef findNormal(mat, n): sum = 0; for i in range(n): for j in range(n): sum += mat[i][j] * mat[i][j]; return math.floor(math.sqrt(sum)); # Returns trace of a matrix of# size n x ndef findTrace(mat, n): sum = 0; for i in range(n): sum += mat[i][i]; return sum; # Driver Codemat = [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]]; print(\"Trace of Matrix =\", findTrace(mat, 5)); print(\"Normal of Matrix =\", findNormal(mat, 5)); # This code is contributed by mits",
"e": 3341,
"s": 2629,
"text": null
},
{
"code": "// C# program to find trace and normal// of given matrixusing System; class GFG { // Returns Normal of a matrix of // size n x n static int findNormal(int [,]mat, int n) { int sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += mat[i,j] * mat[i,j]; return (int)Math.Sqrt(sum); } // Returns trace of a matrix of size // n x n static int findTrace(int [,]mat, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += mat[i,i]; return sum; } // Driven source public static void Main () { int [,]mat = { {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, }; Console.Write (\"Trace of Matrix = \" + findTrace(mat, 5) + \"\\n\"); Console.Write(\"Normal of Matrix = \" + findNormal(mat, 5)); }} // This code is contributed by nitin mittal.",
"e": 4449,
"s": 3341,
"text": null
},
{
"code": "<?php// PHP program to find trace and// normal of given matrix // Size of given matrix$MAX = 100; // Returns Normal of a// matrix of size n x nfunction findNormal($mat, $n){ $sum = 0; for ( $i = 0; $i < $n; $i++) for ( $j = 0; $j < $n; $j++) $sum += $mat[$i][$j] * $mat[$i][$j]; return floor(sqrt($sum));} // Returns trace of a// matrix of size n x nfunction findTrace( $mat, $n){ $sum = 0; for ( $i = 0; $i < $n; $i++) $sum += $mat[$i][$i]; return $sum;} // Driver Code$mat = array(array(1, 1, 1, 1, 1), array(2, 2, 2, 2, 2), array(3, 3, 3, 3, 3), array(4, 4, 4, 4, 4), array(5, 5, 5, 5, 5)); echo \"Trace of Matrix = \", findTrace($mat, 5),\"\\n\"; echo \"Normal of Matrix = \" , findNormal($mat, 5) ; // This code is contributed by anuj_67.?>",
"e": 5305,
"s": 4449,
"text": null
},
{
"code": "<script> // Javascript program to find trace// and normal of given matrix // Size of given matrixvar MAX = 100; // Returns Normal of a matrix of size n x nfunction findNormal(mat, n){ var sum = 0; for(var i = 0; i < n; i++) for(var j = 0; j < n; j++) sum += mat[i][j] * mat[i][j]; return parseInt(Math.sqrt(sum));} // Returns trace of a matrix of size n x nfunction findTrace(mat, n){ var sum = 0; for(var i = 0; i < n; i++) sum += mat[i][i]; return sum;} // Driver codevar mat = [ [ 1, 1, 1, 1, 1 ], [ 2, 2, 2, 2, 2 ], [ 3, 3, 3, 3, 3 ], [ 4, 4, 4, 4, 4 ], [ 5, 5, 5, 5, 5 ] ]; document.write(\"Trace of Matrix = \" + findTrace(mat, 5) + \"<br>\");document.write(\"Normal of Matrix = \" + findNormal(mat, 5)); // This code is contributed by Kirti </script>",
"e": 6194,
"s": 5305,
"text": null
},
{
"code": null,
"e": 6237,
"s": 6194,
"text": "Trace of Matrix = 15\nNormal of Matrix = 16"
},
{
"code": null,
"e": 6286,
"s": 6237,
"text": "Time Complexity : O(n*n) Space Complexity : O(1)"
},
{
"code": null,
"e": 6582,
"s": 6286,
"text": "This article is contributed by DANISH_RAZA. 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. "
},
{
"code": null,
"e": 6595,
"s": 6582,
"text": "nitin mittal"
},
{
"code": null,
"e": 6600,
"s": 6595,
"text": "vt_m"
},
{
"code": null,
"e": 6613,
"s": 6600,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 6626,
"s": 6613,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 6643,
"s": 6626,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6656,
"s": 6643,
"text": "Mathematical"
},
{
"code": null,
"e": 6663,
"s": 6656,
"text": "Matrix"
},
{
"code": null,
"e": 6676,
"s": 6663,
"text": "Mathematical"
},
{
"code": null,
"e": 6683,
"s": 6676,
"text": "Matrix"
}
] |
Number of common digits present in two given numbers | 22 Apr, 2021
Given two positive numbers N and M, the task is to count the number of digits that are present in both N and M.
Examples:
Input: N = 748294, M = 34298156Output: 4Explanation: The digits that are present in both the numbers are {4, 8, 2, 9}. Therefore, the required count is 4.
Input: N = 111222, M = 333444Output: 0Explanation: No common digits present in the two given numbers.
Approach: The given problem can be solved using Hashing. Follow the steps below to solve the problem:
Initialize a variable, say count as 0, to store the number of digits that are common in both the numbers.
Initialize two arrays, say freq1[10] and freq2[10] as {0}, to store the count of digits present in the integers N and M respectively.
Iterate over the digits of the integer N and increment the count of each digit in freq1[] by 1.
Iterate over the digits of the integer M and increment the count of each digit in freq2[] by 1.
Iterate over the range [0, 9] and increment the count by 1 if freq1[i] and freq2[i] both exceeds 0.
Finally, after completing the above steps, print the count obtained as the required answer.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count number of digits// that are common in both N and Mint CommonDigits(int N, int M){ // Stores the count of common digits int count = 0; // Stores the count of digits of N int freq1[10] = { 0 }; // Stores the count of digits of M int freq2[10] = { 0 }; // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = N / 10; } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = M / 10; } // Iterate over the range [0, 9] for (int i = 0; i < 10; i++) { // If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver Codeint main(){ // Input int N = 748294; int M = 34298156; cout << CommonDigits(N, M); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to count number of digits// that are common in both N and Mstatic int CommonDigits(int N, int M){ // Stores the count of common digits int count = 0; // Stores the count of digits of N int freq1[] = new int[10]; // Stores the count of digits of M int freq2[] = new int[10]; // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = N / 10; } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = M / 10; } // Iterate over the range [0, 9] for(int i = 0; i < 10; i++) { // If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver Codepublic static void main(String[] args){ // Input int N = 748294; int M = 34298156; System.out.print(CommonDigits(N, M));}} // This code is contributed by gauravrajput1
# Python3 program for the above approach # Function to count number of digits# that are common in both N and Mdef CommonDigits(N, M): # Stores the count of common digits count = 0 # Stores the count of digits of N freq1 = [0] * 10 # Stores the count of digits of M freq2 = [0] * 10 # Iterate over the digits of N while (N > 0): # Increment the count of # last digit of N freq1[N % 10] += 1 # Update N N = N // 10 # Iterate over the digits of M while (M > 0): # Increment the count of # last digit of M freq2[M % 10] += 1 # Update M M = M // 10 # Iterate over the range [0, 9] for i in range(10): # If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 and freq2[i] > 0): # Increment count by 1 count += 1 # Return the count return count # Driver Codeif __name__ == '__main__': # Input N = 748294 M = 34298156 print (CommonDigits(N, M)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{ // Function to count number of digits// that are common in both N and Mstatic int CommonDigits(int N, int M){ // Stores the count of common digits int count = 0; // Stores the count of digits of N int[] freq1 = new int[10]; // Stores the count of digits of M int[] freq2 = new int[10]; // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = N / 10; } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = M / 10; } // Iterate over the range [0, 9] for(int i = 0; i < 10; i++) { // If freq1[i] and freq2[i] // both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver codestatic void Main(){ // Input int N = 748294; int M = 34298156; Console.WriteLine(CommonDigits(N, M));}} // This code is contributed by sanjoy_62
<script> // javascript program for the above approach // Function to count number of digits// that are common in both N and Mfunction CommonDigits(N,M){ // Stores the count of common digits var count = 0; // Stores the count of digits of N var freq1 = Array(10).fill(0); // Stores the count of digits of M var freq2 = Array(10).fill(0); // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = Math.floor(N / 10); } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = Math.floor(M / 10); } var i; // Iterate over the range [0, 9] for (i = 0; i < 10; i++) { // If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver Code // Input var N = 748294; var M = 34298156; document.write(CommonDigits(N, M)); </script>
4
Time Complexity: O(digits(N)+digits(M))Auxiliary Space: O(10)
mohit kumar 29
GauravRajput1
sanjoy_62
SURENDRA_GANGWAR
frequency-counting
number-digits
Hash
School Programming
Searching
Searching
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Real-time application of Data Structures
Find k numbers with most occurrences in the given array
Find the length of largest subarray with 0 sum
Non-Repeating Element
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 166,
"s": 54,
"text": "Given two positive numbers N and M, the task is to count the number of digits that are present in both N and M."
},
{
"code": null,
"e": 176,
"s": 166,
"text": "Examples:"
},
{
"code": null,
"e": 331,
"s": 176,
"text": "Input: N = 748294, M = 34298156Output: 4Explanation: The digits that are present in both the numbers are {4, 8, 2, 9}. Therefore, the required count is 4."
},
{
"code": null,
"e": 433,
"s": 331,
"text": "Input: N = 111222, M = 333444Output: 0Explanation: No common digits present in the two given numbers."
},
{
"code": null,
"e": 535,
"s": 433,
"text": "Approach: The given problem can be solved using Hashing. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 641,
"s": 535,
"text": "Initialize a variable, say count as 0, to store the number of digits that are common in both the numbers."
},
{
"code": null,
"e": 775,
"s": 641,
"text": "Initialize two arrays, say freq1[10] and freq2[10] as {0}, to store the count of digits present in the integers N and M respectively."
},
{
"code": null,
"e": 871,
"s": 775,
"text": "Iterate over the digits of the integer N and increment the count of each digit in freq1[] by 1."
},
{
"code": null,
"e": 967,
"s": 871,
"text": "Iterate over the digits of the integer M and increment the count of each digit in freq2[] by 1."
},
{
"code": null,
"e": 1067,
"s": 967,
"text": "Iterate over the range [0, 9] and increment the count by 1 if freq1[i] and freq2[i] both exceeds 0."
},
{
"code": null,
"e": 1159,
"s": 1067,
"text": "Finally, after completing the above steps, print the count obtained as the required answer."
},
{
"code": null,
"e": 1210,
"s": 1159,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1216,
"s": 1210,
"text": "C++14"
},
{
"code": null,
"e": 1221,
"s": 1216,
"text": "Java"
},
{
"code": null,
"e": 1229,
"s": 1221,
"text": "Python3"
},
{
"code": null,
"e": 1232,
"s": 1229,
"text": "C#"
},
{
"code": null,
"e": 1243,
"s": 1232,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count number of digits// that are common in both N and Mint CommonDigits(int N, int M){ // Stores the count of common digits int count = 0; // Stores the count of digits of N int freq1[10] = { 0 }; // Stores the count of digits of M int freq2[10] = { 0 }; // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = N / 10; } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = M / 10; } // Iterate over the range [0, 9] for (int i = 0; i < 10; i++) { // If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver Codeint main(){ // Input int N = 748294; int M = 34298156; cout << CommonDigits(N, M); return 0;}",
"e": 2381,
"s": 1243,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to count number of digits// that are common in both N and Mstatic int CommonDigits(int N, int M){ // Stores the count of common digits int count = 0; // Stores the count of digits of N int freq1[] = new int[10]; // Stores the count of digits of M int freq2[] = new int[10]; // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = N / 10; } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = M / 10; } // Iterate over the range [0, 9] for(int i = 0; i < 10; i++) { // If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver Codepublic static void main(String[] args){ // Input int N = 748294; int M = 34298156; System.out.print(CommonDigits(N, M));}} // This code is contributed by gauravrajput1",
"e": 3662,
"s": 2381,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count number of digits# that are common in both N and Mdef CommonDigits(N, M): # Stores the count of common digits count = 0 # Stores the count of digits of N freq1 = [0] * 10 # Stores the count of digits of M freq2 = [0] * 10 # Iterate over the digits of N while (N > 0): # Increment the count of # last digit of N freq1[N % 10] += 1 # Update N N = N // 10 # Iterate over the digits of M while (M > 0): # Increment the count of # last digit of M freq2[M % 10] += 1 # Update M M = M // 10 # Iterate over the range [0, 9] for i in range(10): # If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 and freq2[i] > 0): # Increment count by 1 count += 1 # Return the count return count # Driver Codeif __name__ == '__main__': # Input N = 748294 M = 34298156 print (CommonDigits(N, M)) # This code is contributed by mohit kumar 29",
"e": 4773,
"s": 3662,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to count number of digits// that are common in both N and Mstatic int CommonDigits(int N, int M){ // Stores the count of common digits int count = 0; // Stores the count of digits of N int[] freq1 = new int[10]; // Stores the count of digits of M int[] freq2 = new int[10]; // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = N / 10; } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = M / 10; } // Iterate over the range [0, 9] for(int i = 0; i < 10; i++) { // If freq1[i] and freq2[i] // both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver codestatic void Main(){ // Input int N = 748294; int M = 34298156; Console.WriteLine(CommonDigits(N, M));}} // This code is contributed by sanjoy_62",
"e": 6037,
"s": 4773,
"text": null
},
{
"code": "<script> // javascript program for the above approach // Function to count number of digits// that are common in both N and Mfunction CommonDigits(N,M){ // Stores the count of common digits var count = 0; // Stores the count of digits of N var freq1 = Array(10).fill(0); // Stores the count of digits of M var freq2 = Array(10).fill(0); // Iterate over the digits of N while (N > 0) { // Increment the count of // last digit of N freq1[N % 10]++; // Update N N = Math.floor(N / 10); } // Iterate over the digits of M while (M > 0) { // Increment the count of // last digit of M freq2[M % 10]++; // Update M M = Math.floor(M / 10); } var i; // Iterate over the range [0, 9] for (i = 0; i < 10; i++) { // If freq1[i] and freq2[i] both exceeds 0 if (freq1[i] > 0 & freq2[i] > 0) { // Increment count by 1 count++; } } // Return the count return count;} // Driver Code // Input var N = 748294; var M = 34298156; document.write(CommonDigits(N, M)); </script>",
"e": 7182,
"s": 6037,
"text": null
},
{
"code": null,
"e": 7184,
"s": 7182,
"text": "4"
},
{
"code": null,
"e": 7248,
"s": 7186,
"text": "Time Complexity: O(digits(N)+digits(M))Auxiliary Space: O(10)"
},
{
"code": null,
"e": 7265,
"s": 7250,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7279,
"s": 7265,
"text": "GauravRajput1"
},
{
"code": null,
"e": 7289,
"s": 7279,
"text": "sanjoy_62"
},
{
"code": null,
"e": 7306,
"s": 7289,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 7325,
"s": 7306,
"text": "frequency-counting"
},
{
"code": null,
"e": 7339,
"s": 7325,
"text": "number-digits"
},
{
"code": null,
"e": 7344,
"s": 7339,
"text": "Hash"
},
{
"code": null,
"e": 7363,
"s": 7344,
"text": "School Programming"
},
{
"code": null,
"e": 7373,
"s": 7363,
"text": "Searching"
},
{
"code": null,
"e": 7383,
"s": 7373,
"text": "Searching"
},
{
"code": null,
"e": 7388,
"s": 7383,
"text": "Hash"
},
{
"code": null,
"e": 7486,
"s": 7388,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7524,
"s": 7486,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 7565,
"s": 7524,
"text": "Real-time application of Data Structures"
},
{
"code": null,
"e": 7621,
"s": 7565,
"text": "Find k numbers with most occurrences in the given array"
},
{
"code": null,
"e": 7668,
"s": 7621,
"text": "Find the length of largest subarray with 0 sum"
},
{
"code": null,
"e": 7690,
"s": 7668,
"text": "Non-Repeating Element"
},
{
"code": null,
"e": 7708,
"s": 7690,
"text": "Python Dictionary"
},
{
"code": null,
"e": 7733,
"s": 7708,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 7749,
"s": 7733,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 7772,
"s": 7749,
"text": "Introduction To PYTHON"
}
] |
Difference between module.exports and exports in Node.js | 06 Jul, 2022
The module is a plain JavaScript Object representing the current module. It is local to each module and also it is private. It has exports property which is a plain JavaScript variable, set to module.exports. At the end of the file, Node.js return module.exports to the required function.
When we want to export a single class/variable/function from one module to another module, we use module.exports.
Example: Create two files calculator.js and operation.js and export the Arithmetic class from calculator.js to operation.js using module.exports method. Here, we have created a class Arithmetic and exported the whole class using module.exports.
Filename: calculator.js
Javascript
class Arithmetic { constructor(a, b) { this.a = a; this.b = b; } add() { return this.a + this.b; } subtract() { return this.a - this.b; } multiply() { return this.a * this.b; } divide() { if (this.b != 0) { return this.a / this.b; } return "divided by zero !!!!"; }}; module.exports = Arithmetic;
Filename: operation.js
Javascript
const Arithmetic = require('./calculator.js'); const op = new Arithmetic(100,40); console.log(`Addition -> ${op.add()}`);console.log(`subtraction -> ${op.subtract()}`);console.log(`Multiplication -> ${op.multiply()}`);console.log(`Division -> ${op.divide()}`);
Run the operation.js file using the following command:
node operation.js
Output:
Using module.exports
When we want to export multiple variables/functions from one module to another, we use exports.
Example: Create two files calculator.js and operation.js and export multiple functions from calculator.js file.
Filename: calculator.js
Javascript
exports.add = (a, b) => a + b;exports.subtract = (a, b) => a - b;exports.multiply = (a, b) => a * b;exports.divide = (a, b) => { if (b != 0) { return a / b; } return `Divided by zero !!!`;}
Filename: operation.js
Javascript
const Arithmetic = require('./calculator.js'); console.log(`Addition -> ${Arithmetic.add(100,40)}`);console.log(`subtraction -> ${Arithmetic.subtract(100,40)}`);console.log(`Multiplication -> ${Arithmetic.multiply(100,40)}`);console.log(`Division -> ${Arithmetic.divide(100,40)}`);
Run the operation.js file using the following command:
node operation.js
Output:
Using exports
Key differences between module.exports and exports:
S.no
Module.exports
Exports
1
2.
SAKSHIKULSHRESHTHA
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
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": "\n06 Jul, 2022"
},
{
"code": null,
"e": 317,
"s": 28,
"text": "The module is a plain JavaScript Object representing the current module. It is local to each module and also it is private. It has exports property which is a plain JavaScript variable, set to module.exports. At the end of the file, Node.js return module.exports to the required function."
},
{
"code": null,
"e": 431,
"s": 317,
"text": "When we want to export a single class/variable/function from one module to another module, we use module.exports."
},
{
"code": null,
"e": 676,
"s": 431,
"text": "Example: Create two files calculator.js and operation.js and export the Arithmetic class from calculator.js to operation.js using module.exports method. Here, we have created a class Arithmetic and exported the whole class using module.exports."
},
{
"code": null,
"e": 700,
"s": 676,
"text": "Filename: calculator.js"
},
{
"code": null,
"e": 711,
"s": 700,
"text": "Javascript"
},
{
"code": "class Arithmetic { constructor(a, b) { this.a = a; this.b = b; } add() { return this.a + this.b; } subtract() { return this.a - this.b; } multiply() { return this.a * this.b; } divide() { if (this.b != 0) { return this.a / this.b; } return \"divided by zero !!!!\"; }}; module.exports = Arithmetic;",
"e": 1108,
"s": 711,
"text": null
},
{
"code": null,
"e": 1131,
"s": 1108,
"text": "Filename: operation.js"
},
{
"code": null,
"e": 1142,
"s": 1131,
"text": "Javascript"
},
{
"code": "const Arithmetic = require('./calculator.js'); const op = new Arithmetic(100,40); console.log(`Addition -> ${op.add()}`);console.log(`subtraction -> ${op.subtract()}`);console.log(`Multiplication -> ${op.multiply()}`);console.log(`Division -> ${op.divide()}`);",
"e": 1403,
"s": 1142,
"text": null
},
{
"code": null,
"e": 1458,
"s": 1403,
"text": "Run the operation.js file using the following command:"
},
{
"code": null,
"e": 1476,
"s": 1458,
"text": "node operation.js"
},
{
"code": null,
"e": 1484,
"s": 1476,
"text": "Output:"
},
{
"code": null,
"e": 1506,
"s": 1484,
"text": "Using module.exports "
},
{
"code": null,
"e": 1602,
"s": 1506,
"text": "When we want to export multiple variables/functions from one module to another, we use exports."
},
{
"code": null,
"e": 1715,
"s": 1602,
"text": "Example: Create two files calculator.js and operation.js and export multiple functions from calculator.js file. "
},
{
"code": null,
"e": 1739,
"s": 1715,
"text": "Filename: calculator.js"
},
{
"code": null,
"e": 1750,
"s": 1739,
"text": "Javascript"
},
{
"code": "exports.add = (a, b) => a + b;exports.subtract = (a, b) => a - b;exports.multiply = (a, b) => a * b;exports.divide = (a, b) => { if (b != 0) { return a / b; } return `Divided by zero !!!`;}",
"e": 1956,
"s": 1750,
"text": null
},
{
"code": null,
"e": 1979,
"s": 1956,
"text": "Filename: operation.js"
},
{
"code": null,
"e": 1990,
"s": 1979,
"text": "Javascript"
},
{
"code": "const Arithmetic = require('./calculator.js'); console.log(`Addition -> ${Arithmetic.add(100,40)}`);console.log(`subtraction -> ${Arithmetic.subtract(100,40)}`);console.log(`Multiplication -> ${Arithmetic.multiply(100,40)}`);console.log(`Division -> ${Arithmetic.divide(100,40)}`);",
"e": 2272,
"s": 1990,
"text": null
},
{
"code": null,
"e": 2327,
"s": 2272,
"text": "Run the operation.js file using the following command:"
},
{
"code": null,
"e": 2345,
"s": 2327,
"text": "node operation.js"
},
{
"code": null,
"e": 2353,
"s": 2345,
"text": "Output:"
},
{
"code": null,
"e": 2367,
"s": 2353,
"text": "Using exports"
},
{
"code": null,
"e": 2420,
"s": 2367,
"text": "Key differences between module.exports and exports: "
},
{
"code": null,
"e": 2425,
"s": 2420,
"text": "S.no"
},
{
"code": null,
"e": 2440,
"s": 2425,
"text": "Module.exports"
},
{
"code": null,
"e": 2448,
"s": 2440,
"text": "Exports"
},
{
"code": null,
"e": 2450,
"s": 2448,
"text": "1"
},
{
"code": null,
"e": 2453,
"s": 2450,
"text": "2."
},
{
"code": null,
"e": 2472,
"s": 2453,
"text": "SAKSHIKULSHRESHTHA"
},
{
"code": null,
"e": 2489,
"s": 2472,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 2496,
"s": 2489,
"text": "Picked"
},
{
"code": null,
"e": 2520,
"s": 2496,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2528,
"s": 2520,
"text": "Node.js"
},
{
"code": null,
"e": 2547,
"s": 2528,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2564,
"s": 2547,
"text": "Web Technologies"
}
] |
Python | Getting started with SymPy module | 21 Apr, 2022
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. SymPy only depends on mpmath, a pure Python library for arbitrary floating point arithmetic, making it easy to use. Installing sympy module:
pip install sympy
SymPy defines following numerical types: Rational and Integer. The Rational class represents a rational number as a pair of two Integers, numerator and denominator, so Rational(1, 2) represents 1/2, Rational(5, 2) 5/2 and so on. The Integer class represents Integer number.Example #1 :
Python3
# import everything from sympy modulefrom sympy import * a = Rational(5, 8)print("value of a is :" + str(a)) b = Integer(3.579)print("value of b is :" + str(b))
Output:
value of a is :5/8
value of b is :3
SymPy uses mpmath in the background, which makes it possible to perform computations using arbitrary-precision arithmetic. That way, some special constants, like exp, pi, oo (Infinity), are treated as symbols and can be evaluated with arbitrary precision.Example #2 :
Python3
# import everything from sympy modulefrom sympy import * # you can't get any numerical valuep = pi**3print("value of p is :" + str(p)) # evalf method evaluates the expression to a floating-point numberq = pi.evalf()print("value of q is :" + str(q)) # equivalent to e ^ 1 or e ** 1r = exp(1).evalf()print("value of r is :" + str(r)) s = (pi + exp(1)).evalf()print("value of s is :" + str(s)) rslt = oo + 10000print("value of rslt is :" + str(rslt)) if oo > 9999999 : print("True")else: print("False")
Output:
value of p is :pi^3
value of q is :3.14159265358979
value of r is :2.71828182845905
value of s is :5.85987448204884
value of rslt is :oo
True
In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables explicitly using Symbol() method.Example #3 :
Python3
# import everything from sympy modulefrom sympy import * x = Symbol('x')y = Symbol('y') z = (x + y) + (x-y)print("value of z is :" + str(z))
Output:
value of z is :2*x
The real power of a symbolic computation system such as SymPy is the ability to do all sorts of computations symbolically. SymPy can simplify expressions, compute derivatives, integrals, and limits, solve equations, work with matrices, and much, much more, and do it all symbolically. Here is a small sampling of the sort of symbolic power SymPy is capable of, to whet your appetite.Example #4 : Find derivative, integration, limits, quadratic equation.
Python3
# import everything from sympy modulefrom sympy import * # make a symbolx = Symbol('x') # make the derivative of sin(x)*e ^ xans1 = diff(sin(x)*exp(x), x)print("derivative of sin(x)*e ^ x : ", ans1) # Compute (e ^ x * sin(x)+ e ^ x * cos(x))dxans2 = integrate(exp(x)*sin(x) + exp(x)*cos(x), x)print("indefinite integration is : ", ans2) # Compute definite integral of sin(x ^ 2)dx# in b / w interval of ? and ?? .ans3 = integrate(sin(x**2), (x, -oo, oo))print("definite integration is : ", ans3) # Find the limit of sin(x) / x given x tends to 0ans4 = limit(sin(x)/x, x, 0)print("limit is : ", ans4) # Solve quadratic equation like, example : x ^ 2?2 = 0ans5 = solve(x**2 - 2, x)print("roots are : ", ans5)
Output :
derivative of sin(x)*e^x : exp(x)*sin(x) + exp(x)*cos(x)
indefinite integration is : exp(x)*sin(x)
definite integration is : sqrt(2)*sqrt(pi)/2
limit is : 1
roots are : [-sqrt(2), sqrt(2)]
kartikiyer2892
sumitgumber28
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 447,
"s": 53,
"text": "SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. SymPy only depends on mpmath, a pure Python library for arbitrary floating point arithmetic, making it easy to use. Installing sympy module: "
},
{
"code": null,
"e": 467,
"s": 447,
"text": " pip install sympy "
},
{
"code": null,
"e": 757,
"s": 469,
"text": "SymPy defines following numerical types: Rational and Integer. The Rational class represents a rational number as a pair of two Integers, numerator and denominator, so Rational(1, 2) represents 1/2, Rational(5, 2) 5/2 and so on. The Integer class represents Integer number.Example #1 : "
},
{
"code": null,
"e": 765,
"s": 757,
"text": "Python3"
},
{
"code": "# import everything from sympy modulefrom sympy import * a = Rational(5, 8)print(\"value of a is :\" + str(a)) b = Integer(3.579)print(\"value of b is :\" + str(b))",
"e": 926,
"s": 765,
"text": null
},
{
"code": null,
"e": 936,
"s": 926,
"text": "Output: "
},
{
"code": null,
"e": 974,
"s": 936,
"text": " \nvalue of a is :5/8\nvalue of b is :3"
},
{
"code": null,
"e": 1244,
"s": 974,
"text": "SymPy uses mpmath in the background, which makes it possible to perform computations using arbitrary-precision arithmetic. That way, some special constants, like exp, pi, oo (Infinity), are treated as symbols and can be evaluated with arbitrary precision.Example #2 : "
},
{
"code": null,
"e": 1252,
"s": 1244,
"text": "Python3"
},
{
"code": "# import everything from sympy modulefrom sympy import * # you can't get any numerical valuep = pi**3print(\"value of p is :\" + str(p)) # evalf method evaluates the expression to a floating-point numberq = pi.evalf()print(\"value of q is :\" + str(q)) # equivalent to e ^ 1 or e ** 1r = exp(1).evalf()print(\"value of r is :\" + str(r)) s = (pi + exp(1)).evalf()print(\"value of s is :\" + str(s)) rslt = oo + 10000print(\"value of rslt is :\" + str(rslt)) if oo > 9999999 : print(\"True\")else: print(\"False\")",
"e": 1758,
"s": 1252,
"text": null
},
{
"code": null,
"e": 1768,
"s": 1758,
"text": "Output: "
},
{
"code": null,
"e": 1910,
"s": 1768,
"text": "value of p is :pi^3\nvalue of q is :3.14159265358979\nvalue of r is :2.71828182845905\nvalue of s is :5.85987448204884\nvalue of rslt is :oo\nTrue"
},
{
"code": null,
"e": 2054,
"s": 1910,
"text": " In contrast to other Computer Algebra Systems, in SymPy you have to declare symbolic variables explicitly using Symbol() method.Example #3 : "
},
{
"code": null,
"e": 2062,
"s": 2054,
"text": "Python3"
},
{
"code": "# import everything from sympy modulefrom sympy import * x = Symbol('x')y = Symbol('y') z = (x + y) + (x-y)print(\"value of z is :\" + str(z))",
"e": 2203,
"s": 2062,
"text": null
},
{
"code": null,
"e": 2213,
"s": 2203,
"text": "Output: "
},
{
"code": null,
"e": 2233,
"s": 2213,
"text": "value of z is :2*x "
},
{
"code": null,
"e": 2692,
"s": 2237,
"text": "The real power of a symbolic computation system such as SymPy is the ability to do all sorts of computations symbolically. SymPy can simplify expressions, compute derivatives, integrals, and limits, solve equations, work with matrices, and much, much more, and do it all symbolically. Here is a small sampling of the sort of symbolic power SymPy is capable of, to whet your appetite.Example #4 : Find derivative, integration, limits, quadratic equation. "
},
{
"code": null,
"e": 2700,
"s": 2692,
"text": "Python3"
},
{
"code": "# import everything from sympy modulefrom sympy import * # make a symbolx = Symbol('x') # make the derivative of sin(x)*e ^ xans1 = diff(sin(x)*exp(x), x)print(\"derivative of sin(x)*e ^ x : \", ans1) # Compute (e ^ x * sin(x)+ e ^ x * cos(x))dxans2 = integrate(exp(x)*sin(x) + exp(x)*cos(x), x)print(\"indefinite integration is : \", ans2) # Compute definite integral of sin(x ^ 2)dx# in b / w interval of ? and ?? .ans3 = integrate(sin(x**2), (x, -oo, oo))print(\"definite integration is : \", ans3) # Find the limit of sin(x) / x given x tends to 0ans4 = limit(sin(x)/x, x, 0)print(\"limit is : \", ans4) # Solve quadratic equation like, example : x ^ 2?2 = 0ans5 = solve(x**2 - 2, x)print(\"roots are : \", ans5)",
"e": 3407,
"s": 2700,
"text": null
},
{
"code": null,
"e": 3418,
"s": 3407,
"text": "Output : "
},
{
"code": null,
"e": 3612,
"s": 3418,
"text": "derivative of sin(x)*e^x : exp(x)*sin(x) + exp(x)*cos(x)\nindefinite integration is : exp(x)*sin(x)\ndefinite integration is : sqrt(2)*sqrt(pi)/2\nlimit is : 1\nroots are : [-sqrt(2), sqrt(2)]"
},
{
"code": null,
"e": 3629,
"s": 3614,
"text": "kartikiyer2892"
},
{
"code": null,
"e": 3643,
"s": 3629,
"text": "sumitgumber28"
},
{
"code": null,
"e": 3658,
"s": 3643,
"text": "python-modules"
},
{
"code": null,
"e": 3665,
"s": 3658,
"text": "Python"
},
{
"code": null,
"e": 3763,
"s": 3665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3808,
"s": 3763,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3858,
"s": 3808,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 3874,
"s": 3858,
"text": "Deque in Python"
},
{
"code": null,
"e": 3890,
"s": 3874,
"text": "Queue in Python"
},
{
"code": null,
"e": 3912,
"s": 3890,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3954,
"s": 3912,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3981,
"s": 3954,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4004,
"s": 3981,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 4023,
"s": 4004,
"text": "reduce() in Python"
}
] |
Functors in C++ | 06 Feb, 2020
Please note that the title is Functors (Not Functions)!!
Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done?
One obvious answer might be global variables. However, good coding practices do not advocate the use of global variables and say they must be used only when there is no other alternative.
Functors are objects that can be treated as though they are a function or function pointer. Functors are most commonly used along with STLs in a scenario like following:
Below program uses transform() in STL to add 1 to all elements of arr[].
// A C++ program uses transform() in STL to add // 1 to all elements of arr[]#include <bits/stdc++.h>using namespace std; int increment(int x) { return (x+1); } int main(){ int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); // Apply increment to all elements of // arr[] and store the modified elements // back in arr[] transform(arr, arr+n, arr, increment); for (int i=0; i<n; i++) cout << arr[i] <<" "; return 0;}
Output:
2 3 4 5 6
This code snippet adds only one value to the contents of the arr[]. Now suppose, that we want to add 5 to contents of arr[].
See what’s happening? As transform requires a unary function(a function taking only one argument) for an array, we cannot pass a number to increment(). And this would, in effect, make us write several different functions to add each number. What a mess. This is where functors come into use.
A functor (or function object) is a C++ class that acts like a function. Functors are called using the same old function call syntax. To create a functor, we create a object that overloads the operator().
The line,
MyFunctor(10);
Is same as
MyFunctor.operator()(10);
Let’s delve deeper and understand how this can actually be used in conjunction with STLs.
// C++ program to demonstrate working of// functors.#include <bits/stdc++.h>using namespace std; // A Functorclass increment{private: int num;public: increment(int n) : num(n) { } // This operator overloading enables calling // operator function () on objects of increment int operator () (int arr_num) const { return num + arr_num; }}; // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); int to_add = 5; transform(arr, arr+n, arr, increment(to_add)); for (int i=0; i<n; i++) cout << arr[i] << " ";}
Output:
6 7 8 9 10
Thus, here, Increment is a functor, a c++ class that acts as a function.
The line,
transform(arr, arr+n, arr, increment(to_add));
is the same as writing below two lines,
// Creating object of increment
increment obj(to_add);
// Calling () on object
transform(arr, arr+n, arr, obj);
Thus, an object a is created that overloads the operator(). Hence, functors can be used effectively in conjunction with C++ STLs.
This article is contributed by Supriya Srivatsa. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
saiprathivadi
CPP-Functions
cpp-pointer
STL
C Language
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Functions that cannot be overloaded in C++
Bitwise Operators in C/C++
Switch Statement in C/C++
Vector in C++ STL
Writing First C++ Program - Hello World Example
std::sort() in C++ STL
Functions that cannot be overloaded in C++
Initialize a vector in C++ (7 different ways) | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Feb, 2020"
},
{
"code": null,
"e": 111,
"s": 54,
"text": "Please note that the title is Functors (Not Functions)!!"
},
{
"code": null,
"e": 340,
"s": 111,
"text": "Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done?"
},
{
"code": null,
"e": 528,
"s": 340,
"text": "One obvious answer might be global variables. However, good coding practices do not advocate the use of global variables and say they must be used only when there is no other alternative."
},
{
"code": null,
"e": 698,
"s": 528,
"text": "Functors are objects that can be treated as though they are a function or function pointer. Functors are most commonly used along with STLs in a scenario like following:"
},
{
"code": null,
"e": 771,
"s": 698,
"text": "Below program uses transform() in STL to add 1 to all elements of arr[]."
},
{
"code": "// A C++ program uses transform() in STL to add // 1 to all elements of arr[]#include <bits/stdc++.h>using namespace std; int increment(int x) { return (x+1); } int main(){ int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); // Apply increment to all elements of // arr[] and store the modified elements // back in arr[] transform(arr, arr+n, arr, increment); for (int i=0; i<n; i++) cout << arr[i] <<\" \"; return 0;}",
"e": 1246,
"s": 771,
"text": null
},
{
"code": null,
"e": 1254,
"s": 1246,
"text": "Output:"
},
{
"code": null,
"e": 1264,
"s": 1254,
"text": "2 3 4 5 6"
},
{
"code": null,
"e": 1389,
"s": 1264,
"text": "This code snippet adds only one value to the contents of the arr[]. Now suppose, that we want to add 5 to contents of arr[]."
},
{
"code": null,
"e": 1681,
"s": 1389,
"text": "See what’s happening? As transform requires a unary function(a function taking only one argument) for an array, we cannot pass a number to increment(). And this would, in effect, make us write several different functions to add each number. What a mess. This is where functors come into use."
},
{
"code": null,
"e": 1886,
"s": 1681,
"text": "A functor (or function object) is a C++ class that acts like a function. Functors are called using the same old function call syntax. To create a functor, we create a object that overloads the operator()."
},
{
"code": null,
"e": 1949,
"s": 1886,
"text": "The line,\nMyFunctor(10);\n\nIs same as\nMyFunctor.operator()(10);"
},
{
"code": null,
"e": 2039,
"s": 1949,
"text": "Let’s delve deeper and understand how this can actually be used in conjunction with STLs."
},
{
"code": "// C++ program to demonstrate working of// functors.#include <bits/stdc++.h>using namespace std; // A Functorclass increment{private: int num;public: increment(int n) : num(n) { } // This operator overloading enables calling // operator function () on objects of increment int operator () (int arr_num) const { return num + arr_num; }}; // Driver codeint main(){ int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); int to_add = 5; transform(arr, arr+n, arr, increment(to_add)); for (int i=0; i<n; i++) cout << arr[i] << \" \";}",
"e": 2634,
"s": 2039,
"text": null
},
{
"code": null,
"e": 2642,
"s": 2634,
"text": "Output:"
},
{
"code": null,
"e": 2653,
"s": 2642,
"text": "6 7 8 9 10"
},
{
"code": null,
"e": 2726,
"s": 2653,
"text": "Thus, here, Increment is a functor, a c++ class that acts as a function."
},
{
"code": null,
"e": 2941,
"s": 2726,
"text": "\nThe line,\ntransform(arr, arr+n, arr, increment(to_add));\n\nis the same as writing below two lines,\n// Creating object of increment\nincrement obj(to_add); \n\n// Calling () on object\ntransform(arr, arr+n, arr, obj); \n"
},
{
"code": null,
"e": 3071,
"s": 2941,
"text": "Thus, an object a is created that overloads the operator(). Hence, functors can be used effectively in conjunction with C++ STLs."
},
{
"code": null,
"e": 3341,
"s": 3071,
"text": "This article is contributed by Supriya Srivatsa. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3465,
"s": 3341,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 3479,
"s": 3465,
"text": "saiprathivadi"
},
{
"code": null,
"e": 3493,
"s": 3479,
"text": "CPP-Functions"
},
{
"code": null,
"e": 3505,
"s": 3493,
"text": "cpp-pointer"
},
{
"code": null,
"e": 3509,
"s": 3505,
"text": "STL"
},
{
"code": null,
"e": 3520,
"s": 3509,
"text": "C Language"
},
{
"code": null,
"e": 3524,
"s": 3520,
"text": "C++"
},
{
"code": null,
"e": 3528,
"s": 3524,
"text": "STL"
},
{
"code": null,
"e": 3532,
"s": 3528,
"text": "CPP"
},
{
"code": null,
"e": 3630,
"s": 3532,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3708,
"s": 3630,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 3731,
"s": 3708,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 3774,
"s": 3731,
"text": "Functions that cannot be overloaded in C++"
},
{
"code": null,
"e": 3801,
"s": 3774,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 3827,
"s": 3801,
"text": "Switch Statement in C/C++"
},
{
"code": null,
"e": 3845,
"s": 3827,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3893,
"s": 3845,
"text": "Writing First C++ Program - Hello World Example"
},
{
"code": null,
"e": 3916,
"s": 3893,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 3959,
"s": 3916,
"text": "Functions that cannot be overloaded in C++"
}
] |
How to Implement Custom Searchable Spinner in Android? | 28 Feb, 2022
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using an Adapter we can easily bind the items to the spinner objects. In this article, we are going to implement a custom searchable spinner in the Android Studio so that we can provide a better user experience to the user and make it convenient for them to search and select an item in a list of items. Advantages of a searchable spinner:
It provides an edge over the normal listview as here the user can directly search an item rather than scrolling the whole list.
Searching makes users’ work easier so, many items can be inserted into a single list.
Here we are going to take an array list and then insert different items into that list and then using a dialog and adapter we are going to make that list searchable and selectable. Below is a sample video of a custom searchable spinner that we are going to build in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a new project
Open a new project.
We will be working on Empty Activity with language as Java. Leave all other options unchanged.
You can change the name of the project at your convenience.
There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Add a new vector asset in drawable
Navigate to drawable > right-click > new > vector asset and then select the following drop-down asset from clip art.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!-- Relative layout as parent layout --><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:gravity="center" tools:context=".MainActivity"> <!-- text view to show the selected item--> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/testView" android:hint="Select course" android:padding="12dp" android:gravity="center_vertical" android:drawableEnd="@drawable/ic_arrow" android:background="@android:drawable/editbox_background" /> </RelativeLayout>
Step 4: Creating a new resource file
Navigate to the app > res > layout > right click > New > Layout Resource File and then name it as dialog_searchable_spinner.
Use the below code in the dialog_searchable_spinner.xml file
XML
<?xml version="1.0" encoding="utf-8"?> <!-- Linear layout as parent layout--><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp" android:background="@android:color/white" > <!-- Text view to show the text Select course--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select Course" android:textSize="20sp" android:textStyle="bold" /> <!-- Edit text to allow user to type name of item he/she wants to search--> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/edit_text" android:hint="Search..." android:padding="12dp" android:singleLine="true" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" android:background="@android:drawable/editbox_background" /> <!-- List view to insert list of items--> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/list_view" /> </LinearLayout>
Step 5: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
package com.example.custom_searchable_spinner; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.EditText;import android.widget.ListView;import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Initialize variable TextView textview; ArrayList<String> arrayList; Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable textview=findViewById(R.id.testView); // initialize array list arrayList=new ArrayList<>(); // set value in array list arrayList.add("DSA Self Paced"); arrayList.add("Complete Interview Prep"); arrayList.add("Amazon SDE Test Series"); arrayList.add("Compiler Design"); arrayList.add("Git & Github"); arrayList.add("Python foundation"); arrayList.add("Operating systems"); arrayList.add("Theory of Computation"); textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Initialize dialog dialog=new Dialog(MainActivity.this); // set custom dialog dialog.setContentView(R.layout.dialog_searchable_spinner); // set custom height and width dialog.getWindow().setLayout(650,800); // set transparent background dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // show dialog dialog.show(); // Initialize and assign variable EditText editText=dialog.findViewById(R.id.edit_text); ListView listView=dialog.findViewById(R.id.list_view); // Initialize array adapter ArrayAdapter<String> adapter=new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,arrayList); // set adapter listView.setAdapter(adapter); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s); } @Override public void afterTextChanged(Editable s) { } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // when item selected from list // set selected item on textView textview.setText(adapter.getItem(position)); // Dismiss dialog dialog.dismiss(); } }); } }); }}
We have successfully made the Custom Searchable Spinner for our application. The final output is shown below.
sumitgumber28
nikhatkhan11
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Introduction to Android Development
Animation in Android with Example
Data Binding in Android with Example
Fragment Lifecycle in Android
Activity Lifecycle in Android with Demo App | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 699,
"s": 28,
"text": "Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using an Adapter we can easily bind the items to the spinner objects. In this article, we are going to implement a custom searchable spinner in the Android Studio so that we can provide a better user experience to the user and make it convenient for them to search and select an item in a list of items. Advantages of a searchable spinner:"
},
{
"code": null,
"e": 827,
"s": 699,
"text": "It provides an edge over the normal listview as here the user can directly search an item rather than scrolling the whole list."
},
{
"code": null,
"e": 913,
"s": 827,
"text": "Searching makes users’ work easier so, many items can be inserted into a single list."
},
{
"code": null,
"e": 1268,
"s": 913,
"text": "Here we are going to take an array list and then insert different items into that list and then using a dialog and adapter we are going to make that list searchable and selectable. Below is a sample video of a custom searchable spinner that we are going to build in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 1297,
"s": 1268,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 1317,
"s": 1297,
"text": "Open a new project."
},
{
"code": null,
"e": 1412,
"s": 1317,
"text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged."
},
{
"code": null,
"e": 1472,
"s": 1412,
"text": "You can change the name of the project at your convenience."
},
{
"code": null,
"e": 1551,
"s": 1472,
"text": "There will be two default files named activity_main.xml and MainActivity.java."
},
{
"code": null,
"e": 1692,
"s": 1551,
"text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? "
},
{
"code": null,
"e": 1735,
"s": 1692,
"text": "Step 2: Add a new vector asset in drawable"
},
{
"code": null,
"e": 1852,
"s": 1735,
"text": "Navigate to drawable > right-click > new > vector asset and then select the following drop-down asset from clip art."
},
{
"code": null,
"e": 1900,
"s": 1852,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2043,
"s": 1900,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 2047,
"s": 2043,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- Relative layout as parent layout --><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"16dp\" android:gravity=\"center\" tools:context=\".MainActivity\"> <!-- text view to show the selected item--> <TextView android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/testView\" android:hint=\"Select course\" android:padding=\"12dp\" android:gravity=\"center_vertical\" android:drawableEnd=\"@drawable/ic_arrow\" android:background=\"@android:drawable/editbox_background\" /> </RelativeLayout>",
"e": 2904,
"s": 2047,
"text": null
},
{
"code": null,
"e": 2944,
"s": 2907,
"text": "Step 4: Creating a new resource file"
},
{
"code": null,
"e": 3072,
"s": 2946,
"text": "Navigate to the app > res > layout > right click > New > Layout Resource File and then name it as dialog_searchable_spinner."
},
{
"code": null,
"e": 3137,
"s": 3076,
"text": "Use the below code in the dialog_searchable_spinner.xml file"
},
{
"code": null,
"e": 3143,
"s": 3139,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!-- Linear layout as parent layout--><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\" android:padding=\"16dp\" android:background=\"@android:color/white\" > <!-- Text view to show the text Select course--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Select Course\" android:textSize=\"20sp\" android:textStyle=\"bold\" /> <!-- Edit text to allow user to type name of item he/she wants to search--> <EditText android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/edit_text\" android:hint=\"Search...\" android:padding=\"12dp\" android:singleLine=\"true\" android:layout_marginTop=\"8dp\" android:layout_marginBottom=\"8dp\" android:background=\"@android:drawable/editbox_background\" /> <!-- List view to insert list of items--> <ListView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/list_view\" /> </LinearLayout>",
"e": 4436,
"s": 3143,
"text": null
},
{
"code": null,
"e": 4487,
"s": 4439,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 4679,
"s": 4489,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 4686,
"s": 4681,
"text": "Java"
},
{
"code": "package com.example.custom_searchable_spinner; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.EditText;import android.widget.ListView;import android.widget.TextView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // Initialize variable TextView textview; ArrayList<String> arrayList; Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable textview=findViewById(R.id.testView); // initialize array list arrayList=new ArrayList<>(); // set value in array list arrayList.add(\"DSA Self Paced\"); arrayList.add(\"Complete Interview Prep\"); arrayList.add(\"Amazon SDE Test Series\"); arrayList.add(\"Compiler Design\"); arrayList.add(\"Git & Github\"); arrayList.add(\"Python foundation\"); arrayList.add(\"Operating systems\"); arrayList.add(\"Theory of Computation\"); textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Initialize dialog dialog=new Dialog(MainActivity.this); // set custom dialog dialog.setContentView(R.layout.dialog_searchable_spinner); // set custom height and width dialog.getWindow().setLayout(650,800); // set transparent background dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); // show dialog dialog.show(); // Initialize and assign variable EditText editText=dialog.findViewById(R.id.edit_text); ListView listView=dialog.findViewById(R.id.list_view); // Initialize array adapter ArrayAdapter<String> adapter=new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1,arrayList); // set adapter listView.setAdapter(adapter); editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { adapter.getFilter().filter(s); } @Override public void afterTextChanged(Editable s) { } }); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // when item selected from list // set selected item on textView textview.setText(adapter.getItem(position)); // Dismiss dialog dialog.dismiss(); } }); } }); }}",
"e": 8198,
"s": 4686,
"text": null
},
{
"code": null,
"e": 8311,
"s": 8201,
"text": "We have successfully made the Custom Searchable Spinner for our application. The final output is shown below."
},
{
"code": null,
"e": 8329,
"s": 8315,
"text": "sumitgumber28"
},
{
"code": null,
"e": 8342,
"s": 8329,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 8350,
"s": 8342,
"text": "Android"
},
{
"code": null,
"e": 8358,
"s": 8350,
"text": "Android"
},
{
"code": null,
"e": 8456,
"s": 8358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8488,
"s": 8456,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 8527,
"s": 8488,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 8569,
"s": 8527,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 8620,
"s": 8569,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 8643,
"s": 8620,
"text": "Flutter - Stack Widget"
},
{
"code": null,
"e": 8679,
"s": 8643,
"text": "Introduction to Android Development"
},
{
"code": null,
"e": 8713,
"s": 8679,
"text": "Animation in Android with Example"
},
{
"code": null,
"e": 8750,
"s": 8713,
"text": "Data Binding in Android with Example"
},
{
"code": null,
"e": 8780,
"s": 8750,
"text": "Fragment Lifecycle in Android"
}
] |
Subsets and Splits