I2C using GPIO C code

Understanding the I2C Bus: I2C using GPIO

The I2C bus is a very popular and powerful bus used for communication between a master (or multiple masters) and a single or multiple slave devices. Figure 1 illustrates how many different peripherals may share a bus which is connected to a processor through only 2 wires, which is one of the largest benefits that the I 2C bus can give when compared to other interfaces.

Continue reading

Storage Classes in c language

Storage classes define the scope (visibility) and life time of variables which help us to trace the existence of a particular variable during the run time of a program.

C Language supports 4 types of storage class they are:

Storage Classes

  1. Auto
  2. Register
  3. Static
  4. Extern

Syntax:   <storage class> <data type> <variable name>;

ex:

auto int month; register int month; extern int month; static int month;

Auto:  A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is called and are destroyed automatically when the function exits. Automatic variables can also be called local variables because they are local to a function. By default they are assigned garbage value by the compiler.

Example

{
   int mount;
   auto int month;
}

Register: The register variable functionality is same as auto storage class except that storage of variable is in register instead of memory. Register variable has faster access than normal variable. Frequently used variables are kept in register. Only few variables can be placed inside register depends on the register of processors. The Register variable does not guarantee the storage of variable in register it depends on the availability of register.

NOTE : We can never get the address of such variables.

Example

{
   register int i;
      for(i=0;i<100;i++) {
   printf("register storage class"); }
}

In the above example the variable i is accessed in loop. using register declaration the loop will be executed fast compared to normal storage class i.e auto.

Static : This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.

Example

#include <stdio.h>
void fun()
{
 static number;
 printf("%d\t", number); 
 number++;
}
void main()
{
 fun();
 fun();
 fun(); 
}

output: 0 1 2

In the above example the static variable number is declared inside the fun function but still the value persist after multiple call the  fun function from main.

Extern: The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else. The extern declaration does not allocate storage for variables.

When you have multiple files and you define a global variable or function, which will also be used in other files, then extern will be used in another file to provide the reference of defined variable or function. Just for understanding, extern is used to declare a global variable or function in another file.

The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.

Example

file1: main.c

#include <stdio.h>
 
int count ;
extern void write();
 
main() {

   count = 5;
   write();
}

file2: support.c

#include <stdio.h>
 
extern int count;

void write(void) {
   printf("count is %d\n", count);
}

To compile:

$gcc main.c support.c

It will produce the executable program a.out. When this program is executed, it produces the following result ?

count is 5

 

cakephp titbits usefull development tips

Some of usefull cakephp titbits. These cakephp titbits are for quick reference that are help full while developing the application. These titbits are most commonly used in the development and comes as handy reference.

To get the paths, Url and URL query string

echo $this->request->webroot  will print the webroot directory path.
echo $this->request->base will print the base path.
echo $this->request->here will print the full address to the current request.
echo $this->request->query will print the query string parameters that are passed through URL as query string.

To detect if the current page is the homepage

if ($this->here == $this->webroot){ // this is home page }
or 
if ($this->here == $this->base.'/'){ // this is home page }

To include Element in layout or view

echo $this->element('navbar');

// create the sidebar block. 
$this->start('sidebar'); 
echo $this->element('sidebar/recent_topics');
echo $this->element('sidebar/recent_comments');
$this->end();

To load CSS and JS files in layout

echo $this->fetch(‘css’);
echo $this->Html->css(array(‘forms’, ‘tables’, ‘menu’));
echo $this->fetch(‘script’);
echo $this->Html->css(array(‘forms’, ‘tables’, ‘menu’));

 

Loading vendor files

// Load the class Abc in app/Vendor/Abc.php
App::uses('Abc', 'Vendor');

// To load app/Vendor/abc.php:
App::import('Vendor', 'abc');

//To load app/Vendor/abc/xyz.php:
App::import('Vendor', 'abc/xyz');


To include one controller in another controller

// The same as require('Controller/UsersController.php');
App::import('Controller', 'Users');

// We need to load the class
$Users = new UsersController();

// If we want the model associations, components, etc to be loaded
$Users->constructClasses();

 

Cakephp HtmlHelper functions can be found here

Cakephp FormHelper functions can be found here

 

cakephp login with Email or username

This article “cakephp login with Email or username” will explain how the Auth component will allow user cakephp login with  email or username, instead of using any of username and email address.

Now a days in many application the authentication process is using  either  the username or email with password combination to allow access to the site. In cakephp framework with auth component we can also achieve the same. To allow cakephp login with email or username we need to add some extra code in the app controller which tells the auth component to allow login with either email or username with password combination.

Auth component is used in the cakephp for the process of authentication. It by default allow login with username and password combination. To make auth component  allow cakephp login with email or username we need to add below code in app controller

App controller file will available in “app/controllers” folder with the file name appcontroller.php.

For the combination of

Email + Password
OR
Username + Password

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => array('username', 'email'),'password' => 'password')
            )
        )
    )
);

 

To make auth component  allow cakephp login with only email address we need to add below code in app controller.

For the combination of

Email + Password

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' =>  'email','password' => 'password')
            )
        )
    )
);

 

To make auth component  allow cakephp login with only username we need to add below code in app controller.

For the combination of
Username + Password

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' =>  'username','password' => 'password')
            )
        )
    )
);

cakephp login with Email or username

Cakephp interview questions

Here there are some Cakephp interview questions and answers about How CakePHP Framework works. These cakephp interview questions listed below are  mainly asked in any interview. These cakephp interview questions  are use full both fresher and experienced people.

 

What is Cakephp?

CakePHP is a free, open-source, rapid development framework for PHP. It’s a foundational structure for programmers to create web applications. CakePHP goal is to enable developers to work in a structured and rapid manner–without loss of flexibility. CakePHP takes the monotony out of web development.

Server requirements for cakephp?

Here are the requirements for setting up a server to run CakePHP:
An HTTP server (like Apache) with the following enabled: sessions, mod_rewrite (not absolutely necessary but preferred)
PHP 4.3.2 or greater. Yes, CakePHP works great in either PHP 4 or 5.
A database engine (right now, there is support for MySQL 4+, PostgreSQL and a wrapper for ADODB).

Installation of cakephp

01. Go to cakephp.org and download the latest version of cakephp.
02. Cakephp comes in a .zip file so unzip it.
03. Extract the files in the localhost in the desired folder ( lets say cakephp)
04. Open the browser and run the URL localhost/cakephp
05. Follow the instruction showed in the page

what is the folder structure of Cakephp

cakephp/
app/
config/
controllers/
models/
plugins/
tmp/
vendors/
views/
webroot/
.htaccess
index.php
lib/
plugins/
vendors/
.htaccess
index.php
README

List some of the features in Cakephp?

Basic Features List

  1.     Full support of Model, View, Controller Architecture.
  2.     Good Application Scaffolding.
  3.     Very nice Code generation via Bake.
  4.     Helpers for HTML, Forms, Pagination, AJAX, Javascript, XML, RSS and more.
  5.     Access Control Lists and Authentication.
  6.     Router for mapping urls and handling extensions.
  7.     Security, Session, and RequestHandler Components.
  8.     Utility classes for working with Files, Folders, Arrays and more.
  9.     can manage multiple site(apps) developement

Advance Features List

  1.     Internationalization and Localization with static translations in gettext style or dynamic translations of model data.
  2.     Full Console environment with support for multiple tasks. Included shells: bake, schema, acl, i18 extractor, api.
  3.     CSRF protection via Security Component.
  4.     HTTP Authentication via Security Component.
  5.     Flexible Caching: use memcache, apc, xcache, the file system, or a model to speed up your applicationConfigure class to provide dynamic handling of configuration settings and App class to handle importing required classes. Supports Unit Testing (simpletest,unit test)

what is the difference between two vendors folder available in cakephp?

There will be two vendor folders available in cakephp frame work.
one in ” app ” folder and one in root folder
The vendor folder in the app folder is used to place the third-party libraries which are application specific.
The vendor folder in the root folder is used to place the third-party libraries which are used for multiple applications.

what is the naming convention in cakephp.

According to cakephp naming conventions
1) Table names should be in lowercase and always Plural
2) Model name should be in CamelCased and are always singular eg: ModelName
3) Model file names are also singular and underscored if contains two words eg : model_name.php
4) Controller name should be in CamelCased and are always plural : appended “controller ” eg: ControllerNamesController
5) Controller file names are always plural and underscored : appender “controller” eg: controller_names_controller.php

what is model,view,controller?

1. The Model represents the application data
2. The View renders a presentation of model data
3. The Controller handles and routes requests made by the client

 

what is a component?
Components in CakePHP are associated with Controllers.
Components are created and used to share common functionality bewteen controllers.

What are commonly used components of cakephp?
1. Security
2. Sessions
3. Access control lists
4. Emails
5. Cookies
6. Authentication
7. Request handling

what is a Helper?
Helpers in CakePHP are associated with Presentation layers of application.
Helpers mainly contain presentational logic which is availabel to share between many views, elements, or layouts

What are commonly used helpers of cakephp?
CacheHelper
FormHelper
HtmlHelper
JsHelper
NumberHelper
Paginator
RSS
SessionHelper
TextHelper
TimeHelper

What is a Behavior?
Behaviors in CakePHP are associated with Models.
Behaviors are used to change the way models behaves and enforcing model to act as something else.

Difference between Component, Helper, Behavior?
Component is a Controller extension, Helpers are View extensions, Behavior is a Model Extension.

What is a Element?
Element in cakephp are smaller and reusable bits of view code. Elements are usually rendered inside views.

What is a layout?
Layout in cakephp are used to display the views that contain presentational code. In simple views are rendered inside a layout

what is the first function that gets loaded from a controller?
function index()

In which file cake php database configuration is setup ?
“app/config/database.php”

The four model association types in CakePHP are
1) hasOne
2) hasMany
3) belongsTo
4) hasAndBelongsToMany (HABTM).

Database related functions in cakephp.
1) find
2) find(‘first’)
3) find(‘count’)
4) find(‘all’)
5) find(‘list’)
6) find(‘threaded’)
7) query(),
8) save()

How to set layout in the controller?

var $layout = ‘layout_name’;
to overwrite for a specific action use below code in that action
$this->layout =”layout_name”;

How to including helpers in controller ?

public $helpers = array(‘Form’, ‘Html’, ‘Js’, ‘Time’);
to in specific action use below code in that action
$this->helper[] =”helper_name”;

How to including components in controller ?

public $components = array(‘Emails’, ‘ImageUploader’, ‘Sms’);

Session write, read and delete

1)$this->Session->write(‘Person.eyeColor’, ‘Green’);
2)$green = $this->Session->read(‘Person.eyeColor’);
3)$this->Session->delete(‘Person’);

Which function is executed before every action in the controller?

function beforeFilter()

requestAction is used to ?

To call controller function form view requestAction function is used
$abc = $this->requestAction(‘/controller/action/param:1234’);
// or
$abc = $this->requestAction(‘controller’=>’controller_name’, ‘action’=>’action_name’, ‘param’ => 1234);

what all are drawbacks?

1) The biggest drawback to CakePHP is that it doesn’t completely implement object orientation
2) Can’t be used for small scale apps as it loads the complete application in beginning.
3) The learning curve

php cache engines

PHP Cache Engines

This article will explain all the available cache engines for php. PHP Cache engines are used to implement cache mechanism for the dynamic sites developed using scripting and programming languages. Cache mechanism will help to increase site performance.

CakePHP/PHP comes with several cache engines built-in, and provides an easy system to implement our own caching systems. The built-in caching engines are:

FileCache :

  • File cache is a simple cache that uses local files.
  • Not quite fast and doesn’t provide as many features for atomic operations
  • Concurrent access are not great at all, if several processes try to read/write at the same time
  • since disk storage is often quite cheap, storing large objects, or elements that are infrequently written work well in files

ApcCache  :

  • APC cache uses the PHP APC extension.
  • Really fast
  • Able to provide atomic read/write features
  • But you have less space
  • Uses shared memory on the webserver to store objects and it’s local to each server too

Wincache :

  • Wincache uses the Wincache extension.
  • Wincache is similar to APC in features and performance, but optimized for Windows and IIS.

XcacheEngine :

  • Xcache is a PHP extension that provides similar features to APC.

MemcacheEngine :

  • Uses the Memcache extension.
  • Provides a very fast cache system
  • Can be distributed across many servers, and provides atomic operations

MemcachedEngine :

  • Uses the Memcached extension.
  • It also interfaces with memcache but provides better performance.
  • Quite fast (a bit less than APC ; but still pretty fast)
  • Shared between all your servers : each item has to be cached only once, even if you have several webservers.
  • You can have several servers in your memcached cluster (which means virtually no limit in the size of the cache)

RedisEngine  :

  • Uses the phpredis extension.
  • Redis provides a fast and persistent cache system similar to memcached
  • also provides atomic operations

Read more about Memcache here

Using Memcache for php

Using Memcache for PHP

This article will explain the process of using memcache for php dynamic websites. Memcache is used to implement cache mechanism using PHP. There are also many cache engines available for PHP, but using memcache for PHP will provide some additional benefits.

Memcache itself providing procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

Below are the requirements that has to be accomplished before going to explain the process of using memcache for PHP.

1) Memcache service has to be installed and started. For windows operation system read this page and for Ubuntu read this page

2) Memcache php extension is installed and enabled to run with PHP. To know installation process read this page.

Considering both Memcache service and Memcache php extension are started and working fine, here we go with Using Memcache for PHP explanation.

Here’s some sample code from php.net site

<?php
  $memcache = new Memcache;
  $memcache->connect("localhost",11211); # You might need to set "localhost" to "127.0.0.1"
  echo "Server's version: " . $memcache->getVersion() . "<br />\n";
  $tmp_object = new stdClass;
  $tmp_object->str_attr = "test";
  $tmp_object->int_attr = 123;
  $memcache->set("key",$tmp_object,false,10);
  echo "Store data in the cache (data will expire in 10 seconds)<br />\n";
  echo "Data from the cache:<br />\n";
  var_dump($memcache->get("key"));

?>

If you have any errors, it will most likely be because the php extension didn’t run. Check the webserver error log to see if it had problems starting. The most common problem is the version of memcache.dll is not compatible with the version of php you are running.

Installing Memcache PHP Extension

Installing Memcache PHP Extension

Installing Memcache PHP extension article will explain how to install Memcache dll file both in Xampp and Wamp servers.

Follow the below steps for Installing Memcache PHP Extension in Wamp or Xampp

1) Download the memcache php extension zip file form this link

2) Unzip and find the php_memcache.dll file.

3) For Xampp server place the dll file in D:\xampp\php\ext folder. Here considering that Xampp is installed in D Drive.

4) For Wamp server place the dll file in D:\wamp\bin\php\php5.2.9-1\ext folder. Here considering that Wamp is installed in D Drive.

5) Open the php.ini file which is located at D:\xampp\php  or D:\wamp\bin\php\php5.2.9-1\  for Xampp or Wamp servers respectively

6) Find and replace

;extension=php_memcache.dll

with

extension=php_memcache.dll

7) If you cannot find this line simply add the following to the extensions list

extension=php_memcache.dll

8) Restart the server ( Wamp/Xampp)

To check the Installation is success or not

  • Please create a php file (phpinfo.php) some where in the wamp/xampp.
  • Run that file through browser.
  • Search for Memcache in the page .
  • If you can see it, means the installation is success and is working fine.

Note : If you have any errors, it will most likely be because the php extension didn’t run. Check the webserver error log to see if it had problems starting. The most common problem is the version of memcache.dll is not compatible with the version of php you are running.

Read Installation of Memcached service on Windows here

Read Installation of Memcached service on Ubuntu here

Memcached Installation on Windows

Memcached Installation on Windows

Here in this article ‘Memcached Installation on Windows’ we are going to see how to install Memcached on Windows.
As we know Memcached is a Free & open source, high-performance, distributed memory object caching system , generic in nature, but intended for use in speeding up dynamic web applications.

Steps of Memcached installation on windows are given below

Step 1 :

  •  First of all we need to download Memcahced Installation / Service files based on the operation system bits ( Windows 32 bit OR windows 64 bit) .
  •  For Windows 32 Bit operation system, use the win32 binary version. You can download it form the here 
  •  For Windows 64 Bit operation system, use the win64 binary version. You can download it form here OR from here

Step 2 :

  •  Unzip the downloaded zip file to find the file named memcached.exe.
  • Create a folder with name memcached in any drive.Prefer the drive (C Drive) in which the operating system installed.
  •  Copy memcahced.exe file from the unziped folder to the newly created folder ( C:\memcached )

Step 3 :

Install the Memcached service. This can be done in two ways

  1. Right click on memcached.exe file and Run as administrator .
  2. Find the cmd.exe in the system, right hand click on the icon and select Run as administrator

Step 4 :

Open the command line interface and go to the folder where memcached.exe file is available.

C:\memcached>

Run the below commands to install the Memcached service and start it.

C:\memcached>memcached.exe -d install

C:\memcached>memcached.exe -d start

If you dont get any errors it means it’s worked.

If  you face some problem. It’s may shows some error like “The program can’t install because MSVCR71.dll is missing from your computer .“

To solve this issue you need to download the MSVCR71.dll file. You can download it from here. Download the dll and paste it inside your system 32 folder which is in C:\Windows\system32  and again go to the command prompt and follow the Step 4. Now it should not throw error.

 

Installation of Memcached on Ubuntu

Read about memcache and cakephp here

set up memcache engine for cakephp

Set up memcache engine for cakephp

Here in this article we are going to see how to set up Memcache Engine for cakephp. Memcached is a Free & open source, high-performance, distributed memory object caching system , generic in nature, but intended for use in speeding up dynamic web applications.

CakePHP comes with several cache engines built-in, and provides an easy system to implement our own caching systems.By default it provides file based caching mechanism which uses local files to store the cached content and is slowest cache engine, and doesn’t provide as many features for atomic operations.

Since the default file engine is very slow there comes the search of alternative cache engines that cackephp provides. one of the most fast search engine that comes in cakephp is Memcache Engine. Below are the steps to set up Memcache Engine for cakephp.

1) Installing the Memcached in operating system.

2) Installing Memcache module/extension for php.

3) Restarting the Apache server.

4) Making Memcache Engine as default engine for cakephp App.

  • Open the bootstrap file which will find in ‘root_folder/app/config/bootstrap.php’
  • Find and replace the code.
Cache::config('default', array('engine' => 'File'));

With

Cache::config('default', array(
    'engine' => 'Memcache',
    'duration' => 3600, // 
    'probability' => 100,
    'prefix' => Inflector::slug(APP_DIR) . '_',
    'servers' => array(
        '127.0.0.1'
    ),
    'persistent' => true,
    'compress' => false,
));

5) Set  Memcache engine as the main caching engine for the app

  • Open the core file which will find in ‘root_folder/app/config/core.php’
  • Find and replace the code.
$engine = 'File';

With

$engine = 'Memcache';

Read more about memcache here