Sunday 29 March 2020

General error: 1364 Field city_id doesn't have a default value


I have upgraded the MySQL from 5.5 to 5.6 and then getting below type of errors.
General error: 1364 Field 'city_id' doesn't have a default value

(I was not getting such type of error, it must come after upgrading my MySQL Version from 5.5 to 5.6)

Solution: It have 3 Solutions

  1. In Your Code (PHP), always set a default value (if no value) before save.
    $objSaveData->saveData(
        array(
            'id'=>111,
            'name'=>'New user',
            'city_id'=>0, //default value
        );
    );
    
  2. Create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.
    like below:
    ALTER TABLE `users` CHANGE `city_id` `city_id` INT(10) UNSIGNED NOT NULL DEFAULT '0';
    
  3. Disable MySQL Strict Mode (Most appropriate)
    Disable it by setting your own SQL_MODE in the my.cnf file, then restart MySQL.

    Look for the following line:
    sql-mode = "STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
    Change it to:
    sql-mode="" 
    Restart the MySQL Service.



Saturday 28 March 2020

Laravel Interview Questions and answers

Laravel Interview Questions and answers

Question: What is Laravel?
Laravel is a free and open-source PHP framework that follows the model–view–controller design pattern.


Question: What is the latest version of Laravel?
7.0, released on 3rd March 2020.


Question: Who created Laravel?
Taylor Otwell


Question: Who created Laravel?
Taylor Otwell


Question: What language does Laravel use?
PHP


Question: Which is the best IDE for Laravel?
Netbeans,
PhpStorm,
Atom,
Sublime Text


Question: Features of Laravel?
  1. Eloquent ORM
  2. Reverse routing
  3. Restful controllers
  4. Migrations
  5. Unit testing
  6. Automatic pagination
  7. Database Seeding
  8. Query builder available



Question: What are the new features of Laravel 7?
Laravel 7.0 is incorporated features such as Better routing speed, Laravel Airlock, Custom Eloquent casts, Fluent string operations, CORS support, and many more features like below.
  1. Custom Eloquent Casts
  2. Route Caching Speed Improvements
  3. HTTP Client
  4. Query Time Casts
  5. Blade Component Tags & Improvements
  6. Laravel Airlock
  7. CORS Support
  8. Fluent string operations
  9. Multiple Mail Drivers
  10. New Artisan Commands etc



Question: How to extend login expire time in Auth?
Open config\session.php file and add/update following key's value.
'lifetime' => 180



Question: What is middleware in Laravel?
Middleware operates as a bridge and filtering mechanism between a request and response.


Question: How to pass CSRF token with ajax request?
In between head, tag put
[meta name="csrf-token" content="{{ csrf_token() }}"]


In Ajax, we have to add
$.ajaxSetup({
   headers: {
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
   }
});



Question: What is laravel Service container?
Service Container is a powerful tool which is used to manage class dependencies and perform dependency injection. Also known as the IoC container.


Question: How to use session in laravel?
Retrieving Data from session
session()->get('key');

Retrieving All session data
session()->all();

Remove data from session
session()->forget('key');

Storing Data in session
session()->put('key', 'value');


Friday 27 March 2020

Kali Linux for Beginners



Question: What is Kali Linux?
Kali Linux is open-source security packages of an ethical hacker, containing lot of tools for hacking website, wifi and networks.
Kali Linux can be installed in a machine as an Operating System.


Question: How i can download the kali linux?
https://www.kali.org/downloads/


Question: Can i installed with my current LInux/windows?
Yes, you can installed.
You can install virtual machine(VM) 
In the virtual machine, you can installed kali linux.


Question: How to update the kali linux?
Use following command in linux linux terminal.
apt-get update



Question: What is Metasploitable?
Metasploitable is an intentionally vulnerable Linux virtual machine that can be used to conduct security training, test security tools, and practice common penetration testing techniques.


Question: How to install Metasploitable machine in VM?
  1. Open link 
  2. Sign up, then it will redirect to URL where automatic zip file will be downloaded
  3. Unzip the zipped file
  4. Install Metasploitable in your virtual machine
  5. You need to browse the Metasploitable location file



Question: What is default username/password for Metasploitable machine?
username/password: msfadmin/msfadmin


Question: What is NMAP and ZenMAP?
NMAP and ZenMAP are the same tool used for the scanning phase of Ethical Hacking in Kali Linux.
NMAP uses commandline tool.
ZenMAP uses GUI


Question: What is Vega?
Vega is a free and open source scanner and testing platform to test the security of web applications.
Vega can help you find and validate SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sensitive information, and other vulnerabilities.


Question: How to install Vega?
apt-get install -y vega



Question: What is ZapProxy?
ZapProxy is an easy integrated penetration testing tool for finding vulnerabilities in web applications.


Question: What is sqlmap?
sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers.



Question: What is WPScan?
WPScan is a black box WordPress vulnerability scanner that can be used to scan remote WordPress installations to find security issue.


Question: What is ZapProxy?
ZapProxy is an easy integrated penetration testing tool for finding vulnerabilities in web applications.


Thursday 26 December 2019

Hadoop - Understanding Hadoop Architecture


Hadoop is an open source framework written in java that allows distributed processing of large datasets across clusters of computers.
Hadoop is designed to scale up from single server to thousands of machines and each have local-computation and storage.

Hadoop Architecture have 4 modules.

Understanding Hadoop Architecture
  1. Hadoop Common: These are Java libraries which provides filesystem and OS level abstractions which are required to start Hadoop.
  2. Hadoop YARN: This is used for job scheduling and cluster resource management.
  3. Hadoop Distributed File System: It provides high throughput access to application data and is suitable for applications that have large data sets.
  4. Hadoop MapReduce: This is YARN-based system for parallel processing of large data sets.

Question: What is MapReduce?
MapReduce is a software framework for easily writing applications which process big amounts of data in-parallel on large clusters. It consits of master JobTracker and slave TaskTracker per cluster. The JobTracker is responsible for resource management and schedule the task. TaskTracker is responsibel for execute the task.




Question: How Does HadoopwWork at very basic level?
  1. Job Submission by client to Hadoop.
  2. Input and output files are in "distributed file system" and with use of "Hadoop Common files" Initialization the hadoop.
  3. Execute of map and reduce functions.
  4. Scheduling the task by TaskTracker.
  5. Execution the task by JobTracker.

Saturday 21 December 2019

What are special characters? and how to remove special characters?

What are special characters? and how to remove special characters?

Question: What are special characters?
Special characters are selected punctuation characters present on standard US keyboard.


Question: Provide list of special characters?
Character Name
Space
 ! Exclamation
" Double quote
# Number sign (hash)
$ Dollar sign
 % Percent
& Ampersand
' Single quote
( Left parenthesis
) Right parenthesis
* Asterisk
+ Plus
, Comma
- Minus
. Full stop
/ Slash
 : Colon
 ; Semicolon
< Less than
= Equal sign
> Greater than
 ? Question mark
@ At sign
[ Left bracket
\ Backslash
] Right bracket
^ Caret
_ Underscore
` Grave accent (backtick)
{ Left brace
| Vertical bar
} Right brace
~ Tilde



Question: How to remove special characters from string including space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-]/', '', $string);



Question: How to remove special characters from string except space?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '', $string);



Question: How to replace special characters with hyphen?
$string='test !@#ing';
echo preg_replace('/[^A-Za-z0-9\-\s]/', '-', $string);



Question: How to replace multiple hyphen with single hyphen?
$string='test-----ing';
echo preg_replace('/-+/', '-',$string);



Question: How to remove special characters from array?
$array=array('test !@#ing','sdalkjsad','#$#33');
function cleanData($string){
return preg_replace('/[^A-Za-z0-9\-]/', '', $string);
}
$array = array_map('cleanData',$array);
print_r($array);



Question: How to remove all special characters from javascript?
var stringToReplace='test !@#ing';
stringToReplace=stringToReplace.replace(/[^\w\s]/gi, '')



Monday 16 December 2019

What is CPU Usage and Memory Usage?

What is CPU Usage and Memory Usage

CPU Usage- It is the "amount of time" a CPU was used for processing the given instructions.


Memory Usage- It is the "amount of RAM" was used for processing the given instructions

Entry Processes- It is number of scripts are running at a single time. One entry process take fraction of a second to complete. So in 10 entry process you can have 10-30 visitors.

Number of Processes- It is number of process(script) can run in one time. One process take time till the execution of script.

I/O Usage- It is speed of data transfer between the hard disk and the RAM.



Question: Is high CPU usage bad?
If the CPU usage is around 100%, this means that your computer is trying to do more work than it has the capacity. Always CPU usage must be less than 90%, If so increase the CPU.




Saturday 14 December 2019

How to add number of days to a date in PHP?

How to add number of days to a date?


Program Example
$Date = "2020-09-19";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo date('Y-m-d', strtotime($Date. ' + 2 days'));

Output
2020-09-18
2020-09-19



Question: How to add number of days to a current date?
echo date('Y-m-d', strtotime("+10 days"));

It would add 10 days to the current date.


Question: How to subtract number of days to a current date?
echo date('Y-m-d', strtotime("-10 days"));

It would subtract 10 days to the current date.


Question: How to add number of days to a on given date?
$date = new DateTime('2016-12-14');
echo date('Y-m-d', ($date->getTimestamp()+ (3600*24*10) )); //3600 = 1 hour

It would add 10 days to the current date.


Question: How to subtract number of days to a given date?
$date = new DateTime('2016-12-14');
echo date('Y-m-d', ($date->getTimestamp()- (3600*24*10) )); //3600 = 1 hour

It would subtract 10 days to the current date.


Thursday 12 December 2019

How to get the sizes of the tables in mysql database?

How to get the sizes of the tables in mysql database?


Question: How to get the sizes of the tables in mysql database?
SELECT table_name "Table Name",SUM( data_length + index_length ) / 1024 / 1024 "Table Size (MB)",SUM( data_free )/ 1024 / 1024 "Free Space(MB)" FROM information_schema.TABLES WHERE table_schema='mydb' GROUP BY table_name ORDER BY SUM(TABLE_ROWS) DESC
(Replace mydb with Your Database Name)

Output
How to get the sizes of the tables in mysql database



Question: Get record counts for all tables along with size in MySQL database?
SELECT table_name "Table Name",SUM( data_length + index_length ) / 1024 / 1024 "Table Size (MB)",SUM( data_free )/ 1024 / 1024 "Free Space(MB)", SUM(TABLE_ROWS) AS "Total Record(S)" FROM information_schema.TABLES WHERE table_schema='mydb' GROUP BY table_name ORDER BY SUM(TABLE_ROWS) DESC
(Replace mydb with Your Database Name)

Output

Get record counts for all tables in MySQL database


How to resize images in php

How to resize images in php - with code

Function resizeImage
    
/**
 * 
 * @param type $width
 * @param type $height
 * @param type $mode
 * @param type $imageName
 * @param type $extension
 * @return string
 */
     function resizeImage($width, $height, $mode, $imageName,$extension) {
        $docRoot = getenv("DOCUMENT_ROOT");
        
        /* Get original image x y */
        $tmpNM = $_FILES['files']['tmp_name'];
        
        list($w, $h) = getimagesize($_FILES['files']['tmp_name']);
        /* calculate new image size with ratio */
        $ratio = max($width / $w, $height / $h);
        $h = ceil($height / $ratio);
        $x = ($w - $width / $ratio) / 2;
        $w = ceil($width / $ratio);
        /* new file name */
        if ($mode == 'userphoto') {
                $path = $docRoot . '/upload/userphoto/' . $imageName;
        } 
        
 
        /* read binary data from image file */
        $imgString = file_get_contents($_FILES['files']['tmp_name']);
        /* create image from string */
        $image = imagecreatefromstring($imgString);
        $tmp = imagecreatetruecolor($width, $height);
        imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
        $fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions
        /* Save image */
        $extension = strtolower($extension);
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
            case 'jpe':
                imagejpeg($tmp, $path, 100);
                break;
            case 'png':
                imagepng($tmp, $path,0);
                break;
            case 'gif':
                imagegif($tmp, $path, 100);
                break;
            case 'bmp':
                imagewbmp($tmp, $path);
                break;
            default:
                
                exit;
                break;
        }
        return $path;
        /* cleanup memory */
        imagedestroy($image);
       imagedestroy($tmp);
    }    



How to use Code
HTML Code

<form action="upload.php" enctype="multipart/form-data" method="post">
<input id="image upload" name="files" type="file" />
<input name="submit" type="submit" value="Upload Image" />



PHP Code
  
//List of thumbnails
$sizes = array(200 => 200, 150 => 150);

$files=array();
if (!empty($_FILES)) {
    //Clean the image name
    $_FILES['files']['name'] = preg_replace('/[^a-zA-Z0-9_.-]/', '', strtolower(trim($_FILES['files']['name'])));    
    
    //Temporary file, type, name
    $tmpNM = $_FILES['files']['tmp_name'];
    $imageType = $_FILES['files']['type'];
    $imageName = $_FILES['files']['name'];
    
    //Get image extension
    $imageNameType = explode(".", $_FILES['files']['name']);
    
    //Type of images support for uploading
    $fileMimeTypes = array('image/jpeg', 'image/png', 'image/bmp', 'image/gif'); // mime  extensions
    $fileTypes = array('jpg', 'jpeg', 'jpe', 'png', 'bmp', 'gif'); // File extensions
    
    if (in_array(strtolower($imageNameType[1]), $fileTypes)) {
        $fullImageName = time('his') . '_' . $_FILES['files']['name'];
        foreach ($sizes as $w => $h) {
            $files[] = $this->resizeImage($w, $h, 'userphoto', "{$w}_{$fullImageName}", $imageNameType[1]);
        }

    } 
}

Sunday 8 December 2019

Swagger - REST API documentation tool

Swagger - REST API documentation tool


Question: What is swagger?
It is REST API documentation tool which is used to list the APIs and view the request and response.
In this, we need to add some annotations in your functions and then it will automatically generate a beautiful and user-friendly documentation for your APIs.



Question: Where it is used?
Whenever we develop an android, IOS (Apple) application, we need to create an APIs for them.

To check the API details (URL, Request, response), we use Swagger.


Question: Who is using swagger?
Backend Developer: developer used it while creating Or updating an API.
Team Leader: As it give List of APIs with request and response. Team leader used it review the APIs.
Android/IOS Developer: While integrating the APIs, Its quite help the developer because they can check the response of APIs with different request.


Question: What are benefits of swagger?
  1. Its give list of APIs with short description.
  2. Its give the Request and Response of API.
  3. We can test the response of API with different request.
  4. We need to integrate in application first time, after the we need to add some annotations in functions/APIs.
  5. Can be integrate in Core PHP or Framework.
  6. We need not to list and details of apis manually.



Question: What is Swagger Editor?
The Swagger Editor is the tool for quickly getting started with the Swagger Specification.
Create new APIs OR update existing ones in a powerful Editor which visually renders your Swagger definition and provides real time error-feedback.
http://editor.swagger.io/#/


Question: Give a Demo URL?
http://petstore.swagger.io/


Question: From where i can download?
http://swagger.io/docs/#swagger-ui-documentation-29


Question: How to Add API in swagger?
Add Following code before the class declaration
/**
 * @SWG\Resource(
 *     apiVersion="1.0",
 *     swaggerVersion="1.2",
 *     description="Search users"
 * )
 */



Question: How to add new Operation for an API?
Add Following code before the method declaration
    /**
     * @SWG\Api(
     *     path="/search",
     *     @SWG\Operation(
     *         method="POST",
     *         summary="Get users near your location",
     *         type="Users list",
     *         @SWG\Parameters(
     *             @SWG\Parameter(
     *                 name="interests",
     *                 paramType="form",
     *                 description="comma seperated looking for",
     *                 required=false,
     *                 type="string",
     *                 minimum="1.0"
     *             ),
     *             @SWG\Parameter(
     *                 name="page",
     *                 paramType="form",
     *                 description="page number",
     *                 required=true,
     *                 type="string",
     *                 minimum="1.0"
     *             ),
     *         ),
     *         @SWG\ResponseMessage(code=400, message="Invalid Data")
     *     )
     * )
     */



Difference between channel and playlist on youtube

Difference between channel and playlist on youtube

A channel is your identity on YouTube, like your name, where your upload videos.
OR
A channel  is the home page for an your youtube account.

Question: What details are available on Channel page?
--- Basic information like Your Name, Account type etc.
--- Your public videos which you have uploaded.
--- Listing of playlist.


Question: What we can do on Channel page?
--- Update your information. --- upload videos.
--- customize the color theme of your channel.
--- Others can subscribe your channel.



Question: Sample of Youtbe Channel?
https://www.youtube.com/channel/UCFPS0qKgr-GbSRAppOkdpUA



Question: What is playlist?
A playlist is a collection of videos you may saved.


Question: List of Playlist (After Login on youtube.com with your gmail.com account)
https://www.youtube.com/view_all_playlists


Create a New Playlist (After Login on youtube)
https://www.youtube.com/view_all_playlists
Click on "New Playlist", an popup will prompt, just add the your playlist name


Question: How to add videos in playlist?
Go to playlist page (Like https://www.youtube.com/playlist?list=PLREKFLRZTg5xJJHmLiKZ0VBTKpubGXksb).
Click on "Add Videos" (Middle Right side).
An Popup will prompt.
Just add the YouTube video URL (Any video which you like) and follow Steps.


Question: What you can do with your playlist?
--- Make the playlist as public/private.
--- Add notes to each videos.
--- Re-ordering the videos.
--- AutoPlay on/off for videos.
--- Share your playlist on Fb.
--- Embed your playlist videos in your website/blog.



Question: Need Playlist Sample URL

https://www.youtube.com/playlist?list=PLREKFLRZTg5xJJHmLiKZ0VBTKpubGXksb



Question: Can we earn money with playlist?
No, You can't earn money on other's video (Uploaded by other).
You can earn money with your own videos (uploaded by you)



Saturday 7 December 2019

How to Validate email address in PHP?


How to Validate email address in PHP?


Following are in built PHP function to validate the email address and Ip Address.


Validate Email - Example 1
$email='helo@gmail.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. ' - Invalid'; 
}else{
echo $email. ' - Valid';     
}

helo@gmail.com - Valid

Validate Email - Example 2
$email='464646@gmail.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. '- Invalid'; 
}else{
echo $email. ' - Valid';     
}

464646@gmail.com - Valid

Validate Email - Example 3
$email='arunkumar.com';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo $email. ' - Invalid'; 
}else{
echo $email. ' - Valid';     
}


arunkumar.com - Invalid



Validate IP Address - Example 1
Question: How to Validate IP Address?
$ipAddress = '127.0.0.1';
if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
    echo "$ipAddress is In-valid.";
}else{
    echo "$ipAddress is Valid.";
}

127.0.0.1 is Valid

Validate IP Address - Example 2
$ipAddress = '127.test.0.0.1';
if (!filter_var($ipAddress, FILTER_VALIDATE_IP)) {
    echo "$ipAddress is In-valid.";
}else{
    echo "$ipAddress is In-Valid.";
}

127.test.0.0.1 is Valid


Validate URL - Example 1
$ipAddress = '127.test.0.0.1';
$website = 'https://www.web-technology-experts-notes.in';
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  echo   "Invalid URL";
}else{
echo   "Valid URL";
}

Valid URL

Friday 22 November 2019

How to setup different configs in server (development, production)?

How to implement different configs for development, production?

Question: How to implement different configs for development, production etc?
  1. Added following line in .htacess (Location: /public/.htaccess)
    SetEnv APPLICATION_ENV development
    This is for development.
  2. Open application.config.php in /config/application.config.php
  3. Get the current environment.
    $applicationEnv = getenv('APPLICATION_ENV');

    Dynamic the file like below:
            'config_glob_paths' => array(         
                "config/autoload/{,*.}{$applicationEnv}.php"
            )
  4. Create the config files like below in /config/autoload
    development.php
    production.php
    
  5. Below are the sample of config file.
    return array(
        'db' => array(
            'driver' => 'Pdo',
            'dsn' => 'mysql:dbname=DBNAME;host=HOST',
            'username' => 'DB_USERNAME',
            'password' => 'DB_PASSWORD'
        )
    );
    Please update the database credentials.

Saturday 16 November 2019

How to Send Tweets automatically with PHP?

How to Send Tweets automatically with PHP?


Basic Requirements
  1. An Twitter account.
  2. An Twitter app. If don't have please create @ https://apps.twitter.com
  3. Twitter Auth REST API, If don't have please download from https://github.com/abraham/twitteroauth
  4. An Server, You can also test in local wampserver or xampserver


How to Send Tweets automatically with PHP, Follow following Steps:
  1. Include twitter files.
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/twitteroauth.php');
    require_once($_SERVER['DOCUMENT_ROOT'].'/twitteroauth/config.php');
  2. Collect all constants values from your twitter app (i.e apps.twitter.com)

  3. Add constants in TwitterOAuth constructor.
    define('CONSUMER_KEY', 'YOUR_KEY');
    define('CONSUMER_SECRET', 'YOUR_SECRET_KEY');
    define('ACCESS_TOKEN', 'YOUR_TOKEN');
    define('ACCESS_TOKEN_SECRET', 'YOUR_TOKEN_SECRET');
    
  4. $twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET,ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
  5. Now post the message.
    $message='This is test tweet.';
    $twitter->post('statuses/update', array('status' => $message));
  6. Refresh the twitter.com, you will see your message at top of page.

Saturday 9 November 2019

Paypal Mass Payment - Pay with email Address

Paypal Mass Payment - Pay with email Address

Mass Pay. Merchants can use the Mass Pay API to send money instantly to multiple recipients at once.


Question: Can I pay someone with their email address (Manual Transaction)?
Yes, you can pay.


Question: When money will deduct from sender account(Manual Transaction)?
As soon as you pay, money will be deducted from the sender account.


Question: When money will be credited to the receiver account(Manual Transaction)?
When you pay with email address and that email is already register with paypal.
Money will be credited immediately.

If email address is not registered, then receiver will get an email from paypal and he need to follow the steps in email to received.


Question: When money will deduct from sender account(Manual Transaction)?
As soon as you pay, money will be deducted from the sender account.


Question: What are transaction charges (Manual Transaction)?
If you are paying to your friend/family member and they are within same country - Its Free.
If you are paying for commerical purpose, No transaction charges for Sender/Buyer and (2.3% +.30 USD) will be deducted from seller/reciever.


Question: Can I can Cancel the payment after sending?
You can cancel only if he has not accept the payment.
but receiver can refund money to you.


Question: Is there any API available to pay with email address?

You can use MassPay API OR Adaptive Payments API. Question: What is Mass Paypal?
In this case, One Merchant can send the money to his partner's paypal email address (Paypal email address), mean each merchant must have paypal account. https://developer.paypal.com/docs/classic/mass-pay/integration-guide/MassPayOverview/


Question: What are keys of Mass Paypal through API?
  1. When we send payment with email address PayPal takes the payment amounts from your account and attempts to put them into the recipients' PayPal account.
  2. If the recipients do not have PayPal accounts, PayPal notifies them that a payment is available and they must create a PayPal account to receive the payment.
  3. Payments processing can take from a couple of minutes to several hours.
  4. PayPal will temporarily hold the total monetary value of the mass payment, plus associated fees, until processing is completed.
  5. If a payment is sent to a recipient who does not have a PayPal account, and it remains unclaimed for 30 days from the payment date, the money is returned to your PayPal account.
  6. Mass Payments need to enable for PayPal.
  7. You can only cancel payments that have an unclaimed payment.



Question: What is Mass Paypal Request parameter?
Array
(
    [METHOD] => MassPay
    [USER] => testname_api1.no-spam.ws
    [PWD] => 55555526677
    [SIGNATURE] => Alsdfdsfafdsfs.zYsROoDYkL2AigOq
    [VERSION] => 95
    [RECEIVERTYPE] => EmailAddress
    [CURRENCYCODE] => USD
    [L_EMAIL0] => testnamel@no-spam.ws
    [L_AMT0] => 10.00
    [L_EMAIL1] => testname2@no-spam.ws
    [L_AMT1] => 10.00
)



Git interview questions and answers - Problem and Solutions


Git interview questions and answers - Problem and Solutions

Question: How to delete a Git branch both locally and remotely?
To remove a local branch from your local system.
git branch -d the_local_branch

To remove a remote branch from the server.
git push origin :the_remote_branch



Question: How do you undo the last commit?
git revert commit-id



Question: How to Edit an incorrect commit message in Git?
git commit --amend -m "This is your new git message"



Question: What are the differences between 'git pull' and 'git fetch'?
Git pull automatically merges the commits without letting you review them first.
Git fetch stores them in your local repository but it not merge them with your current branch.
git fetch similar to guit pull but it does not merge the changes.


Question: How do you rename the local branch?
git branch -m oldBranchName newBranchName



Question: How do I remove local files (Not in Repo) from my current Git branch?
git clean -f -n


Question: How to Checkout remote Git branch?
git checkout test



Question: How do I remove a Git submodule?
git rm the_submodule
rm -rf .git/modules/the_submodule



Question: How do you create a remote Git branch?
git checkout -b your_branch_name
git push -u origin your_branch_name



Question: How to Change the URL for a remote Git repository?
git remote set-url origin git://this.is.new.url



Question: How to Change the author of a commit in Git?
git filter-branch -f --env-filter "GIT_AUTHOR_NAME='NewAuthorName'; GIT_AUTHOR_EMAIL='authoremail@gmail.com'; GIT_COMMITTER_NAME='CommiterName'; GIT_COMMITTER_EMAIL='committergmail@gmail.com';" HEAD



Question: What is .gitignore?
.gitignore tells git which files/folder should be ignore.
Create a file with name of .gitignore in root.
temporay files, system files, hidden files or local downloaded modules we can add in .gitignore file, so that git will not added this.


Question: How do I delete a Git branch locally?
git branch -d {the_local_branch}


Question: How do I delete a Git branch remotely?
git push origin --delete {the_remote_branch}
(use -D instead to force deleting the branch without checking merged status)


Question: What is the difference between git pull and git fetch?
git pull does a git fetch followed by a git merge.



Question: How do I undo git add before commit?
git reset file.php



Question: How do I rename a local Git branch?
git branch -m oldname newname




Question: How do I discard unstaged changes in Git?
git stash save --keep-index --include-untracked

You don't need to include --include-untracked if you don't want to be thorough about it.
After that, you can drop that stash with a git stash drop command if you like.


Sunday 3 November 2019

Node.js questions and answers for 1 year experience

Node.JS questions and answers for 1 year experience

Question: How to update NPM?
npm install -g npm



Question: How to write in file through NodeJs?
For this, you need to use filesystem API.
var fs = require('fs'); //Create Object
var fileName='/tmp/myfile.txt';
var fileContent='Hello this is text message';
fs.writeFile(fileName, fileContent, function(err) {
    if(err) {
        return console.log('error:'+err);
    }
    console.log("Content saved in File successfully");
}); 



Question: How to check File Exist OR Not?
For this, you need to use filesystem API.
var fs = require('fs');
var fileName='/tmp/myfile.txt';
if (fs.existsSync(fileName)) {
    console.log('File Exist');
}else{
 console.log('File Does not Exist');
}



Question: How to remove a file?
For this, you need to use filesystem API.
var fs = require('fs');
var fileName='/tmp/myfile.txt';
fs.unlinkSync(fileName);



Question: How to read process EVN?
console.log(process.env)
Output
{ 
  ENV_NODE_CONSOLE: 'production',
  DYNO: 'web.1',
  PATH: '/app/vendor/node/bin:/app/bin:/app/node_modules/.bin:bin:node_modules/.bin:/usr/local/bin:/usr/bin:/bin',
  PWD: '/app',
  MONGOLAB_URI: 'mongodb://heroku_app14996339_A:PQrhCoawHlCQcpOQNRkBeEbXLXnhYNSz@ds043987.mongolab.com:43987/heroku_app14996339',
  PS1: '[033[01;34m]',
  NODE_ENV: 'production',
  SHLVL: '1',
  HOME: '/app',
  NO_CLUSTER: 'true',
  PORT: '24118',
  _: '/app/vendor/node/bin/node'
 }



Question: How to retrieve POST query parameters in Express?
app.post('/test-page', function(req, res) {
    console.log(req.body);//here is post data
});



Question: How to encode a sting using base64_encode?
console.log(new Buffer("1").toString('base64')); //MQ==



Question: How to decode a sting using base64_decode?
console.log(new Buffer("MQ==", 'base64').toString('ascii'));//1



Question: How can I pretty-print JSON using node.js?
var testVar ='{ a:1, b:2, c:3 }, null, 4';
JSON.stringify(testVar);



Question: How to exit in Node.js?
process.exit()
.


Question: How to exit from unix terminal in Node.js?
ctr+c twice




Saturday 2 November 2019

PHP interview questions and answers for 3 year experience

PHP interview questions and answers for 3 year experience

Question: Are PHP functions case sensitive?
Inbuilt function are not sensitive.
User defined functions are senstivie.

Case sensitive (both user defined and PHP defined)
  1. variables
  2. constants
  3. array keys
  4. class properties
  5. class constants

Case insensitive (both user defined and PHP defined)
  1. functions
  2. class constructors
  3. class methods
  4. keywords and constructs (if, else, null, foreach, echo etc.)






Question: How to return call by reference value from function?
Just use &(ampersand) before the function name.
For Example.
function &showData($data){
   $data.=' New String';    
   return $data;
}



Question: How to check a form is submited OR Not?
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //form is submitted
}



Question: How to remove all leading zeros from string?
echo ltrim('00000012', '0'); //12



Question: How to find HTTP Method?
$_SERVER['REQUEST_METHOD']
It will return GET, HEAD, POST, PUT etc


Question: How to Serializing PHP object to JSON?
$userModel = new UserModel();
echo json_encode($userModel);//serialize data



Question: How to get current URL of web page?
echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];



Question: How to add N number of days in an data?
echo date('Y-m-d', strtotime("+30 days"));



Question: How to get Yesterday date?
echo date("F j, Y", time() - 60 * 60 * 24); //November 1, 2016


Question: What's the maximum size for an int in PHP? The size of an integer is platform-dependent
Maximum value of about two billion for 32 bit system.


Question: How to remove all specific characters at the end of a string?
$string = 'Hello. * cool';
echo $string = str_replace(array('*', '.',' '), '', $string); //Remove * . and space [you can add more as you want]