text:
#include "hw/hw.h"
#include "ui/console.h"
#include "hw/input/ps2.h"
#include "hw/i386/pc.h"
#include "hw/qdev.h"

/* debug only vmmouse */
//#define DEBUG_VMMOUSE

/* VMMouse Commands */
#define VMMOUSE_GETVERSION	10
#define VMMOUSE_DATA		39
#define VMMOUSE_STATUS		40
#define VMMOUSE_COMMAND		41

#define VMMOUSE_READ_ID			0x45414552
#define VMMOUSE_DISABLE			0x000000f5
#define VMMOUSE_REQUEST_RELATIVE	0x4c455252
#define VMMOUSE_REQUEST_ABSOLUTE	0x53424152

#define VMMOUSE_QUEUE_SIZE	1024

#define VMMOUSE_VERSION		0x3442554a

#ifdef DEBUG_VMMOUSE
#define DPRINTF(fmt, ...) printf(fmt, ## __VA_ARGS__)
#else
#define DPRINTF(fmt, ...) do { } while (0)
#endif

#define TYPE_VMMOUSE "vmmouse"
#define VMMOUSE(obj) OBJECT_CHECK(VMMouseState, (obj), TYPE_VMMOUSE)

typedef struct VMMouseState
{
    ISADevice parent_obj;

    uint32_t queue[VMMOUSE_QUEUE_SIZE];
    int32_t queue_size;
    uint16_t nb_queue;
    uint16_t status;
    uint8_t absolute;
    QEMUPutMouseEntry *entry;
    void *ps2_mouse;
} VMMouseState;

static uint32_t vmmouse_get_status(VMMouseState *s)
{
    DPRINTF("vmmouse_get_status()\n");
    return (s->status << 16) | s->nb_queue;
}

static void vmmouse_mouse_event(void *opaque, int x, int y, int dz, int buttons_state)
{
    VMMouseState *s = opaque;
    int buttons = 0;

    if (s->nb_queue > (VMMOUSE_QUEUE_SIZE - 4))
        return;

    DPRINTF("vmmouse_mouse_event(%d, %d, %d, %d)\n",
            x, y, dz, buttons_state);

    if ((buttons_state & MOUSE_EVENT_LBUTTON))
        buttons |= 0x20;
    if ((buttons_state & MOUSE_EVENT_RBUTTON))
        buttons |= 0x10;
    if ((buttons_state & MOUSE_EVENT_MBUTTON))
        buttons |= 0x08;

    if (s->absolute) {
        x <<= 1;
        y <<= 1;
    }

    s->queue[s->nb_queue++] = buttons;
    s->queue[s->nb_queue++] = x;
    s->queue[s->nb_queue++] = y;
    s->queue[s->nb_queue++] = dz;

    /* need to still generate PS2 events to notify driver to
       read from queue */
    i8042_isa_mouse_fake_event(s->ps2_mouse);
}

static void vmmouse_remove_handler(VMMouseState *s)
{
    if (s->entry) {
        qemu_remove_mouse_event_handler(s->entry);
        s->entry = NULL;
    }
}

static void vmmouse_update_handler(VMMouseState *s, int absolute)
{
    if (s->status != 0) {
        return;
    }
    if (s->absolute != absolute) {
        s->absolute = absolute;
        vmmouse_remove_handler(s);
    }
    if (s->entry == NULL) {
        s->entry = qemu_add_mouse_event_handler(vmmouse_mouse_event,
                                                s, s->absolute,
                                                "vmmouse");
        qemu_activate_mouse_event_handler(s->entry);
    }
}

static void vmmouse_read_id(VMMouseState *s)
{
    DPRINTF("vmmouse_read_id()\n");

    if (s->nb_queue == VMMOUSE_QUEUE_SIZE)
        return;

    s->queue[s->nb_queue++] = VMMOUSE_VERSION;
    s->status = 0;
}

static void vmmouse_request_relative(VMMouseState *s)
{
    DPRINTF("vmmouse_request_relative()\n");
    vmmouse_update_handler(s, 0);
}

static void vmmouse_request_absolute(VMMouseState *s)
{
    DPRINTF("vmmouse_request_absolute()\n");
    vmmouse_update_handler(s, 1);
}

static void vmmouse_disable(VMMouseState *s)
{
    DPRINTF("vmmouse_disable()\n");
    s->status = 0xffff;
    vmmouse_remove_handler(s);
}

static void vmmouse_data(VMMouseState *s, uint32_t *data, uint32_t size)
{
    int i;

    DPRINTF("vmmouse_data(%d)\n", size);

    if (size == 0 || size > 6 || size > s->nb_queue) {
        printf("vmmouse: driver requested too much data %d\n", size);
        s->status = 0xffff;
        vmmouse_remove_handler(s);
        return;
    }

    for (i = 0; i < size; i++)
        data[i] = s->queue[i];

    s->nb_queue -= size;
    if (s->nb_queue)
        memmove(s->queue, &s->queue[size], sizeof(s->queue[0]) * s->nb_queue);
}

static uint32_t vmmouse_ioport_read(void *opaque, uint32_t addr)
{
    VMMouseState *s = opaque;
    uint32_t data[6];
    uint16_t command;

    vmmouse_get_data(data);

    command = data[2] & 0xFFFF;

    switch (command) {
    case VMMOUSE_STATUS:
        data[0] = vmmouse_get_status(s);
        break;
    case VMMOUSE_COMMAND:
        switch (data[1]) {
        case VMMOUSE_DISABLE:
            vmmouse_disable(s);
            break;
        case VMMOUSE_READ_ID:
            vmmouse_read_id(s);
            break;
        case VMMOUSE_REQUEST_RELATIVE:
            vmmouse_request_relative(s);
            break;
        case VMMOUSE_REQUEST_ABSOLUTE:
            vmmouse_request_absolute(s);
            break;
        default:
            printf("vmmouse: unknown command %x\n", data[1]);
            break;
        }
        break;
    case VMMOUSE_DATA:
        vmmouse_data(s, data, data[1]);
        break;
    default:
        printf("vmmouse: unknown command %x\n", command);
        break;
    }

    vmmouse_set_data(data);
    return data[0];
}

static int vmmouse_post_load(void *opaque, int version_id)
{
    VMMouseState *s = opaque;

    vmmouse_remove_handler(s);
    vmmouse_update_handler(s, s->absolute);
    return 0;
}

static const VMStateDescription vmstate_vmmouse = {
    .name = "vmmouse",
    .version_id = 0,
    .minimum_version_id = 0,
    .post_load = vmmouse_post_load,
    .fields = (VMStateField[]) {
        VMSTATE_INT32_EQUAL(queue_size, VMMouseState),
        VMSTATE_UINT32_ARRAY(queue, VMMouseState, VMMOUSE_QUEUE_SIZE),
        VMSTATE_UINT16(nb_queue, VMMouseState),
        VMSTATE_UINT16(status, VMMouseState),
        VMSTATE_UINT8(absolute, VMMouseState),
        VMSTATE_END_OF_LIST()
    }
};

static void vmmouse_reset(DeviceState *d)
{
    VMMouseState *s = VMMOUSE(d);

    s->queue_size = VMMOUSE_QUEUE_SIZE;

    vmmouse_disable(s);
}

static void vmmouse_realizefn(DeviceState *dev, Error **errp)
{
    VMMouseState *s = VMMOUSE(dev);

    DPRINTF("vmmouse_init\n");

    vmport_register(VMMOUSE_STATUS, vmmouse_ioport_read, s);
    vmport_register(VMMOUSE_COMMAND, vmmouse_ioport_read, s);
    vmport_register(VMMOUSE_DATA, vmmouse_ioport_read, s);
}

static Property vmmouse_properties[] = {
    DEFINE_PROP_PTR("ps2_mouse", VMMouseState, ps2_mouse),
    DEFINE_PROP_END_OF_LIST(),
};

static void vmmouse_class_initfn(ObjectClass *klass, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = vmmouse_realizefn;
    dc->reset = vmmouse_reset;
    dc->vmsd = &vmstate_vmmouse;
    dc->props = vmmouse_properties;
    /* Reason: pointer property "ps2_mouse" */
    dc->cannot_instantiate_with_device_add_yet = true;
}

static const TypeInfo vmmouse_info = {
    .name          = TYPE_VMMOUSE,
    .parent        = TYPE_ISA_DEVICE,
    .instance_size = sizeof(VMMouseState),
    .class_init    = vmmouse_class_initfn,
};

static void vmmouse_register_types(void)
{
    type_register_static(&vmmouse_info);
}

type_init(vmmouse_register_types)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>P-Index</title>
<meta name="date" content="2015-04-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I J L M N O P R S T U V W

P

pager - Static variable in class com.ohtu.wearable.wearabledataservice.R.id

PagerAdapter - Class in com.ohtu.wearable.wearabledataservice.fragments

Adapter class to populate views with fragments.

PagerAdapter(FragmentManager) - Constructor for class com.ohtu.wearable.wearabledataservice.fragments.PagerAdapter

parseBody(Map<String, String>) - Method in class com.ohtu.wearable.wearabledataservice.server.NanoHTTPD.HTTPSession

parseBody(Map<String, String>) - Method in interface com.ohtu.wearable.wearabledataservice.server.NanoHTTPD.IHTTPSession

Adds the files in the request body to the files map.

primary_text_dark - Static variable in class com.ohtu.wearable.wearabledataservice.R.color

primary_text_light - Static variable in class com.ohtu.wearable.wearabledataservice.R.color

A B C D E F G H I J L M N O P R S T U V W

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
require 'rubygems/command'

class Gem::Commands::HelpCommand < Gem::Command

  # :stopdoc:
  EXAMPLES = <<-EOF
Some examples of 'gem' usage.

* Install 'rake', either from local directory or remote server:

    gem install rake

* Install 'rake', only from remote server:

    gem install rake --remote

* Install 'rake', but only version 0.3.1, even if dependencies
  are not met, and into a user-specific directory:

    gem install rake --version 0.3.1 --force --user-install

* List local gems whose name begins with 'D':

    gem list D

* List local and remote gems whose name contains 'log':

    gem search log --both

* List only remote gems whose name contains 'log':

    gem search log --remote

* Uninstall 'rake':

    gem uninstall rake

* Create a gem:

    See http://guides.rubygems.org/make-your-own-gem/

* See information about RubyGems:

    gem environment

* Update all gems on your system:

    gem update

* Update your local version of RubyGems

    gem update --system
  EOF

  PLATFORMS = <<-'EOF'
RubyGems platforms are composed of three parts, a CPU, an OS, and a
version.  These values are taken from values in rbconfig.rb.  You can view
your current platform by running `gem environment`.

RubyGems matches platforms as follows:

  * The CPU must match exactly unless one of the platforms has
    "universal" as the CPU or the local CPU starts with "arm" and the gem's
    CPU is exactly "arm" (for gems that support generic ARM architecture).
  * The OS must match exactly.
  * The versions must match exactly unless one of the versions is nil.

For commands that install, uninstall and list gems, you can override what
RubyGems thinks your platform is with the --platform option.  The platform
you pass must match "#{cpu}-#{os}" or "#{cpu}-#{os}-#{version}".  On mswin
platforms, the version is the compiler version, not the OS version.  (Ruby
compiled with VC6 uses "60" as the compiler version, VC8 uses "80".)

For the ARM architecture, gems with a platform of "arm-linux" should run on a
reasonable set of ARM CPUs and not depend on instructions present on a limited
subset of the architecture.  For example, the binary should run on platforms
armv5, armv6hf, armv6l, armv7, etc.  If you use the "arm-linux" platform
please test your gem on a variety of ARM hardware before release to ensure it
functions correctly.

Example platforms:

  x86-freebsd        # Any FreeBSD version on an x86 CPU
  universal-darwin-8 # Darwin 8 only gems that run on any CPU
  x86-mswin32-80     # Windows gems compiled with VC8
  armv7-linux        # Gem complied for an ARMv7 CPU running linux
  arm-linux          # Gem compiled for any ARM CPU running linux

When building platform gems, set the platform in the gem specification to
Gem::Platform::CURRENT.  This will correctly mark the gem with your ruby's
platform.
  EOF
  # :startdoc:

  def initialize
    super 'help', "Provide help on the 'gem' command"

    @command_manager = Gem::CommandManager.instance
  end

  def arguments # :nodoc:
    args = <<-EOF
      commands      List all 'gem' commands
      examples      Show examples of 'gem' usage
      <command>     Show specific help for <command>
    EOF
    return args.gsub(/^\s+/, '')
  end

  def usage # :nodoc:
    "#{program_name} ARGUMENT"
  end

  def execute
    arg = options[:args][0]

    if begins? "commands", arg then
      show_commands

    elsif begins? "options", arg then
      say Gem::Command::HELP

    elsif begins? "examples", arg then
      say EXAMPLES

    elsif begins? "platforms", arg then
      say PLATFORMS

    elsif options[:help] then
      show_help

    elsif arg then
      show_command_help arg

    else
      say Gem::Command::HELP
    end
  end

  def show_commands # :nodoc:
    out = []
    out << "GEM commands are:"
    out << nil

    margin_width = 4

    desc_width = @command_manager.command_names.map { |n| n.size }.max + 4

    summary_width = 80 - margin_width - desc_width
    wrap_indent = ' ' * (margin_width + desc_width)
    format = "#{' ' * margin_width}%-#{desc_width}s%s"

    @command_manager.command_names.each do |cmd_name|
      command = @command_manager[cmd_name]

      summary =
        if command then
          command.summary
        else
          "[No command found for #{cmd_name}]"
        end

      summary = wrap(summary, summary_width).split "\n"
      out << sprintf(format, cmd_name, summary.shift)
      until summary.empty? do
        out << "#{wrap_indent}#{summary.shift}"
      end
    end

    out << nil
    out << "For help on a particular command, use 'gem help COMMAND'."
    out << nil
    out << "Commands may be abbreviated, so long as they are unambiguous."
    out << "e.g. 'gem i rake' is short for 'gem install rake'."

    say out.join("\n")
  end

  def show_command_help command_name # :nodoc:
    command_name = command_name.downcase

    possibilities = @command_manager.find_command_possibilities command_name

    if possibilities.size == 1 then
      command = @command_manager[possibilities.first]
      command.invoke("--help")
    elsif possibilities.size > 1 then
      alert_warning "Ambiguous command #{command_name} (#{possibilities.join(', ')})"
    else
      alert_warning "Unknown command #{command_name}.  Try: gem help commands"
    end
  end

  def show_help # :nodoc:
    command = @command_manager[options[:help]]
    if command then
      # help with provided command
      command.invoke("--help")
    else
      alert_error "Unknown command #{options[:help]}.  Try 'gem help commands'"
    end
  end

end


text:
function(from, to) {
    if (from > to) {
        var arr = this.measure(to, from-to+1);
        arr.reverseInPlace();
        return arr.sequence();
    }
    return this.measure(from, to-from+1);
}


text:
var util = require('util');
var https = require('https');
var crypto = require('crypto');
var moment = require('moment');
var errorProxy = require(process.cwd() + '/error');
var router = require('express').Router();

var config = {}
	config.accountId = '65924dd16c9b3bdcf0fb693ea1abd487'
	config.appId = 'b8d2f890ee0843c483582ddf0307ad42'
	config.authTocken = '39ee828c25c3afd530de88dd5536c666'
	config.templateId = '3490'

exports.postValidCodeTOPhone = function(params, callback){
	var tempPath = '/%s/Accounts/%s/Messages/templateSMS?sig=%s'
	var timestamp = moment().format('YYYYMMDDHHmmss')
	var number = Math.floor(Math.random() * 1000)
	var sig = crypto.createHash('md5')
					.update(config.accountId)
					.update(config.authTocken)
					.update(timestamp)
					.digest('hex')
					.toUpperCase()
	var data = {
		"templateSMS": {
			"appId": config.appId,
			"param": number,
			"templateId": config.templateId,
			"to": params.phoneNumber
		}

	}

	data = JSON.stringify(data)

	var options = {
		hostname: 'api.ucpaas.com',
		path: util.format(tempPath,'2014-06-30', config.accountId, sig),
		method: 'post'
	}
	var headers = {
		"Content-Type": "application/json;charset=utf-8",
		"Accept": "application/json",
		"Content-Length": data.length,
		"Authorization": new Buffer(config.accountId + ':' + timestamp).toString('base64')

	}

	options.headers = headers

	var req = https.request(options, function(res){
		res.on('data', function(buffer) {
			var rslt = JSON.parse(buffer.toString())
			if (rslt.resp.respCode == '000000') {
				callback(null, {
									phone_auth_code: number,
									phone_number: params.phoneNumber,
									create_date: rslt.resp.templateSMS.createDate
								})
			} else {
				callback(errorProxy(2000));
			}

		})
	})
	req.on('error', function(e) {
	  callback(errorProxy(2000))
	})
	req.write(data)
	req.end()
}


text:
class CreateHospitals < ActiveRecord::Migration
  def change
    create_table :hospitals do |t|
      t.string :name
      t.string :address
      t.float :latitude
      t.float :longitude
    end
  end
end


text:
Routing
=======

The default routes used in the CRUD controller are accessible through the
``Admin`` class.

The ``Admin`` class contains two routing methods:

* ``getRoutes()``: Returns the available routes;
* ``generateUrl($name, $options)``: Generates the related routes.

Routing Definition
------------------

Route names
^^^^^^^^^^^

You can set a ``baseRouteName`` property inside your ``Admin`` class. This
represents the route prefix, to which an underscore and the action name will
be added to generate the actual route names. Note: this is the internal *name*
given to a route (it has nothing to do with the route's visible *URL*).

.. code-block:: php

    <?php
    class PostAdmin extends Admin
    {
        protected $baseRouteName = 'sonata_post';
        // will result in routes named:
        //   sonata_post_list
        //   sonata_post_create
        //   etc..
    }

If no ``baseRouteName`` is defined then the Admin will generate one for you,
based on the following format: 'admin_vendor_bundlename_entityname' so you will have
route names for your actions like 'admin_vendor_bundlename_entityname_list'.

If the Admin fails to find a baseRouteName for your Admin class a ``RuntimeException``
will be thrown with a related message.

Route patterns (URLs)
^^^^^^^^^^^^^^^^^^^^^

You can use ``baseRoutePattern`` to set a custom URL for a given ``Admin`` class.

For example, to use ``http://yourdomain.com/admin/foo`` as the base URL for
the ``FooAdmin`` class (instead of the default of ``http://yourdomain.com/admin/vendor/bundle/foo``)
use the following code:

.. code-block:: php

    <?php
    class FooAdmin extends Admin
    {
        protected $baseRoutePattern = 'foo';
    }

You will then have route URLs like ``http://yourdomain.com/admin/foo/list`` and
``http://yourdomain.com/admin/foo/1/edit``

Routing usage
-------------

Inside a CRUD template, a route for the current ``Admin`` class can be generated via
the admin variable's ``generateUrl()`` command:

.. code-block:: html+jinja

    List

    List

Note that you do not need to provide the Admin's route prefix (baseRouteName) to
generate a URL for the current Admin, just the action name.

To generate a URL for a different Admin you just use the Route Name with the usual
Twig helpers:

.. code-block:: html+jinja

    List

Create a route
--------------

You can register new routes by defining them in your ``Admin`` class. Only Admin
routes should be registered this way.

The routes you define in this way are generated within your Admin's context, and
the only required parameter to ``add()`` is the action name. The second parameter
can be used to define the URL format to append to ``baseRoutePattern``, if not set
explicitly this defaults to the action name.

.. code-block:: php

    <?php
    use Sonata\AdminBundle\Route\RouteCollection;

    class MediaAdmin extends Admin
    {
        protected function configureRoutes(RouteCollection $collection)
        {
            $collection->add('myCustom'); // Action gets added automatically
            $collection->add('view', $this->getRouterIdParameter().'/view');
        }
    }

Make use of all route parameters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

As the ``add`` method create a Symfony ``Route``, you can use all constructor arguments of the ``Route`` as parameters
in the ``add`` method to set additional settings like this:

.. code-block:: php

    <?php
    use Sonata\AdminBundle\Route\RouteCollection;

    class MediaAdmin extends Admin
    {
        protected function configureRoutes(RouteCollection $collection)
        {
            $collection->add('custom_action', $this->getRouterIdParameter().'/custom-action', array(), array(), array(), '', array('https'), array('GET','POST'));
        }
    }

Other steps needed to create your new action
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In addition to defining the route for your new action you also need to create a
handler for it in your Controller. By default Admin classes use ``SonataAdminBundle:CRUD``
as their controller, but this can be changed by altering the third argument when defining
your Admin service (in your admin.yml file).

For example, lets change the Controller for our MediaAdmin class to AcmeDemoBundle:MediaCRUD:

.. configuration-block::

    .. code-block:: yaml

        # src/Acme/DemoBundle/Resources/config/admin.yml
        sonata.admin.media:
            class: Acme\DemoBundle\Admin\MediaAdmin
            tags:
                - { name: sonata.admin, manager_type: orm, label: "Media" }
            arguments:
                - ~
                - Acme\DemoBundle\Entity\Page
                - 'AcmeDemoBundle:MediaCRUD' # define the new controller via the third argument
            calls:
                - [ setTranslationDomain, [Acme\DemoBundle]]

We now need to create our Controller, the easiest way is to extend the basic Sonata CRUD controller:

.. code-block:: php

    <?php
    // /src/Acme/DemoBundle/Controller/MediaCRUDController.php
    namespace Acme\DemoBundle\Controller;

    use Sonata\AdminBundle\Controller\CRUDController;

    class MediaCRUDController extends CRUDController
    {
        public function myCustomAction()
        {
            // your code here ...
        }
    }

Removing a route
----------------

Extending ``Sonata\AdminBundle\Admin\Admin`` will give your Admin classes the following
default routes:

* batch
* create
* delete
* export
* edit
* list
* show

You can view all of the current routes defined for an Admin class by using the console to run

``php app/console sonata:admin:explain <<admin.service.name>>``

for example if your Admin is called sonata.admin.foo you would run

``php app/console sonata:admin:explain sonata.admin.foo``

Sonata internally checks for the existence of a route before linking to it. As a result, removing a
route will prevent links to that action from appearing in the administrative interface. For example,
removing the 'create' route will prevent any links to "Add new" from appearing.

Removing a single route
^^^^^^^^^^^^^^^^^^^^^^^

Any single registered route can be easily removed by name:

.. code-block:: php

    <?php
    use Sonata\AdminBundle\Route\RouteCollection;

    class MediaAdmin extends Admin
    {
        protected function configureRoutes(RouteCollection $collection)
        {
            $collection->remove('delete');
        }
    }

Removing all routes except named ones
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you want to disable all default Sonata routes except few whitelisted ones, you can use
the ``clearExcept()`` method. This method accepts an array of routes you want to keep active.

.. code-block:: php

    <?php
    use Sonata\AdminBundle\Route\RouteCollection;

    class MediaAdmin extends Admin
    {
        protected function configureRoutes(RouteCollection $collection)
        {
            // Only `list` and `edit` route will be active
            $collection->clearExcept(array('list', 'edit'));
        }
    }

Removing all routes
^^^^^^^^^^^^^^^^^^^

If you want to remove all default routes, you can use ``clear()`` method.

.. code-block:: php

    <?php
    use Sonata\AdminBundle\Route\RouteCollection;

    class MediaAdmin extends Admin
    {
        protected function configureRoutes(RouteCollection $collection)
        {
            // All routes are removed
            $collection->clear();
        }
    }

Removing routes only when an Admin is embedded
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To prevent some routes from being available when one Admin is embedded inside another one
(e.g. to remove the "add new" option when you embed ``TagAdmin`` within ``PostAdmin``) you
can use ``hasParentFieldDescription()`` to detect this case and remove the routes.

.. code-block:: php

    <?php
    use Sonata\AdminBundle\Route\RouteCollection;

    class TagAdmin extends Admin
    {
        protected function configureRoutes(RouteCollection $collection)
        {
            if ($this->hasParentFieldDescription()) { // prevent display of "Add new" when embedding this form
                $collection->remove('create');
            }
        }
    }

Persistent parameters
---------------------

In some cases, the interface might be required to pass the same parameters
across the different ``Admin``'s actions. Instead of setting them in the
template or doing other weird hacks, you can define a ``getPersistentParameters``
method. This method will be used when a link is being generated.

.. code-block:: php

    <?php
    class MediaAdmin extends Admin
    {
        public function getPersistentParameters()
        {
            if (!$this->getRequest()) {
                return array();
            }

            return array(
                'provider' => $this->getRequest()->get('provider'),
                'context'  => $this->getRequest()->get('context', 'default'),
            );
        }
    }

    // the result:
    // $admin->generateUrl('create') => /admin/module/create?context=default

Changing the default route in a List Action
-------------------------------------------

Usually the identifier column of a list action links to the edit screen. To change the
list action's links to point to a different action, set the ``route`` option in your call to
``ListMapper::addIdentifier()``. For example, to link to show instead of edit:

.. code-block:: php

    <?php
    class PostAdmin extends Admin
    {
        public function configureListFields(ListMapper $listMapper)
        {
            $listMapper
                ->addIdentifier('name', null, array(
                    'route' => array('name' => 'show')
                ));
        }
    }


text:
function MasterView() {
	//create object instance, parasitic subclass of Observable
	var self = Ti.UI.createView({
		backgroundColor:'white'
	});

	//some dummy data for our table view
	var tableData = [
		{title:'Touring Rock Band', xml:'jm05.xml', hasChild:true, color: '#000' },
		{title:'Gangster London', xml:'gw01.xml', hasChild:true, color: '#000'},
		{title:'Last Frontier', xml:'jm06.xml', hasChild:true, color: '#000'},
	];

	var table = Ti.UI.createTableView({
		data:tableData
	});
	self.add(table);

	//add behavior
	table.addEventListener('click', function(e) {
		self.fireEvent('itemSelected', {
			name:e.rowData.title,
			file:e.rowData.xml
			//price:e.rowData.price
		});
	});

	return self;
};

module.exports = MasterView;


text:
<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //
    protected $table = 'user';
    protected $primaryKey = 'user_name';
    public  $timestamps = false;
}


text:
class Rss::PubSubHubbub::VerificationParam
  include ActiveModel::Model

  attr_accessor :cur_node
  attr_accessor :mode, :topic, :challenge, :lease_seconds

  validate :validate_mode
  validate :validate_topic
  validate :validate_challenge

  private

  def validate_mode
    errors.add :mode, :invalid unless %w(subscribe unsubscribe).include?(mode)
  end

  def validate_topic
    if topic.blank?
      errors.add :topic, :blank
      return
    end

    return if cur_node.blank?
    return if cur_node.topic_urls.blank?

    unless cur_node.topic_urls.include?(topic)
      errors.add :topic, :inclusion
    end
  end

  def validate_challenge
    errors.add :challenge, :blank if mode == 'subscribe' && challenge.blank?
  end
end


text:
import { module } from 'angular';

import { CloudProviderRegistry, DeploymentStrategyRegistry } from '@spinnaker/core';

import './help/azure.help';
import './logo/azure.logo.less';
import { AZURE_PIPELINE_STAGES_DESTROYASG_AZUREDESTROYASGSTAGE } from './pipeline/stages/destroyAsg/azureDestroyAsgStage';
import { AZURE_PIPELINE_STAGES_ENABLEASG_AZUREENABLEASGSTAGE } from './pipeline/stages/enableAsg/azureEnableAsgStage';
import { AZURE_PIPELINE_STAGES_DISABLEASG_AZUREDISABLEASGSTAGE } from './pipeline/stages/disableAsg/azureDisableAsgStage';
import { AZURE_PIPELINE_STAGES_BAKE_AZUREBAKESTAGE } from './pipeline/stages/bake/azureBakeStage';
import { AZURE_SERVERGROUP_DETAILS_SERVERGROUP_DETAILS_MODULE } from './serverGroup/details/serverGroup.details.module';
import { AZURE_SERVERGROUP_SERVERGROUP_TRANSFORMER } from './serverGroup/serverGroup.transformer';
import { AZURE_SERVERGROUP_CONFIGURE_WIZARD_CLONESERVERGROUP_AZURE_CONTROLLER } from './serverGroup/configure/wizard/CloneServerGroup.azure.controller';
import { AZURE_SERVERGROUP_CONFIGURE_SERVERGROUP_CONFIGURE_AZURE_MODULE } from './serverGroup/configure/serverGroup.configure.azure.module';
import { AZURE_INSTANCE_AZUREINSTANCETYPE_SERVICE } from './instance/azureInstanceType.service';
import { AZURE_LOADBALANCER_LOADBALANCER_TRANSFORMER } from './loadBalancer/loadBalancer.transformer';
import { AZURE_LOADBALANCER_DETAILS_LOADBALANCERDETAIL_CONTROLLER } from './loadBalancer/details/loadBalancerDetail.controller';
import { AZURE_LOADBALANCER_CONFIGURE_CREATELOADBALANCER_CONTROLLER } from './loadBalancer/configure/createLoadBalancer.controller';
import { AZURE_INSTANCE_DETAILS_INSTANCE_DETAILS_CONTROLLER } from './instance/details/instance.details.controller';
import { AZURE_SECURITYGROUP_DETAILS_SECURITYGROUPDETAIL_CONTROLLER } from './securityGroup/details/securityGroupDetail.controller';
import { AZURE_SECURITYGROUP_CONFIGURE_CREATESECURITYGROUPCTRL } from './securityGroup/configure/CreateSecurityGroupCtrl';
import { AZURE_SECURITYGROUP_CONFIGURE_EDITSECURITYGROUPCTRL } from './securityGroup/configure/EditSecurityGroupCtrl';
import { AZURE_SECURITYGROUP_SECURITYGROUP_TRANSFORMER } from './securityGroup/securityGroup.transformer';
import { AZURE_SECURITYGROUP_SECURITYGROUP_READER } from './securityGroup/securityGroup.reader';
import { AZURE_IMAGE_IMAGE_READER } from './image/image.reader';
import { AZURE_VALIDATION_APPLICATIONNAME_VALIDATOR } from './validation/applicationName.validator';

// load all templates into the $templateCache
const templates = require.context('./', true, /\.html$/);
templates.keys().forEach(function(key) {
  templates(key);
});

export const AZURE_MODULE = 'spinnaker.azure';
module(AZURE_MODULE, [
  AZURE_PIPELINE_STAGES_DESTROYASG_AZUREDESTROYASGSTAGE,
  AZURE_PIPELINE_STAGES_ENABLEASG_AZUREENABLEASGSTAGE,
  AZURE_PIPELINE_STAGES_DISABLEASG_AZUREDISABLEASGSTAGE,
  AZURE_PIPELINE_STAGES_BAKE_AZUREBAKESTAGE,
  AZURE_SERVERGROUP_DETAILS_SERVERGROUP_DETAILS_MODULE,
  AZURE_SERVERGROUP_SERVERGROUP_TRANSFORMER,
  AZURE_SERVERGROUP_CONFIGURE_WIZARD_CLONESERVERGROUP_AZURE_CONTROLLER,
  AZURE_SERVERGROUP_CONFIGURE_SERVERGROUP_CONFIGURE_AZURE_MODULE,
  AZURE_INSTANCE_AZUREINSTANCETYPE_SERVICE,
  AZURE_LOADBALANCER_LOADBALANCER_TRANSFORMER,
  AZURE_LOADBALANCER_DETAILS_LOADBALANCERDETAIL_CONTROLLER,
  AZURE_LOADBALANCER_CONFIGURE_CREATELOADBALANCER_CONTROLLER,
  AZURE_INSTANCE_DETAILS_INSTANCE_DETAILS_CONTROLLER,
  AZURE_SECURITYGROUP_DETAILS_SECURITYGROUPDETAIL_CONTROLLER,
  AZURE_SECURITYGROUP_CONFIGURE_CREATESECURITYGROUPCTRL,
  AZURE_SECURITYGROUP_CONFIGURE_EDITSECURITYGROUPCTRL,
  AZURE_SECURITYGROUP_SECURITYGROUP_TRANSFORMER,
  AZURE_SECURITYGROUP_SECURITYGROUP_READER,
  AZURE_IMAGE_IMAGE_READER,
  AZURE_VALIDATION_APPLICATIONNAME_VALIDATOR,
]).config(function() {
  CloudProviderRegistry.registerProvider('azure', {
    name: 'Azure',
    logo: {
      path: require('./logo/logo_azure.png'),
    },
    image: {
      reader: 'azureImageReader',
    },
    serverGroup: {
      transformer: 'azureServerGroupTransformer',
      detailsTemplateUrl: require('./serverGroup/details/serverGroupDetails.html'),
      detailsController: 'azureServerGroupDetailsCtrl',
      cloneServerGroupTemplateUrl: require('./serverGroup/configure/wizard/serverGroupWizard.html'),
      cloneServerGroupController: 'azureCloneServerGroupCtrl',
      commandBuilder: 'azureServerGroupCommandBuilder',
      configurationService: 'azureServerGroupConfigurationService',
    },
    instance: {
      instanceTypeService: 'azureInstanceTypeService',
      detailsTemplateUrl: require('./instance/details/instanceDetails.html'),
      detailsController: 'azureInstanceDetailsCtrl',
    },
    loadBalancer: {
      transformer: 'azureLoadBalancerTransformer',
      detailsTemplateUrl: require('./loadBalancer/details/loadBalancerDetail.html'),
      detailsController: 'azureLoadBalancerDetailsCtrl',
      createLoadBalancerTemplateUrl: require('./loadBalancer/configure/createLoadBalancer.html'),
      createLoadBalancerController: 'azureCreateLoadBalancerCtrl',
      CreateLoadBalancerModal: require('./loadBalancer/configure/AzureLoadBalancerChoiceModal')
        .AzureLoadBalancerChoiceModal,
    },
    securityGroup: {
      transformer: 'azureSecurityGroupTransformer',
      reader: 'azureSecurityGroupReader',
      detailsTemplateUrl: require('./securityGroup/details/securityGroupDetail.html'),
      detailsController: 'azureSecurityGroupDetailsCtrl',
      createSecurityGroupTemplateUrl: require('./securityGroup/configure/createSecurityGroup.html'),
      createSecurityGroupController: 'azureCreateSecurityGroupCtrl',
    },
  });
});

DeploymentStrategyRegistry.registerProvider('azure', ['redblack']);


text:
@interface OCMCancellableToken ()

@property (nonatomic,strong) dispatch_semaphore_t semaphore;

@property (nonatomic,strong) OCMRequestTask *requestTask;

@end

@implementation OCMCancellableToken

- (instancetype)init{
    if (self = [super init]) {
        _semaphore =  dispatch_semaphore_create(1);
    }

    return self;
}

- (instancetype)initWithRequestTask:(OCMRequestTask *)requestTask{
    if (self = [self init]) {
        _requestTask = requestTask;
    }

    return self;
}

- (void)cancel{

    dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);

    if (self.isCancelled) {
        return;
    }

    [self.requestTask cancel];
    self.isCancelled = YES;
    dispatch_semaphore_signal(self.semaphore);
}

@end


text:
<!doctype html>
<html>
  <head>
    <title>Synth</title>
    <meta charset="utf-8"/>
    <script src="lib/AudioContextMonkeyPatch.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
	<script src="lib/jquery.jsPlumb-1.5.2.js"></script>
	<script src="utils.js"></script>
    <script src="synthmodel.js"></script>
	<script src="synthview.js"></script>
	<script src="init.js"></script>
	<link rel="stylesheet" href="synth.css" type="text/css" media="screen" />
  </head>
  <body>

  </body>
</html>


text:
#ifndef __APPLE_USE_RFC_3542
#define __APPLE_USE_RFC_3542 // for PKTINFO
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE // for in6_pktinfo
#endif

#ifdef __TIZENRT__
#include <tinyara/config.h>
#include <sys/uio.h>
#endif

#include "iotivity_config.h"
#include <sys/types.h>
#if !defined(_WIN32)
#include <sys/socket.h>
#endif

#if defined(_WIN32)
#include <assert.h>
#include <winsock2.h>
#include <ws2def.h>
#include <mswsock.h>
#include <ws2tcpip.h>
#endif

#include <stdio.h>
#include <string.h>
#if !defined(_MSC_VER)
#include <unistd.h>
#endif //!defined(_MSC_VER)
#include <sys/types.h>
#include <fcntl.h>
#if !defined(_WIN32)
#include <sys/select.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#endif
#include <errno.h>
#ifdef __linux__
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#endif

#ifdef __TIZENRT__
#include <mqueue.h>
#endif
#include <coap/pdu.h>
#include "caipinterface.h"
#include "caipnwmonitor.h"
#include "caadapterutils.h"
#if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
#include "ca_adapter_net_ssl.h"
#endif
#include "octhread.h"
#include "oic_malloc.h"
#include "oic_string.h"

#define USE_IP_MREQN
#if defined(_WIN32) || defined (__TIZENRT__)
#undef USE_IP_MREQN
#endif

/*
 * Logging tag for module name
 */
//#define TAG "OIC_CA_IP_SERVER"
#define TAG IP_SERVER_TAG

#ifdef __TIZENRT__
mqd_t g_nwevent_mqfd;
#ifdef CONFIG_NET_LWIP
#define SOCK_CLOEXEC 0
#else
#define SOCK_CLOEXEC 1
#endif
#endif
#define SELECT_TIMEOUT 1     // select() seconds (and termination latency)

#define IPv4_MULTICAST     "224.0.1.187"
static struct in_addr IPv4MulticastAddress = { 0 };

#define IPv6_DOMAINS       16
#define MOBILE_INTERFACES  2
#define IPv6_MULTICAST_INT "ff01::158"
static struct in6_addr IPv6MulticastAddressInt;
#define IPv6_MULTICAST_LNK "ff02::158"
static struct in6_addr IPv6MulticastAddressLnk;
#define IPv6_MULTICAST_RLM "ff03::158"
static struct in6_addr IPv6MulticastAddressRlm;
#define IPv6_MULTICAST_ADM "ff04::158"
static struct in6_addr IPv6MulticastAddressAdm;
#define IPv6_MULTICAST_SIT "ff05::158"
static struct in6_addr IPv6MulticastAddressSit;
#define IPv6_MULTICAST_ORG "ff08::158"
static struct in6_addr IPv6MulticastAddressOrg;
#define IPv6_MULTICAST_GLB "ff0e::158"
static struct in6_addr IPv6MulticastAddressGlb;

static char *ipv6mcnames[IPv6_DOMAINS] = {
    NULL,
    IPv6_MULTICAST_INT,
    IPv6_MULTICAST_LNK,
    IPv6_MULTICAST_RLM,
    IPv6_MULTICAST_ADM,
    IPv6_MULTICAST_SIT,
    NULL,
    NULL,
    IPv6_MULTICAST_ORG,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    IPv6_MULTICAST_GLB,
    NULL
};

// Samsung Mobile
static char *mobileinferfaces[MOBILE_INTERFACES] = {
    "rmnet", "pdp"
};

#ifdef __TIZENRT__
struct in6_pktinfo {
        struct in6_addr ipi6_addr;
        int             ipi6_ifindex;
};

struct in_pktinfo
{
  unsigned int   ipi_ifindex;  /* Interface index */
  struct in_addr ipi_spec_dst; /* Local address */
  struct in_addr ipi_addr;     /* Header Destination
                                    address */
};

#define RTMGRP_LINK 1
#define IP_PKTINFO         8
#define IPV6_PKTINFO            50
#define IPV6_MULTICAST_IF 9
#define IPV6_V6ONLY 27
#define IPV6_RECVPKTINFO       50
#define IPV6_JOIN_GROUP 12
#endif

/**
 * By default, IP multicast datagrams are sent with a time-to-live (TTL) of 1.
 * An application can choose an initial TTL.
 */
static size_t multicastTTL = 1;

#if defined (_WIN32)
#define IFF_UP_RUNNING_FLAGS  (IFF_UP)

    char* caips_get_error(){
        static char buffer[32];
        snprintf(buffer, 32, "%i", WSAGetLastError());
        return buffer;
    }
#define CAIPS_GET_ERROR \
    caips_get_error()
#else
#define IFF_UP_RUNNING_FLAGS  (IFF_UP|IFF_RUNNING)

#define CAIPS_GET_ERROR \
    strerror(errno)
#endif
static CAIPErrorHandleCallback g_ipErrorHandler = NULL;

static CAIPPacketReceivedCallback g_packetReceivedCallback = NULL;

static void CAFindReadyMessage();
#if !defined(WSA_WAIT_EVENT_0)
static void CASelectReturned(fd_set *readFds, int ret);
#else
static void CAEventReturned(CASocketFd_t socket);
#endif

static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags);

static void CAReceiveHandler(void *data)
{
    (void)data;
    OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler");

    while (!caglobals.ip.terminate)
    {
        CAFindReadyMessage();
    }
#ifndef __TIZENRT__
    if (caglobals.ip.shutdownFds[0] != OC_INVALID_SOCKET)
    {
        close(caglobals.ip.shutdownFds[0]);
        caglobals.ip.shutdownFds[0] = OC_INVALID_SOCKET;
    }
#endif
    OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
}

#if !defined(WSA_WAIT_EVENT_0)

#define CLOSE_SOCKET(TYPE) \
    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
    { \
        close(caglobals.ip.TYPE.fd); \
        caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
    }

#define SET(TYPE, FDS) \
    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
    { \
        FD_SET(caglobals.ip.TYPE.fd, FDS); \
    }

#define ISSET(TYPE, FDS, FLAGS) \
    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET && FD_ISSET(caglobals.ip.TYPE.fd, FDS)) \
    { \
        fd = caglobals.ip.TYPE.fd; \
        flags = FLAGS; \
    }

static void CAFindReadyMessage()
{
    fd_set readFds;
    struct timeval timeout;

    timeout.tv_sec = caglobals.ip.selectTimeout;
    timeout.tv_usec = 0;
    struct timeval *tv = caglobals.ip.selectTimeout == -1 ? NULL : &timeout;

    FD_ZERO(&readFds);
    SET(u6,  &readFds)
    SET(u6s, &readFds)
    SET(u4,  &readFds)
    SET(u4s, &readFds)
    SET(m6,  &readFds)
    SET(m6s, &readFds)
    SET(m4,  &readFds)
    SET(m4s, &readFds)
#ifndef __TIZENRT__
    if (caglobals.ip.shutdownFds[0] != -1)
    {
        FD_SET(caglobals.ip.shutdownFds[0], &readFds);
    }
#endif
    if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
    {
        FD_SET(caglobals.ip.netlinkFd, &readFds);
    }

    int ret = select(caglobals.ip.maxfd + 1, &readFds, NULL, NULL, tv);

    if (caglobals.ip.terminate)
    {
        OIC_LOG_V(INFO, TAG, "Packet receiver Stop request received.");
        return;
    }

#ifdef __TIZENRT__
    u_arraylist_t *iflist = CAFindInterfaceChange();
    if (iflist)
    {
        uint32_t listLength = u_arraylist_length(iflist);
        for (uint32_t i = 0; i < listLength; i++)
        {
            CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
            if (ifitem)
            {
                CAProcessNewInterface(ifitem);
            }
        }
        u_arraylist_destroy(iflist);
    }
#endif
    if (0 < ret)
    {
        CASelectReturned(&readFds, ret);
    }
    else if (0 > ret)
    {
        OIC_LOG_V(FATAL, TAG, "select error %s", CAIPS_GET_ERROR);
    }
}

static void CASelectReturned(fd_set *readFds, int ret)
{
    (void)ret;
    CASocketFd_t fd = OC_INVALID_SOCKET;
    CATransportFlags_t flags = CA_DEFAULT_FLAGS;

    while (!caglobals.ip.terminate)
    {
        ISSET(u6,  readFds, CA_IPV6)
        else ISSET(u6s, readFds, CA_IPV6 | CA_SECURE)
        else ISSET(u4,  readFds, CA_IPV4)
        else ISSET(u4s, readFds, CA_IPV4 | CA_SECURE)
        else ISSET(m6,  readFds, CA_MULTICAST | CA_IPV6)
        else ISSET(m6s, readFds, CA_MULTICAST | CA_IPV6 | CA_SECURE)
        else ISSET(m4,  readFds, CA_MULTICAST | CA_IPV4)
        else ISSET(m4s, readFds, CA_MULTICAST | CA_IPV4 | CA_SECURE)
        else if ((caglobals.ip.netlinkFd != OC_INVALID_SOCKET) && FD_ISSET(caglobals.ip.netlinkFd, readFds))
        {
#ifndef __TIZENRT__
            u_arraylist_t *iflist = CAFindInterfaceChange();
            if (iflist)
            {
                uint32_t listLength = u_arraylist_length(iflist);
                for (uint32_t i = 0; i < listLength; i++)
                {
                    CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
                    if (ifitem)
                    {
                        CAProcessNewInterface(ifitem);
                    }
                }
                u_arraylist_destroy(iflist);
            }
            break;
#endif
        }
#ifndef __TIZENRT__
        else if (FD_ISSET(caglobals.ip.shutdownFds[0], readFds))
        {
            char buf[10] = {0};
            ssize_t len = read(caglobals.ip.shutdownFds[0], buf, sizeof (buf));
            if (-1 == len)
            {
                continue;
            }
            break;
        }
#endif
        else
        {
            break;
        }
        (void)CAReceiveMessage(fd, flags);
        FD_CLR(fd, readFds);
    }
}

#else // if defined(WSA_WAIT_EVENT_0)

#define CLOSE_SOCKET(TYPE) \
    if (caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) \
    { \
        closesocket(caglobals.ip.TYPE.fd); \
        caglobals.ip.TYPE.fd = OC_INVALID_SOCKET; \
    }

#define PUSH_HANDLE(HANDLE, ARRAY, INDEX) \
{ \
    ARRAY[INDEX] = HANDLE; \
    INDEX++; \
}

// Turn handle into WSAEvent and push to ARRAY
#define PUSH_SOCKET(SOCKET, ARRAY, INDEX) \
    if (SOCKET != OC_INVALID_SOCKET) \
    { \
        WSAEVENT NewEvent; \
        NewEvent = WSACreateEvent(); \
        if (WSA_INVALID_EVENT != NewEvent) \
        { \
            if (0 != WSAEventSelect(SOCKET, NewEvent, FD_READ)) \
            { \
                OIC_LOG_V(ERROR, TAG, "WSAEventSelect failed 0x%08x ", WSAGetLastError()); \
                if (!WSACloseEvent(NewEvent)) \
                { \
                    OIC_LOG_V(ERROR, TAG, "WSACloseEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
                } \
            } \
            else \
            { \
                PUSH_HANDLE(NewEvent, ARRAY, INDEX); \
            } \
        } \
        else \
        { \
            OIC_LOG_V(ERROR, TAG, "WSACreateEvent(NewEvent) failed 0x%08x", WSAGetLastError()); \
        }\
    }

#define INSERT_SOCKET(FD, ARRAY, INDEX) \
    { \
        if (OC_INVALID_SOCKET != FD) \
        { \
            ARRAY[INDEX] = FD; \
        } \
    }

// Inserts the socket into the SOCKET_ARRAY and pushes the socket event into EVENT_ARRAY
#define PUSH_IP_SOCKET(TYPE, EVENT_ARRAY, SOCKET_ARRAY, INDEX) \
    { \
        if (OC_INVALID_SOCKET != caglobals.ip.TYPE.fd) \
        { \
            INSERT_SOCKET(caglobals.ip.TYPE.fd, SOCKET_ARRAY, INDEX); \
            PUSH_SOCKET(caglobals.ip.TYPE.fd, EVENT_ARRAY, INDEX); \
        } \
    }

#define IS_MATCHING_IP_SOCKET(TYPE, SOCKET, FLAGS) \
    if ((caglobals.ip.TYPE.fd != OC_INVALID_SOCKET) && (caglobals.ip.TYPE.fd == SOCKET)) \
    { \
        fd = caglobals.ip.TYPE.fd; \
        flags = FLAGS; \
    }

#define EVENT_ARRAY_SIZE  10

static void CAFindReadyMessage()
{
    CASocketFd_t socketArray[EVENT_ARRAY_SIZE];
    HANDLE eventArray[EVENT_ARRAY_SIZE];
    int arraySize = 0;
    int eventIndex;

    // socketArray and eventArray should have same number of elements
    OC_STATIC_ASSERT(_countof(socketArray) == _countof(eventArray), "Arrays should have same number of elements");

    PUSH_IP_SOCKET(u6,  eventArray, socketArray, arraySize);
    PUSH_IP_SOCKET(u6s, eventArray, socketArray, arraySize);
    PUSH_IP_SOCKET(u4,  eventArray, socketArray, arraySize);
    PUSH_IP_SOCKET(u4s, eventArray, socketArray, arraySize);
    PUSH_IP_SOCKET(m6,  eventArray, socketArray, arraySize);
    PUSH_IP_SOCKET(m6s, eventArray, socketArray, arraySize);
    PUSH_IP_SOCKET(m4,  eventArray, socketArray, arraySize);
    PUSH_IP_SOCKET(m4s, eventArray, socketArray, arraySize);

    if (WSA_INVALID_EVENT != caglobals.ip.shutdownEvent)
    {
        INSERT_SOCKET(OC_INVALID_SOCKET, socketArray, arraySize);
        PUSH_HANDLE(caglobals.ip.shutdownEvent, eventArray, arraySize);
    }

    /** @todo Support netlink events */

    // Should not have overflowed buffer
    assert(arraySize <= (_countof(socketArray)));

    // Timeout is unnecessary on Windows
    assert(-1 == caglobals.ip.selectTimeout);

    while (!caglobals.ip.terminate)
    {
        int ret = WSAWaitForMultipleEvents(arraySize, eventArray, FALSE, WSA_INFINITE, FALSE);

        switch (ret)
        {
            case WSA_WAIT_FAILED:
                OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_FAILED 0x%08x", WSAGetLastError());
                break;
            case WSA_WAIT_IO_COMPLETION:
                OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_IO_COMPLETION 0x%08x", WSAGetLastError());
                break;
            case WSA_WAIT_TIMEOUT:
                OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents returned WSA_WAIT_TIMEOUT 0x%08x", WSAGetLastError());
                break;
            default:
                eventIndex = ret - WSA_WAIT_EVENT_0;
                if ((eventIndex >= 0) && (eventIndex < arraySize))
                {
                    if (false == WSAResetEvent(eventArray[eventIndex]))
                    {
                        OIC_LOG_V(ERROR, TAG, "WSAResetEvent failed 0x%08x", WSAGetLastError());
                    }

                    // Break out if shutdownEvent is triggered.
                    if ((caglobals.ip.shutdownEvent != WSA_INVALID_EVENT) &&
                        (caglobals.ip.shutdownEvent == eventArray[eventIndex]))
                    {
                        break;
                    }
                    CAEventReturned(socketArray[eventIndex]);
                }
                else
                {
                    OIC_LOG_V(ERROR, TAG, "WSAWaitForMultipleEvents failed 0x%08x", WSAGetLastError());
                }
                break;
        }

    }

    while (arraySize > 0)
    {
        arraySize--;
        if (!WSACloseEvent(eventArray[arraySize]))
        {
            OIC_LOG_V(ERROR, TAG, "WSACloseEvent (Index %i) failed 0x%08x", arraySize, WSAGetLastError());
        }
    }

    if (caglobals.ip.terminate)
    {
        caglobals.ip.shutdownEvent = WSA_INVALID_EVENT;
        WSACleanup();
    }
}

static void CAEventReturned(CASocketFd_t socket)
{
    CASocketFd_t fd = OC_INVALID_SOCKET;
    CATransportFlags_t flags = CA_DEFAULT_FLAGS;

    while (!caglobals.ip.terminate)
    {
        IS_MATCHING_IP_SOCKET(u6,  socket, CA_IPV6)
        else IS_MATCHING_IP_SOCKET(u6s, socket, CA_IPV6 | CA_SECURE)
        else IS_MATCHING_IP_SOCKET(u4,  socket, CA_IPV4)
        else IS_MATCHING_IP_SOCKET(u4s, socket, CA_IPV4 | CA_SECURE)
        else IS_MATCHING_IP_SOCKET(m6,  socket, CA_MULTICAST | CA_IPV6)
        else IS_MATCHING_IP_SOCKET(m6s, socket, CA_MULTICAST | CA_IPV6 | CA_SECURE)
        else IS_MATCHING_IP_SOCKET(m4,  socket, CA_MULTICAST | CA_IPV4)
        else IS_MATCHING_IP_SOCKET(m4s, socket, CA_MULTICAST | CA_IPV4 | CA_SECURE)
        else
        {
            break;
        }
        (void)CAReceiveMessage(socket, flags);
        // We will never get more than one match per socket, so always break.
        break;
    }
}

#endif

void CADeInitializeIPGlobals()
{
    CLOSE_SOCKET(u6);
    CLOSE_SOCKET(u6s);
    CLOSE_SOCKET(u4);
    CLOSE_SOCKET(u4s);
    CLOSE_SOCKET(m6);
    CLOSE_SOCKET(m6s);
    CLOSE_SOCKET(m4);
    CLOSE_SOCKET(m4s);

    if (caglobals.ip.netlinkFd != OC_INVALID_SOCKET)
    {
#ifdef _WIN32
        closesocket(caglobals.ip.netlinkFd);
#else
        close(caglobals.ip.netlinkFd);
#endif
        caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
    }
}

static CAResult_t CAReceiveMessage(CASocketFd_t fd, CATransportFlags_t flags)
{
    OIC_LOG(DEBUG, TAG, "IN - CAReceiveMessage");
    char recvBuffer[COAP_MAX_PDU_SIZE] = {0};

    size_t len = 0;
    int level = 0;
    int type = 0;
    int namelen = 0;
    struct sockaddr_storage srcAddr = { .ss_family = 0 };
    unsigned char *pktinfo = NULL;
#if !defined(WSA_CMSG_DATA)
    struct cmsghdr *cmp = NULL;
    struct iovec iov = { .iov_base = recvBuffer, .iov_len = sizeof (recvBuffer) };
    union control
    {
        struct cmsghdr cmsg;
        unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
    } cmsg;
#if defined (CONFIG_NET_IPv6)
    if (flags & CA_IPV6)
    {
        namelen = sizeof (struct sockaddr_in6);
        level = IPPROTO_IPV6;
        type = IPV6_PKTINFO;
        len = sizeof (struct in6_pktinfo);
    }
    else
#endif
    {
        namelen = sizeof (struct sockaddr_in);
        level = IPPROTO_IP;
        type = IP_PKTINFO;
        len = sizeof (struct in6_pktinfo);
    }

    struct msghdr msg = { .msg_name = &srcAddr,
                          .msg_namelen = namelen,
                          .msg_iov = &iov,
                          .msg_iovlen = 1,
                          .msg_control = &cmsg,
                          .msg_controllen = CMSG_SPACE(len) };

    ssize_t recvLen = recvmsg(fd, &msg, flags);
    if (OC_SOCKET_ERROR == recvLen)
    {
        OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
        return CA_STATUS_FAILED;
    }
    OIC_LOG_V(DEBUG, TAG, "recvd %u bytes from recvmsg", recvLen);

    if (flags & CA_MULTICAST)
    {
        for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
        {
            if (cmp->cmsg_level == level && cmp->cmsg_type == type)
            {
                pktinfo = CMSG_DATA(cmp);
            }
        }
    }
#else // if defined(WSA_CMSG_DATA)
    union control
    {
        WSACMSGHDR cmsg;
        uint8_t data[WSA_CMSG_SPACE(sizeof (IN6_PKTINFO))];
    } cmsg;
    memset(&cmsg, 0, sizeof(cmsg));

#if defined (CONFIG_NET_IPv6)
    if (flags & CA_IPV6)
    {
        namelen  = sizeof (struct sockaddr_in6);
        level = IPPROTO_IPV6;
        type = IPV6_PKTINFO;
    }
    else
#endif
    {
        namelen = sizeof (struct sockaddr_in);
        level = IPPROTO_IP;
        type = IP_PKTINFO;
    }

    WSABUF iov = {.len = sizeof (recvBuffer), .buf = recvBuffer};
    WSAMSG msg = {.name = (PSOCKADDR)&srcAddr,
                  .namelen = namelen,
                  .lpBuffers = &iov,
                  .dwBufferCount = 1,
                  .Control = {.buf = cmsg.data, .len = sizeof (cmsg)}
                 };

    uint32_t recvLen = 0;
    uint32_t ret = caglobals.ip.wsaRecvMsg(fd, &msg, &recvLen, 0,0);
    OIC_LOG_V(DEBUG, TAG, "WSARecvMsg recvd %u bytes", recvLen);
    if (OC_SOCKET_ERROR == ret)
    {
        OIC_LOG_V(ERROR, TAG, "WSARecvMsg failed %i", WSAGetLastError());
    }

    if (flags & CA_MULTICAST)
    {
        for (WSACMSGHDR *cmp = WSA_CMSG_FIRSTHDR(&msg); cmp != NULL;
             cmp = WSA_CMSG_NXTHDR(&msg, cmp))
        {
            if (cmp->cmsg_level == level && cmp->cmsg_type == type)
            {
                pktinfo = WSA_CMSG_DATA(cmp);
            }
        }
    }
#endif // !defined(WSA_CMSG_DATA)
    CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};

#ifndef __TIZENRT__
    if (flags & CA_IPV6)
    {
        /** @todo figure out correct usage for ifindex, and sin6_scope_id.*/
        if ((flags & CA_MULTICAST) && pktinfo)
        {
            struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
            unsigned char topbits = ((unsigned char *)addr)[0];
            if (topbits != 0xff)
            {
                sep.endpoint.flags &= ~CA_MULTICAST;
            }
        }
    }
    else
#endif
    {
        if ((flags & CA_MULTICAST) && pktinfo)
        {
            struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
            uint32_t host = ntohl(addr->s_addr);
            unsigned char topbits = ((unsigned char *)&host)[3];
            if (topbits < 224 || topbits > 239)
            {
                sep.endpoint.flags &= ~CA_MULTICAST;
            }
        }
    }

    CAConvertAddrToName(&srcAddr, namelen, sep.endpoint.addr, &sep.endpoint.port);

    if (flags & CA_SECURE)
    {
#ifdef __WITH_DTLS__
        int ret = CAdecryptSsl(&sep, (uint8_t *)recvBuffer, recvLen);
        OIC_LOG_V(INFO, TAG, "CAdecryptSsl returns [%d]", ret);
#else
        OIC_LOG(ERROR, TAG, "Encrypted message but no DTLS");
#endif
    }
    else
    {
        if (g_packetReceivedCallback)
        {
            OIC_LOG(DEBUG, TAG, "call receivedCB");
            g_packetReceivedCallback(&sep, recvBuffer, recvLen);
        }
    }

    OIC_LOG(DEBUG, TAG, "OUT - CAReceiveMessage");
    return CA_STATUS_OK;

}

void CAIPPullData()
{
    OIC_LOG(DEBUG, TAG, "IN");
    OIC_LOG(DEBUG, TAG, "OUT");
}

static CASocketFd_t CACreateSocket(int family, uint16_t *port, bool isMulticast)
{
    int socktype = SOCK_DGRAM;
#ifdef SOCK_CLOEXEC
    socktype |= SOCK_CLOEXEC;
#endif
    CASocketFd_t fd = socket(family, socktype, IPPROTO_UDP);
    if (OC_INVALID_SOCKET == fd)
    {
        OIC_LOG_V(ERROR, TAG, "create socket failed: %s", CAIPS_GET_ERROR);
        return OC_INVALID_SOCKET;
    }

#if !defined(SOCK_CLOEXEC) && defined(FD_CLOEXEC)
    int fl = fcntl(fd, F_GETFD);
    if (-1 == fl || -1 == fcntl(fd, F_SETFD, fl|FD_CLOEXEC))
    {
        OIC_LOG_V(ERROR, TAG, "set FD_CLOEXEC failed: %s", strerror(errno));
        close(fd);
        return OC_INVALID_SOCKET;
    }
#endif
    struct sockaddr_storage sa = { .ss_family = family };
    socklen_t socklen = 0;

#if defined (CONFIG_NET_IPv6)
    if (family == AF_INET6)
    {
        int on = 1;

        if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, OPTVAL_T(&on), sizeof (on)))
        {
            OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", CAIPS_GET_ERROR);
        }

        if (isMulticast && *port) // only do this for multicast ports
        {
#if defined(IPV6_RECVPKTINFO)
            if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
#else
            if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IPV6, IPV6_PKTINFO, OPTVAL_T(&on), sizeof (on)))
#endif
            {
                OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s",CAIPS_GET_ERROR);
            }
        }

        ((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
        socklen = sizeof (struct sockaddr_in6);
    }
    else
#endif /* CONFIG_NET_IPv6 */
    {
        if (isMulticast && *port) // only do this for multicast ports
        {
            int on = 1;
            if (OC_SOCKET_ERROR == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, OPTVAL_T(&on), sizeof (on)))
            {
                OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", CAIPS_GET_ERROR);
            }
        }

        ((struct sockaddr_in *)&sa)->sin_port = htons(*port);
        socklen = sizeof (struct sockaddr_in);
    }

    if (isMulticast && *port) // use the given port
    {
        int on = 1;
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, OPTVAL_T(&on), sizeof (on)))
        {
            OIC_LOG_V(ERROR, TAG, "SO_REUSEADDR failed: %s", CAIPS_GET_ERROR);
#ifdef _WIN32
            closesocket(fd);
#else
            close(fd);
#endif
            return OC_INVALID_SOCKET;
        }
    }

    if (OC_SOCKET_ERROR == bind(fd, (struct sockaddr *)&sa, socklen))
    {
        OIC_LOG_V(ERROR, TAG, "bind socket failed: %s", CAIPS_GET_ERROR);
#ifdef _WIN32
        closesocket(fd);
#else
        close(fd);
#endif
        return OC_INVALID_SOCKET;
    }

    if (!*port) // return the assigned port
    {
        if (OC_SOCKET_ERROR == getsockname(fd, (struct sockaddr *)&sa, &socklen))
        {
            OIC_LOG_V(ERROR, TAG, "getsockname failed: %s", CAIPS_GET_ERROR);
#ifdef _WIN32
            closesocket(fd);
#else
            close(fd);
#endif
            return OC_INVALID_SOCKET;
        }
        *port = ntohs(family == AF_INET6 ?
                      ((struct sockaddr_in6 *)&sa)->sin6_port :
                      ((struct sockaddr_in *)&sa)->sin_port);
    }

    return fd;
}

#define CHECKFD(FD) \
    if (FD > caglobals.ip.maxfd) \
        caglobals.ip.maxfd = FD;
#define NEWSOCKET(FAMILY, NAME, MULTICAST) \
    caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
    if (caglobals.ip.NAME.fd == OC_INVALID_SOCKET) \
    {   \
        caglobals.ip.NAME.port = 0; \
        caglobals.ip.NAME.fd = CACreateSocket(FAMILY, &caglobals.ip.NAME.port, MULTICAST); \
    }   \
    CHECKFD(caglobals.ip.NAME.fd)

static void CAInitializeNetlink()
{
    caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
#ifdef __linux__
    // create NETLINK fd for interface change notifications
    struct sockaddr_nl sa = { AF_NETLINK, 0, 0,
                              RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR };

    caglobals.ip.netlinkFd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC, NETLINK_ROUTE);
    if (caglobals.ip.netlinkFd == OC_INVALID_SOCKET)
    {
        OIC_LOG_V(ERROR, TAG, "netlink socket failed: %s", strerror(errno));
    }
    else
    {
        int r = bind(caglobals.ip.netlinkFd, (struct sockaddr *)&sa, sizeof (sa));
        if (r)
        {
            OIC_LOG_V(ERROR, TAG, "netlink bind failed: %s", strerror(errno));
            close(caglobals.ip.netlinkFd);
            caglobals.ip.netlinkFd = OC_INVALID_SOCKET;
        }
        else
        {
            CHECKFD(caglobals.ip.netlinkFd);
        }
    }
#elif defined (__TIZENRT__) // pkmsgq
	struct mq_attr lq_attr;
	lq_attr.mq_maxmsg = 10;
	lq_attr.mq_msgsize = 4;
	lq_attr.mq_flags = 0;
	g_nwevent_mqfd = mq_open("netlink_evtq", O_RDWR | O_NONBLOCK | O_CREAT, 0666, &lq_attr);
	if (g_nwevent_mqfd == (mqd_t) - 1)
	{
		OIC_LOG_V(ERROR, TAG,"RECV mq_open failed\n");
		return ;
	}
#endif
}

static void CAInitializeFastShutdownMechanism()
{
    caglobals.ip.selectTimeout = -1; // don't poll for shutdown
    int ret = -1;
#if defined(WSA_WAIT_EVENT_0)
    caglobals.ip.shutdownEvent = WSACreateEvent();
    if (WSA_INVALID_EVENT != caglobals.ip.shutdownEvent)
    {
        ret = 0;
    }
#elif defined(HAVE_PIPE2)
#ifndef __TIZENRT__
    ret = pipe2(caglobals.ip.shutdownFds, O_CLOEXEC);
    CHECKFD(caglobals.ip.shutdownFds[0]);
    CHECKFD(caglobals.ip.shutdownFds[1]);
#endif
#else
#ifndef __TIZENRT__
    ret = pipe(caglobals.ip.shutdownFds);
    if (-1 != ret)
    {
        ret = fcntl(caglobals.ip.shutdownFds[0], F_GETFD);
        if (-1 != ret)
        {
            ret = fcntl(caglobals.ip.shutdownFds[0], F_SETFD, ret|FD_CLOEXEC);
        }
        if (-1 != ret)
        {
            ret = fcntl(caglobals.ip.shutdownFds[1], F_GETFD);
        }
        if (-1 != ret)
        {
            ret = fcntl(caglobals.ip.shutdownFds[1], F_SETFD, ret|FD_CLOEXEC);
        }
        if (-1 == ret)
        {
            close(caglobals.ip.shutdownFds[1]);
            close(caglobals.ip.shutdownFds[0]);
            caglobals.ip.shutdownFds[0] = -1;
            caglobals.ip.shutdownFds[1] = -1;
        }
    }
    CHECKFD(caglobals.ip.shutdownFds[0]);
    CHECKFD(caglobals.ip.shutdownFds[1]);
#endif
#endif
    if (-1 == ret)
    {
        OIC_LOG_V(ERROR, TAG, "fast shutdown mechanism init failed: %s", CAIPS_GET_ERROR);
        caglobals.ip.selectTimeout = SELECT_TIMEOUT; //poll needed for shutdown
    }
}

CAResult_t CAIPStartServer(const ca_thread_pool_t threadPool)
{
    CAResult_t res = CA_STATUS_OK;

    if (caglobals.ip.started)
    {
        return res;
    }
#if defined (_WIN32)
    WORD wVersionRequested = MAKEWORD(2, 2);
    WSADATA wsaData ={.wVersion = 0};
    int err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
    {
        OIC_LOG_V(ERROR, TAG, "WSAStartup failed: %i", err);
        return CA_STATUS_FAILED;
    }
    OIC_LOG(DEBUG, TAG, "WSAStartup Succeeded");
#endif
    if (!IPv4MulticastAddress.s_addr)
    {
        (void)inet_pton(AF_INET, IPv4_MULTICAST, &IPv4MulticastAddress);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_INT, &IPv6MulticastAddressInt);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_LNK, &IPv6MulticastAddressLnk);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_RLM, &IPv6MulticastAddressRlm);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_ADM, &IPv6MulticastAddressAdm);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_SIT, &IPv6MulticastAddressSit);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_ORG, &IPv6MulticastAddressOrg);
        (void)inet_pton(AF_INET6, IPv6_MULTICAST_GLB, &IPv6MulticastAddressGlb);
    }

    if (!caglobals.ip.ipv6enabled && !caglobals.ip.ipv4enabled)
    {
        caglobals.ip.ipv4enabled = true;  // only needed to run CA tests
    }

    if (caglobals.ip.ipv6enabled)
    {
        NEWSOCKET(AF_INET6, u6, false)
        NEWSOCKET(AF_INET6, u6s, false)
        NEWSOCKET(AF_INET6, m6, true)
        NEWSOCKET(AF_INET6, m6s, true)
        OIC_LOG_V(INFO, TAG, "IPv6 unicast port: %u", caglobals.ip.u6.port);
    }
    if (caglobals.ip.ipv4enabled)
    {
        NEWSOCKET(AF_INET, u4, false)
        NEWSOCKET(AF_INET, u4s, false)
        NEWSOCKET(AF_INET, m4, true)
        NEWSOCKET(AF_INET, m4s, true)
        OIC_LOG_V(INFO, TAG, "IPv4 unicast port: %u", caglobals.ip.u4.port);
    }

    OIC_LOG_V(INFO, TAG,
              "socket summary: u6=%d, u6s=%d, u4=%d, u4s=%d, m6=%d, m6s=%d, m4=%d, m4s=%d",
              caglobals.ip.u6.fd, caglobals.ip.u6s.fd, caglobals.ip.u4.fd, caglobals.ip.u4s.fd,
              caglobals.ip.m6.fd, caglobals.ip.m6s.fd, caglobals.ip.m4.fd, caglobals.ip.m4s.fd);

    OIC_LOG_V(INFO, TAG,
              "port summary: u6 port=%d, u6s port=%d, u4 port=%d, u4s port=%d, m6 port=%d,"
              "m6s port=%d, m4 port=%d, m4s port=%d",
              caglobals.ip.u6.port, caglobals.ip.u6s.port, caglobals.ip.u4.port,
              caglobals.ip.u4s.port, caglobals.ip.m6.port, caglobals.ip.m6s.port,
              caglobals.ip.m4.port, caglobals.ip.m4s.port);
#if defined (SIO_GET_EXTENSION_FUNCTION_POINTER)
    caglobals.ip.wsaRecvMsg = NULL;
    GUID GuidWSARecvMsg = WSAID_WSARECVMSG;
    DWORD copied = 0;
    err = WSAIoctl(caglobals.ip.u4.fd, SIO_GET_EXTENSION_FUNCTION_POINTER, &GuidWSARecvMsg, sizeof(GuidWSARecvMsg), &(caglobals.ip.wsaRecvMsg), sizeof(caglobals.ip.wsaRecvMsg), &copied, 0, 0);
    if (0 != err)
    {
        OIC_LOG_V(ERROR, TAG, "WSAIoctl failed %i", WSAGetLastError());
        return CA_STATUS_FAILED;
    }
#endif
    // set up appropriate FD mechanism for fast shutdown
    CAInitializeFastShutdownMechanism();

    // create source of network interface change notifications
    CAInitializeNetlink();

    caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);

    res = CAIPStartListenServer();
    if (CA_STATUS_OK != res)
    {
        OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
        return res;
    }

    caglobals.ip.terminate = false;
#ifndef __TIZENRT__
    res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL, NULL);
#else
    res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL, NULL, "IoT_ReceiveHandler",
                                  CONFIG_IOTIVITY_RECEIVEHANDLER_PTHREAD_STACKSIZE);
#endif
    if (CA_STATUS_OK != res)
    {
        OIC_LOG(ERROR, TAG, "thread_pool_add_task failed");
        CAIPStopServer();
        return res;
    }
    OIC_LOG(INFO, TAG, "CAReceiveHandler thread started successfully.");

    caglobals.ip.started = true;
    return CA_STATUS_OK;
}

void CAIPStopServer()
{
    caglobals.ip.started = false;
    caglobals.ip.terminate = true;

    CADeInitializeIPGlobals();

#if !defined(WSA_WAIT_EVENT_0)
#ifndef __TIZENRT__
    if (caglobals.ip.shutdownFds[1] != -1)
    {
        close(caglobals.ip.shutdownFds[1]);
        // receive thread will stop immediately
    }
    else
    {
        // receive thread will stop in SELECT_TIMEOUT seconds.
    }
#endif
#else
    // receive thread will stop immediately.
    if (!WSASetEvent(caglobals.ip.shutdownEvent))
    {
        OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
    }
#endif

    OIC_LOG(INFO, TAG, "Adapter terminated successfully");
}

void CAWakeUpForChange()
{
#if !defined(WSA_WAIT_EVENT_0)
#ifndef __TIZENRT__
    if (caglobals.ip.shutdownFds[1] != -1)
    {
        ssize_t len = 0;
        do
        {
            len = write(caglobals.ip.shutdownFds[1], "w", 1);
        } while ((len == -1) && (errno == EINTR));
        if ((len == -1) && (errno != EINTR) && (errno != EPIPE))
        {
            OIC_LOG_V(DEBUG, TAG, "write failed: %s", strerror(errno));
        }
    }
#endif
#else
    if (!WSASetEvent(caglobals.ip.shutdownEvent))
    {
        OIC_LOG_V(DEBUG, TAG, "set shutdown event failed: %#08X", GetLastError());
    }
#endif
}

static void applyMulticastToInterface4(uint32_t ifindex)
{
    if (!caglobals.ip.ipv4enabled)
    {
        return;
    }

#if defined(USE_IP_MREQN)
    struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
                             .imr_address.s_addr = htonl(INADDR_ANY),
                             .imr_ifindex = ifindex };
#else
    struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
                             .imr_interface.s_addr = htonl(ifindex) };
#endif

    int ret = setsockopt(caglobals.ip.m4.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
    if (OC_SOCKET_ERROR == ret)
    {
#if !defined(WSAEINVAL)
        if (EADDRINUSE != errno)
#else
        if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
#endif
        {
            OIC_LOG_V(ERROR, TAG, "       IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
        }
    }
    ret = setsockopt(caglobals.ip.m4s.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, OPTVAL_T(&mreq), sizeof (mreq));
    if (OC_SOCKET_ERROR == ret)
    {
#if !defined(WSAEINVAL)
        if (EADDRINUSE != errno)
#else
        if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv4 Flavor)
#endif
        {
            OIC_LOG_V(ERROR, TAG, "SECURE IPv4 IP_ADD_MEMBERSHIP failed: %s", CAIPS_GET_ERROR);
        }
    }
}

static void applyMulticast6(int fd, struct in6_addr *addr, uint32_t ifindex)
{
#ifndef __TIZENRT__
    struct ipv6_mreq mreq = {.ipv6mr_multiaddr = {0},
                             .ipv6mr_interface = ifindex };

    // VS2013 has problems with struct copies inside struct initializers, so copy separately.
    mreq.ipv6mr_multiaddr = *addr;

    int ret = setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, OPTVAL_T(&mreq), sizeof (mreq));
    if (OC_SOCKET_ERROR == ret)
    {
#if !defined(_WIN32)
                if (EADDRINUSE != errno)
#else
                if (WSAEINVAL != WSAGetLastError()) // Joining multicast group more than once (IPv6 Flavor)
#endif
        {
            OIC_LOG_V(ERROR, TAG, "IPv6 IPV6_JOIN_GROUP failed: %s", CAIPS_GET_ERROR);
        }
    }
#endif /* ! __TIZENRT__ */
}

static void applyMulticastToInterface6(uint32_t ifindex)
{
    if (!caglobals.ip.ipv6enabled)
    {
        return;
    }
    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressInt, ifindex);
    applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressLnk, ifindex);
    applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressRlm, ifindex);
    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressAdm, ifindex);
    applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressSit, ifindex);
    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressOrg, ifindex);
    //applyMulticast6(caglobals.ip.m6.fd, &IPv6MulticastAddressGlb, ifindex);

    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressInt, ifindex);
    applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressLnk, ifindex);
    applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressRlm, ifindex);
    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressAdm, ifindex);
    applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressSit, ifindex);
    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressOrg, ifindex);
    //applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, ifindex);
}

CAResult_t CAIPStartListenServer()
{
    u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
    if (!iflist)
    {
        OIC_LOG_V(ERROR, TAG, "CAIPGetInterfaceInformation() failed: %s", strerror(errno));
        return CA_STATUS_FAILED;
    }

    uint32_t len = u_arraylist_length(iflist);
    OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);

    for (uint32_t i = 0; i < len; i++)
    {
        CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);

        if (!ifitem)
        {
            continue;
        }
        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
        {
            continue;
        }
        if (ifitem->family == AF_INET)
        {
            OIC_LOG_V(DEBUG, TAG, "Adding IPv4 interface(%d) to multicast group", ifitem->index);
            applyMulticastToInterface4(ifitem->index);
        }
        if (ifitem->family == AF_INET6)
        {
            OIC_LOG_V(DEBUG, TAG, "Adding IPv6 interface(%d) to multicast group", ifitem->index);
            applyMulticastToInterface6(ifitem->index);
        }
    }

    u_arraylist_destroy(iflist);
    return CA_STATUS_OK;
}

CAResult_t CAIPStopListenServer()
{
    u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
    if (!iflist)
    {
        OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
        return CA_STATUS_FAILED;
    }

    uint32_t len = u_arraylist_length(iflist);
    OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);

    for (uint32_t i = 0; i < len; i++)
    {
        CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);

        if (!ifitem)
        {
            continue;
        }
        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
        {
            continue;
        }
        if (ifitem->family == AF_INET)
        {
            CLOSE_SOCKET(m4);
            CLOSE_SOCKET(m4s);
            OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
        }
        if (ifitem->family == AF_INET6)
        {
            CLOSE_SOCKET(m6);
            CLOSE_SOCKET(m6s);
            OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
        }
    }
    u_arraylist_destroy(iflist);
    return CA_STATUS_OK;
}

void CAProcessNewInterface(CAInterface_t *ifitem)
{
    if (!ifitem)
    {
        OIC_LOG(DEBUG, TAG, "ifitem is null");
        return;
    }

    if (ifitem->family == AF_INET6)
    {
        OIC_LOG_V(DEBUG, TAG, "Adding a new IPv6 interface(%d) to multicast group", ifitem->index);
        applyMulticastToInterface6(ifitem->index);
    }
    if (ifitem->family == AF_INET)
    {
        OIC_LOG_V(DEBUG, TAG, "Adding a new IPv4 interface(%d) to multicast group", ifitem->index);
        applyMulticastToInterface4(ifitem->index);
    }
}

void CAIPSetPacketReceiveCallback(CAIPPacketReceivedCallback callback)
{
    g_packetReceivedCallback = callback;
}

static void sendData(int fd, const CAEndpoint_t *endpoint,
                     const void *data, uint32_t dlen,
                     const char *cast, const char *fam)
{
    OIC_LOG(DEBUG, TAG, "IN");

    if (!endpoint)
    {
        OIC_LOG(DEBUG, TAG, "endpoint is null");
        if (g_ipErrorHandler)
        {
            g_ipErrorHandler(endpoint, data, dlen, CA_STATUS_INVALID_PARAM);
        }
        return;
    }

    (void)cast;  // eliminates release warning
    (void)fam;

    struct sockaddr_storage sock = { .ss_family = 0 };
    CAConvertNameToAddr(endpoint->addr, endpoint->port, &sock);

    socklen_t socklen = 0;
    if (sock.ss_family == AF_INET6)
    {
        /** @todo figure out correct usage for ifindex, and sin6_scope_id */
        socklen = sizeof(struct sockaddr_in6);
    }
    else
    {
        socklen = sizeof(struct sockaddr_in);
    }

#ifdef TB_LOG
    const char *secure = (endpoint->flags & CA_SECURE) ? "secure " : "";
#endif
#if !defined(_WIN32)
    ssize_t len = sendto(fd, data, dlen, 0, (struct sockaddr *)&sock, socklen);
    if (OC_SOCKET_ERROR == len)
    {
         // If logging is not defined/enabled.
        if (g_ipErrorHandler)
        {
            g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
        }
#ifdef TB_LOG
        OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %s", secure, cast, fam, strerror(errno));
#endif
        CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
                           len, false, strerror(errno));
    }
    else
    {
#ifdef TB_LOG
        OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %zd bytes", secure, cast, fam, len);
#endif
        CALogSendStateInfo(endpoint->adapter, endpoint->addr, endpoint->port,
                           len, true, NULL);
    }
#else
    int err = 0;
    int len = 0;
    int sent = 0;
    do {
        len = sendto(fd, ((char*)data) + sent, dlen - sent, 0, (struct sockaddr *)&sock, socklen);
        if (OC_SOCKET_ERROR == len)
        {
            err = WSAGetLastError();
            if ((WSAEWOULDBLOCK != err) && (WSAENOBUFS != err))
            {
                 // If logging is not defined/enabled.
                if (g_ipErrorHandler)
                {
                    g_ipErrorHandler(endpoint, data, dlen, CA_SEND_FAILED);
                }

                OIC_LOG_V(ERROR, TAG, "%s%s %s sendTo failed: %i", secure, cast, fam, err);
            }
        }
        else
        {
            sent += len;
            if (sent != len)
            {
                OIC_LOG_V(INFO, TAG, "%s%s %s sendTo (Partial Send) is successful: "
                          "currently sent: %ld bytes, "
                          "total sent: %ld bytes, "
                          "remaining: %ld bytes",
                          secure, cast, fam, len, sent, dlen-sent);
            }
            else
            {
                OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes",
                                     secure, cast, fam, len);
            }
        }
    } while ((OC_SOCKET_ERROR == len) && ((WSAEWOULDBLOCK == err) || (WSAENOBUFS == err)) || (sent < dlen));
#endif
}

static void sendMulticastData6(const u_arraylist_t *iflist,
                               CAEndpoint_t *endpoint,
                               const void *data, uint32_t datalen)
{
#ifndef __TIZENRT__
    if (!endpoint)
    {
        OIC_LOG(DEBUG, TAG, "endpoint is null");
        return;
    }

    int scope = endpoint->flags & CA_SCOPE_MASK;
    char *ipv6mcname = ipv6mcnames[scope];
    if (!ipv6mcname)
    {
        OIC_LOG_V(INFO, TAG, "IPv6 multicast scope invalid: %d", scope);
        return;
    }
    OICStrcpy(endpoint->addr, sizeof(endpoint->addr), ipv6mcname);
    int fd = caglobals.ip.u6.fd;

    uint32_t len = u_arraylist_length(iflist);
    for (uint32_t i = 0; i < len; i++)
    {
        CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
        if (!ifitem)
        {
            continue;
        }
        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
        {
            continue;
        }
        if (ifitem->family != AF_INET6)
        {
            continue;
        }

        bool isMobile = false;
        for (uint32_t j = 0; j < MOBILE_INTERFACES; j++)
        {
            if (strstr(ifitem->name, mobileinferfaces[j]))
            {
                isMobile = true;
                break;
            }
        }
        if (isMobile)
        {
            continue;
        }

        int index = ifitem->index;
        if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, OPTVAL_T(&index), sizeof (index)))
        {
            OIC_LOG_V(ERROR, TAG, "setsockopt6 failed: %s", CAIPS_GET_ERROR);
            return;
        }

        // Set multicast packet TTL; default TTL is 1
        if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &multicastTTL, sizeof(multicastTTL)))
        {
            OIC_LOG_V(ERROR, TAG, "IPV6_MULTICAST_HOPS failed: %s", CAIPS_GET_ERROR);
        }
        sendData(fd, endpoint, data, datalen, "multicast", "ipv6");
    }
#endif /* ! __TIZENRT__*/
}

static void sendMulticastData4(const u_arraylist_t *iflist,
                               CAEndpoint_t *endpoint,
                               const void *data, uint32_t datalen)
{
    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");

#if defined(USE_IP_MREQN)
    struct ip_mreqn mreq = { .imr_multiaddr = IPv4MulticastAddress,
                             .imr_address.s_addr = htonl(INADDR_ANY),
                             .imr_ifindex = 0};
#else
    struct ip_mreq mreq  = { .imr_multiaddr.s_addr = IPv4MulticastAddress.s_addr,
                             .imr_interface = {0}};
#endif

    OICStrcpy(endpoint->addr, sizeof(endpoint->addr), IPv4_MULTICAST);
    int fd = caglobals.ip.u4.fd;

    uint32_t len = u_arraylist_length(iflist);
    for (uint32_t i = 0; i < len; i++)
    {
        CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
        if (!ifitem)
        {
            continue;
        }
        if ((ifitem->flags & IFF_UP_RUNNING_FLAGS) != IFF_UP_RUNNING_FLAGS)
        {
            continue;
        }
        if (ifitem->family != AF_INET)
        {
            continue;
        }

        bool isMobile = false;
        for (uint32_t j = 0; j < MOBILE_INTERFACES; j++)
        {
            if (strstr(ifitem->name, mobileinferfaces[j]))
            {
                isMobile = true;
                break;
            }
        }
        if (isMobile)
        {
            continue;
        }

#if defined(USE_IP_MREQN)
        mreq.imr_ifindex = ifitem->index;
#else
        mreq.imr_interface.s_addr = htonl(ifitem->index);
#endif
        if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, OPTVAL_T(&mreq), sizeof (mreq)))
        {
            OIC_LOG_V(ERROR, TAG, "send IP_MULTICAST_IF failed: %s (using defualt)",
                    CAIPS_GET_ERROR);
        }

        // Set multicast packet TTL; default TTL is 1
        if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, &multicastTTL, sizeof(multicastTTL)))
        {
            OIC_LOG_V(ERROR, TAG, "IP_MULTICAST_TTL failed: %s", CAIPS_GET_ERROR);
        }
        sendData(fd, endpoint, data, datalen, "multicast", "ipv4");
    }
}

void CAIPSendData(CAEndpoint_t *endpoint, const void *data, uint32_t datalen,
                  bool isMulticast)
{
    VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint is NULL");
    VERIFY_NON_NULL_VOID(data, TAG, "data is NULL");

    bool isSecure = (endpoint->flags & CA_SECURE) != 0;

    if (isMulticast)
    {
        endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;

        u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
        if (!iflist)
        {
            OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
            return;
        }

        if ((endpoint->flags & CA_IPV6) && caglobals.ip.ipv6enabled)
        {
            sendMulticastData6(iflist, endpoint, data, datalen);
        }
        if ((endpoint->flags & CA_IPV4) && caglobals.ip.ipv4enabled)
        {
            sendMulticastData4(iflist, endpoint, data, datalen);
        }

        u_arraylist_destroy(iflist);
    }
    else
    {
        if (!endpoint->port)    // unicast discovery
        {
            endpoint->port = isSecure ? CA_SECURE_COAP : CA_COAP;
        }

        CASocketFd_t fd;
        if (caglobals.ip.ipv6enabled && (endpoint->flags & CA_IPV6))
        {
            fd = isSecure ? caglobals.ip.u6s.fd : caglobals.ip.u6.fd;
#ifndef __WITH_DTLS__
            fd = caglobals.ip.u6.fd;
#endif
            sendData(fd, endpoint, data, datalen, "unicast", "ipv6");
        }
        if (caglobals.ip.ipv4enabled && (endpoint->flags & CA_IPV4))
        {
            fd = isSecure ? caglobals.ip.u4s.fd : caglobals.ip.u4.fd;
#ifndef __WITH_DTLS__
            fd = caglobals.ip.u4.fd;
#endif
            sendData(fd, endpoint, data, datalen, "unicast", "ipv4");
        }
    }
}

CAResult_t CAGetIPInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
{
    VERIFY_NON_NULL(info, TAG, "info is NULL");
    VERIFY_NON_NULL(size, TAG, "size is NULL");

    u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
    if (!iflist)
    {
        OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
        return CA_STATUS_FAILED;
    }

    uint32_t len = u_arraylist_length(iflist);
    uint32_t length = len;

#ifdef __WITH_DTLS__
    //If DTLS is supported, each interface can support secure port as well
    length = len * 2;
#endif

    CAEndpoint_t *eps = (CAEndpoint_t *)OICCalloc(length, sizeof (CAEndpoint_t));
    if (!eps)
    {
        OIC_LOG(ERROR, TAG, "Malloc Failed");
        u_arraylist_destroy(iflist);
        return CA_MEMORY_ALLOC_FAILED;
    }

    for (uint32_t i = 0, j = 0; i < len; i++)
    {
        CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
        if(!ifitem)
        {
            continue;
        }

        eps[j].adapter = CA_ADAPTER_IP;
        eps[j].ifindex = 0;

        if (ifitem->family == AF_INET6)
        {
            eps[j].flags = CA_IPV6;
            eps[j].port = caglobals.ip.u6.port;
        }
        else
        {
            eps[j].flags = CA_IPV4;
            eps[j].port = caglobals.ip.u4.port;
        }
        OICStrcpy(eps[j].addr, sizeof(eps[j].addr), ifitem->addr);

#ifdef __WITH_DTLS__
        j++;

        eps[j].adapter = CA_ADAPTER_IP;
        eps[j].ifindex = 0;

        if (ifitem->family == AF_INET6)
        {
            eps[j].flags = CA_IPV6 | CA_SECURE;
            eps[j].port = caglobals.ip.u6s.port;
        }
        else
        {
            eps[j].flags = CA_IPV4 | CA_SECURE;
            eps[j].port = caglobals.ip.u4s.port;
        }
        OICStrcpy(eps[j].addr, sizeof(eps[j].addr), ifitem->addr);
#endif
        j++;
    }

    *info = eps;
    *size = length;

    u_arraylist_destroy(iflist);

    return CA_STATUS_OK;
}

void CAIPSetErrorHandler(CAIPErrorHandleCallback errorHandleCallback)
{
    g_ipErrorHandler = errorHandleCallback;
}

CAResult_t CAIPSetMulticastTTL(size_t ttl)
{
    multicastTTL = ttl;
    return CA_STATUS_OK;
}

CAResult_t CAIPGetMulticastTTL(size_t *ttl)
{
    VERIFY_NON_NULL(ttl, TAG, "ttl is NULL");

    *ttl = multicastTTL;
    return CA_STATUS_OK;
}


text:
require 'sinatra/base'
require 'sinatra/async'
require 'thin'

module Sinatra
  module Pollers
    POLLER_TYPES = [:file_watchers, :illustrate_watchers]

    def self.registered(app)
      POLLER_TYPES.each do |poller|
        app.set poller, []
      end
    end

    # Public: Notify a given poller that something has happened
    #
    # poller_type - one of the POLLER_TYPES symbol
    # *args - the arguments to be passed to the poller
    #
    # Returns nothing.
    def notify(poller_type, *args)
      self.settings.send(poller_type).each do |poller|
        poller.call(*args)
      end
      self.set poller_type, []
    end
  end

  register Pollers
end

class Server < Sinatra::Base
  register Sinatra::Async
  register Sinatra::Pollers

  # Load the basic page
  get '/' do
    @illustrate_templates = File.read(settings.resource_locations["illustrate_template"]).to_s
    @error_templates = File.read(settings.resource_locations["error_template"]).to_s
    erb File.read(settings.resource_locations["index"]).to_s
  end

  # Ping pong
  get '/ping' do
    body { 'pong' }
  end

  # Public: Returns the illustrate results if they're available
  # otherwise waits asynchronously waits until results are available.
  #
  # Returns illustrate json (eventually)
  aget '/illustrate-results.json' do
    if settings.grunt.illustrating? or settings.illustrate_data == nil
      settings.illustrate_watchers << lambda { |data|
        body { data }
      }
    else
      body { settings.illustrate_data }
    end
  end

  # Public: Asynchronously waits for the script to change
  #
  # Returns a JSON object
  aget '/wait-for-change.json' do
    settings.file_watchers << lambda {
      body { '{ "changed" : "Yup" }'}
    }
  end
end

# Globally set certain server attributes
Server.set :public_folder, File.expand_path("../../../../../" ,__FILE__)
Server.set(:resource_locations, {
  "index" => File.expand_path("../../../../../templates/illustrate-live.html", __FILE__),
  "illustrate_template" => File.expand_path("../../../../../templates/underscore/illustrate.html", __FILE__),
  "error_template" => File.expand_path("../../../../../templates/underscore/error.html", __FILE__)
})

Server.set :illustrate_data, nil


text:
function hiddenFunction(toHidden, toShow) {
    var x = document.getElementById(toHidden);
/*    if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }*/
    x.style.display = 'none';
    var x = document.getElementById(toShow);
  /*  if (x.style.display === 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }*/
    x.style.display = 'block';
}


text:
Spring MVC JSON
===============

Spring MVC + JQuery + @RequestBody + JSON - making it work together
-------------------------------------------------------------------

* return java object as json type. --> @ResponseBody

  @RequestMapping(method = RequestMethod.GET)
  public @ResponseBody Person helloWorld(HttpServletResponse res) {

  	Person person = new Person();
  	person.setId(1);
  	person.setName("hmk");

      return person;
  }

* Receive json data sent by POST request and map it into java object. --> @RequestBody

@RequestMapping(value="person", method = RequestMethod.POST)
  public @ResponseBody Person getRequest( @RequestBody final  Person person) {
      System.out.println(person.getId() + " " + person.getName());
      return person;
  }


text:
package com.otogami.freemarker;

import java.io.Writer;
import java.util.Map;

/**
 * Interface created to avoid circular dependencies between FreemarkerTemplateRenderer and DecoratorMacro
 * and construction problems in Guice
 *
 */

public interface TemplateRendererInterface {

	void render(String template, Map<String, Object> model, Writer writer);

}


text:
package controllers;

import play.*;
import play.mvc.*;

import java.util.*;

import models.*;

public class WithAuthenticity extends Controller {

    public static void index() {
        render();
    }

    public static void needAuthenticity() {
        checkAuthenticity();
        renderText("OK");
    }

}


text:
package jodd.madvoc;

import jodd.http.HttpBrowser;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

public abstract class ExcTestBase {

	@Test
	public void testException() {
		HttpBrowser httpBrowser = new HttpBrowser();
		HttpResponse response = httpBrowser.sendRequest(HttpRequest.get("localhost:8173/exc.html"));

		assertEquals("500!", response.bodyText().trim());
	}

	@Test
	public void testRedirect500() {
		HttpBrowser httpBrowser = new HttpBrowser();
		HttpResponse response = httpBrowser.sendRequest(HttpRequest.get("localhost:8173/exc.red.html"));

		assertEquals("500!", response.bodyText().trim());
	}
}


text:
"""
    flaskproject.events.forms
    ~~~~~~~~~~~~~~~~~~~~~
    Event forms
"""

from flask_wtf import Form
from wtforms import StringField, DateField, DateTimeField
from wtforms import validators

class NewEventForm(Form):
    name = StringField('Name', [
        validators.DataRequired(),
        validators.Length(min=1, max=250)
    ])
    address = StringField('Address', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    address_line_two = StringField('Line 2', [validators.Length(max=70)])
    city = StringField('City', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    state = StringField('State', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    zip_code = StringField('Zip Code', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    country = StringField('Country', [validators.Length(max=70)
    ])
    # start_date = DateTimeField('Start Date', [validators.DataRequired()], format='%m-%d-%Y %H:%M')
    # start_date = DateTimeField('Start Date', [validators.DataRequired()])
    start_date = StringField('Start Date', [validators.DataRequired()])
    # end_date = DateTimeField('End Date', [validators.DataRequired()], format='%m-%d-%Y %H:%M')
    # end_date = DateTimeField('End Date', [validators.DataRequired()])
    end_date = StringField('End Date', [validators.DataRequired()])

class UpdateEventForm(Form):
    name = StringField('Name', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    address = StringField('Address', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    address_line_two = StringField('Line 2', [validators.Length(max=70)])
    city = StringField('City', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    state = StringField('State', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    zip_code = StringField('Zip Code', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    country = StringField('Country', [
        validators.DataRequired(),
        validators.Length(min=1, max=70)
    ])
    start_date = DateTimeField('Start Date', [validators.DataRequired()], format='%m-%d-%Y %H:%M')
    end_date = DateTimeField('End Date', [validators.DataRequired()], format='%m-%d-%Y ')