Ad
Saturday, December 9, 2023
Chapter 5 Handling email with php
-Which protocols are used to retrieve mail from server?
POP3 (Post Office Protocol version 3) and IMAP (Internet Message Access Protocol) are commonly used protocols to retrieve mail from the server.
-Explain SMTP Protocol
SMTP (Simple Mail Transfer Protocol):
What it does:
SMTP helps send emails from one server to another over the internet.
How it works:
When you send an email, your email program talks to a server using SMTP. This server then talks to the recipient's server to deliver the email.
Steps involved:
Connect to the server, say who the email is from, who it's going to, and then send the actual message.
Special Codes:
The servers use special codes to talk to each other, like saying "hello" (EHLO), "here's the email" (DATA), and "all done" (QUIT).
Security:
Some servers need a password to make sure only authorized people can send emails. There are also ways to make the conversation between servers more private.
Why it's important:
SMTP makes sure emails get from one place to another reliably, even if the other server isn't available right away.
-Explain how to send email with PHP
PHP provides the mail() function to send email. Example:
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";
mail($to, $subject, $message, $headers);
-Explain advantages and disadvantages of IMAP4 protocol.
Advantages:
Allows access to emails stored on the server.
Supports synchronization of email across multiple devices.
Provides the ability to organize emails into folders on the server.
Disadvantages:
Requires a constant internet connection for accessing emails.
More server resources may be needed.
Potential security concerns if not configured properly.
Chapter 2 Function and String
- Explain anonymous function concept in PHP.
-What is difference between echo ( ) and print ( ) function?
Both echo and print are used to output data in PHP. The main differences are:
echo can take multiple parameters, while print can only take one.
echo is slightly faster, and print always returns 1, so it can be used in expressions.
-Explain any two directory functions.
opendir(): Opens a directory handle.
readdir(): Reads the contents of the directory handle.
-Differentiate between single quoted string and double quoted string.
Single-quoted strings ('') treat everything as plain text. Variables and escape sequences are not interpreted within single quotes.
Example: echo 'Hello, $name'; will output Hello, $name.
Double-quoted strings ("") interpret variables and escape sequences. For example, echo "Hello, $name"; will output Hello, [value of $name].
-Write any two functions of decompose string with suitable example.
explode() function:
Splits a string into an array based on a specified delimiter.
Example: $str = "apple,orange,banana"; $arr = explode(",", $str);
str_split() function:
Splits a string into an array of characters.
Example: $str = "hello"; $arr = str_split($str);
- How to find out the position of the first occurrence of a substring in a string?
The strpos() function.
Example: $pos = strpos("Hello, world!", "world");
- What is the purpose of array_splice ( ) function?
array_splice() is used to remove a portion of the array and return it while modifying the original array.
Example: $arr = [1, 2, 3, 4]; $removed = array_splice($arr, 1, 2);
- Explain the functions used for reading and writing characters in files.
Reading: fread(), fgets(), file_get_contents()
Writing: fwrite(), file_put_contents()
-Explain the concept of missing parameters to a function with suitable example
If a function is called with missing parameters, PHP will generate a warning or error depending on how the function is defined.
function addNumbers($num1, $num2) {
return $num1 + $num2;
}
// Calling the function with missing parameters will result in an error
$result = addNumbers(5);
- State the use of foreach() function.
The foreach() function in PHP is used to iterate over arrays or other iterable objects, making it easy to loop through each element without the need for explicit indexing. It simplifies the process of iterating over arrays and collections.
-Give any two functions of random access of file data.
fseek():
Sets the file position indicator for the file pointer. It allows you to move the pointer to a specific position within the file.
ftell():
Returns the current position of the file pointer in a file. It is often used to determine the size of a file.
- Explain any two of the following functions with syntax
array _ intersect ()
array _ slice ()
shuffle ()
The array_intersect() function is used to find the intersection of two or more arrays, i.e., it returns an array containing values that are present in all input arrays.
Syntax:
$resultArray = array_intersect($array1, $array2, ...);
The array_slice() function is used to extract a portion of an array. It returns a new array containing a specified number of elements from the original array, starting at a specified offset.
Syntax:
$slicedArray = array_slice($array, $offset, $length, $preserve_keys);
The shuffle() function is used to shuffle the elements of an array randomly, changing their order.
Syntax:
shuffle($array);
- Give function to check if variable has value or not.
function isValueSet($variable) {
return isset($variable) && !empty($variable);
}
// Example usage:
$myVar = "Hello";
if (isValueSet($myVar)) {
echo "Variable has a value.";
} else {
echo "Variable is empty or not set.";
}
The explode function in PHP is used to split a string into an array of substrings based on a specified delimiter. The purpose is to break a string into parts, making it easier to process or analyze individual components.
-Explain the following functions with example
Ucwords ( )
Trim ( )
Str- Pad ( )
Ucfirst )
Chunk - Split ( )(
ucwords() Function:
Converts the first character of each word in a string to uppercase.
$str = "hello world";
echo ucwords($str); // Output: Hello World
trim() Function:
Removes whitespace or other characters from both ends of a string.
$str = " Trim Me ";
echo trim($str); // Output: Trim Me
str_pad() Function:
Pads a string to a certain length with another string.
$str = "Hello";
echo str_pad($str, 10, "-"); // Output: Hello-----
ucfirst() Function:
Converts the first character of a string to uppercase.
$str = "capitalize";
echo ucfirst($str); // Output: Capitalize
chunk_split() Function:
Splits a string into a series of smaller parts.
$str = "123456789";
echo chunk_split($str, 3, "-"); // Output: 123-456-789
-Explain different types of arguments passing to functions with
example.
Pass by Value:
The actual value is passed to the function.
Pass by Reference:
The memory address of the variable is passed to the function.
-Explain Implode ( ) with suitable example.
The implode function is used to join array elements with a string. Example:
$array = array("red", "green", "blue");
$string = implode(", ", $array);
echo $string; // Output: red, green, blue
- Explain following functions
fread ( )
fwrite ( )
fgetc ( )
fgets ( )
fread() Function:
Reads from an open file.
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
fclose($file);
fwrite() Function:
Writes to an open file.
$file = fopen("example.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);
fgetc() Function:
Reads a single character from an open file.
$file = fopen("example.txt", "r");
echo fgetc($file);
fclose($file);
fgets() Function:
Reads a line from an open file.
$file = fopen("example.txt", "r");
echo fgets($file);
fclose($file);
-State True/False :
‘‘The names of user-defined classes and functions as well as
built-in constructs are case-insensitive.
False: In PHP, the names of user-defined classes and functions are case-insensitive, but the names of built-in constructs are case-sensitive.
- Explain the following functions with respect to a file :
(1) filectime()
(2) file()
(3) stat ()
(4) unlink()
(5) fwrite()
filectime(): Returns the last change time of the file.
file(): Reads an entire file into an array.
stat(): Returns information about a file.
unlink(): Deletes a file.
fwrite(): Writes to an open file.
-What is an Anonymous function ? How is it different from
normal function ?
An anonymous function, also known as a lambda function, is a function without a name. It can be assigned to a variable or passed as an argument to other functions. Example:
$add = function ($a, $b) {
return $a + $b;
};
echo $add(3, 4); // Output: 7
-How to access data members of a class inside member
function ?
Within a class, you can access data members using $this->propertyName. For example:
class MyClass {
public $myProperty = "Hello";
public function printProperty() {
echo $this->myProperty;
}
}
$obj = new MyClass();
$obj->printProperty(); // Output: Hello
-Explain different types of arguments passing to function with example.
Pass by Value:
The actual value is passed to the function. Changes to the parameter inside the function do not affect the original value.
function increment($num) {
$num++;
}
$value = 5;
increment($value);
// $value remains 5
Pass by Reference:
The memory address of the variable is passed to the function. Changes to the parameter inside the function affect the original value.
function incrementByReference(&$num) {
$num++;
}
$value = 5;
incrementByReference($value);
// $value is now 6
-How to pass parameters to a function by reference ? Explain
with example. Also write its advantage.
In PHP, you can pass parameters to a function by reference by using the ampersand (&) before the parameter in both the function definition and the function call. This allows the function to modify the original value of the variable. Here's an example:
<?php
function incrementByReference(&$num) {
$num++;
}
$value = 10;
incrementByReference($value);
echo $value; // Output: 11
?>
Advantage:
Passing by reference allows a function to modify the original value of a variable directly, which can be useful when you want to update a variable's value within a function.
- Explain the following functions with syntax and example :
Func_get_arg( )
Var_dump( )
Strrev( )
Similar_text( )
Str_replace( )
-Explain the following function with example :
Fputs( )
Fseek( )
readFile( )
Filemtime( )
- ‘‘A function can have variable number of arguments.’’ State
true or false
-How to find out the position of the first occurrence of a substring
in a string ?
-Explain the concept of missing parameters to a function
with suitable example.
-Explain the functions used for reading and writing characters
in files.
- Give function to check if a variable has value or not ?
In PHP, you can use the isset function to check if a variable has a value or not. isset returns true if the variable exists and has a value other than null, and false otherwise.
$variable = 42;
if (isset($variable)) {
echo "Variable is set and has a value.";
} else {
echo "Variable is not set or has a value of null.";
}
In this example, the isset function checks if the variable $variable is set and has a value. If it does, it prints "Variable is set and has a value," otherwise, it prints "Variable is not set or has a value of null."
-Which function is used to check if class is present or not?
-Write any two functions of decompose string with suitable example
- What is the different between nchal and print functions.
-State the purpose of $this variable
- Write the purpose of rewind() function
-Explain the following functions with syntax and example Pune num args
1) Func_nun_args()
2)Var_dump()
3) Print_r()
4)Soundex()
5)strrpos()
-Write an anonymous function to maximum of two numbers
- What is the use of count( ) ?
Chapter 4 Files and Database handling
- What is a DSN?
DSN stands for Data Source Name. It is a string that specifies a database connection, typically used in database-related operations.
-How to delete file in PHP?
The unlink() function is used to delete a file in PHP. For example:
$fileToDelete = 'example.txt';
unlink($fileToDelete);
-Write a PHP script accept and insert records in employee table.
<?php
// Assuming database connection is established
$employeeName = $_POST['employeeName'];
$employeeAge = $_POST['employeeAge'];
$employeeSalary = $_POST['employeeSalary'];
$sql = "INSERT INTO employee (name, age, salary) VALUES ('$employeeName', $employeeAge, $employeeSalary)";
// Execute the SQL query to insert records
mysqli_query($conn, $sql);
// Close the database connection
mysqli_close($conn);
?>
-What are the different placeholders used in SQL query?
? (Question Mark):
Used as a parameter placeholder in prepared statements.
:name (Colon Name):
Named placeholders in prepared statements, commonly used in PDO.
$1, $2, ... (Dollar Sign):
Parameter placeholders in PostgreSQL.
- Write steps to create connection with Postgre SQL database and display
the data.
Install PostgreSQL Extension:
Ensure that the PostgreSQL extension is installed and enabled in PHP.
Create Database Connection:
Use pg_connect or PDO to establish a connection to the PostgreSQL database.
Execute Queries:
Use pg_query or other relevant functions to execute SQL queries.
-Consider the following relational data base
Movie (Movie - no , Movie - name, year)
Actor (Actor - no, Actor - name, Movie - no)
<?php
// Assuming database connection is established
$movieName = $_POST['movieName'];
$sql = "SELECT Actor_name FROM Actor WHERE Movie_name = '$movieName'";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['Actor_name'] . "<br>";
}
// Close the database connection
mysqli_close($conn);
?>
-State the advantage of using PEAR DB functions.
The PEAR DB library provides a database abstraction layer, making it easier to switch between different database systems without changing the code. It promotes portability and helps in maintaining a consistent interface for database operations.
-Consider a table student (rno, name, class). Assume database
stud already exists. Write a PHP script to accept a student
roll no. and display details of that student using PEAR DB
functions.
<?php
// Assuming database connection is established using PEAR DB
$rollNo = $_POST['rollNo'];
// Execute a query to fetch student details based on roll number
// Use PEAR DB functions like db_query, etc.
// Display student details
echo "Student Roll No: $rollNo";
// Display other details fetched from the database
?>
-Explain prepare ( ) and execute ( ) command in database handling
In PHP database handling with PDO, prepare() is used to prepare an SQL statement, and execute() is used to execute that prepared statement.
-Accept directory name from user. Write PHP program to change current
directory to accepted directory name and count number of files and directories in it
$dir = "/path/to/directory";
chdir($dir);
$files = scandir($dir);
$numFiles = count($files) - 2; // Subtracting . and .. from the count
echo "Number of files and directories: $numFiles";
-Write a PHP script to accept a file name from user and
display last access date and time of a file.
<?php
$filename = 'example.txt';
// Display last access date and time
echo "Last access time: " . date("F d Y H:i:s.", fileatime($filename));
?>
- State the pear db function to get system error message, if
the database connection fails.
-How to get the user ID of the owner of the specified
file ?
-Assume database empdb is already exists. Write a PHP script
using postgreSQL to increment salary of all employees by 10%.
- Consider table emp(eno, ename, salary).
-Write a PHP script to display date and time of a file when
it was last accessed.
-Explain DB :: connect( )
- Which operator is used to compare data as well as data type ?
-What is purpose of file)?
- Write connect function in PEAR DB for pestgreSQL How to release connection in database specifir way?
- Write stope to seept database using database specific way.
-Write a PHP program to add aasigronment record of the given student. Consider-heo, name, assignment, set, question eo, marks, date accept from student).
-What is Data type List different Data types in PHP? Explain
-What are the different class methods and object methods available in PRAR DB ibrary? Kaplain.
- Write purpose of resource data type with suitable example.
Chapter 3 Arrays
-Which construct is used to define an array?
The array() construct is used to define an array in PHP.
-How to convert an object to array?
The get_object_vars() function to convert an object to an associative array.
-What is associative array? Explain with example how is it different from indexed
array
An associative array in PHP is an array that uses named keys instead of numerical indices to store data. Each key is associated with a specific value. Example:
$person = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
Therefore, indexed arrays where data is accessed by numerical indices ($array[0]), associative arrays allow access using descriptive keys ($person['name']).
-How will you find number of elements in array?
the count function to find the number of elements in an array.
$array = [1, 2, 3, 4, 5];
$numElements = count($array);
echo "Number of elements: " . $numElements;
- Which function is used to remove duplicate elements from
an array ?
The array_unique function is used to remove duplicate elements from an array.
-How to get array of keys and array of values from an associative
array ? Illustrate with suitable example using built-in functions.
$associativeArray = array("name" => "John", "age" => 25, "city" => "New York");
// Get array of keys
$keys = array_keys($associativeArray);
// Get array of values
$values = array_values($associativeArray);
print_r($keys); // Output: Array ( [0] => name [1] => age [2] => city )
print_r($values); // Output: Array ( [0] => John [1] => 25 [2] => New York )
- Explain the following function :
(1) array-flip( )
(2) array-filter( )
(3) is-object( )
(4) die( )
array_flip():
Purpose: Swaps the keys and values of an array.
Example:
$originalArray = array("a" => 1, "b" => 2, "c" => 3);
$flippedArray = array_flip($originalArray);
print_r($flippedArray);
// Output: Array ( [1] => a [2] => b [3] => c )
array_filter():
Purpose: Filters elements of an array using a callback function.
Example:
$numbers = array(1, 2, 3, 4, 5);
$filteredNumbers = array_filter($numbers, function($value) {
return $value % 2 == 0; // Keep only even numbers
});
print_r($filteredNumbers);
// Output: Array ( [1] => 2 [3] => 4 )
is_object():
Purpose: Checks if a variable is an object.
Example:
$obj = new stdClass();
$result = is_object($obj);
echo $result ? 'It is an object' : 'It is not an object';
// Output: It is an object
die() (or exit()):
Purpose: Terminates the script and outputs a message.
Example:
$age = 17;
if ($age < 18) {
die('You must be 18 or older.');
}
// Script won't continue if the condition is true.
-How to Insert and Remove the last element of an array
-Explain the following functions with respect to Array
1) Extract()
2) Shuffle()
3) Array_splice()
4) Arsort()
-How to check if given variable is Array or not?
-What is array ? Write a short note on multidimensional array with examples.
- State the purpose of Array_filter ( )function.
- Explain the following functions with respect to Array :
Explode( )
Array_unshift( )
Array_slice( )
Krsort( )
- Define array_unique( ).
-What is an associative array? Give an example.
Friday, December 8, 2023
Blockchain:PYQ's
- Who published a white paper proposing Ethereum in 2013?
Ethereum was proposed by Vitalik Buterin. He published the white paper in late 2013.
- What is EVM?
EVM is the runtime environment for smart contracts in Ethereum.
-What happens if someone loses the private key of his wallet?
If someone loses the private key of their wallet, they lose access to the associated funds permanently. Recovery is usually impossible, emphasizing the importance of securely storing and backing up private keys.
- Which institute standardized AES algorithm?
The Advanced Encryption Standard (AES) algorithm was standardized by the National Institute of Standards and Technology (NIST).
-What is Nonce?
In blockchain, a nonce is a number that is used only once. It is often employed in the mining process to vary the output of hash functions.
- What is Non-repudiation?
Non-repudiation refers to the assurance that a party involved in a communication cannot deny the authenticity or origin of a message or transaction.
- What is ICO?
ICO is a fundraising method in which new cryptocurrency projects sell their underlying crypto tokens to early investors. It is a way to raise capital for a new blockchain-based project.
-Who owns the Blockchain?
No single entity owns the entire blockchain. It is a decentralized and distributed ledger maintained by a network of nodes.
-What is Gas & Gas limit?
Gas is the unit used to measure the computational effort required to execute operations or contracts on the Ethereum network. Gas limit is the maximum amount of gas a user is willing to pay for a transaction or contract execution.
-What are the advantages of smart contract? Explain any four.
Advantages of Smart Contracts:
Trust: Smart contracts execute automatically based on predefined rules, eliminating the need for trust in a third party. The decentralized and transparent nature of blockchain builds trust.
Efficiency: Automation reduces the time and costs associated with traditional contract execution, as there's no need for intermediaries or manual verification.
Accuracy: Since smart contracts operate on code, the execution is precise, minimizing errors and misunderstandings that can arise in traditional contracts.
Security: Smart contracts are secured by blockchain's cryptographic features. Once deployed, they cannot be altered, providing a high level of security.
- What are the layers of blockchain?
Network Layer: Manages network communication, peer discovery, and data synchronization among nodes.
Consensus Layer: Determines how nodes agree on the state of the blockchain. It includes algorithms like Proof-of-Work (PoW) or Proof-of-Stake (PoS).
Smart Contract Layer: Facilitates the creation, execution, and enforcement of smart contracts. Ethereum is a prominent example with its EVM (Ethereum Virtual Machine).
Application Layer: Houses decentralized applications (DApps) that utilize the underlying blockchain infrastructure.
-What is the formula to calculate transaction fee in Etheream?
Transaction Fee = Gas Used (units) * Gas Price (wei per unit)
Gas represents computational effort, and the fee is calculated based on the amount of gas consumed and the gas price set by the user.
-What is plain text and cipher text?
Plain Text: The original, readable data before any encryption is applied.
Cipher Text: The encrypted data that results from applying an encryption algorithm to the plain text. It appears as random and unreadable without the decryption key.
- What is FPGA?
FPGA is a hardware device with reconfigurable logic gates and circuits.
Unlike ASICs, FPGAs can be programmed and reprogrammed, making them versatile for different applications, including cryptocurrency mining.
-What is smart contract?
A self-executing contract with the terms directly written into code.
Smart contracts automatically enforce and execute the terms when predefined conditions are met, without the need for intermediaries.
-What is the size of encryption key in DES?
DES (Data Encryption Standard) uses a 56-bit key. The key length influences the security of the encryption.
What is ASIC?
ASIC is a hardware designed for a specific task or application, such as cryptocurrency mining.
It offers high performance for a specific function but lacks flexibility compared to general-purpose processors.
- Which algorithm is used by Bitcoin to verify transactions?
Bitcoin uses the SHA-256 hashing algorithm to verify transactions. Miners must find a nonce that, when hashed with the transaction data, produces a hash with a specific pattern.
- Which is a unique PoS cryptocurrency that is aimed at delivering ateroperability among other blockchains
Unique PoS Cryptocurrency for Interoperability:
Cardano (ADA) is known for its Proof-of-Stake consensus algorithm and focuses on providing interoperability and scalability in the blockchain space.
What is DAPP?
A DApp operates on a decentralized network and is built on blockchain technology.
DApps use smart contracts to automate processes, ensuring transparency and security.
-What is the difference between public and private blockchains?
Public Blockchain: Open to anyone, decentralized, and transparent (e.g., Bitcoin, Ethereum).
Private Blockchain: Restricted access, often controlled by a single entity for specific purposes like business applications.
-What is P2P сrypto Exchange?
A Peer-to-Peer (P2P) crypto exchange allows users to trade directly with each other without intermediaries.
It provides more control and ownership over assets compared to centralized exchanges.
Whis is 'BFT?
BFT (Byzantine Fault Tolerance):
BFT is a consensus algorithm that ensures the integrity of a distributed system, even when some nodes fail or act maliciously.
It's crucial for maintaining the reliability and security of blockchain networks.
-What is Hybrid Blockchain?
Combines features of both public and private blockchains.
Offers flexibility, allowing certain data to be private while utilizing the security and transparency of a public blockchain.
-Write a short note on life cycle of smart contract
Creation: Developers write the code for the smart contract.
Execution: The smart contract is deployed on the blockchain and operates based on predefined conditions.
Termination: The smart contract completes its tasks, and outcomes are recorded on the blockchain.
-What is HArd & Soft forks?
Hard Fork: Involves a fundamental change that is not backward-compatible. All nodes must upgrade to continue participating.
Soft Fork: Involves a backward-compatible change, allowing non-upgraded nodes to still participate in the network.
-What is POW?
POW (Proof-of-Work):
POW is a consensus algorithm where participants (miners) solve complex mathematical problems to validate transactions and create new blocks.
It's resource-intensive and helps secure the network against attacks.
-Write a short note on challenges of blockchain
Challenges of Blockchain:
Challenges include scalability issues, interoperability concerns between different blockchains, regulatory uncertainties, and the environmental impact of energy-intensive consensus mechanisms like PoW.
-Write a short note on ICO?
ICO (Initial Coin Offering):
ICO is a fundraising method where new cryptocurrency tokens are sold to investors before being listed on exchanges.
It allows projects to raise capital by selling a portion of their cryptocurrency.
-Which are the different value data types in solidity?
Solidity, the programming language for Ethereum smart contracts, includes data types like uint (unsigned integer), int (signed integer), address, bool, string, and more.
- Describe EVM with the help of neat diagram.
Stream Cipher and Block Cipher:
Stream Cipher: Operates on individual bits or bytes of data, encrypting or decrypting one at a time. It is often used for real-time communication and is more efficient for streaming data.
Block Cipher: Operates on fixed-size blocks of data, encrypting or decrypting the entire block at once. It is commonly used for securing stored data and messages.
-Define transaction and explain its structure.
- What are the uses of SHA algorithm?
The Secure Hash Algorithm (SHA) family of cryptographic hash functions, designed by the National Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST), has several important uses:
Data Integrity: SHA algorithms generate fixed-size hash values (digests) that uniquely represent input data. By comparing hash values, one can verify the integrity of the original data. Any change to the data will result in a different hash value.
Digital Signatures: SHA is commonly used in combination with asymmetric encryption algorithms to create digital signatures. These signatures provide authentication and verify the origin and integrity of digital messages.
Password Hashing: SHA algorithms are employed to securely hash passwords. Storing hashed passwords instead of plaintext enhances security, as it makes it more challenging for attackers to reverse-engineer passwords.
Blockchain Technology: In blockchain, SHA algorithms are used to create cryptographic hashes for blocks and transactions. For example, Bitcoin's PoW consensus relies on SHA-256 to generate a hash that meets specific criteria, contributing to the security of the network.
-What is Public & Private blockchain?
Public Blockchain:
Accessibility: Open to anyone; anyone can join the network, participate in transactions, and validate blocks.
Decentralization: Multiple nodes (computers) maintain the network, and no single entity controls it.
Transparency: All transactions are visible to all participants, enhancing transparency and accountability.
Examples: Bitcoin and Ethereum are examples of public blockchains.
Private Blockchain:
Accessibility: Restricted to a specific group of participants, usually within a single organization or consortium.
Decentralization: Controlled by a centralized entity or a limited number of nodes.
Privacy: Access to data and transactions is restricted, providing privacy among participants.
Examples: Hyperledger Fabric and R3 Corda are examples of private blockchains.
- Write a short note on crypto wallet.
A crypto wallet is a digital tool that allows users to securely store and manage their cryptocurrency assets.
It consists of a public key (for receiving funds) and a private key (for authorizing transactions).
Wallets can be software-based (online, desktop, or mobile) or hardware-based (physical devices).
Wallets enable users to send, receive, and monitor their cryptocurrency balances.
.
-What are the tasks of miners?
Tasks of Miners:
Transaction Verification: Miners verify transactions by solving complex mathematical problems using computational power.
Block Creation: Verified transactions are grouped into blocks, and miners compete to solve the proof-of-work problem to create a new block.
Consensus: Miners participate in the consensus mechanism (e.g., Proof-of-Work) to agree on the state of the blockchain.
Incentive: Miners are rewarded with newly created cryptocurrency and transaction fees for their efforts.
-Which are the components of blockchain?
Blocks: Containers for transaction data and other information.
Transactions: Records of data exchanges between participants.
Chain: The linkage of blocks through cryptographic hashes, forming a secure and chronological sequence.
Consensus Mechanism: Rules or algorithms that facilitate agreement on the state of the blockchain.
Decentralized Network: Nodes that maintain copies of the entire blockchain, ensuring redundancy and security.
- Write a short note on DES.
DES (Data Encryption Standard):
DES is a symmetric-key block cipher used for encryption and decryption of electronic data.
Developed by IBM in the 1970s, it became a widely adopted encryption standard.
DES uses a 56-bit key, and its 64-bit block size encrypts data in 64-bit chunks.
Over time, DES became vulnerable to brute-force attacks due to its small key size, leading to the development of more secure encryption algorithms.
Data Science:PYQ's
- What is Data science?
Data science is a field that involves using scientific methods, processes, algorithms, and systems to extract insights and knowledge from structured and unstructured data.
-Define Data source?
A data source is any location, platform, or system from which data originates or is collected.
- What is missing values?
Missing values refer to the absence of data in a specific field or variable where information is expected.
- List the visualization libraries in python.
Matplotlib
Seaborn
Plotly
Bokeh
Pyplot
-List applications of data science.
Climate Modeling:
Studying climate patterns and making predictions for climate change mitigation.
Recommendation Systems:
Providing personalized recommendations for products, movies, music, etc.
Social Network Analysis:
Studying relationships and patterns within social networks.
Predictive Analytics:
Forecasting future trends and outcomes based on historical data.
Fraud Detection:
Identifying and preventing fraudulent activities by analyzing patterns.
Customer Segmentation:
Grouping customers based on common characteristics for targeted marketing.
- What is data transformation?
Data transformation refers to the process of converting raw data into a more suitable format for analysis.
- What is use of Bubble plot?
A Bubble plot is a variation of a scatter plot where a third dimension of the data is shown through the size of markers (bubbles). It is useful for visualizing three variables in a two-dimensional space, where the size of the bubbles represents the magnitude of the third variable.
-Define Data cleaning?
Data cleaning, or data cleansing, is the process of identifying and correcting errors or inconsistencies in datasets. It involves handling missing values, removing duplicates, correcting inaccuracies, and ensuring data quality for accurate analysis.
-Define standard deviation?
Standard Deviation is a measure of the amount of variation in a set of values. It indicates how much individual data points differ from the mean (average) of the dataset.
- List the tools for data scientist.
Python (with libraries like NumPy, Pandas, Scikit-learn)
Jupyter Notebooks
Tableau
Excel (for basic analysis)
- Define statistical data analysis?
Statistical Data Analysis involves using statistical methods to explore, summarize, and draw inferences from data. It includes descriptive statistics, hypothesis testing, regression analysis, and other techniques to understand patterns and relationships in the data.
-What is data cube?
A data cube is a multidimensional representation of data, where values are organized along multiple dimensions. It allows for the analysis of data by enabling users to slice, dice, and drill down into the information
-Give the purpose of data preprocessing?
Data preprocessing is done to prepare raw data for analysis. Its purposes include cleaning and handling missing values, transforming data into a suitable format, and ensuring that data is ready for machine learning algorithms.
-What is the purpose of data visualization?
Data visualization is used to represent data graphically, making complex patterns and trends more understandable. Its purposes include:
Communicating insights effectively
Identifying patterns and outliers
Supporting decision-making
Presenting data in a visually appealing manner.
-What are the measures of central tendency? Explain any two of them in
brief.
Measures of central tendency describe the center or average of a data set. Two common measures are:
Mean (Average): It is calculated by summing up all values and dividing by the total number of values.
Median: It is the middle value when data is arranged in ascending order. If there's an even number of values, the median is the average of the two middle values.
- What are the various types of data available? Give example of each?
Nominal Data: Categorical data with no inherent order (e.g., colors, types of fruit).
Ordinal Data: Categorical data with a meaningful order (e.g., ranking in a race, customer satisfaction levels).
Interval Data: Numeric data with equal intervals but no true zero point (e.g., temperature in Celsius).
Ratio Data: Numeric data with equal intervals and a true zero point (e.g., height, weight).
- What is venn diagram? How to create it? Explain with example.
A Venn diagram is a visual representation of the relationships between different sets. To create one, draw overlapping circles to represent each set, and where the circles overlap, you show the elements that belong to both sets.
Example: If Set A represents mammals and Set B represents four-legged animals, the overlapping part shows mammals that are also four-legged.
- Explain different data formats in brief.
CSV (Comma-Separated Values): Text-based format where values are separated by commas.
JSON (JavaScript Object Notation): Lightweight data interchange format.
Excel Spreadsheets: Tabular format with rows and columns.
- What is data quality? Which factors are affected data qualities?
Data quality refers to the accuracy, completeness, consistency, and reliability of data. Factors affecting data quality include:
Accuracy
Completeness
Consistency
Timeliness
Relevance
-Write details notes on basic data visualization tools?
Matplotlib: A popular 2D plotting library for Python.
Seaborn: Built on Matplotlib, it provides a high-level interface for attractive and informative statistical graphics.
Tableau: A powerful and interactive data visualization tool.
-What is outlier? State types of outliers.
n outlier is an observation that lies an abnormal distance from other values in a random sample from a population. Types of outliers include:
Univariate Outliers: Unusual values in a single variable.
Multivariate Outliers: Unusual combinations of values across multiple variables.
-State and explain any three data transformation techniques
Normalization: Scaling values to a standard range, often between 0 and 1.
Log Transformation: Applying the logarithm to data to handle skewed distributions.
Standardization: Transforming data to have a mean of 0 and a standard deviation of 1.
- Define volume characteristic of data in reference to data science.
Volume refers to the sheer size of data. In data science, dealing with large volumes of data is common, and technologies like big data tools and distributed computing are employed to handle and analyze massive datasets.
- Give examples of semistructured data.
XML (eXtensible Markup Language)
JSON (JavaScript Object Notation)
- Define Data Discretization.
Data discretization involves converting continuous data into discrete intervals or categories. It's useful for simplifying complex data and can be applied to numerical variables.
- What is a quartile?
Quartiles divide a dataset into four equal parts. The three quartiles (Q1, Q2, and Q3) are the values that separate the data into quarters. Q2 is the median.
- List different types of attributes.
Nominal Attributes: Categorical with no inherent order.
Ordinal Attributes: Categorical with a meaningful order.
Interval Attributes: Numeric with equal intervals but no true zero.
Ratio Attributes: Numeric with equal intervals and a true zero point.
- Define Data object.
In data science, a data object refers to an individual unit of information, such as a row in a dataset.
-What is Data Transformation?
Data transformation involves converting data from one format or structure into another to make it more suitable for analysis or modeling.
-Write the tools used for geospatial data.
ArcGIS: A geographic information system for working with maps and geographic information.
QGIS (Quantum GIS): An open-source alternative for geospatial data analysis
- State the methods of feature selection.
Filter Methods: Select features based on statistical characteristics.
Wrapper Methods: Evaluate feature subsets using a specific machine learning model.
- List any two libraries used in Python for data analysis.
Pandas: For data manipulation and analysis.
NumPy: For numerical operations and array processing.
- Explain any two ways in which data is stored in files.
CSV (Comma-Separated Values): Text-based format with values separated by commas.
JSON (JavaScript Object Notation): Lightweight data interchange format.
- Explain role of statistics in data science.
Statistics helps in making sense of data by providing methods for summarizing, analyzing, and interpreting information.
- Explain two methods of data cleaning for missing values.
Imputation: Replacing missing values with estimated or calculated values.
Deletion: Removing rows or columns with missing values.
- Explain any two tools in data scientist tool box.
Jupyter Notebooks: For interactive and collaborative coding.
Git: Version control system for tracking changes in code.
- Write a short note on word clouds.
Word clouds visually represent the frequency of words in a text, with the size of each word indicating its frequency. They are often used for textual data exploration and visualization.
-Explain data science life cycle with suitable diagram.
The data science life cycle typically involves stages like problem definition, data collection, data cleaning, exploration, modeling, evaluation, and deployment. It forms a cyclical process where insights drive further iterations.
-Explain concept and use of data visualisation.
Data visualization is the presentation of data in graphical or visual formats, making complex patterns and trends easily understandable. It conveys insights, patterns, and relationships within the data.
- Calculate the variance and standard deviation for the following data.
X : 14 9 13 16 25 7 12
Mean (X̄) = (14 + 9 + 13 + 16 + 25 + 7 + 12) / 7 = 96 / 7 ≈ 13.71
Variance (σ²) = Σ(Xᵢ - X̄)² / n = (0.04 + 12.49 + 0.09 + 4.84 + 64.69 + 37.69 + 1.96) / 7 ≈ 20.70
Standard Deviation (σ) = √Variance ≈ √20.70 ≈ 4.55
- Write a short note on hypothesis testing.
Hypothesis testing is a statistical method to make inferences about a population based on a sample. It involves forming a hypothesis, collecting and analyzing data, and drawing conclusions about the validity of the hypothesis.
-Differentiate between structured data and unstructured data.
Structured Data: Well-organized data with a clear format, often stored in databases.
Unstructured Data: Data lacking a predefined data model or structure, such as text, images, or videos.
- Explain data visualization libraries in Python.
Matplotlib:
- A versatile 2D plotting library that provides a wide range of charts and plots.
Seaborn:
- Built on top of Matplotlib, it simplifies the creation of attractive statistical graphics.
Pandas Plotting:
- Integrated with the Pandas library, it offers a simple interface for creating basic visualizations directly from DataFrames.
Plotly:
- Enables the creation of interactive, web-based visualizations and supports various chart types.
Bokeh:
- Another library for interactive visualizations, with a focus on modern web browsers and dynamic plots.
- Define data science.
Data Science is a deep study of the massive amount of data, which involes extracting meaningful insights from row,structured and unstructured data.
-Explain any one technique of data transformation.
Normalization:
Normalization is a data transformation technique used to scale numerical features, bringing them to a standard range, typically between 0 and 1. This ensures that all features contribute equally to analyses, especially in machine learning, by preventing features with larger scales from dominating the model. The Min-Max normalization formula is commonly employed for this purpose.
-Write any two applications of data science
1)Healthcare Predictive Analytics:
Application: Predicting disease outcomes, optimizing patient care, and personalized medicine.
2)E-commerce Recommendation Systems:
Application: Enhancing user experience and driving sales through personalized product recommendations.
WEB TECH PYQ
-Which tag is used to set the text in Superscript format?
The <sup> tag is used for superscript text in HTML.
- Explain the use of <Style>
The <style> tag in HTML is used to define the style information for a document, including CSS (Cascading Style Sheets) properties.
-How to create a directory in PHP?
The mkdir() function is used to create a directory in PHP.
- How External CSS is used?
External CSS is applied by linking an external stylesheet file to an HTML document using the <link> tag within the document's <head> section.
Example: <link rel="stylesheet" type="text/css" href="styles.css">
-Discuss the Scope of a Variable in PHP with an example
PHP has three variable scopes: local, global, and static.
CODE:-
$globalVar = "I am global";
function exampleFunction() {
$localVar = "I am local";
echo $localVar; // Accessible only inside the function
echo $GLOBALS['globalVar']; // Accessing a global variable
}
exampleFunction();
echo $localVar; // Will cause an error
-Design HTML form that will accept user input of user name, Address, provide buttons to submit the input as -wellas to refresh it.
<form action="process.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="address">Address:</label>
<textarea id="address" name="address" required></textarea>
<button type="submit">Submit</button>
<button type="reset">Refresh</button>
</form>
-Write PHP Script to accept associative array and sort in descending
order. Display sorted array to user.
$array = array("John" => 30, "Jane" => 25, "Doe" => 35);
arsort($array);
foreach($array as $key => $value) {
echo "$key: $value<br>";
}
-Explain terms HTTP request and HTTP response.
An HTTP request is a message sent by a client (usually a web browser) to request information from a server. It includes a method (like GET or POST) and a URL.
An HTTP response is a message sent by the server back to the client in response to an HTTP request. It includes information such as status codes, headers, and the requested data.
-What is hyperlink?
A hyperlink is a clickable element on a web page, typically text or an image, that, when clicked, navigates the user to another location, which can be within the same document, to another web page, or to a different resource on the internet.
- List the advantages of CSS
Separation of Concerns:
CSS separates the style and layout from the HTML structure, making the code more modular and easier to maintain.
Consistency:
CSS allows for consistent styling across multiple pages, ensuring a uniform look and feel throughout a website.
Page Load Speed:
External CSS files can be cached, reducing the load time for subsequent pages and improving overall performance.
Responsive Design:
CSS enables the creation of responsive designs that adapt to different screen sizes and devices.
- Which tag is used to set the text in superscript format?
- State the purpose of pathinfo()
The pathinfo() function in PHP is used to extract information about a file path, such as the directory name, file name, extension, and filename without extension.
- List any two features of HTTP protocol.
Statelessness:
Each request from a client to a server is independent, and the server does not retain information about the client's state between requests.
Connectionless:
After a request is made and a response is sent, the connection between the client and server is closed. Subsequent requests require establishing a new connection.
- What is web server?
A web server is software that processes incoming network requests over HTTP or HTTPS protocols. It serves web content (HTML pages, images, CSS, etc.) to clients (web browsers) based on their requests.
-Write any 2 features of PHP & HTML
PHP:
Server-Side Scripting:
PHP is a server-side scripting language, meaning it is executed on the server, and only the result is sent to the client. This allows for dynamic content generation.
Extensive Database Support:
PHP has robust support for interacting with databases, making it suitable for developing database-driven web applications.
HTML:
Markup Language:
HTML is a markup language used to structure content on the web. It provides a set of tags to define the structure of a web page.
Platform-Independent:
HTML is platform-independent, meaning it can be rendered and displayed consistently across different devices and browsers.
-Write the output of the following PHP Script
<?php
$ age = array("Anna"=>"45", "Julie"=>"38", "Benne"=>"53");
usort($age);
print_r($age);
?>
$age = array("Anna"=>"45", "Julie"=>"38", "Benne"=>"53");
usort($age);
print_r($age);
The output will be an error because usort() expects an array and usort($age) does not provide a comparison function.
-Write the output of the following script?
<?php
$a='PHP';
$b='$a interpolation ';
echo $b;
?>
$a = 'PHP';
$b = '$a interpolation ';
echo $b;
-Write the output of the following PHP Script.
$str=' abc,pqr,lmn,xyz';
$p=explode(',',$str,3);
print_r($p);
$str = 'abc,pqr,lmn,xyz';
$p = explode(',', $str, 3);
print_r($p);
OUTPUT
Array
(
[0] => abc
[1] => pqr
[2] => lmn,xyz
)
- What is the output of the following?
<?php
$p=array(1,2,3,4,5);
$q=array(1,3,5,7,9);
$s=array_diff($p,$q);
print_r($s);
?>
$p = array(1, 2, 3, 4, 5);
$q = array(1, 3, 5, 7, 9);
$s = array_diff($p, $q);
print_r($s);
-Design HTML form that will accept user input as first name, middle
name and last name, address, contact number. Provide buttons to submit
the input as well as to refresh form.
<form action="process.php" method="post">
<label for="firstName">First Name:</label>
<input type="text" id="firstName" name="firstName" required>
<label for="middleName">Middle Name:</label>
<input type="text" id="middleName" name="middleName">
<label for="lastName">Last Name:</label>
<input type="text" id="lastName" name="lastName" required>
<label for="address">Address:</label>
<textarea id="address" name="address" required></textarea>
<label for="contactNumber">Contact Number:</label>
<input type="tel" id="contactNumber" name="contactNumber" required>
<button type="submit">Submit</button>
<button type="reset">Refresh</button>
</form>
-Write a PHP script to read a file abc.txt where file contains character,
B,C,T,G and space. Count occurrences of each character and write it
to the abccount.txt file.
<?php
$filename = 'abc.txt';
$fileContents = file_get_contents($filename);
$charCount = array_count_values(str_split($fileContents));
// Write counts to a file
file_put_contents('abccount.txt', print_r($charCount, true));
?>
-Define an Introspection
Introspection is the ability of a program to examine the type or properties of an object during runtime. It allows a program to analyze its own structure or the structure of other objects.
- What is use of serialization?
Serialization is the process of converting complex data types (objects, arrays) into a format that can be easily stored or transmitted. In PHP, it's commonly used to store and retrieve object states, such as when working with sessions or caching.
-What is a constructor?
A constructor in PHP is a special method that is automatically called when an object is created from a class. It is used to initialize object properties or perform any necessary setup when an object is instantiated
class MyClass {
public function __construct() {
echo "Constructor called.";
}
}
- Write a Php program to accept associative array of five expenses
(electricity bill, phone bill, petrol bill property tax, college fees) and their
respective amount of’ two persons. print the total expenditure of each
person.
<?php
$expenses = array(
"electricity" => 120,
"phone" => 50,
"petrol" => 80,
"property_tax" => 200,
"college_fees" => 500
);
$person1 = array_sum($expenses) / 2;
$person2 = array_sum($expenses) / 2;
echo "Total expenditure for person 1: $" . $person1 . "<br>";
echo "Total expenditure for person 2: $" . $person2;
?>
-What is inheritance? Explain with suitable example.
Inheritance is a feature in object-oriented programming where a class inherits properties and methods from another class. Example:
class Animal {
public function sound() {
echo "Animal makes a sound.";
}
}
class Dog extends Animal {
public function sound() {
echo "Dog barks.";
}
}
$dog = new Dog();
$dog->sound(); // Output: Dog barks.
- Write a Php script to read a file DNA. TXT where file contains character
A, T, C G and space. Count occurrences of each character and write it
to the DNACOUNT. TXT file.
<?php
$filename = 'DNA.txt';
$fileContents = file_get_contents($filename);
$charCount = array_count_values(str_split($fileContents));
// Write counts to a file
file_put_contents('DNACOUNT.txt', print_r($charCount, true));
?>
-Explain the following statements with syntax and example
While statement
Switch statement
While Statement:
Executes a block of code repeatedly as long as a specified condition is true.
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
// Output: 1 2 3 4 5
Switch Statement:
Selects one of many blocks of code to be executed.
$day = "Monday";
switch ($day) {
case "Monday":
echo "It's the start of the week.";
break;
// More cases...
}
-What is class? Give syntax of class declaration in Php.
class MyClass {
// Properties and methods go here
}
-How to move back to the first entry in a given directory
while working with it ?
the rewinddir function to move the directory handle back to the first entry.
-Write the output of the following PHP script :
function change( )
{ $cnt ++; }
$cnt = 20;
change( );
echo $cnt;
<?php
function change() {
$cnt++;
}
<?php
function change() {
$cnt++;
}
$cnt = 20;
change();
echo $cnt;
?>
OUTPUT:
20
-Write a PHP script to define class vector with size and integer
elements. Define a construction to initialize the object. Accept
vector elements and its size from user. Also write member
functions to display its elements.
<?php
class Vector {
public $size;
public $elements;
public function __construct($size) {
$this->size = $size;
// Initialize other properties as needed
}
public function setElements($elements) {
$this->elements = $elements;
}
public function displayElements() {
print_r($this->elements);
}
}
// Usage example
$obj = new Vector(5);
$obj->setElements([1, 2, 3, 4, 5]);
$obj->displayElements();
?>
- Explain the concept of extends and implements with
class.
extends: Used for inheritance, allowing a class to inherit properties and methods from another class.
class ParentClass {
// Properties and methods
}
class ChildClass extends ParentClass {
// Additional properties and methods
}
implements: Used to implement an interface, ensuring that the class contains the methods specified by the interface.
interface MyInterface {
public function method1();
public function method2();
}
class MyClass implements MyInterface {
public function method1() {
// Implementation
}
public function method2() {
// Implementation
}
}
- How do you define constant PI with value 3.142 in PHP ?
define('PI', 3.142);
echo PI; // Output: 3.142
-What is type casting ?
Type casting is the conversion of a variable from one data type to another.
Example: Converting a string to an integer.
$strNumber = "123";
$intNumber = (int)$strNumber;
echo $intNumber; // Output: 123
-How to create object in PHP ?
To create an object in PHP, you need to define a class and then instantiate it. Here's a simple example:
class MyClass {
public $property;
public function myMethod() {
echo "Hello, I'm a method!";
}
}
// Instantiate the class
$obj = new MyClass();
// Access the property and call the method
$obj->property = "Some value";
$obj->myMethod();
-What will be output of the following :
<?php
?>
$a = “LK9”;
$a++;
Echo $a;
-List any four web browser names.
Google Chrome
Mozilla Firefox
Microsoft Edge
Safari
-List and explain (any three)the functions of PCRE.
preg_match(): Used to perform a regular expression match.
preg_replace(): Used to perform a regular expression search and replace.
preg_split(): Splits a string into an array using a regular expression.
- Write a PHP script to accept filename from the user and
print total number of words.
-Write a php script display the student details in table
format.
<?php
$filename = readline("Enter the filename: ");
$fileContent = file_get_contents($filename);
$wordCount = str_word_count($fileContent);
echo "Total number of words: $wordCount";
?>
- Explain anonymous function concept in PHP.
Anonymous functions, also known as closures, allow the creation of functions without giving them a specific name. They can be assigned to variables and used as arguments in functions. Example:
$add = function($a, $b) {
return $a + $b;
};
echo $add(3, 4); // Output: 7
- Write a short note on Interface
An interface in PHP is a contract specifying a set of methods that a class must implement. It allows for multiple inheritance and helps achieve abstraction. Classes implementing an interface must provide definitions for all the methods declared in the interface.
- State the features of PHP.
Open source.
Cross-platform (works on Windows, Linux, macOS).
Supports various databases.
Easy integration with HTML.
- State true or false :
"Include "abc.php" can be written two times in a PHP
script."
True. You can include a file multiple times in a PHP script.
- What is serialization ?
Serialization is the process of converting a data structure or object into a format that can be easily stored or transmitted, such as converting a PHP array into a string. This string can then be reversed back into the original data structure through deserialization.
-Write the output of the following PHP script :
$white="show";
$black=&$while;
unset($white);
print$black;
$white = "show";
$black = &$white;
unset($white);
print $black;
- Explain the PHP functions used to convert array into variables
and vice versa.
To convert an array into variables: extract()
To convert variables into an array: compact()
- Write a PHP script to accept three strings str1, str2, str3
from user. Search str2 in str1 and replace all occurrences
of str2 by str3. Also display total number of occurrences.
<?php
$str1 = readline("Enter the main string: ");
$str2 = readline("Enter the string to search: ");
$str3 = readline("Enter the string to replace with: ");
// Perform the search and replace
$result = str_replace($str2, $str3, $str1, $count);
// Display the result and count
echo "Result: $result\n";
echo "Total occurrences replaced: $count\n";
?>
- How to call a constructor of a parent class from a child
class ? Explain with suitable example.
Using the parent::__construct()
class ParentClass {
public function __construct() {
echo "Parent constructor\n";
}
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
echo "Child constructor\n";
}
}
// Creating an object of the child class
$obj = new ChildClass();
-Write the difference between break and continue statement
break: Exits the current loop or switch statement.
continue: Skips the rest of the current loop iteration and continues with the next one.
- Write a PHP script to implement any two set operations.
eg. union, intersection, difference.
<?php
$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 4, 5, 6, 7];
// Union
$union = array_merge($array1, $array2);
// Intersection
$intersection = array_intersect($array1, $array2);
// Difference
$difference = array_diff($array1, $array2);
// Displaying results
echo "Union: " . implode(", ", $union) . "\n";
echo "Intersection: " . implode(", ", $intersection) . "\n";
echo "Difference: " . implode(", ", $difference) . "\n";
?>
- What is abstract class ? Write features of it.
An abstract class in PHP is a class that cannot be instantiated and may contain abstract methods. Features:
May have abstract methods with no implementation.
Can have both abstract and concrete methods.
Can't be instantiated; requires subclassing.
Provides a way to define a common interface for multiple classes.
- Discuss PCRE preg_match( ) and preg_grep( ) with
example.
preg_match(): Used to perform a regular expression match against a string.
$pattern = "/[0-9]+/";
$string = "The year is 2023.";
if (preg_match($pattern, $string, $matches)) {
echo "Match found: " . $matches[0];
} else {
echo "No match found.";
}
preg_grep(): Used to perform a regular expression search in an array.
$pattern = "/^John/";
$array = ["John Doe", "Jane Smith", "Doe John"];
$result = preg_grep($pattern, $array);
print_r($result);
- Give two examples of web browsers
- Abstract class must contain all abstract methods" Justify True/False.
False. An abstract class may contain abstract methods, but it is not required to have only abstract methods. It can also have concrete (implemented) methods.
- Write a PHP program to acrept a string and print string divided into equal number of characters. (Consider spaces and enter character in calculation).
<?php
$string = readline("Enter a string: ");
$length = readline("Enter the length of each part: ");
// Using str_split to divide the string
$parts = str_split($string, $length);
// Displaying the result
echo "Result: " . implode(", ", $parts) . "\n";
?>
-Accept directory name from user. Write a PHP program to change norrent directory to acceptod directory name and count number of files and directories in it.
<?php
$directory = readline("Enter the directory path: ");
chdir($directory);
// Counting files and directories
$files = glob("*");
$fileCount = count($files);
$dirCount = count(array_filter($files, 'is_dir'));
echo "Number of files: $fileCount\n";
echo "Number of directories: $dirCount\n";
?>
-What in serialization? How is it used in PHPT
Serialization is the process of converting data into a format that can be easily stored or transmitted. In PHP, serialize() is used to convert data into a storable string, and unserialize() is used to reconstruct the original data from the serialized string.
Example:
$data = array("name" => "John", "age" => 25);
$serializedData = serialize($data);
// Store $serializedData in a file or transmit over the network
// Later, retrieve and unserialize the data
$originalData = unserialize($serializedData);
-Write a PHP program to sort array on marka (Array emtains names and marks)
<?php
$students = array(
array("name" => "Alice", "marks" => 85),
array("name" => "Bob", "marks" => 72),
array("name" => "Charlie", "marks" => 95),
);
// Sorting the array based on marks
usort($students, function($a, $b) {
return $b['marks'] - $a['marks'];
});
// Displaying the sorted array
print_r($students);
?>
- Write a short note en prepare and execute functions in databases
<?php
$students = array(
array("name" => "Alice", "marks" => 85),
array("name" => "Bob", "marks" => 72),
array("name" => "Charlie", "marks" => 95),
);
// Sorting the array based on marks
usort($students, function($a, $b) {
return $b['marks'] - $a['marks'];
});
// Displaying the sorted array
print_r($students);
?>
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind parameters
$stmt->bindParam(':username', $username);
// Execute the statement
$stmt->execute();
// Fetch results
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
-Write a PHP program to create class college and derive class science from it with accept and print methods. -Accept. information from user assign it la class members and print 141
<?php
class College {
protected $name;
public function acceptInfo($name) {
$this->name = $name;
}
public function printInfo() {
echo "College Name: " . $this->name . "\n";
}
}
class Science extends College {
// Additional properties or methods specific to the Science class can be added here.
}
// Example usage
$scienceCollege = new Science();
$scienceCollege->acceptInfo("Science College");
$scienceCollege->printInfo();
?>
- Write a short note in directory manipulation.
Directory manipulation in PHP involves operations such as creating, reading, updating, and deleting directories. Functions like mkdir (create directory), rmdir (remove directory), opendir (open directory), and scandir (scan directory) are commonly used.
-Write role of web server in internet programming. 121
A web server handles requests from clients (usually browsers), processes them, and sends back responses. It interprets server-side scripts, manages resources, and communicates with databases. Common web servers include Apache, Nginx, and Microsoft IIS.
-Stats the advantages of PHP.
-What will be output of the following
<?php
$a= "K9;
$a++;
Echo $a;
?>
<?php
$a = "K9";
$a++;
echo $a;
?>
- What is interface?
An interface in PHP is a contract that defines a set of methods a class must implement. It provides a way to achieve abstraction and multiple inheritance in PHP.
-Keywords are ense sensitive in PHP Justify True or False
True. Keywords like if, else, class, etc., are case-sensitive in PHP. For example, IF or Else would not be recognized.
What is a scientific array? Explain with an example how it's different from an indexed array. Explain a French function.
An associative array in PHP is an array where each key is associated with a specific value. Unlike indexed arrays that use numeric indices, associative arrays use named keys.
Example:
$student = array(
"name" => "John",
"age" => 20,
"grade" => "A"
);
In the example, "name," "age," and "grade" are keys associated with their respective values. A French function might be a function written in French, but it's not a standard term in PHP.
Thursday, December 7, 2023
JAVA : Chapter 5 : EXAM PREPARATION : TYBCS : SPPU
Chapter 5 User Interface with AWT and Swing
1m
(d) What is AutoBoxing and unboxing ?
d) What is AWT?
Answer: AWT stands for Abstract Window Toolkit. It is a part of JFC (Java Foundation Classes). It is a standard API for providing graphical user interface (GUI) for java program.
j) List any two listener.
Answer: Listener Is an object that watch for events and handles them when they occur.
Types of listeners:
1) Mouse listener: This interface is used for receiving mouse events.
2) Key listener: This interface is used for receiving key events.
3) Action listener: This interface is used for receiving action events.
i) What is Anonymous classes?
Answer: It is a class in java which has no name. They are used for creating event listeners where short implementation is needed.
a) Explain Inner and Nested class with example.
Answer:
2 mark
e) What is anonymous inner class?
Answer: Anonymous classes in java are more accurately known as anonymous inner class. They are defined insider another class.
4 mark
(j) Why swing objects are called as light weight components ?
Answer: The swing objects are light weight components because they are rendered mostly using pure JAVA code instead of operating system calls.
(c) Explain inner class with an example.
a) Write a Java program using AWT to change background color of table to 'RED' by clicking on button.
c) Differentiate between AWT and swing.
| Feature | AWT | Swing |
|---|---|---|
| Platform Dependency | Platform-dependent | Platform-independent |
| Component Type | Heavyweight | Lightweight |
| Customization | Limited | Extensive |
| Components | Basic set | Rich set |
| Performance | May have issues | Generally better |
| Popularity | Widely used historically | Common in modern GUI development |
Answer:
(B) (i) Explain Layout Managers used in AWT. [4]
Answer: In AWT layout managers are used to control placement and sizing of components within a container. They help us organize components within a container.
AWT provides several layout managers:
1) FlowLayout Manager:
-Here the components are arranged in left to right flow.
- It wraps the component to next row if there is not enough space.
- Few of it's constructors are
FlowLayout() : It centers all components and leaves five pixel spaces between each component.
FlowLayout(int align): It allows to specify how each line of component is align
i.e. Flowlayout.LEFT
Flowlayout.RIGHT
Flowlayout.Centre
2) Grid Layout Manager:
: It arranges components in a two dimensional grid. It has a defined number of rows and columns.
- It places items in rows (left to right) and columns (top to bottom).
- The components are present in cells and each of them have same size.
- Few of it's contructors:
GridLayout(): It creates single column grid layout.
GridLayout(int numRows, int numColumns) : It creates a grid layout with specified number of rows and columns.
3) Card Layout Manager:
- It arranges each component in a container as a card.
- Only one card is visible at a time, container acts as stack of cards.
- It has following constructors:
CardLayout(): It creates default card layout.
CardLayout(int horz, int vert): It allows us to specify horizontal and vertical space left between components horizontically and vertically respectively.
- (c) What is use of layout manager ? Explain any one layout manager ?
a) Write a Java program which will create a frame if we try to close it. It should change it’s color Red and it display closing message on the screen.(Use swing)
b) What are the different types of dialogs in Java? Write any one in detail
Answer: Dialogs are GUI elements in java used to interact with user, to gather input or present information.
Types of Dialogs
1) Message Dialogs: It displays informative messages to users like warning, error or general information.
JOptionPane.showMessageDialog();
2) JFile Chooser: Allows users to select files or directories.
JFileChooser(File currentDirectory)
3) JColor Chooser: Allows user to pick a color.
JColorChooser(Color initialColor): This constructor creates a color chooser pane with specified initial color.
c) Which swing classes are used to create menu? [2]
Answer: Swing classes used to create menus are :
1) JMenuBar: It represents menu bar , which is located at top of swing application.
2) JMenu: It represents a menu inside a menu bar.
3) JMenuItem: It represents an item in a menu.
4) JPopupMenu: It represents a pop-up menu that can be shown at specific location.
(b) How is menu created in java ? Explain with suitable example.
Answer:
(i) What is the use of Checkboxes and RadioButtons ? Explain with suitable example.
Answer: Checkboxes and Radiobuttons are components used in GUI allows users to make selections or choices. They are types of input components. They are used when users need to provide input by selecting one or more options from a set of choices.
Checkboxes are used when users can make multiple selections from a group of options.
Example of checkboxes:
JCheckBox checkbox1= new JCheckBox("Option 1");
JCheckBox checkbox2= newJCheckBox("Option 2");
JCheckBox checkbox3= newJCheckBox("Option 3");
RadioButtons are used when users need to make a single selection from a group of mutually exclusive options.
JRadioButton radioButton1 = new JRadioButton("Option 1"); JRadioButton radioButton2 = new JRadioButton("Option 2"); JRadioButton radioButton3 = new JRadioButton("Option 3");
(h) Write a syntax of JFileChooser class.
Answer: The JFileChooser class in Java Swing is used to create a file dialog that allows user to select files or directories.
import javax.swing.JFileChooser;
JFileChooser fileChooser = new JFileChooser(); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { java.io.File selectedFile = fileChooser.getSelectedFile(); // Process the selected file } else { // User canceled file selection }