Sunday, February 26, 2017

How to do a regular expression replace string in MySQL?

How to do a regular expression replace string in MySQL?

Install a MySQL user defined function called lib_mysqludf_preg from:

http://www.mysqludf.org/

https://github.com/mysqludf/lib_mysqludf_preg

For RedHat / CentOS:

# yum -y install pcre-devel gcc make automake mysql-devel

For Debian / Ubuntu:

# apt-get update
# apt-get install build-essential libmysqld-dev libpcre3-dev

Install lib_mysqludf_preg:

# git clone https://github.com/mysqludf/lib_mysqludf_preg.git
# ./configure
# make
# make install
# make installdb
# make test

Example:

SELECT CONVERT( PREG_REPLACE( '/fox/i' , 'dog' , 'The brown fox' ) USING UTF8) as replaced;

Saturday, February 25, 2017

To reset admin password:

Method 1 - reset admin password directly in database:

mysql> SET @salt = MD5(UNIX_TIMESTAMP());
mysql> UPDATE admin_user SET password = CONCAT(SHA2(CONCAT(@salt, 'MyNewPassword'), 256), ':', @salt, ':1') WHERE username = 'admin';

Method 2 - using PHP to generate the password. Then, reset it in database:

# php -r '$salt = md5(time()); echo hash("sha256", $salt . $argv[1]).":$salt:1\n";' MyNewPassword

66bdd4e5008cad465a6cd23eb6ac3aa6ef4c65d07a179157bab11935f9f4d62f:a4506164831ba6f12474a3ffe57602d0:1

mysql> UPDATE admin_user SET password = '<code above>' WHERE username='admin';

Method 3 - Generating the password. Then, reset it in database:

Add the following line at the last line and loot at the footer of any page.

# vim pub/index.php

echo \Magento\Framework\App\ObjectManager::getInstance()->get("\Magento\Framework\Encryption\Encryptor")->getHash("MyNewPassword");

Method 4 - Create a new admin user. Then, reset the previous admin password:

# php bin/magento admin:user:create --admin-user=admin2 --admin-password=MyNewPassword2 --admin-email=admin@example.com --admin-firstname=admin --admin-lastname=admin

Reference:

http://magento.stackexchange.com/questions/90922/how-to-reset-lost-admin-password-in-magento-2/161792#161792

Wednesday, February 22, 2017

To dump access database to MySQL sql file

To dump access database to MySQL sql file

1. Use Navicat

https://www.navicat.com/

2. Use Access To MySQL by bullzip

http://www.bullzip.com/products/a2m/info.php

Wednesday, February 15, 2017

View Google Chrome downloaded cached images and videos

View Google Chrome downloaded cached images and videos

Type: chrome://cache/

Print SQL query for the collection for debugging in Magento 2

Print SQL query for the collection for debugging in Magento 2

$productCollection->getSelect()->assemble();

Change Session timeout in Magento 2

Change Session timeout in Magento 2

System > Configuration > Advanced > Admin > Security > Session Lifetime (Seconds)

# vim php.ini

session.gc_maxlifetime = 36000

Tuesday, February 14, 2017

Get product tier pricing programmatically in Magento 2

Get product tier pricing programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$productId = 1;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product_obj = $objectManager->create('\Magento\Catalog\Model\Product')->load($productId);

getDefaultGroup($product_obj);
getAnyGroup($product_obj);

function getDefaultGroup($product_obj) {
 $tier_price = $product_obj->getTierPrice();

 if(count($tier_price) > 0){
  echo "price_id\tprice_qty\tprice\twebsite_price\n";

  foreach($tier_price as $price){
   echo $price['price_id'];
   echo "\t";
   echo $price['price_qty'];
   echo "\t";
   echo $price['price'];
   echo "\t";
   echo $price['website_price'];
   echo "\n";
  }
 } else {
  echo 'There is no tiering price for the default group.' . PHP_EOL;
 }
}

function getAnyGroup($product_obj) {
 $tier_price = $product_obj->getTierPrices();

 if(count($tier_price) > 0){
  echo "price_qty\tprice\tCustomerGroupId\n";

  foreach($tier_price as $price){
   echo $price->getQty();
   echo "\t";
   echo $price->getValue();
   echo "\t";
   echo $price->getCustomerGroupId();
   echo "\t";
   echo "\n";
   print_r($price->getData());
   echo "\t";
   echo "\n";
  }
 }
}

#print_r($tier_price);
#print_r(get_class_methods($price));

Get customer information programmatically in Magento 2

Get customer information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getId();

#$websiteId = $storeManager->getWebsite()->getWebsiteId();
$websiteId = $storeManager->getStore($storeId)->getWebsiteId();

// Customer Factory to Create Customer
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
$customer = $customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail('test@example.com');  

$data = $customer->getData(); 
print_r($data);

$defaultBilling = $customer->getDefaultBillingAddress();
$defaultShipping = $customer->getDefaultShippingAddress();

foreach ($customer->getAddresses() as $address) {
 echo 'IsDefaultBillingAddress: ' . ($defaultBilling && $defaultBilling->getId() == $address->getId() ? 'Yes' : 'No') . PHP_EOL;
 echo 'IsDefaultShippingAddress: ' . ($defaultShipping && $defaultShipping->getId() == $address->getId() ? 'Yes' : 'No') . PHP_EOL;

 echo 'ID: ' . $address->getId() . PHP_EOL;
 echo 'First Name: ' . $address->getFirstname() . PHP_EOL;
 echo 'Last Name: ' . $address->getLastname() . PHP_EOL;
 echo 'Street: ' . implode("\n", $address->getStreet()) . PHP_EOL;
 echo 'City: ' . $address->getCity() . PHP_EOL;
 echo 'Country: ' . $address->getCountry() . PHP_EOL;
 echo 'Region: ' . $address->getRegion() . PHP_EOL;
 echo 'Postal Code: ' . $address->getPostcode() . PHP_EOL;
 echo 'Phone: ' . $address->getTelephone() . PHP_EOL;
 echo PHP_EOL;

 #print_r(get_class_methods($address));
 #break;
}

Get product information programmatically in Magento 2

Get product information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getId();

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$productCollection = $productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');

foreach ($productCollection as $product) {
 echo 'Id: ' . $product->getId() . PHP_EOL;
 echo 'Sku: ' . $product->getSku() . PHP_EOL;
 echo 'Price: ' . $product->getPrice() . PHP_EOL;
 echo 'Weight: ' . $product->getWeight() . PHP_EOL;
 print_r($product->getData());
 echo PHP_EOL;
}

Get store information programmatically in Magento 2

Get store information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getId();

$baseURL = $storeManager->getStore($storeId)->getBaseUrl();
$mediaBaseURL = $storeManager->getStore($storeId)->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$linkBaseURL = $storeManager->getStore($storeId)->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_LINK);

$websiteId = $storeManager->getStore($storeId)->getWebsiteId();
$storeCode = $storeManager->getStore($storeId)->getCode();
$storeName = $storeManager->getStore($storeId)->getName();
$currentUrl = $storeManager->getStore($storeId)->getCurrentUrl();
$isActive = $storeManager->getStore($storeId)->isActive();
$isFrontUrlSecure = $storeManager->getStore($storeId)->isFrontUrlSecure();
$isCurrentlySecure = $storeManager->getStore($storeId)->isCurrentlySecure();

echo 'baseURL: ' . $baseURL . PHP_EOL;
echo 'mediaBaseURL: ' . $mediaBaseURL . PHP_EOL;
echo 'linkBaseURL: ' . $linkBaseURL . PHP_EOL;
echo 'websiteId: ' . $websiteId . PHP_EOL;
echo 'storeCode: ' . $storeCode . PHP_EOL;
echo 'storeName: ' . $storeName . PHP_EOL;
echo 'currentUrl: ' . $currentUrl . PHP_EOL;
echo 'isActive: ' . $isActive . PHP_EOL;
echo 'isFrontUrlSecure: ' . var_export($isFrontUrlSecure, true) . PHP_EOL;
echo 'isCurrentlySecure: ' . var_export($isCurrentlySecure, true) . PHP_EOL;

Update product stock information programmatically in Magento 2

Update product stock information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

### Reference:
### http://magento.stackexchange.com/questions/96519/magento-2-programmatically-updating-inventory
$sku = 'WWW1';
$stockQty = 55;

$productRepository = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface');
$stockRegistry = $objectManager->create('\Magento\CatalogInventory\Api\StockRegistryInterface');

### Load product by SKU
$product = $productRepository->get($sku);

### Load stock item
$stockItem = $stockRegistry->getStockItem($product->getId());

$stockItem->setQty($stockQty);
#$stockItem->setData('qty', $stockQty);

#$stockItem->setData('manage_stock', $stockData['manage_stock']);
#$stockItem->setData('is_in_stock', $stockData['is_in_stock']);
#$stockItem->setData('use_config_notify_stock_qty', 1);

print_r($stockItem->getData());

$stockRegistry->updateStockItemBySku($sku, $stockItem);

Monday, February 13, 2017

Get product stock information programmatically in Magento 2

Get product stock information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$stockItemRepository = $objectManager->get('\Magento\CatalogInventory\Model\Stock\StockItemRepository');

$productId = 1;

$productStock = $stockItemRepository->get($productId);

echo 'Qty: ' . $productStock->getQty() . PHP_EOL;
echo 'getMinQty: ' . $productStock->getMinQty() . PHP_EOL;
echo 'getMinSaleQty: ' . $productStock->getMinSaleQty() . PHP_EOL;
echo 'getMaxSaleQty: ' . $productStock->getMaxSaleQty() . PHP_EOL;
echo 'getIsInStock: ' . $productStock->getIsInStock() . PHP_EOL;

Create customer with address programmatically in Magento 2

Create customer with address programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

### Reference:
### https://vinothkumaarr.wordpress.com/2016/05/13/add-customer-and-address-programmatically-magento2/

createCustomer();

function createCustomer() {
 global $objectManager;

 $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
 $storeId = $storeManager->getStore()->getId();

 #$websiteId = $storeManager->getWebsite()->getWebsiteId();
 $websiteId = $storeManager->getStore($storeId)->getWebsiteId();

 ### Instantiate object (this is the most important part)
 $customer = null;

 try{
  #$customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
  $customer = $objectManager->get('\Magento\Customer\Api\Data\CustomerInterfaceFactory')->create();
  $customer->setWebsiteId($websiteId);

  ### Preparing data for new customer
  $email = 'test14@example.com';
  $customer->setEmail($email);
  $customer->setFirstname("test first");
  $customer->setLastname("test last");
  #$customer->setPassword("test123");
  $hashedPassword = $objectManager->get('\Magento\Framework\Encryption\EncryptorInterface')->getHash('MyNewPass', true);

  ### Save data
  #$customer->save();
  $objectManager->get('\Magento\Customer\Api\CustomerRepositoryInterface')->save($customer, $hashedPassword);

  ### Reload customer data
  $customer = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create();
  $customer->setWebsiteId($websiteId)->loadByEmail($email);
 }
 catch(Exception $e)
 {
  // stored in var/log/debug.log
  #$objectManager->get('\Psr\Log\LoggerInterface')->addDebug($e->getMessage());

  // stored in var/log/exception.log
  $objectManager->get('\Psr\Log\LoggerInterface')->addCritical($e);

  Zend_Debug::dump($e->getMessage());
 }

 if ($customer->getId()) {
  echo 'Succesfully Saved. Customer ID: ' . $customer->getId();
  echo PHP_EOL;

  try{
   ### Add Address For created customer
   $address = $objectManager->get('\Magento\Customer\Api\Data\AddressInterfaceFactory')->create();

   $address->setCustomerId($customer->getId())
    ->setFirstname('test first')
    ->setLastname('test last')
    ->setCountryId('US')
    ->setRegionId('62') //state/province, only needed if the country is USA
    ->setPostcode('98248')
    ->setCity('Ferndale')
    ->setTelephone('7781234567')
    ->setFax('7781234567')
    ->setCompany('test company')
    ->setStreet(['test street'])
    #->setSaveInAddressBook('1')
    ->setIsDefaultBilling('1')
    ->setIsDefaultShipping('1');

   $objectManager->get('\Magento\Customer\Api\AddressRepositoryInterface')->save($address);
  }
  catch (Exception $e) {
   Zend_Debug::dump($e->getMessage());
  }
 }
}

Create and list categories programmatically in Magento 2

Create and list categories programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$state->setAreaCode('base');

createCategory();
listCategory();

function createCategory() {
 global $objectManager;

 $category = $objectManager->get('\Magento\Catalog\Model\CategoryFactory')->create();

 $category->setName('Computer 3');
 $category->setParentId(1); // 1: root category.
 $category->setIsActive(true);
 $category->setCustomAttributes([
  'description' => 'Computer 3 desc',
 ]);

 $objectManager->get('\Magento\Catalog\Api\CategoryRepositoryInterface')->save($category);
}

function listCategory() {
 global $objectManager;

 $categoryCollection = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory')->create();
 $categoryCollection->addAttributeToSelect('*');
 $categoryCollection->addIsActiveFilter();
 $categoryCollection->addLevelFilter(2);

 foreach ($categoryCollection as $category) {
  #print_r($category->getData());
  #print_r($category->getCustomAttributes());

  echo 'Id: ' . $category->getId() . PHP_EOL;
  echo 'Name: ' . $category->getName() . PHP_EOL;
  echo 'ParentId: ' . $category->getParentId() . PHP_EOL;
  echo 'Url: ' . $category->getUrl() . PHP_EOL;
  echo 'UrlKey: ' . $category->getUrlKey() . PHP_EOL;
  echo 'Path: ' . $category->getPath() . PHP_EOL;
  echo 'Position: ' . $category->getPosition() . PHP_EOL;
  echo 'Level: ' . $category->getLevel() . PHP_EOL;
  echo 'ChildrenCount: ' . $category->getChildrenCount() . PHP_EOL;
  echo 'Description: ' . $category->getDescription() . PHP_EOL;
  echo PHP_EOL;
 }
}

Sunday, February 12, 2017

__construct() must be an instance of Magento\Framework\App\Action\Context, instance of Magento\Framework\ObjectManager\ObjectManager given

After I created a Magento 2 module, when I check out the page, I see the following error message:

__construct() must be an instance of Magento\Framework\App\Action\Context, instance of Magento\Framework\ObjectManager\ObjectManager given

Try to run the following command to solve it:

# rm -rf var/di/* var/generation/*

Check Ubuntu version

Check Ubuntu version

# cat /etc/os-release

# cat /etc/lsb-release

# lsb_release -a

Ubuntu Software (Software Center) Crash - Ubuntu 16.04

# apt-get update
# apt-get upgrade gnome-software

or

# rm ~/.local/share/gnome-software/*

Reference:

http://askubuntu.com/questions/783398/ubuntu-software-software-center-crash-ubuntu-16-04#

PhpStorm or IntelliJ suddenly hangs / freezes / keyboard not responsive/ unresponsive while editing in Linux / Ubuntu

PhpStorm or IntelliJ suddenly hangs / freezes / keyboard not responsive/ unresponsive while editing in Linux / Ubuntu

Try:

# ibus restart

or

Help > Diagnostic > Change memory settings

Reference:

https://blog.cppse.nl/phpstorm-intellij-hangs-freezes-unresponsive-keyboard

http://stackoverflow.com/questions/26524923/phpstorm-freezes-very-often

https://stackoverflow.com/questions/25546022/phpstorm-webstorm-increase-memory-to-more-than-512mb

Saturday, February 11, 2017

Install Vim plug for Zend Studio / Eclipse

Zend Studio > Help > Install New Software > Enter the following address in "Work with":

http://vrapper.sourceforge.net/update-site/stable

How to create desktop shortcut (launcher icon) for PhpStorm?

Use IDE to create launcher. Open Tools -> Create Desktop Entry.

apt-get install does not ask for confirmation

apt-get install does not ask for confirmation

apt-get will not ask for the confirmation if every package (including dependencies) is provided on the command line; apt-get will ask for the confirmation if the installation required installing a package not specified on the command line.

Use dry run instead before installing:

# apt-get -s tree

Thursday, February 9, 2017

How do I disable the blinking cursor in gnome-terminal?

How do I disable the blinking cursor in gnome-terminal?

Method 1:

System settings > Keyboard > uncheck "Cursor blink in text field"

Method 2:

# gsettings set org.gnome.desktop.interface cursor-blink false

Reference:

http://askubuntu.com/questions/49606/how-do-i-disable-the-blinking-cursor-in-gnome-terminal

Wednesday, February 8, 2017

Move Ubuntu launcher to the bottom

Move Ubuntu launcher to the bottom

Run this command in Terminal:

# gsettings set com.canonical.Unity.Launcher launcher-position Bottom

Tuesday, February 7, 2017

How to get Tier Price of product magento2?

<?php
use \Magento\Framework\App\Bootstrap;
include('/www/magento2.1/app/bootstrap.php');

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');

$productId = 1;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product_obj = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);

getAnyGroup($product_obj);

function getAnyGroup($product_obj) {
    $tier_price = $product_obj->getTierPrices();

    if(count($tier_price) > 0){
        echo "price_qty\tprice\tCustomerGroupId\n";

        foreach($tier_price as $price){
            echo $price->getQty();
            echo "\t";
            echo $price->getValue();
            echo "\t";
            echo $price->getCustomerGroupId();
            echo "\t";
            echo "\n";
            print_r($price->getData());
            echo "\t";
            echo "\n";
        }
    }
}

Thursday, February 2, 2017

Google MAP API group marker together cluster zoom out

This example shows six different ways of adding mouseover event listener to the marker.

Download js-marker-clusterer: https://github.com/googlemaps/js-marker-clusterer

or from

https://github.com/googlemaps/v3-utility-library

test.json:

var data = {
  'points': [
    {lat: 37.4119, lng: -122.1419, idDealer: 1, dealerName: 'test 1', salesDiff: 100},
    {lat: 37.4219, lng: -122.1419, idDealer: 2, dealerName: 'test 2', salesDiff: -100},
    {lat: 37.4319, lng: -122.1419, idDealer: 3, dealerName: 'test 3', salesDiff: 100},
    {lat: 37.4419, lng: -122.1419, idDealer: 4, dealerName: 'test 4', salesDiff: -100},
    {lat: 37.4519, lng: -122.1419, idDealer: 5, dealerName: 'test 5', salesDiff: 100},
    {lat: 37.4619, lng: -122.1419, idDealer: 6, dealerName: 'test 6', salesDiff: -100},
    {lat: 37.4719, lng: -122.1419, idDealer: 7, dealerName: 'test 7', salesDiff: 100},
    {lat: 37.4819, lng: -122.1419, idDealer: 8, dealerName: 'test 8', salesDiff: 100},
  ],
};

test.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>MarkerClusterer v3 Simple Example</title>
    <style >
      #map {
        width: 800px;
        height: 600px;
      }
    </style>

    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="test.json"></script>
    <script src="jquery-2.1.3.min.js"></script>
    <script type="text/javascript" src="../src/markerclusterer_compiled.js"></script>
    <script>
      function initialize() {
        var center = new google.maps.LatLng(37.4419, -122.1419);

        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 13,
          center: center,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
        });
        var infowindow = new google.maps.InfoWindow();

        var iconURL = 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=';
        var iconRed = iconURL + 'D|FF0000|000000';
        var iconOrange = iconURL + 'D|ff9933|000000';
        var iconGreen = iconURL + 'U|33cc00|000000';
        var myIcon = iconGreen;

        var markers = [];

        for (var i = 0; i < data.points.length; i++) {
          var latLng = new google.maps.LatLng(data.points[i].lat, data.points[i].lng);
          var marker = new google.maps.Marker({
            //id: 'test' + i, // this is optional.
            icon: myIcon,
            //icon: genIcon(),
            position: latLng,
            mystr: 'str ' + i,
          });

          // infowindow mouseover - version 1
          google.maps.event.addListener(marker, 'mouseover', setInfoWindowContent_v1(map, marker, infowindow));

          // (preferred) infowindow mouseover - version 2
          // without passing map, marker to the closure function.
          google.maps.event.addListener(marker, 'mouseover', setInfoWindowContent_v2(infowindow));

          // infowindow mouseover - version 3
          google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
            return function() {
              infowindow.setContent(data.points[i].dealerName);
              infowindow.open(map, marker); // or change marker to this.
            }
          })(marker, i));

          // infowindow mouseover - version 4
          google.maps.event.addListener(marker, 'mouseover', (function(marker, dataPoint) {
            return function() {
              infowindow.setContent(dataPoint.dealerName);
              infowindow.open(map, marker); // or change marker to this
            }
          })(marker, data.points[i]));

          // infowindow mouseover - version 5
          // without passing marker to the closure function. Use this instead of marker.
          google.maps.event.addListener(marker, 'mouseover', (function(dataPoint) {
            return function() {
              infowindow.setContent(dataPoint.dealerName);
              infowindow.open(this.map, this);
            }
          })(data.points[i]));

          // infowindow mouseover - version 6
          google.maps.event.addListener(marker, 'mouseover', function() {
            infowindow.setContent(this.mystr);
            infowindow.open(map, this);
          });

          // click
          google.maps.event.addListener(marker, 'click', function() {
            console.log($(this).attr('mystr'));
          });

          markers.push(marker);
        }

        var markerCluster = new MarkerClusterer(map, markers);
      }

      google.maps.event.addDomListener(window, 'load', initialize);

      $(document).ready(function(){
        $(document).on('click', '#test0', function(e){
          e.preventDefault();
          console.log('clicked!');
        });

        $(document).on('click', '.gan', function(e){
          e.preventDefault();
          console.log('clicked!!!!');
        });
      });

      function setInfoWindowContent_v1(map, marker, infowindow) {
        return function() {
          infowindow.setContent(marker.mystr);
          infowindow.open(map, marker);
        }
      }

      function setInfoWindowContent_v2(infowindow) {
        return function() {
          infowindow.setContent(this.mystr);
          infowindow.open(this.map, this);
        }
      }

      function genIcon() {
        var icon = {
          path: google.maps.SymbolPath.CIRCLE,
          fillOpacity: 1,
          fillColor: '#002664',
          strokeWeight: 1, 
          strokeColor: '#FFFFFF',
          scale: 5 //pixels
        };
        return icon;
      }
    </script>
  </head>
  <body>
    <div id="map"></div>
    <a class="gan">test</a>
  </body>
</html>

Reference:

http://stackoverflow.com/questions/7044587/adding-multiple-markers-with-infowindows-google-maps-api
http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example/16325107#16325107
http://codereview.stackexchange.com/questions/25882/adding-events-to-multiple-markers-in-a-google-map?newreg=8f84e1facf3c42ac9e3adb089a3c6559