How to write a wordpress plugin ( Tutorial)

If you are programmer and you are using wordpress then you always try to how to write wordpress plugin. Now i am going to write the steps of wordpress plugin writting. In More »

How can run php file through command prompt

if you have installed wamp and you want to run php file through command prompt Click On Start->Command prompt (In Windows 7) IN my System is showing C:\Users\Nanhe> Then Type Command C:\Users\Nanhe> More »

 

Find 2 number in the array whose difference is minimum. Array is unsorted. Complexity should be less than o(nlogn).

Q1. Find 2 number in the array whose difference is minimum. Array is unsorted. Complexity should be less than o(nlogn).
eg 2 4 6 1 2 5 – Output should be 2,2

Ans :

<?php

$list = array(2, 4, 6, 1, 2, 5);
$fn = $list[0];
$sn = $list[1];
$diff = $fn – $sn;
$diff = $diff < 0 ? ($diff * -1) : $diff;
for ($i = 0; $i < count($list); $i++) {
for ($j = $i + 1; $j < count($list); $j++) {
$no = $list[$j] – $list[$i];
$no = $no < 0 ? ($no * -1) : $no;
if ($no < $diff) {
$diff = $no;
$fn = $list[$i];
$sn = $list[$j];
}
}
}
echo $fn,$sn;

EMI Calculator code in php


<?php
/*
* @author : Nanhe Kumar
*/
class EMICalculator {

protected $_emi;
protected $_interest;
protected $_principalAmount;
protected $_interestRate;
protected $_annualInterestRate;
protected $_totalMonth;

//Setter
public function setPrincipalAmount($principalAmount) {
$this->_principalAmount = $principalAmount;
}

public function setInterestRate($interestRate) {
$this->_interestRate = $interestRate;
$this->_setannualInterestRate();
}

protected function _setannualInterestRate() {
$this->_annualInterestRate = $this->_interestRate / (12 * 100);
}

public function setTotalMonth($totalMonth) {
$this->_totalMonth = $totalMonth;
}

//Getter
public function getPrincipalAmount() {
return $this->_principalAmount;
}

public function getInterestRate() {
return $this->_interestRate;
}

public function getTotalMonth() {
return $this->_totalMonth;
}

public function getEMI() {
return $this->_emi;
}
public function getInterest(){
return $this->_interest;
}


public function showValue() {
if (php_sapi_name() == 'cli') {
$nl = "\n";
} else {
$nl="</br>";
}
echo 'Principle Amount=', $this->_principalAmount,$nl;
echo 'Interest Rate=' . $this->_interestRate,$nl;
echo 'Annual Interest Rate =' . $this->_annualInterestRate,$nl;
echo 'Total Month=', $this->_totalMonth,$nl;
echo 'EMI=', $this->_emi,$nl;
echo 'Interest=', $this->_interest,$nl;
}

/*
periodicPayment = (principalAmount*annualInterestRate)* {(1+annualInterestRate)^totalMonth / [(1+annualInterestRate)^totalMonth]-1}

*/
public function calculateEMI() {

$this->_emi = ($this->_principalAmount * $this->_annualInterestRate) * (pow((1 + $this->_annualInterestRate), $this->_totalMonth) / (pow((1 + $this->_annualInterestRate), $this->_totalMonth) - 1));
$this->_interest=($this->_emi*$this->_totalMonth)-$this->_principalAmount;
}

}

$emi = new EMICalculator();
$emi->setPrincipalAmount(100);
$emi->setTotalMonth(3);
$emi->setInterestRate(12);

$emi->calculateEMI();
$emi->showValue();
?>

PHP Fatal error: Maximum execution time of 0 seconds exceeded

I was running a long PHP script. Error coming was :

Maximum execution time of 30 seconds exceeded. I tried searching on google that Way i made a change ,

ini_set(‘max_execution_time’, 0);

I again run the script but could not solve the purpose and error converted into

Maximum execution time of 0 seconds exceeded.

then i Made the following change and that solved the purpose.

ini_set(‘max_execution_time’, -1);

 

Its working huraa!!!!!!!!

Runs JavaScript code on the MongoDB database server


$m = new MongoClient();
$db = $m->test;

$inset = "db.getCollection('foo').insert({'name':'nanhe','age':30});";
$response = $db->execute($inset);
print_r($response); //Array ( [retval] => [ok] => 1 )

$response = $m->test->execute("db.getCollection('foo').insert({'name':'happy','age':18});");
print_r($response); //Array ( [retval] => [ok] => 1 )

$response = $m->test->execute("db.foo.insert({'name':'prince','age':16});");
print_r($response); //Array ( [retval] => [ok] => 1 )

$response= $m->test->execute("return db.foo.count();");
print_r($response); //Array ( [retval] => 3 [ok] => 1 )

$response= $m->test->execute("return db.foo.findOne();");
print_r($response); //Array ( [retval] => Array ( [_id] => MongoId Object ( [$id] => 5287ccbe60e2eac9a0e2f1c6 ) [name] => nanhe [age] => 30 ) [ok] => 1 )

/*
* If you want use find function then use toArray because The find() function returns a cursor, which can't be returned from JavaScript.
*/
$response= $m->test->execute("return db.foo.find().toArray();");
print_r($response); //[$id] => 5287cd2260e2eac9a0e2f1ca ) [name] => happy [age] => 18 ) [2] => Array ( [_id] => MongoId Object ( [$id] => 5287cd2260e2eac9a0e2f1cb ) [name] => prince [age] => 16 ) [3] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1cc ) [name] => nanhe [age] => 30 ) [4] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1cd ) [name] => happy [age] => 18 ) [5] => Array ( [_id] => MongoId Object ( [$id] => 5287cdea60e2eac9a0e2f1ce ) [name] => prince [age] => 16 ) ) [ok] => 1 )

$response= $m->test->execute("return db.foo.find({'name':'nanhe'}).toArray();");
print_r($response); //Array ( [retval] => Array ( [0] => Array ( [_id] => MongoId Object ( [$id] => 5287ce9b60e2eac9a0e2f1d2 ) [name] => nanhe [age] => 30 ) ) [ok] => 1 )
// $id value will be different in your case

CakePHP Bake in Ubuntu Step By Step in Nginx

Screenshot from 2013-11-09 00:30:42

Step 1 : Download CakePHP ( http://cakephp.org/downloads)

Step2 : Unzip File place in your /usr/share/nginx/www/ directory  suppose your directory name is cakephp

Step3 : Configure your database .

copy   /usr/share/nginx/www/dewop/app/Config/database.php.default  to /usr/share/nginx/www/dewop/app/Config/database.php

Example :

class DATABASE_CONFIG {

public $default = array(
‘datasource’ => ‘Database/Mysql’,
‘persistent’ => false,
‘host’ => ‘localhost’,
‘login’ => ‘root’,
‘password’ => ”,
‘database’ => ‘blog’,
‘prefix’ => ”,
//’encoding’ => ‘utf8′,
);

public $test = array(
‘datasource’ => ‘Database/Mysql’,
‘persistent’ => false,
‘host’ => ‘localhost’,
‘login’ => ‘user’,
‘password’ => ‘password’,
‘database’ => ‘test_database_name’,
‘prefix’ => ”,
//’encoding’ => ‘utf8′,
);
}

Step 4 : Open Your Terminal (Ctrl + Alt + T)

Step 5 :  $ cd /usr/share/nginx/www/cakephp/app

Step 6:  $ Console/cake bake

 

How can find duplicate ID’s on an HTML page

Screenshot from 2013-10-21 12:49:16

Run the code on your browser’s javascript console

(function findDuplicateIds() {
var ids = {};
var all = document.all || document.getElementsByTagName(“*”);
for (var i = 0, l = all.length; i < l; i++) {
var id = all[i].id;
if (id) {
if (ids[id]) {
console.log(“Duplicate id: #” + id);
} else {
ids[id] = 1;
}
}
}
})();

Desing Pattern

Adapter Pattern
The Adapter Design Pattern simply adapts one object’s interfaces to what another object expects.

Swap 2 number without using third variable in php


$no1=50;

$no2=100;
echo "no1=$no1 and no2=$no2";
$no1=$no1+$no2; //or $no1+=$no2 Now $no1=150

$no2=$no1-$no2; //$no2=50

$no1=$no1-$no2;
echo "no1=$no1 and no2=$no2";

How to force file download with PHP


<?php

class downloadFile {

public $file;

public function __construct($file = "") {
$this->file = $file;
}

public function download() {
$name=  str_replace('../crmreport/','',$this->file);
header('Content-Type: application/download');
header("Content-Disposition: attachment; filename=$name");
header("Content-Length: " . filesize($this->file));

$fp = fopen($this->file, "r");
fpassthru($fp);
fclose($fp);
}

}
?>

<?php

$objDR = new downloadFile($_GET['file']);
$objDR->download();
?>

WordPress Widget


<?php
/*
Plugin Name: My Example
Plugin URI: http://nanhe.in
Description: A Simple test Widget where you can enter music detail
Version: 1.0
Author: Nanhe Kumar
Author URI: http://nanhe.in
License: GPLv2
*/

class example_widget extends   WP_Widget {

//process the new widget
function example_widget() {
$widget_ops = array(
'classname' => 'boj_widgetexample_widget_class',
'description' => 'Display a user\'s favorite movie and song.'
);
$this->WP_Widget( 'example_widget', 'My Info Widget',
$widget_ops );
}

//build the widget settings form
function form($instance) {
$defaults = array( 'title' => 'My Info', 'movie' => '', 'song' => '' );
$instance = wp_parse_args((array) $instance, $defaults);
$title = $instance['title'];
$movie = $instance['movie'];
$song = $instance['song'];
?>
<p>Title: <input name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>
<p>Favorite Movie: <input name="<?php echo $this->get_field_name('movie'); ?>"  type="text" value="<?php echo esc_attr($movie); ?>" /></p>
<p>Favorite Song: <textarea name="<?php echo $this->get_field_name('song'); ?>" ><?php echo esc_attr($song); ?></textarea></p>
<?php
}

//save the widget settings
function update($new_instance, $old_instance) {

$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['movie'] = strip_tags($new_instance['movie']);
$instance['song'] = strip_tags($new_instance['song']);
return $instance;
}

//display the widget
function widget($args, $instance) {
extract($args);
echo $before_widget;
$title = apply_filters('widget_title ', $instance['title']);
$movie = empty( $instance['movie'] ) ? '&nbsp;' : $instance['movie'];
$song = empty( $instance['song'] ) ? '&nbsp;' : $instance['song'];
if (!empty($title)) {
echo $before_title . $title . $after_title;
}

echo '<p>Fav Movie: ' . $movie . '</p>';
echo '<p>Fav Song: ' . $song . '</p>';
echo $after_widget;
}

}
add_action( 'widgets_init', 'example_widgetregister_widgets' );
/**
* Register the widget
*
* @since 1.0
*/
function example_widgetregister_widgets() {

register_widget( 'example_widget' );

}