Github copilot usage and integration with VS Code

Github copilot is an AI pair programming tools, which can be integrated with your IDEs. This will give you AI based autocomplete suggestions, code fixes, unit tests etc.

You can visit https://docs.github.com/en/copilot to get the details about copilot

Currently copilot will only be available on these platforms/IDEs/tools. Azure Data Studio, Jetbrains, VIM/NeoVIm, Visual Studio and in Visual studio code.

Here I am using VS code. let’s learn.

First you have to install or download VS code in your machine. After installing

  1. Search for copilot extension in Extension tab.
  2. Install copilot and copilot chat
  3. If you are using an enterprise authentication, you may need Win CA or Mac CA extensions as well.

After installing above, restart the VS code and Authenticate your copilot with your github credentials.

Once it’s successfully installed, you should be able to see an icon on right side bottom side of VS code, which will show ready status of copilot in your VS code.

Here are some shortcut keys that you can use with VS code.

For windows

ActionShortcutCommand name
Accept an inline suggestionTabeditor.action.inlineSuggest.commit
Dismiss an inline suggestionEsceditor.action.inlineSuggest.hide
Show next inline suggestionAlt+]editor.action.inlineSuggest.showNext
Show previous inline suggestionAlt+[editor.action.inlineSuggest.showPrevious
Trigger inline suggestionAlt+\editor.action.inlineSuggest.trigger
Open GitHub Copilot (additional suggestions in separate pane)Ctrl+Entergithub.copilot.generate
Toggle GitHub Copilot on/offNo default shortcutgithub.copilot.toggleCopilot

For Mac

ActionShortcutCommand name
Accept an inline suggestionTabeditor.action.inlineSuggest.commit
Dismiss an inline suggestionEsceditor.action.inlineSuggest.hide
Show next inline suggestionOption (⌥)+]editor.action.inlineSuggest.showNext
Show previous inline suggestionOption (⌥)+[editor.action.inlineSuggest.showPrevious
Trigger inline suggestionOption (⌥)+\editor.action.inlineSuggest.trigger
Open GitHub Copilot (additional suggestions in separate pane)Ctrl+Returngithub.copilot.generate
Toggle GitHub Copilot on/offNo default shortcutgithub.copilot.toggleCopilot

For Linux

ActionShortcutCommand name
Accept an inline suggestionTabeditor.action.inlineSuggest.commit
Dismiss an inline suggestionEsceditor.action.inlineSuggest.hide
Show next inline suggestionAlt+]editor.action.inlineSuggest.showNext
Show previous inline suggestionAlt+[editor.action.inlineSuggest.showPrevious
Trigger inline suggestionAlt+\editor.action.inlineSuggest.trigger
Open GitHub Copilot (additional suggestions in separate pane)Ctrl+Entergithub.copilot.generate
Toggle GitHub Copilot on/offNo default shortcutgithub.copilot.toggleCopilot

java.lang.NoSuchMethodError: ‘com.google.common.collect.ImmutableMap Selenium 4 webdriver chrome Maven project

To fix this, first check your project has any dependency related to “com.google.guava”. like older versions resolve that dependencies. Remove the older versions

And add this dependency in your pom.xml or in project build path

<dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>31.0.1-jre</version>
    </dependency>

Module not found: Error: Can’t resolve ‘./serviceWorker’ in React compilation error

Use

npx create-react-app app-name –template cra-template-pwa

Rather

npx create-react-app app-name

Read excel and convert to Hashmap ConcurrentHashMap using Java

public static ConcurrentHashMap<String, ConcurrentHashMap<String, String>> dataMap = new ConcurrentHashMap<>();
	public static ConcurrentHashMap<String, String> cellValues = null;

	public static void main(String[] args) {
		getData();
		for (String key : dataMap.keySet()) {

			System.out.println(dataMap.get(key));
		}
	}

	private static Object getCellValue(Cell cell) {

		switch (cell.getCellType()) {
		case STRING:
			return cell.getStringCellValue();
		case NUMERIC:
			return cell.getNumericCellValue();

		case BOOLEAN:
			return cell.getBooleanCellValue();
		default:
			break;
		}

		return null;
	}

	public static void getData() {
		try {

			FileInputStream fis = new FileInputStream("Data/ServiceTesting.xlsx");
			XSSFWorkbook workbook = new XSSFWorkbook(fis);
			XSSFSheet sheet = workbook.getSheetAt(0);
			Iterator<Row> rowIterator = sheet.iterator();
			while (rowIterator.hasNext()) {
				Row row = rowIterator.next();
				Iterator<Cell> cellIterator = row.cellIterator();
				String key = row.getCell(0).toString();
				cellValues = new ConcurrentHashMap<>();
				while (cellIterator.hasNext()) {
					Cell cell = cellIterator.next();
					if (cell.getRowIndex() != 0) {

						String header = sheet.getRow(0).getCell(cell.getColumnIndex()).getStringCellValue();
						String clellValue = (String) getCellValue(cell);
						cellValues.put(header, clellValue);
					}

				}
				if (row.getRowNum() != 0) {
					dataMap.put(key, cellValues);
				}

			}
			workbook.close();
			fis.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

Paypal Smart Button Payment Gateway Integration Using pure PHP and ajax post Save to DB

Reference

https://developer.paypal.com/docs/checkout/integrate/

and server side setup https://developer.paypal.com/docs/checkout/reference/server-integration/setup-sdk/

  1. Create paypal developer account
  2. Create an app and get client id and secret id
  3. Use sandbox or business and personal accounts
  4. Install Composer in your machine https://getcomposer.org/
  5. Create a project
  6. Create dependency for PHP
  7. Inside project folder execute “composer require paypal/paypal-checkout-sdk 1.0.1” reference from and server side setup https://developer.paypal.com/docs/checkout/reference/server-integration/setup-sdk/
  8. create index.php with below code
<!DOCTYPE html>
<html lang="en">

    <head>
        <script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
        <!-- Add meta tags for mobile and IE -->
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title> PayPal Checkout Integration | Server Demo </title>

    </head>

    <body>
        <!-- Set up a container element for the button -->
        <div id="paypal-button-container"></div>

        <!-- Include the PayPal JavaScript SDK -->
        <script src="https://www.paypal.com/sdk/js?client-id=Giveyourclientid"></script>

        <script>
            // Render the PayPal button into #paypal-button-container
            paypal.Buttons({
                // Call your server to set up the transaction
                createOrder: function(data, actions) {
                    // This function sets up the details of the transaction, including the amount and line item details.
                    return actions.order.create({
                        purchase_units: [{
                                amount: {
                                    value: '10.01'
                                }
                            }]
                    });
                },
                onApprove: function(data, actions) {
                    // This function captures the funds from the transaction.
                    return actions.order.capture().then(function(details) {
                        if (details.status === 'COMPLETED') {
                            // This function shows a transaction success message to your buyer.
                            $.ajax({
                                url: 'gettransaction.php',
                                type: 'POST',
                                data: JSON.stringify(data),
                                contentType: 'application/json; charset=utf-8',
                                dataType: 'json',
                                async: false,
                                success: function(msg) {
                                    alert(msg);
                                }
                            }).then(function(response) {
                                // redirect to the completed page if paid
                                console.log(response);
                                window.location.href = 'ThankYou.php';
                            }). catch (function(error) {
                                // redirect to failed page 
                                console.log(error);
                                window.location.href = 'paymentFailed.php?reason=internalerror';
                            });
                            // alert('Transaction completed by ' + details.payer.name.given_name);
                        } else {
                            window.location.href = 'paymentFailed.php?reason=failed';

                        }
                    });
                },
                onCancel: function(data) {
                    window.location.href = 'paymentFailed.php?reason=cancelled';
                }


            }).render('#paypal-button-container');
        </script>
    </body>

</html>

9. Create Thank you page, payment failed pages.. etc for your redirections.

10. Create get transaction page, which has code to save it to db

<?php

namespace Sample;

require __DIR__ . '/vendor/autoload.php';

//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;

class GetOrder
{

    // 2. Set up your server to receive a call from the client
    /**
     * You can use this function to retrieve an order by passing order ID as an argument.
     */
    public static function getOrder($orderId)
    {

        // 3. Call PayPal to get the transaction details
        $client = PayPalClient::client();
        $response = $client->execute(new OrdersGetRequest($orderId));
        echo json_encode($response->result, JSON_PRETTY_PRINT);
        die();
        /**
         * Enable the following line to print complete response as JSON.
         */
        print json_encode($response->result);
        print "Status Code: {$response->statusCode}\n";
        print "Status: {$response->result->status}\n";
        print "Order ID: {$response->result->id}\n";
        print "Intent: {$response->result->intent}\n";
        print "Links:\n";
        foreach ($response->result->links as $link) {
            print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
        }
        // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
        print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
        print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
        $sl = $response->result->status;
        //code to db
        $db = mysqli_connect('localhost:3306', 'root', '', 'paymentdetails');
        echo "database connected";
        $sql = "INSERT INTO transaction(orderid) VALUES('$sl')";
        mysqli_query($db, $sql);
        echo "data inserted successfully";
        // To print the whole response body, uncomment the following line
        // echo json_encode($response->result, JSON_PRETTY_PRINT);
    }

}

/**
 * This driver function invokes the getOrder function to retrieve
 * sample order details.
 *
 * To get the correct order ID, this sample uses createOrder to create a new order
 * and then uses the newly-created order ID with GetOrder.
 */
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
print_r($data);
echo 'order id = ' . $data->orderID;
if (!count(debug_backtrace())) {
    GetOrder::getOrder($data->orderID, true);
}
?>

execute from index.php

Error: Could not import “app”. vs code

Update vscode launch.json with correct path to

“FLASK_APP”: “yourfolderorthefolderofapp.py/app.py”,

“configurations”: [        {            “name”: “Python: Flask”,            “type”: “python”,            “request”: “launch”,            “module”: “flask”,            “env”: {                “FLASK_APP”: “backend/app.py”,                “FLASK_ENV”: “development”,                “FLASK_DEBUG”: “0”            },

ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly

Update the installation requirements.txt with cryptography==3.1.1

How to install Python packages with pip and requirements.txt

cd to the directory where requirements.txt is located.
activate your virtualenv.
execute pip install -r requirements.txt in your terminal

python flask vs code error FullyQualifiedErrorId : UnauthorizedAccess

IF you are getting an error while activating venv in pythong flask

CategoryInfo : SecurityError: (:) [], PSSecurityException
FullyQualifiedErrorId : UnauthorizedAccess

Then Open powershell as administrator and set execution policy

type : Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine

Reopen vscode again and try the venv activation again.


phpmyadmin mysql root user no privileges error

Run mysql server using “mysqld_safe –skip-grant-tables &” from command prompt.

or update mysql config with mysql/my.cnf or my.ini with

[mysqld]
skip-grant-tables

Now create a new user with mysqladmin -u USERNAME password ‘password’

Then login to mysql with mysql -u USERNAME -p

Enter password

Enter command “flush privileges;”

Then enter command “GRANT ALL on *.* to ‘USERNAME’@’localhost’ identified by ‘password’;”

Restart the server.

Now login to phpmyadmin with created user.

Update config.inc.php with

$cfg[‘Servers’][$i][‘auth_type’] = ‘cookie’;
$cfg[‘Servers’][$i][‘user’] = ‘USERNAME’;
$cfg[‘Servers’][$i][‘password’] = ”;

Restart mysql server

Login to Phpmyadmin with the created new user.