Monday, May 6, 2013

How to find random documents with Mongoose? [Get random data with MongoDb]

Mongoose is an ORM module for node.js that give you utility to create ORM database with no-sql database MongoDB. NoSql database has a lot of pros come with it, but has a lot of cons too. For example RDBMS can Select * From rand(), mongodb can't do that.

Yes, you can't find random document in mongodb. But I have found how to create schema that able to find it by random. Here is mine:


var exampleSchema  = new Schema({
name: String,
random_point: {type: Schema.Types.Mixed, default: [Math.random(), 0]}
}); 
Insert some documents: 
var Example  = mongoose.model('Example', exampleSchema);
var example = new Example({ name: "Testa", random_point: [Math.random(), 0] });
example.save(function (err) {
  if (err) // ...
  console.log('testa successfull');
});
And you can find it by random: 
Example.find({random_point: {$near: [Math.random(), 0] }}, function(error, result){console.log(result); })
Actually for mongodb this requires only one query and no null checks, and the code is cleaner, simpler and more flexible. for example:


// Enable geospatial indexing on a collection
db.docs.ensureIndex( { random_point: '2d' } )

// Create a bunch of documents with random points on the X-axis
for ( i = 0; i < 10; ++i ) db.docs.insert( { key: i, random_point: [Math.random(), 0] } );

// Get a random document
db.docs.findOne( {random_point : { $near : [Math.random(), 0] } } )

// Or you can retrieve several document nearest to a random point
db.docs.find( { random_point : { $near : [Math.random(), 0] } } ).limit( 4 )



Friday, May 3, 2013

Amazon ASIN Collector / Grabber

If you are Amazon's Affiliate, ASIN (Amazon Standard Identification Number) is as important as make money itself. You can build a store, or find a product by ASIN.

Find bulk ASIN is easy. This script show you how to create Amazon ASIN collector. (this script only works in search page). Create a new bookmark in your browser, paste below script as URL or just paste this script to your address bar while you currently in amazon search result (after searching some product with filtered result):

javascript:(function(){ /* inject jquery into amazon page */ var GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js';
GM_JQ.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(GM_JQ);
GM_JQ.onload = function(){ /* to do on script loaded */
$('body').append('<div class="asin_grabber"></div>'); /* create div of asin grabber*/
$('.asin_grabber').css('position', 'fixed');
$('.asin_grabber').css('right', '10px');
$('.asin_grabber').css('top', '10px');
$('.asin_grabber').css('width', '250px');
$('.asin_grabber').css('background-color', '#fff');
$('.asin_grabber').css('border', '1px solid #000');
$('.asin_grabber').css('z-index', '10000');
$('.asin_grabber').append('<div class="ttle" style="text-align:center;font-size:20px;font-family:tahoma">ASIN Grabber</div>');
$('.asin_grabber').append('<div class="mn" style="padding:10px;"><textarea rows="18" cols="10" style="width:95%;" id="grabber_textarea"></textarea></div>');
$('.asin_grabber').append('<div style="padding:10px;padding-top:5px"><button id="collect_asin">Collect ASIN</button> <button id="clear_asin">Clear</button></div>');
$('.asin_grabber').append('<div style="padding:10px;padding-top:5px"><button id="next_page_asin">Next Page</button></div>');
$('#collect_asin').off('click').on('click', function(){ /* create collect asin function */
$('h3.newaps').each(function(v, i){
var asin = $(this).children('a').attr('href');
asin = asin.match(/\/dp\/(.*?)\//);
$('#grabber_textarea').val($('#grabber_textarea').val()+asin[1]+'\n');
});
});
$('#clear_asin').off('click').on('click', function(){  /* create clear text area */
$('#grabber_textarea').val('');
});
$('#next_page_asin').on('click', function(){
$('a#pagnNextLink > span#pagnNextString').trigger('click');
});
}})();void(0);

You can modify that script. It's just basic script. I hope it will help you to collect a hundred of ASIN in amazon search page. (tips: find products that filtered, to be more works). If that script doesn't work, just delete comment statement ( statement that start with /* and end with */ )

Saturday, September 10, 2011

Empty All Memcache Data in PHP

Do you want to delete all data or empty all data that is store in memcache? How to delete all memcache data in server using PHP? How to empty all memcache data in server by PHP?

I have my own function. I hope this is work for you. While, I'm typing this, I did not directly testing it. So, If you found the bug. Report it by commenting below.

function get_memcache_keys($host = '127.0.0.1', $port = 11211) {

    $memcache = new Memcache;
    $memcache->connect($host, $port) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    $items = $memcache->getExtendedStats('items');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                if (!is_array($arrVal)) continue;
                foreach($arrVal AS $k => $v) {                   
                    $return[] = $k;
                }
           }
        }
    } 
   if(is_array($return))
   {
      return $return;
   }
   else
   {
      return '';
   }
}

function empty_memcache_data($host = '127.0.0.1', $port = 11211)
{
     
     $memcache = new Memcache;
     $memcache->connect($host, $port) or die ("Could not connect to memcache server");
     $keys = get_memcache_key($host, $port);
     if(is_array($keys))
     {
          foreach($keys as $k)
          {
              $memcache->delete($k);
          }
     }
}
empty_memcache_data();

Next, I will write down how to empty memcache data / delete all memcache data by specific namespace. See you ;)

PS: Sorry for my english and bad grammar. Actually, I am not native English speaker. If you have an errata, please free to correct it.

Wednesday, July 20, 2011

Installing MongoDB on WampServer

Installing mongodb on Wampserver is more difficult than on LAMP. But, I will give a tutorial about it, as easy as possible. Please follow these steps :