text:
set -euo pipefail

addl=${1:-}

cd $HOME

echo "Bootstrap"
wget -qO- https://raw.githubusercontent.com/andrewtchin/ansible-common/master/ubuntu-bootstrap.sh | bash

echo "Clone ansible-ubuntu"
ANSIBLE_UBUNTU_DIR="$HOME/ansible-ubuntu"
if [ -d "$ANSIBLE_UBUNTU_DIR" ]; then
  rm -rf $ANSIBLE_UBUNTU_DIR
fi
git clone https://github.com/andrewtchin/ansible-ubuntu.git $ANSIBLE_UBUNTU_DIR

cd $ANSIBLE_UBUNTU_DIR
echo "Run ansible-ubuntu"
ansible-playbook -vvv playbooks/ubuntu-server.yml --ask-become-pass -c local --extra-vars=@vars/ubuntu.json -i inventory

if [ -n "$addl" ]; then
  echo "Running additional playbook"
  ansible-playbook -vvv playbooks/$addl.yml --ask-become-pass -c local --extra-vars=@vars/ubuntu.json -i inventory
fi

echo "Install script exiting"


text:
Security
========
Security in Caravel is handled by Flask AppBuilder (FAB). FAB is a
"Simple and rapid application development framework, built on top of Flask.".
FAB provides authentication, user management, permissions and roles.

Provided Roles
--------------
Caravel ships with 3 roles that are handled by Caravel itself. You can
assume that these 3 roles will stay up-to-date as Caravel evolves.

Admin
"""""
Admins have all possible rights, including granting or revoking rights from
other users and altering other people's slices and dashboards.

Alpha
"""""
Alpha have access to all data sources, but they cannot grant or revoke access
from other users. They are also limited to altering the objects that they
own. Alpha users can add and alter data sources.

Gamma
"""""
Gamma have limited access. They can only consume data coming from data sources
they have been giving access to through another complementary role.
They only have access to view the slices and
dashboards made from data sources that they have access to. Currently Gamma
users are not able to alter or add data sources. We assume that they are
mostly content consumers, though they can create slices and dashboards.

Also note that when Gamma users look at the dashboards and slices list view,
they will only see the objects that they have access to.

Managing Gamma per data source access
-------------------------------------
Here's how to provide users access to only specific datasets. First make
sure the users with limited access have [only] the Gamma role assigned to
them. Second, create a new role (``Menu -> Security -> List Roles``) and
click the ``+`` sign.

.. image:: _static/img/create_role.png
   :scale: 50 %

This new window allows you to give this new role a name, attribute it to users
and select the tables in the ``Permissions`` dropdown. To select the data
sources you want to associate with this role, simply click in the dropdown
and use the typeahead to search for your table names.

You can then confirm with your Gamma users that they see the objects
(dashboards and slices) associated with the tables related to their roles.

Customizing
-----------

The permissions exposed by FAB are very granular and allow for a great level
of customization. FAB creates many permissions automagically for each model
that is create (can_add, can_delete, can_show, can_edit, ...) as well as for
each view. On top of that, Caravel can expose more granular permissions like
``all_datasource_access``.

We do not recommend altering the 3 base roles as there
are a set of assumptions that Caravel build upon. It is possible though for
you to create your own roles, and union them to existing ones.

Permissions
"""""""""""

Roles are composed of a set of permissions, and Caravel has many categories
of permissions. Here are the different categories of permissions:

- **Model & action**: models are entities like ``Dashboard``,
  ``Slice``, or ``User``. Each model has a fixed set of permissions, like
  ``can_edit``, ``can_show``, ``can_delete``, ``can_list``, ``can_add``, and
  so on. By adding ``can_delete on Dashboard`` to a role, and granting that
  role to a user, this user will be able to delete dashboards.
- **Views**: views are individual web pages, like the ``explore`` view or the
  ``SQL Lab`` view. When granted to a user, he/she will see that view in
  the its menu items, and be able to load that page.
- **Data source**: For each data source, a permission is created. If the user
  does not have the ``all_datasource_access`` permission granted, the user
  will only be able to see Slices or explore the data sources that are granted
  to them
- **Database**: Granting access to a database allows for the user to access
  all data sources within that database, and will enable the user to query
  that database in SQL Lab, provided that the SQL Lab specific permission
  have been granted to the user

Restricting access to a subset of data sources
""""""""""""""""""""""""""""""""""""""""""""""

The best way to go is probably to give user ``Gamma`` plus one or many other
roles that would add access to specific data sources. We recommend that you
create individual roles for each access profile. Say people in your finance
department might have access to a set of databases and data sources, and
these permissions can be consolidated in a single role. Users with this
profile then need to be attributed ``Gamma`` as a foundation to the models
and views they can access, and that ``Finance`` role that is a collection
of permissions to data objects.

One user can have many roles, so a finance executive could be granted
``Gamma``, ``Finance``, and perhaps another ``Executive`` role that gather
a set of data sources that power dashboards only made available to executives.
When looking at its dashboard list, this user will only see the
list of dashboards it has access to, based on the roles and
permissions that were attributed.

Restricting the access to some metrics
""""""""""""""""""""""""""""""""""""""

Sometimes some metrics are relatively sensitive (e.g. revenue).
We may want to restrict those metrics to only a few roles.
For example, assumed there is a metric ``[cluster1].[datasource1].[revenue]``
and only Admin users are allowed to see it. Here's how to restrict the access.

1. Edit the datasource (``Menu -> Source -> Druid datasources -> edit the
   record "datasource1"``) and go to the tab ``List Druid Metric``. Check
   the checkbox ``Is Restricted`` in the row of the metric ``revenue``.

2. Edit the role (``Menu -> Security -> List Roles -> edit the record
   "Admin"``), in the permissions field, type-and-search the permission
   ``metric access on [cluster1].[datasource1].[revenue] (id: 1)``, then
   click the Save button on the bottom of the page.

Any users without the permission will see the error message
*Access to the metrics denied: revenue (Status: 500)* in the slices.
It also happens when the user wants to access a post-aggregation metric that
is dependent on revenue.

redpajama_set_name: RedPajamaGithub


text:
#ifndef __LINUX_IMA_H
#define __LINUX_IMA_H

#include <linux/types.h>
#include <linux/crypto.h>
#include <linux/security.h>
#include <linux/hash.h>
#include <linux/tpm.h>
#include <linux/audit.h>

#include "../integrity.h"

enum ima_show_type { IMA_SHOW_BINARY, IMA_SHOW_ASCII };
enum tpm_pcrs { TPM_PCR0 = 0, TPM_PCR8 = 8 };

/* digest size for IMA, fits SHA1 or MD5 */
#define IMA_DIGEST_SIZE		SHA1_DIGEST_SIZE
#define IMA_EVENT_NAME_LEN_MAX	255

#define IMA_HASH_BITS 9
#define IMA_MEASURE_HTABLE_SIZE (1 << IMA_HASH_BITS)

/* set during initialization */
extern int ima_initialized;
extern int ima_used_chip;
extern char *ima_hash;

/* IMA inode template definition */
struct ima_template_data {
	u8 digest[IMA_DIGEST_SIZE];	/* sha1/md5 measurement hash */
	char file_name[IMA_EVENT_NAME_LEN_MAX + 1];	/* name + \0 */
};

struct ima_template_entry {
	u8 digest[IMA_DIGEST_SIZE];	/* sha1 or md5 measurement hash */
	const char *template_name;
	int template_len;
	struct ima_template_data template;
};

struct ima_queue_entry {
	struct hlist_node hnext;	/* place in hash collision list */
	struct list_head later;		/* place in ima_measurements list */
	struct ima_template_entry *entry;
};
extern struct list_head ima_measurements;	/* list of all measurements */

/* declarations */
void integrity_audit_msg(int audit_msgno, struct inode *inode,
			 const unsigned char *fname, const char *op,
			 const char *cause, int result, int info);

/* Internal IMA function definitions */
int ima_init(void);
void ima_cleanup(void);
int ima_fs_init(void);
void ima_fs_cleanup(void);
int ima_inode_alloc(struct inode *inode);
int ima_add_template_entry(struct ima_template_entry *entry, int violation,
			   const char *op, struct inode *inode);
int ima_calc_hash(struct file *file, char *digest);
int ima_calc_template_hash(int template_len, void *template, char *digest);
int ima_calc_boot_aggregate(char *digest);
void ima_add_violation(struct inode *inode, const unsigned char *filename,
		       const char *op, const char *cause);

/*
 * used to protect h_table and sha_table
 */
extern spinlock_t ima_queue_lock;

struct ima_h_table {
	atomic_long_t len;	/* number of stored measurements in the list */
	atomic_long_t violations;
	struct hlist_head queue[IMA_MEASURE_HTABLE_SIZE];
};
extern struct ima_h_table ima_htable;

static inline unsigned long ima_hash_key(u8 *digest)
{
	return hash_long(*digest, IMA_HASH_BITS);
}

/* LIM API function definitions */
int ima_must_measure(struct inode *inode, int mask, int function);
int ima_collect_measurement(struct integrity_iint_cache *iint,
			    struct file *file);
void ima_store_measurement(struct integrity_iint_cache *iint, struct file *file,
			   const unsigned char *filename);
int ima_store_template(struct ima_template_entry *entry, int violation,
		       struct inode *inode);
void ima_template_show(struct seq_file *m, void *e, enum ima_show_type show);

/* rbtree tree calls to lookup, insert, delete
 * integrity data associated with an inode.
 */
struct integrity_iint_cache *integrity_iint_insert(struct inode *inode);
struct integrity_iint_cache *integrity_iint_find(struct inode *inode);

/* IMA policy related functions */
enum ima_hooks { FILE_CHECK = 1, FILE_MMAP, BPRM_CHECK };

int ima_match_policy(struct inode *inode, enum ima_hooks func, int mask);
void ima_init_policy(void);
void ima_update_policy(void);
ssize_t ima_parse_add_rule(char *);
void ima_delete_rules(void);

/* LSM based policy rules require audit */
#ifdef CONFIG_IMA_LSM_RULES

#define security_filter_rule_init security_audit_rule_init
#define security_filter_rule_match security_audit_rule_match

#else

static inline int security_filter_rule_init(u32 field, u32 op, char *rulestr,
					    void **lsmrule)
{
	return -EINVAL;
}

static inline int security_filter_rule_match(u32 secid, u32 field, u32 op,
					     void *lsmrule,
					     struct audit_context *actx)
{
	return -EINVAL;
}
#endif /* CONFIG_IMA_LSM_RULES */
#endif


text:
[![Join the chat at https://gitter.im/Antaris/RazorEngine](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Antaris/RazorEngine?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

This project is searching for new maintainers, so if you want to help write on gitter or start sending PRs :)

*latest* documentation available on https://antaris.github.io/RazorEngine/.

## Build status

Develop Branch (`master`)

[![Build Status](https://travis-ci.org/Antaris/RazorEngine.svg?branch=master)](https://travis-ci.org/Antaris/RazorEngine)
[![Build status](https://ci.appveyor.com/api/projects/status/39bi38wonhwolrgy/branch/master?svg=true)](https://ci.appveyor.com/project/Antaris/razorengine/branch/master)

Release Branch (`releases`)

[![Build Status](https://travis-ci.org/Antaris/RazorEngine.svg?branch=releases)](https://travis-ci.org/Antaris/RazorEngine)
[![Build status](https://ci.appveyor.com/api/projects/status/39bi38wonhwolrgy/branch/releases?svg=true)](https://ci.appveyor.com/project/Antaris/razorengine/branch/releases)

## Quickstart

First install the nuget package (>=3.5.0).

	Install-Package RazorEngine

A templating engine built on Microsoft's Razor parsing engine, RazorEngine allows you to use Razor syntax to build dynamic templates.
You can find an introduction [here](http://www.asp.net/web-pages/overview/getting-started/introducing-razor-syntax-%28c%29).
All you need to do is use the static `Engine` class (the `Engine.Razor` instance) in the 'RazorEngine' namespace:

```csharp
using RazorEngine;
using RazorEngine.Templating; // For extension methods.

string template = "Hello @Model.Name, welcome to RazorEngine!";
var result =
	Engine.Razor.RunCompile(template, "templateKey", null, new { Name = "World" });
```

> The `RunCompile` method used here is an extension method and you need to open the `RazorEngine.Templating` namespace.

The `"templateKey"` must be unique and after running the above example you can re-run the cached template with this key.

```csharp
// using RazorEngine.Templating; // Dont forget to include this.
var result =
	Engine.Razor.Run("templateKey", null, new { Name = "Max" });
```

The null parameter is the `modelType` and `null` in this case means we use `dynamic` as the type of the model.
You can use a static model as well by providing a type object.

```csharp
// using RazorEngine.Templating; // Dont forget to include this.
var result =
	Engine.Razor.RunCompile("templateKey", typeof(Person), new Person { Name = "Max" });
```

Note that we now re-compile the model with a different type.
When you do not run the same template a lot of times (like several 1000 times), compiling uses the most time.
So the benefit you get from a static type will most likely not compensate the additional compile time.
Therefore you should either stick to one type for a template (best of both worlds) or just use (the slower) `dynamic` (`null`).
You can specify the `modelType` of a template with the `@model` directive.
When you do this the `modelType` parameter is ignored, but you should use the same type instance (or `null`)
on every call to prevent unnecessary re-compilations because of type mismatches in the caching layer.

## Configuration

You can configure RazorEngine with the `TemplateServiceConfiguration` class.

```csharp
var config = new TemplateServiceConfiguration();
// .. configure your instance

var service = RazorEngineService.Create(config);
```

If you want to use the static `Engine` class with this new configuration:

```csharp
Engine.Razor = service;
```

### General Configuration

By default RazorEngine is configured to encode using Html.
This supports the majority of users but with some configuration changes you can also set it to encode using Raw format
which is better suited for templates that generate things like javascript, php, C# and others.

```csharp
config.Language = Language.VisualBasic; // VB.NET as template language.
config.EncodedStringFactory = new RawStringFactory(); // Raw string encoding.
config.EncodedStringFactory = new HtmlEncodedStringFactory(); // Html encoding.
```

### Debugging

One thing you might want to enable is the debugging feature:

```csharp
config.Debug = true;
```

When `Debug` is true you can straight up debug into the generated code.
RazorEngine also supports debugging directly into the template files (normally `.cshtml` files).
As you might see in the above code there is no file to debug into.
To provide RazorEngine with the necessary information you need to tell where the file can be found:

```csharp
// using RazorEngine.Templating; // Dont forget to include this.
string template = "Hello @Model.Name, welcome to RazorEngine!";
string templateFile = "C:/mytemplate.cshtml"
var result =
	Engine.Razor.RunCompile(new LoadedTemplateSource(template, templateFile), "templateKey", null, new { Name = "World" });
```

This time when debugging the template you will jump right into the template file.

### Set a template manager

The API is designed around the idea that you do not have the templates sitting around in the source code
(while you can do that as seen above).
The main interface to provide RazorEngine with templates is the `ITemplateManager` interface.
You should either pick one of the available implementations or write your own.
See [TemplateManager and Caching documentation](http://antaris.github.io/RazorEngine/TemplateManager.html) for details.

## Temporary files

RazorEngine tries hard to delete the temporary files it creates, but this is not always possible.
This is especially true if you run RazorEngine from the default `AppDomain`.
RazorEngine will warn you in this situation by writing to the stderr.
One way to switch into a new AppDomain is to use the following snippet:

```csharp
static int Main(string[] args)
{
    if (AppDomain.CurrentDomain.IsDefaultAppDomain())
    {
        // RazorEngine cannot clean up from the default appdomain...
        Console.WriteLine("Switching to secound AppDomain, for RazorEngine...");
        AppDomainSetup adSetup = new AppDomainSetup();
        adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        var current = AppDomain.CurrentDomain;
        // You only need to add strongnames when your appdomain is not a full trust environment.
        var strongNames = new StrongName[0];

        var domain = AppDomain.CreateDomain(
            "MyMainDomain", null,
            current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
            strongNames);
        var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
        // RazorEngine will cleanup.
        AppDomain.Unload(domain);
        return exitCode;
    }
    // Continue with your code.
}
```

Depending on your scenario you probably need to edit it to your needs.
Note that you need to `Unload` the domain to trigger cleanup.

For the following scenario:

 * Your templates are limited in number.
 * You fully trust your templates / don't need isolation.
 * You don't need any kind of debugging support.
 * Your templates do not change in runtime.

You can use `config.DisableTempFileLocking = true` as well. This will work in any AppDomain (including the default one).
To remove the RazorEngine warnings you can additionally use `config.CachingProvider = new DefaultCachingProvider(t => {})`.

See also https://github.com/Antaris/RazorEngine/issues/244 for more details.

## More

On the right side you can find links to advanced topics and additional [documentation](http://antaris.github.io/RazorEngine/).
You should definitely read "About Razor" and "Template basics".


text:
Go bindings for libhdfs, for manipulating files on Hadoop distributed file system.

# Types #

- `hdfs.Fs`: file system handle
- `hdfs.File`: file handle
- `hdfs.FileInfo`: file metadata structure, represented within Go

# Methods #

see `go doc`

# Usage #

## Prerequisite ##

- JVM
- HDFS: c bindings for libhdfs, java binary packages
- HDFS: configured cluster

### Tips for building libhdfs on OS X ###

Based on hadoop-1.0.4.

1. change `<error.h>` to `<err.h>` in `src/c++/libhdfs/hdfsJniHelper.c`
2. change `md5sum` to `md5` in `src/saveVersion.sh`
2. run `chmod +x src/c++/libhdfs/install-sh`
3. run `ant -Dcompile.c++=true -Dlibhdfs=true compile-c++-libhdfs` to build libhdfs.
4. Upon successful building, libraries have been installed in `build/c++/Mac_OS_X-x86_64-64/lib`; `Makefile` in `build/c++-build/Mac_OS_X-x86_64-64/libhdfs` is very helpful for later-on re-compilation. it is ok the build ends up with installation errors if you can already find compiled libs in `build/c++-build/Mac_OS_X-x86_64-64/libhdfs/.libs` or so
5. change *install_name* for libhdfs: `install_name_tool -id /usr/lib/java/libhdfs.0.0.0.dylib libhdfs.0.0.0.dylib`
6. put `libhdfs*.dylib` in `/usr/lib/java`

### Tips for building libhadoop on OS X ###

Based on hadoop-1.0.1; libhadoop would be loaded by `util.NativeCodeLoader` when accessing local file system.

1. java: change `-ljvm` to `-framework JavaVM` in both `Makefile.am` and `Makefile.in`
2. libz: apply [patch](https://issues.apache.org/jira/secure/attachment/12423498/HADOOP-3659.patch) to `acinclude.m4`:

        elif test ! -z "`which otool | grep -v 'no otool'`"; then
            ac_cv_libname_$1=\"`otool -L conftest | grep $1 | sed -e 's/^[  ]*//' -e 's/ .*//' -e 's/.*\/\(.*\)$/\1/'`\";

    and `configure`:

        elif test ! -z "`which otool | grep -v 'no otool'`"; then
            ac_cv_libname_z=\"`otool -L conftest | grep z | sed -e 's/^  *//' -e 's/ .*//' -e 's/.*\/\(.*\)$/\1/'`\";

3. apply [patch](https://gist.github.com/1327040) to source code `src/org/apache/hadoop/security/JniBasedUnixGroupsNetgroupMapping.c`.

4. run `ant compile-native`
5. put the compiled library `libhadoop.1.0.0.dylib` and its symbolic links in `/usr/lib/java`, which is one of the default element of `java.library.path`.
6. change *install_name* for libhadoop: `sudo install_name_tool -id /usr/lib/java/libhadoop.1.dylib /usr/lib/java/libhadoop.1.0.0.dylib`

## Prepare ##

1. put `.jar` from hadoop in `.libs/javalibs`; `conf/` in `.libs`; see `mktest.sh` for details, or you can modify it to accommodate your environment.

2. set `LD_LIBRARY_PATH` for Linux:

        export LD_LIBRARY_PATH=./lib:/opt/jdk/jre/lib/amd64/server

    make sure `libhdfs.so` and `libjvm` are declared in `LD_LIBRARY_PATH`

    You don't have to do this on OS X. You can always use `install_name_tool` to set or change a library's _install name_, also jvm on OS X is a _system framework_, so that it is not necessory to add jvm's path, while the only thing in step 3 is providing `hdfs.h` header path for _#cgo_.

3. correct the _#cgo_ header in `hdfs.go`, according to your enviornment.

## Test ##

- After the preparation, correct the _constants_ in `hdfs_test.go`.
- run `./mktest.sh`.

# Known Issues #

1. Currently connecting to local file system is not handled correctly. So `Connect("", 0)` would lead to error. It is okay now to access to local file system.
1. `errno` in libhdfs is not handled precisely. For example, `invokeMethod()` would probably sets `errno` to **2** in a lot of routines.


text:
struts2-samples : hello_world
===============================
This is the example project referred to in the
Struts 2 documentation, Hello World tutorial.
See:  http://struts.apache.org.

To build the application's war file run mvn clean package
from the project's root folder.

The war file is created in the target sub-folder.

Deploy the war file to your WSO2 Application Server instance.

In a web browser go to:  http://localhost:9764/hello_world_struts2/

You should see a web page with Welcome to Struts 2!


text:
import threading
import time
import queue
from python_homeautomation.devices.BaseDevice import BaseDevice

class BooleanInputDevice(BaseDevice):

    # TODO: Add UI params

    def monitor(self):
        while self.running:
            time.sleep(1)

    def event(self):
        while self.running:
            try:
                data = self.in_queue.get(timeout=5)
                if 'status' in data and 'power' in data['status']:
                    # This is where something useful would happen
                    self.out_queue.put(data)
            except queue.Empty:
                pass

    def run(self):
        self.monitor_thread = threading.Thread(target=self.monitor)
        self.event_thread = threading.Thread(target=self.event)
        self.monitor_thread.start()
        self.event_thread.start()
        self.monitor_thread.join()
        self.event_thread.join()

    def stop(self):
        self.running = False

    def __init__(self, name, in_queue, out_queue, device_id):
        BaseDevice.__init__(self, device_id)
        self.name = name
        self.in_queue = in_queue
        self.out_queue = out_queue
        self.monitor_thread = None
        self.event_thread = None
        self.running = True


text:
#ifndef TAGINTERFACE_H
#define TAGINTERFACE_H

#include <QUrl>
struct TrackData;
class TagInterface
{
public:
    virtual ~TagInterface() {}
    virtual uint trackData(TrackData *data, const QUrl &path, int types = All) const = 0;
};

#endif


text:
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var StringDecoder = require('string_decoder').StringDecoder;
var EventEmitter = require('events').EventEmitter;
var net = require('net');
var dgram = require('dgram');
var assert = require('assert');
var util = require('util');

var Process = process.binding('process_wrap').Process;
var uv = process.binding('uv');

var constants;  // Lazy-loaded process.binding('constants')

var errnoException = util._errnoException;
var handleWraps = {};

function handleWrapGetter(name, callback) {
  var cons;

  Object.defineProperty(handleWraps, name, {
    get: function() {
      if (!util.isUndefined(cons)) return cons;
      return cons = callback();
    }
  });
}

handleWrapGetter('Pipe', function() {
  return process.binding('pipe_wrap').Pipe;
});

handleWrapGetter('TTY', function() {
  return process.binding('tty_wrap').TTY;
});

handleWrapGetter('TCP', function() {
  return process.binding('tcp_wrap').TCP;
});

handleWrapGetter('UDP', function() {
  return process.binding('udp_wrap').UDP;
});

// constructors for lazy loading
function createPipe(ipc) {
  return new handleWraps.Pipe(ipc);
}

function createSocket(pipe, readable) {
  var s = new net.Socket({ handle: pipe });

  if (readable) {
    s.writable = false;
    s.readable = true;
  } else {
    s.writable = true;
    s.readable = false;
  }

  return s;
}

// this object contain function to convert TCP objects to native handle objects
// and back again.
var handleConversion = {
  'net.Native': {
    simultaneousAccepts: true,

    send: function(message, handle) {
      return handle;
    },

    got: function(message, handle, emit) {
      emit(handle);
    }
  },

  'net.Server': {
    simultaneousAccepts: true,

    send: function(message, server) {
      return server._handle;
    },

    got: function(message, handle, emit) {
      var server = new net.Server();
      server.listen(handle, function() {
        emit(server);
      });
    }
  },

  'net.Socket': {
    send: function(message, socket) {
      // if the socket was created by net.Server
      if (socket.server) {
        // the slave should keep track of the socket
        message.key = socket.server._connectionKey;

        var firstTime = !this._channel.sockets.send[message.key];
        var socketList = getSocketList('send', this, message.key);

        // the server should no longer expose a .connection property
        // and when asked to close it should query the socket status from
        // the slaves
        if (firstTime) socket.server._setupSlave(socketList);

        // Act like socket is detached
        socket.server._connections--;
      }

      // remove handle from socket object, it will be closed when the socket
      // will be sent
      var handle = socket._handle;
      handle.onread = function() {};
      socket._handle = null;

      return handle;
    },

    postSend: function(handle) {
      // Close the Socket handle after sending it
      handle.close();
    },

    got: function(message, handle, emit) {
      var socket = new net.Socket({handle: handle});
      socket.readable = socket.writable = true;

      // if the socket was created by net.Server we will track the socket
      if (message.key) {

        // add socket to connections list
        var socketList = getSocketList('got', this, message.key);
        socketList.add({
          socket: socket
        });
      }

      emit(socket);
    }
  },

  'dgram.Native': {
    simultaneousAccepts: false,

    send: function(message, handle) {
      return handle;
    },

    got: function(message, handle, emit) {
      emit(handle);
    }
  },

  'dgram.Socket': {
    simultaneousAccepts: false,

    send: function(message, socket) {
      message.dgramType = socket.type;

      return socket._handle;
    },

    got: function(message, handle, emit) {
      var socket = new dgram.Socket(message.dgramType);

      socket.bind(handle, function() {
        emit(socket);
      });
    }
  }
};

// This object keep track of the socket there are sended
function SocketListSend(slave, key) {
  EventEmitter.call(this);

  this.key = key;
  this.slave = slave;
}
util.inherits(SocketListSend, EventEmitter);

SocketListSend.prototype._request = function(msg, cmd, callback) {
  var self = this;

  if (!this.slave.connected) return onclose();
  this.slave.send(msg);

  function onclose() {
    self.slave.removeListener('internalMessage', onreply);
    callback(new Error('Slave closed before reply'));
  };

  function onreply(msg) {
    if (!(msg.cmd === cmd && msg.key === self.key)) return;
    self.slave.removeListener('disconnect', onclose);
    self.slave.removeListener('internalMessage', onreply);

    callback(null, msg);
  };

  this.slave.once('disconnect', onclose);
  this.slave.on('internalMessage', onreply);
};

SocketListSend.prototype.close = function close(callback) {
  this._request({
    cmd: 'NODE_SOCKET_NOTIFY_CLOSE',
    key: this.key
  }, 'NODE_SOCKET_ALL_CLOSED', callback);
};

SocketListSend.prototype.getConnections = function getConnections(callback) {
  this._request({
    cmd: 'NODE_SOCKET_GET_COUNT',
    key: this.key
  }, 'NODE_SOCKET_COUNT', function(err, msg) {
    if (err) return callback(err);
    callback(null, msg.count);
  });
};

// This object keep track of the socket there are received
function SocketListReceive(slave, key) {
  EventEmitter.call(this);

  var self = this;

  this.connections = 0;
  this.key = key;
  this.slave = slave;

  function onempty() {
    if (!self.slave.connected) return;

    self.slave.send({
      cmd: 'NODE_SOCKET_ALL_CLOSED',
      key: self.key
    });
  }

  this.slave.on('internalMessage', function(msg) {
    if (msg.key !== self.key) return;

    if (msg.cmd === 'NODE_SOCKET_NOTIFY_CLOSE') {
      // Already empty
      if (self.connections === 0) return onempty();

      // Wait for sockets to get closed
      self.once('empty', onempty);
    } else if (msg.cmd === 'NODE_SOCKET_GET_COUNT') {
      if (!self.slave.connected) return;
      self.slave.send({
        cmd: 'NODE_SOCKET_COUNT',
        key: self.key,
        count: self.connections
      });
    }
  });
}
util.inherits(SocketListReceive, EventEmitter);

SocketListReceive.prototype.add = function(obj) {
  var self = this;

  this.connections++;

  // Notify previous owner of socket about its state change
  obj.socket.once('close', function() {
    self.connections--;

    if (self.connections === 0) self.emit('empty');
  });
};

function getSocketList(type, slave, key) {
  var sockets = slave._channel.sockets[type];
  var socketList = sockets[key];
  if (!socketList) {
    var Construct = type === 'send' ? SocketListSend : SocketListReceive;
    socketList = sockets[key] = new Construct(slave, key);
  }
  return socketList;
}

var INTERNAL_PREFIX = 'NODE_';
function handleMessage(target, message, handle) {
  var eventName = 'message';
  if (!util.isNull(message) &&
      util.isObject(message) &&
      util.isString(message.cmd) &&
      message.cmd.length > INTERNAL_PREFIX.length &&
      message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX) {
    eventName = 'internalMessage';
  }
  target.emit(eventName, message, handle);
}

function setupChannel(target, channel) {
  target._channel = channel;
  target._handleQueue = null;

  var decoder = new StringDecoder('utf8');
  var jsonBuffer = '';
  channel.buffering = false;
  channel.onread = function(nread, pool, recvHandle) {
    // TODO(bnoordhuis) Check that nread > 0.
    if (pool) {
      jsonBuffer += decoder.write(pool);

      var i, start = 0;

      //Linebreak is used as a message end sign
      while ((i = jsonBuffer.indexOf('\n', start)) >= 0) {
        var json = jsonBuffer.slice(start, i);
        var message = JSON.parse(json);

        // There will be at most one NODE_HANDLE message in every chunk we
        // read because SCM_RIGHTS messages don't get coalesced. Make sure
        // that we deliver the handle with the right message however.
        if (message && message.cmd === 'NODE_HANDLE')
          handleMessage(target, message, recvHandle);
        else
          handleMessage(target, message, undefined);

        start = i + 1;
      }
      jsonBuffer = jsonBuffer.slice(start);
      this.buffering = jsonBuffer.length !== 0;

    } else {
      this.buffering = false;
      target.disconnect();
      channel.onread = nop;
      channel.close();
      maybeClose(target);
    }
  };

  // object where socket lists will live
  channel.sockets = { got: {}, send: {} };

  // handlers will go through this
  target.on('internalMessage', function(message, handle) {
    // Once acknowledged - continue sending handles.
    if (message.cmd === 'NODE_HANDLE_ACK') {
      assert(util.isArray(target._handleQueue));
      var queue = target._handleQueue;
      target._handleQueue = null;

      queue.forEach(function(args) {
        target._send(args.message, args.handle, false);
      });

      // Process a pending disconnect (if any).
      if (!target.connected && target._channel && !target._handleQueue)
        target._disconnect();

      return;
    }

    if (message.cmd !== 'NODE_HANDLE') return;

    // Acknowledge handle receival. Don't emit error events (for example if
    // the other side has disconnected) because this call to send() is not
    // initiated by the user and it shouldn't be fatal to be unable to ACK
    // a message.
    target._send({ cmd: 'NODE_HANDLE_ACK' }, null, true);

    var obj = handleConversion[message.type];

    // Update simultaneous accepts on Windows
    if (process.platform === 'win32') {
      handle._simultaneousAccepts = false;
      net._setSimultaneousAccepts(handle);
    }

    // Convert handle object
    obj.got.call(this, message, handle, function(handle) {
      handleMessage(target, message.msg, handle);
    });
  });

  target.send = function(message, handle) {
    if (!this.connected)
      this.emit('error', new Error('channel closed'));
    else
      this._send(message, handle, false);
  };

  target._send = function(message, handle, swallowErrors) {
    assert(this.connected || this._channel);

    if (util.isUndefined(message))
      throw new TypeError('message cannot be undefined');

    // package messages with a handle object
    if (handle) {
      // this message will be handled by an internalMessage event handler
      message = {
        cmd: 'NODE_HANDLE',
        type: null,
        msg: message
      };

      if (handle instanceof net.Socket) {
        message.type = 'net.Socket';
      } else if (handle instanceof net.Server) {
        message.type = 'net.Server';
      } else if (handle instanceof process.binding('tcp_wrap').TCP ||
                 handle instanceof process.binding('pipe_wrap').Pipe) {
        message.type = 'net.Native';
      } else if (handle instanceof dgram.Socket) {
        message.type = 'dgram.Socket';
      } else if (handle instanceof process.binding('udp_wrap').UDP) {
        message.type = 'dgram.Native';
      } else {
        throw new TypeError("This handle type can't be sent");
      }

      // Queue-up message and handle if we haven't received ACK yet.
      if (this._handleQueue) {
        this._handleQueue.push({ message: message.msg, handle: handle });
        return;
      }

      var obj = handleConversion[message.type];

      // convert TCP object to native handle object
      handle = handleConversion[message.type].send.apply(target, arguments);

      // Update simultaneous accepts on Windows
      if (obj.simultaneousAccepts) {
        net._setSimultaneousAccepts(handle);
      }
    } else if (this._handleQueue) {
      // Queue request anyway to avoid out-of-order messages.
      this._handleQueue.push({ message: message, handle: null });
      return;
    }

    var req = { oncomplete: nop };
    var string = JSON.stringify(message) + '\n';
    var err = channel.writeUtf8String(req, string, handle);

    if (err) {
      if (!swallowErrors)
        this.emit('error', errnoException(err, 'write'));
    } else if (handle && !this._handleQueue) {
      this._handleQueue = [];
    }

    if (obj && obj.postSend) {
      req.oncomplete = obj.postSend.bind(null, handle);
    }

    /* If the master is > 2 read() calls behind, please stop sending. */
    return channel.writeQueueSize < (65536 * 2);
  };

  // connected will be set to false immediately when a disconnect() is
  // requested, even though the channel might still be alive internally to
  // process queued messages. The three states are distinguished as follows:
  // - disconnect() never requested: _channel is not null and connected
  //   is true
  // - disconnect() requested, messages in the queue: _channel is not null
  //   and connected is false
  // - disconnect() requested, channel actually disconnected: _channel is
  //   null and connected is false
  target.connected = true;

  target.disconnect = function() {
    if (!this.connected) {
      this.emit('error', new Error('IPC channel is already disconnected'));
      return;
    }

    // Do not allow any new messages to be written.
    this.connected = false;

    // If there are no queued messages, disconnect immediately. Otherwise,
    // postpone the disconnect so that it happens internally after the
    // queue is flushed.
    if (!this._handleQueue)
      this._disconnect();
  }

  target._disconnect = function() {
    assert(this._channel);

    // This marks the fact that the channel is actually disconnected.
    this._channel = null;

    var fired = false;
    function finish() {
      if (fired) return;
      fired = true;

      channel.close();
      target.emit('disconnect');
    }

    // If a message is being read, then wait for it to complete.
    if (channel.buffering) {
      this.once('message', finish);
      this.once('internalMessage', finish);

      return;
    }

    process.nextTick(finish);
  };

  channel.readStart();
}

function nop() { }

exports.fork = function(modulePath /*, args, options*/) {

  // Get options and args arguments.
  var options, args, execArgv;
  if (util.isArray(arguments[1])) {
    args = arguments[1];
    options = util._extend({}, arguments[2]);
  } else {
    args = [];
    options = util._extend({}, arguments[1]);
  }

  // Prepare arguments for fork:
  execArgv = options.execArgv || process.execArgv;
  args = execArgv.concat([modulePath], args);

  // Leave stdin open for the IPC channel. stdout and stderr should be the
  // same as the parent's if silent isn't set.
  options.stdio = options.silent ? ['pipe', 'pipe', 'pipe', 'ipc'] :
      [0, 1, 2, 'ipc'];

  options.execPath = options.execPath || process.execPath;

  return spawn(options.execPath, args, options);
};

exports._forkChild = function(fd) {
  // set process.send()
  var p = createPipe(true);
  p.open(fd);
  p.unref();
  setupChannel(process, p);

  var refs = 0;
  process.on('newListener', function(name) {
    if (name !== 'message' && name !== 'disconnect') return;
    if (++refs === 1) p.ref();
  });
  process.on('removeListener', function(name) {
    if (name !== 'message' && name !== 'disconnect') return;
    if (--refs === 0) p.unref();
  });
};

exports.exec = function(command /*, options, callback */) {
  var file, args, options, callback;

  if (util.isFunction(arguments[1])) {
    options = undefined;
    callback = arguments[1];
  } else {
    options = arguments[1];
    callback = arguments[2];
  }

  if (process.platform === 'win32') {
    file = 'cmd.exe';
    args = ['/s', '/c', '"' + command + '"'];
    // Make a shallow copy before patching so we don't clobber the user's
    // options object.
    options = util._extend({}, options);
    options.windowsVerbatimArguments = true;
  } else {
    file = '/bin/sh';
    args = ['-c', command];
  }

  if (options && options.shell)
    file = options.shell;

  return exports.execFile(file, args, options, callback);
};

exports.execFile = function(file /* args, options, callback */) {
  var args, callback;
  var options = {
    encoding: 'utf8',
    timeout: 0,
    maxBuffer: 200 * 1024,
    killSignal: 'SIGTERM',
    cwd: null,
    env: null
  };

  // Parse the parameters.

  if (util.isFunction(arguments[arguments.length - 1])) {
    callback = arguments[arguments.length - 1];
  }

  if (util.isArray(arguments[1])) {
    args = arguments[1];
    options = util._extend(options, arguments[2]);
  } else {
    args = [];
    options = util._extend(options, arguments[1]);
  }

  var child = spawn(file, args, {
    cwd: options.cwd,
    env: options.env,
    windowsVerbatimArguments: !!options.windowsVerbatimArguments
  });

  var encoding;
  var _stdout;
  var _stderr;
  if (options.encoding !== 'buffer' && Buffer.isEncoding(options.encoding)) {
    encoding = options.encoding;
    _stdout = '';
    _stderr = '';
  } else {
    _stdout = [];
    _stderr = [];
    encoding = null;
  }
  var stdoutLen = 0;
  var stderrLen = 0;
  var killed = false;
  var exited = false;
  var timeoutId;

  var ex = null;

  function exithandler(code, signal) {
    if (exited) return;
    exited = true;

    if (timeoutId) {
      clearTimeout(timeoutId);
      timeoutId = null;
    }

    if (!callback) return;

    // merge chunks
    var stdout;
    var stderr;
    if (!encoding) {
      stdout = Buffer.concat(_stdout);
      stderr = Buffer.concat(_stderr);
    } else {
      stdout = _stdout;
      stderr = _stderr;
    }

    if (ex) {
      // Will be handled later
    } else if (code === 0 && signal === null) {
      callback(null, stdout, stderr);
      return;
    }

    var cmd = file;
    if (args.length !== 0)
      cmd += ' ' + args.join(' ');

    if (!ex) {
      ex = new Error('Command failed: ' + cmd + '\n' + stderr);
      ex.killed = child.killed || killed;
      ex.code = code < 0 ? uv.errname(code) : code;
      ex.signal = signal;
    }

    ex.cmd = cmd;
    callback(ex, stdout, stderr);
  }

  function errorhandler(e) {
    ex = e;
    child.stdout.destroy();
    child.stderr.destroy();
    exithandler();
  }

  function kill() {
    child.stdout.destroy();
    child.stderr.destroy();

    killed = true;
    try {
      child.kill(options.killSignal);
    } catch (e) {
      ex = e;
      exithandler();
    }
  }

  if (options.timeout > 0) {
    timeoutId = setTimeout(function() {
      kill();
      timeoutId = null;
    }, options.timeout);
  }

  child.stdout.addListener('data', function(chunk) {
    stdoutLen += chunk.length;

    if (stdoutLen > options.maxBuffer) {
      ex = new Error('stdout maxBuffer exceeded.');
      kill();
    } else {
      if (!encoding)
        _stdout.push(chunk);
      else
        _stdout += chunk;
    }
  });

  child.stderr.addListener('data', function(chunk) {
    stderrLen += chunk.length;

    if (stderrLen > options.maxBuffer) {
      ex = new Error('stderr maxBuffer exceeded.');
      kill();
    } else {
      if (!encoding)
        _stderr.push(chunk);
      else
        _stderr += chunk;
    }
  });

  if (encoding) {
    child.stderr.setEncoding(encoding);
    child.stdout.setEncoding(encoding);
  }

  child.addListener('close', exithandler);
  child.addListener('error', errorhandler);

  return child;
};

var spawn = exports.spawn = function(file, args, options) {
  args = args ? args.slice(0) : [];
  args.unshift(file);

  var env = (options ? options.env : null) || process.env;
  var envPairs = [];
  for (var key in env) {
    envPairs.push(key + '=' + env[key]);
  }

  var child = new ChildProcess();
  if (options && options.customFds && !options.stdio) {
    options.stdio = options.customFds.map(function(fd) {
      return fd === -1 ? 'pipe' : fd;
    });
  }

  child.spawn({
    file: file,
    args: args,
    cwd: options ? options.cwd : null,
    windowsVerbatimArguments: !!(options && options.windowsVerbatimArguments),
    detached: !!(options && options.detached),
    envPairs: envPairs,
    stdio: options ? options.stdio : null,
    uid: options ? options.uid : null,
    gid: options ? options.gid : null
  });

  return child;
};

function maybeClose(subprocess) {
  subprocess._closesGot++;

  if (subprocess._closesGot == subprocess._closesNeeded) {
    subprocess.emit('close', subprocess.exitCode, subprocess.signalCode);
  }
}

function ChildProcess() {
  EventEmitter.call(this);

  // Initialize TCPWrap and PipeWrap
  process.binding('tcp_wrap');
  process.binding('pipe_wrap');

  var self = this;

  this._closesNeeded = 1;
  this._closesGot = 0;
  this.connected = false;

  this.signalCode = null;
  this.exitCode = null;
  this.killed = false;

  this._handle = new Process();
  this._handle.owner = this;

  this._handle.onexit = function(exitCode, signalCode) {
    //
    // follow 0.4.x behaviour:
    //
    // - normally terminated processes don't touch this.signalCode
    // - signaled processes don't touch this.exitCode
    //
    // new in 0.9.x:
    //
    // - spawn failures are reported with exitCode < 0
    //
    var err = (exitCode < 0) ? errnoException(exitCode, 'spawn') : null;

    if (signalCode) {
      self.signalCode = signalCode;
    } else {
      self.exitCode = exitCode;
    }

    if (self.stdin) {
      self.stdin.destroy();
    }

    self._handle.close();
    self._handle = null;

    if (exitCode < 0) {
      self.emit('error', err);
    } else {
      self.emit('exit', self.exitCode, self.signalCode);
    }

    // if any of the stdio streams have not been touched,
    // then pull all the data through so that it can get the
    // eof and emit a 'close' event.
    // Do it on nextTick so that the user has one last chance
    // to consume the output, if for example they only want to
    // start reading the data once the process exits.
    process.nextTick(function() {
      flushStdio(self);
    });

    maybeClose(self);
  };
}
util.inherits(ChildProcess, EventEmitter);

function flushStdio(subprocess) {
  subprocess.stdio.forEach(function(stream, fd, stdio) {
    if (!stream || !stream.readable || stream._consuming ||
        stream._readableState.flowing)
      return;
    stream.resume();
  });
}

function getHandleWrapType(stream) {
  if (stream instanceof handleWraps.Pipe) return 'pipe';
  if (stream instanceof handleWraps.TTY) return 'tty';
  if (stream instanceof handleWraps.TCP) return 'tcp';
  if (stream instanceof handleWraps.UDP) return 'udp';

  return false;
}

ChildProcess.prototype.spawn = function(options) {
  var self = this,
      ipc,
      ipcFd,
      // If no `stdio` option was given - use default
      stdio = options.stdio || 'pipe';

  // Replace shortcut with an array
  if (util.isString(stdio)) {
    switch (stdio) {
      case 'ignore': stdio = ['ignore', 'ignore', 'ignore']; break;
      case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break;
      case 'inherit': stdio = [0, 1, 2]; break;
      default: throw new TypeError('Incorrect value of stdio option: ' + stdio);
    }
  } else if (!util.isArray(stdio)) {
    throw new TypeError('Incorrect value of stdio option: ' + stdio);
  }

  // At least 3 stdio will be created
  // Don't concat() a new Array() because it would be sparse, and
  // stdio.reduce() would skip the sparse elements of stdio.
  // See http://stackoverflow.com/a/5501711/3561
  while (stdio.length < 3) stdio.push(undefined);

  // Translate stdio into C++-readable form
  // (i.e. PipeWraps or fds)
  stdio = stdio.reduce(function(acc, stdio, i) {
    function cleanup() {
      acc.filter(function(stdio) {
        return stdio.type === 'pipe' || stdio.type === 'ipc';
      }).forEach(function(stdio) {
        stdio.handle.close();
      });
    }

    // Defaults
    if (util.isNullOrUndefined(stdio)) {
      stdio = i < 3 ? 'pipe' : 'ignore';
    }

    if (stdio === 'ignore') {
      acc.push({type: 'ignore'});
    } else if (stdio === 'pipe' || util.isNumber(stdio) && stdio < 0) {
      acc.push({type: 'pipe', handle: createPipe()});
    } else if (stdio === 'ipc') {
      if (!util.isUndefined(ipc)) {
        // Cleanup previously created pipes
        cleanup();
        throw Error('Child process can have only one IPC pipe');
      }

      ipc = createPipe(true);
      ipcFd = i;

      acc.push({ type: 'pipe', handle: ipc, ipc: true });
    } else if (util.isNumber(stdio) || util.isNumber(stdio.fd)) {
      acc.push({ type: 'fd', fd: stdio.fd || stdio });
    } else if (getHandleWrapType(stdio) || getHandleWrapType(stdio.handle) ||
               getHandleWrapType(stdio._handle)) {
      var handle = getHandleWrapType(stdio) ?
          stdio :
          getHandleWrapType(stdio.handle) ? stdio.handle : stdio._handle;

      acc.push({
        type: 'wrap',
        wrapType: getHandleWrapType(handle),
        handle: handle
      });
    } else {
      // Cleanup
      cleanup();
      throw new TypeError('Incorrect value for stdio stream: ' + stdio);
    }

    return acc;
  }, []);

  options.stdio = stdio;

  if (!util.isUndefined(ipc)) {
    // Let child process know about opened IPC channel
    options.envPairs = options.envPairs || [];
    options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd);
  }

  var err = this._handle.spawn(options);

  if (err == uv.UV_ENOENT) {
    process.nextTick(function() {
      self._handle.onexit(err);
    });
  } else if (err) {
    // Close all opened fds on error
    stdio.forEach(function(stdio) {
      if (stdio.type === 'pipe') {
        stdio.handle.close();
      }
    });

    this._handle.close();
    this._handle = null;
    throw errnoException(err, 'spawn');
  }

  this.pid = this._handle.pid;

  stdio.forEach(function(stdio, i) {
    if (stdio.type === 'ignore') return;

    if (stdio.ipc) {
      self._closesNeeded++;
      return;
    }

    if (stdio.handle) {
      // when i === 0 - we're dealing with stdin
      // (which is the only one writable pipe)
      stdio.socket = createSocket(self.pid !== 0 ? stdio.handle : null, i > 0);

      if (i > 0 && self.pid !== 0) {
        self._closesNeeded++;
        stdio.socket.on('close', function() {
          maybeClose(self);
        });
      }
    }
  });

  this.stdin = stdio.length >= 1 && !util.isUndefined(stdio[0].socket) ?
      stdio[0].socket : null;
  this.stdout = stdio.length >= 2 && !util.isUndefined(stdio[1].socket) ?
      stdio[1].socket : null;
  this.stderr = stdio.length >= 3 && !util.isUndefined(stdio[2].socket) ?
      stdio[2].socket : null;

  this.stdio = stdio.map(function(stdio) {
    return util.isUndefined(stdio.socket) ? null : stdio.socket;
  });

  // Add .send() method and start listening for IPC data
  if (!util.isUndefined(ipc)) setupChannel(this, ipc);

  return err;
};

ChildProcess.prototype.kill = function(sig) {
  var signal;

  if (!constants) {
    constants = process.binding('constants');
  }

  if (sig === 0) {
    signal = 0;
  } else if (!sig) {
    signal = constants['SIGTERM'];
  } else {
    signal = constants[sig];
  }

  if (util.isUndefined(signal)) {
    throw new Error('Unknown signal: ' + sig);
  }

  if (this._handle) {
    var err = this._handle.kill(signal);
    if (err === 0) {
      /* Success. */
      this.killed = true;
      return true;
    }
    if (err === uv.UV_ESRCH) {
      /* Already dead. */
    } else if (err === uv.UV_EINVAL || err === uv.UV_ENOSYS) {
      /* The underlying platform doesn't support this signal. */
      throw errnoException(err, 'kill');
    } else {
      /* Other error, almost certainly EPERM. */
      this.emit('error', errnoException(err, 'kill'));
    }
  }

  /* Kill didn't succeed. */
  return false;
};

ChildProcess.prototype.ref = function() {
  if (this._handle) this._handle.ref();
};

ChildProcess.prototype.unref = function() {
  if (this._handle) this._handle.unref();
};


text:
require 'spec_helper'

describe "projects/show" do
  before(:each) do
    @project = assign(:project, stub_model(Project,
      :name => "Name",
      :archive => false,
      :user => nil
    ))
  end

  it "renders attributes in <p>" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    rendered.should match(/Name/)
    rendered.should match(/false/)
    rendered.should match(//)
  end
end


text:
The crux of the issue is that for mapping or coercing I might want to inject some values, such as null values to compare against. These values differ on a per-attribute basis.

The library calls specific methods with specific arguments. I need to get those args into the library.

It does feel like more of a coercion problem than a mapping problem. I think I originally reached for the mapper because I thought I had more control.

- [ ] ? Via coercer registry?

- [ ] ? Change to the attribute DSL for coercer? Pass hash with args? If not a hash, but simply a symbol, assume it's the name?

- [ ] ? How might we do this with blocks?

## Current refactorings

- [ ] Process pending specs: delete unnecessary, make valid ones pass.

## Handling missing data

I think these are the rules...

It should probably be nil. Perhaps if the mapper returns nil we don't even bother coercing it. There's a concept here and it's around extracting data. Every attribute has a coercer, by rule of API, and every attribute has a mapper, either explicitly declared or the default KeyMapper. When an attribute is missing, in other words when the mapper cannot extract data (returns nil), the default value is applied. The "default" default value is nil. When the default value is applied, no coercion is performed.

ValueExtractor (or a better named class) takes a mapper, a coercer, and a default value, which defaults to nil.

- [ ] Write up some spec/examples and also for the README

## Attributes

### Collaborators

In which collaborator would it most make sense to add in default value behavior?

Mapper: Simply retrieves the data from raw attributes data. `call` it with an object and a hash of data and it returns a value. It might return nil. Potentially, it could accept a default and fallback to that value, but I'm not sure that's within the responsibility of this object.

Coercer: Simply assures the data its passed comes back as the correct type.

Who knows how to assemble/initialize a Mapper? I don't think Attribute needs to
be the keeper of that knowledge. If Mapper's public interface is to receive the
call message with obj, attributes_data, and an optional default value, then a
fully realized mapper should be passed into an Attribute, moving that work
outside of Attribute and simplifying it.

Of the 2 objects, coercer and mapper, if I had to choose between the two to shim
default value behavior, I would choose the mapper.

Do we map a coerced value OR do we coerce a mapped value? I think we coerce a
mapped value. Right. Map, then send the result to the coercer.

Do we map/coerce before handing the value to an InstanceAttribute?

I like the idea of working inside-out here, from the innermost objects outward,
because I think we have the right objects, they're just combined in funky ways.
At this point, it feels right to start with mapper -> coercer -> ?.
(ClassAttribute probably doesn't need any of those data-related collaborators.)

### Coercers

I'm concerned the return value/behavior of coercers is inconsistent. I'm not
sure what to do about it yet, though, other than note it.

Coercers::Integer - It's possible in a couple different ways to raise an error,
so we normalize the different kinds of errors into a single
Attrocity::CoercionError. We are simply using Kernel.Integer for this coercer,
which is the source for raising (at least) a couple different errors: TypeError,
ArgumentError.

Coercers::String: - It doesn't seem possible for this coercer to raise an error
in its current implementation. It uses Kernel.String, which in turn uses to_s,
which is implemented in Object.

Coercers::Boolean - At this point, this is a custom implementation, specific to
RentPath, but I'm thinking that it should default to the Ruby notion of
truthiness. Yes, the default boolean coercer will adhere to the Ruby notion of
truthiness. But we need to then inject a coercer that's not part of the built-in
coercers, which we should probably do in RentalsModels. This work is done.

### ClassAttribute

- [ ] Start with default_value as a simple Ruby attribute (data).

### InstanceAttribute

Start here and work backwards towards ClassAttribute.

---

DefaultValue
NullDefaultValue

Should a default value of nil be supported?

default_value_for

---

clone is confusing

---

Is options a class or a module?

Options attributes are first-class attributes (with coercion, mapping, etc.)

# TODO

- Convert all specs to require spec_helper

- Attribute should have a method for setting its own value that take the
  arguments that attribute set uses to do the job. ???

- [ ] ? Should attrocity_spec specs be moved to something like module builder
  spec?

- [ ] ? Re-evaluate attrocity_spec. There are some oddities. It seems like it's
  been a default place to put spec code that we weren't sure about the eventual
  home for.

Attribute set cloning
---------------------

Consider making attributes that are attached to a class, that basically act as
templates for instance attributes, to be a different kind of thing so that we're
not cloning, per se, but creating an instance variant of the class attribute
variant on the fly. So, factory approach vs. cloning approach.

Inventory
---------

### Default values

For now, let's just implement the simple version of default values. Will need to
think through best implementation. Guessing some here... the simplest
implementation is to pass an option to Attribute.new and have the attribute
handle default values. DO NOT put this responsibility into the coercer. Coercers
must be kept simple.

How to handle defaults because `Integer(nil)` raises an error

Probably handle defaults at attribute level. Based on default property of an
attribute instance, it will handle coercion errors accordingly. Does this affect
validation?

Default values should not be conflated with coercers. However, when analyzing a
default value, we might want to check that it does not get transformed when
coerced. In other words, with an integer coercer and a default value of 1,
Integer(1) does not change the value, but a default value of '1' would be
considered incorrect and we could catch that by coercing and comparing.

It should be possible to have a nil value, but I don't like the idea of nil
being the fallback value. A string coerced attribute should probably default to
''. Not sure what an integer coerced attribute should default to. Maybe nil as
fallback is the only consistent way to do this.

### Validation?

Design inspiration
------------------

- Virtus
- attrio
  http://igor-alexandrov.github.io/blog/2013/05/23/attrio-typed-attributes-for-ruby-objects/

Concepts
--------

- Coercing: Converting attribute data to the desired type

- Mapping: Getting attribute data from a known hash key that differs from the
  attribute name

Ideas
-----

Lazy forwarding to attribute_set (using method_missing or similar) will allow us
to modify the attribute set on an object instance without having to muck around
with undefining methods and such. For an attribute named :age, we want to allow
for methods: age, age=, [:age], age?. We want to be able to add and remove
attributes and the object should just work without a bunch of metaprogramming on
our part.

On initialize, attributes are collected into an instance-scope AttributeSet.
When an instance of this class is extended, e.g., `my_class.extend(MyModule)`,
the attribute set of the instance gets the attributes of the module. This is
very much like Virtus, only we're working with instances. We might also work
with classes, but definitely instances, which allows us to do DCI-style dynamic
role/behavior extensions.

Documentation
-------------

Initialization with a hash is required.

### AttributeSet

- AttributeSet#to_h
- AttributeSet#to_value_object. Should attribute_set be the thing that handles
  handing back a value object.

Value object may be the wrong term. It may be 'immutable' not value. Investigate
ways to generate bare immutable objects in Ruby.
[immutable_struct](https://github.com/iconara/immutable_struct) looks like a
good and not bloated option. It's a bit dated, so might need to be forked.

Lightweight, but not great option:

```ruby
# from attributes hash
Struct.new(*keys).new(*values).freeze
# raises a RuntimeError on mutation
```

Attrocity objects forward #umapped_attributes and #attributes to AttributeSet

### Hooks

Implement Mod.extended(obj) hook such that when the obj.extend(Mod) triggers it,
the obj.attribute_set is merged with Mod.attributes (or Mod.attribute_set)

Coercers
--------

Comes with a built-in set of coercers.

Additional coercers are added through a registry.

The library emphasizes custom coercion over types. For example,

```ruby
attribute :publication, :book # looks for a Book coercer
```

Should coercers be initialized with an attribute? That way they can get
defaults, etc.

I don't think the cost of inheritance is worth the enforcement of implementing a
simple API. Let's just define what coercers are and document it.

The coercion API is defined as: an instance method called coerce. Why an
instance method? Because it's more accommodating to future changes.

Documentation for README
------------------------

Attribute values are set and retrieved through their containing AttributeSet.
The Attribute set acts as an aggregate root (in DDD parlance).


text:
from django import forms

from .models import Flash

class FlashForm(forms.ModelForm):
    class Meta:
        model = Flash
        exclude = ('page', 'position', 'placeholder', 'language',
                   'plugin_type')


text:
package feature.pca;

import data.DataSet;
import data.builder.Builder;
import data.builder.FullMatrixDataSetBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import utils.random.RandomUtils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.IntStream;

/**
 * Created by hanxuan on 11/10/15 for machine_learning.
 */
public class PCAMain {

    private static Logger log = LogManager.getLogger(PCA.class);

    public static void main(String[] args) throws Exception{

        String path = "/Users/hanxuan/Dropbox/neu/fall15/machine learning/data/spam_polluted/allSet";
        String sep = "\t";
        boolean hasHeader = false;
        boolean needBias = false;
        int m = 1057;
        int n = 4601;
        int[] featureCategoryIndex = {};
        boolean classification = true;

        Builder builder =
                new FullMatrixDataSetBuilder(path, sep, hasHeader, needBias, m, n, featureCategoryIndex, classification);

        builder.build();

        DataSet dataset = builder.getDataSet();
        dataset.meanVarianceNorm();

        PCA pca = new PCA(dataset);
        pca.rotate();

        double totalVar = pca.totalVar(dataset);
        double[] pve = new double[dataset.getFeatureLength()];
        IntStream.range(0, pve.length).forEach(j -> pve[j] = pca.varianceExplainedM(j, dataset) / totalVar);
        double[] cpve = new double[pve.length];
        cpve[0] = pve[0];
        for (int j = 1; j < cpve.length; j++) {
            cpve[j] = cpve[j - 1] + pve[j];
        }

        int[] index = RandomUtils.getIndexes(pve.length);

        log.info("{}", index);
        log.info("{}", pve);
        log.info("{}", cpve);
        log.info("==============");

        DataSet principleTopNSet = pca.project(dataset, 200);
        String pcaOut = "/Users/hanxuan/Dropbox/neu/fall15/machine learning/data/spam_polluted/allSet.pca.200";
        BufferedWriter writer = new BufferedWriter(new FileWriter(pcaOut), 1024 * 1024 * 32);
        Map indexClassMap = dataset.getLabels().getIndexClassMap();
        for (int i = 0; i < principleTopNSet.getInstanceLength(); i++) {
            double[] x = principleTopNSet.getInstance(i);
            int label = (int) principleTopNSet.getLabel(i);
            StringBuilder sb = new StringBuilder();
            Arrays.stream(x).forEach(e -> sb.append(e + "\t"));
            sb.append(indexClassMap.get(label));
            writer.write(sb.toString() + "\n");
        }
        writer.close();
    }
}


text:
.class final Lcom/payu/android/sdk/internal/st$1;
.super Lcom/payu/android/sdk/internal/st;

# annotations
.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic b:Ljava/lang/String;

.field final synthetic c:Lcom/payu/android/sdk/internal/st;

# direct methods
.method constructor <init>(Lcom/payu/android/sdk/internal/st;Lcom/payu/android/sdk/internal/st;Ljava/lang/String;)V
    .locals 1

    .line 219
    iput-object p1, p0, Lcom/payu/android/sdk/internal/st$1;->c:Lcom/payu/android/sdk/internal/st;

    iput-object p3, p0, Lcom/payu/android/sdk/internal/st$1;->b:Ljava/lang/String;

    const/4 v0, 0x0

    invoke-direct {p0, p2, v0}, Lcom/payu/android/sdk/internal/st;-><init>(Lcom/payu/android/sdk/internal/st;Lcom/payu/android/sdk/internal/st$1;)V

    return-void
.end method

# virtual methods
.method public final a()Lcom/payu/android/sdk/internal/st;
    .locals 2

    .line 229
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    const-string v1, "already specified useForNull"

    invoke-direct {v0, v1}, Ljava/lang/UnsupportedOperationException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

.method final a(Ljava/lang/Object;)Ljava/lang/CharSequence;
    .locals 1
    .param p1    # Ljava/lang/Object;
        .annotation runtime Ljavax/annotation/Nullable;
        .end annotation
    .end param

    .line 221
    if-nez p1, :cond_0

    iget-object v0, p0, Lcom/payu/android/sdk/internal/st$1;->b:Ljava/lang/String;

    return-object v0

    :cond_0
    iget-object v0, p0, Lcom/payu/android/sdk/internal/st$1;->c:Lcom/payu/android/sdk/internal/st;

    invoke-virtual {v0, p1}, Lcom/payu/android/sdk/internal/st;->a(Ljava/lang/Object;)Ljava/lang/CharSequence;

    move-result-object v0

    return-object v0
.end method

.method public final b(Ljava/lang/String;)Lcom/payu/android/sdk/internal/st;
    .locals 2

    .line 225
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    const-string v1, "already specified useForNull"

    invoke-direct {v0, v1}, Ljava/lang/UnsupportedOperationException;-><init>(Ljava/lang/String;)V

    throw v0
.end method


text:
/*!
* \file Episode.hpp
* \brief Fichier contenant les entêtes de la classe Episodes
* \author Camille Le Luët
* \author Thomas Minier
* \date 26.11.2014
*/
#ifndef Episode_H
#define Episode_H

#include "Video.hpp"

#include <string>
#include <vector>

//--------------------------------------------------
/*!
* \class Episode
* \brief Classe héritant de Video et représentant un épisode d'une série
*/
class Episode : public virtual Video {
	private:
		//Attributs
		int numero; //!< Numéro de l'épisode dans la saison
		int saison; //!< Numéro de la saison de l'épisode
		std::string serie; //!< Identifiant de la série associée à l'épisode

	public:
		//Constructeurs & destructeur
		Episode(std::string id, std::string titre, std::string lien, int annee, std::string affiche, int numero, int saison, std::string serie, std::string synopsis, std::string pays);
		Episode(std::string id, std::string titre, std::string lien, int annee, std::string affiche, int numero, int saison, std::string serie, std::string synopsis , std::vector<std::string> acteurs, std::vector<std::string> real, std::string pays);
		Episode(std::string id, std::string titre, std::string lien, int annee, std::string affiche, std::string synopsis , std::vector<std::string> acteurs, std::vector<std::string> real, std::string pays);
		~Episode();
		//Methodes publiques
		int getNumero();
		void setNumero(int num);
		int getSaison();
		void setSaison(int num);
		std::string getSerie();
		void setSerie(std::string serie);
		//Méthode héritée de Video
		virtual std::string getStatut();
};
//--------------------------------------------------
#endif


text:
/*
 * ut_sim.c
 *
 * an unreliable transport simulator
 * (for testing replay databases and suchlike)
 *
 * David A. McGrew
 * Cisco Systems, Inc.
 */

/*
 *
 * Copyright (c) 2001-2017, Cisco Systems, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 *   Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the following
 *   disclaimer in the documentation and/or other materials provided
 *   with the distribution.
 *
 *   Neither the name of the Cisco Systems, Inc. nor the names of its
 *   contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "ut_sim.h"
#include "cipher_priv.h"

int ut_compar(const void *a, const void *b)
{
    uint8_t r;
    srtp_cipher_rand_for_tests(&r, sizeof(r));
    return r > (UINT8_MAX / 2) ? -1 : 1;
}

void ut_init(ut_connection *utc)
{
    int i;
    utc->index = 0;

    for (i = 0; i < UT_BUF; i++)
        utc->buffer[i] = i;

    qsort(utc->buffer, UT_BUF, sizeof(uint32_t), ut_compar);

    utc->index = UT_BUF - 1;
}

uint32_t ut_next_index(ut_connection *utc)
{
    uint32_t tmp;

    tmp = utc->buffer[0];
    utc->index++;
    utc->buffer[0] = utc->index;

    qsort(utc->buffer, UT_BUF, sizeof(uint32_t), ut_compar);

    return tmp;
}

#ifdef UT_TEST

#include <stdio.h>

int main()
{
    uint32_t i, irecvd, idiff;
    ut_connection utc;

    ut_init(&utc);

    for (i = 0; i < 1000; i++) {
        irecvd = ut_next_index(&utc);
        idiff = i - irecvd;
        printf("%lu\t%lu\t%d\n", i, irecvd, idiff);
    }

    return 0;
}

#endif


text:
package com.example.suspent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class CameraActivity extends Activity {

	protected static final String TAG = "Camera Capture";
	public static final String IMAGE_FILEPATH_KEY = "image_filepath";
	public static final String AUDIO_FILEPATH_KEY = "audio_filepath";
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int AUDIO_LENGTH = 7000;
	public static final int WAIT_DURATION_BEFORE_PICTURE = 5000;
	public static final int WAIT_DURATION_AFTER_PICTURE = 2000;

	private Camera mCamera;
	private CameraPreview mPreview;
	private Button mCaptureButton;

	private String mUniqueStamp;
	private String mImageFilepath;
	private String mAudioFilepath;

	private static final String LOG_TAG = "AudioRecordTest";
	private MyRecorder mRecorder = null;
	private MyCountdown mTimerCount;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_camera_activity);

		mCaptureButton = (Button) findViewById(R.id.button_capture);
		FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);

		// Create an instance of Camera
		mCamera = getCameraInstance();
		mTimerCount = new MyCountdown(WAIT_DURATION_BEFORE_PICTURE, 1000);

		// Create our Preview view and set it as the content of our activity.
		mPreview = new CameraPreview(this, mCamera);
		preview.addView(mPreview);

		// Add a listener to the Capture button
		mCaptureButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mCaptureButton.setClickable(false);
				mCaptureButton.setText("" + WAIT_DURATION_BEFORE_PICTURE / 1000);
				startRecording();
				mTimerCount.start();
			}
		});
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mRecorder != null) {
			mRecorder.release();
			mRecorder = null;
		}
	}

	/** A safe way to get an instance of the Camera object. */
	public static Camera getCameraInstance() {
		Camera c = null;
		try {
			c = Camera.open(); // attempt to get a Camera instance
			// c.setDisplayOrientation(90); // Set camera to portrait mode
		} catch (Exception e) {
			// Camera is not available (in use or does not exist)
		}
		return c; // returns null if camera is unavailable
	}

	private PictureCallback mPicture = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {

			File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
			if (pictureFile == null) {
				Log.d(TAG, "Error creating media file, check storage permissions");
				return;
			}

			try {
				FileOutputStream fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
			} catch (FileNotFoundException e) {
				Log.d(TAG, "File not found: " + e.getMessage());
			} catch (IOException e) {
				Log.d(TAG, "Error accessing file: " + e.getMessage());
			}
		}
	};

	private void startRecording() {
		mRecorder = new MyRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		mRecorder.setMaxDuration(AUDIO_LENGTH);
		mRecorder.setOnInfoListener(mRecorder);
		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/suspent/audio");
		dir.mkdirs();
		mUniqueStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		mAudioFilepath = dir.getAbsolutePath() + "/AUD_" + mUniqueStamp + ".3gp";

		mRecorder.setOutputFile(mAudioFilepath);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		try {
			mRecorder.prepare();
		} catch (IOException e) {
			Log.e(LOG_TAG, "prepare() failed");
		}

		mRecorder.start();
	}

	private void stopRecording() {
		mRecorder.stop();
		mRecorder.release();
		mRecorder = null;
	}

	/** Create a File for saving an image or video */
	private File getOutputMediaFile(int type) {

		String state = Environment.getExternalStorageState();
		if (!Environment.MEDIA_MOUNTED.equals(state)) {
			// We can't read or write to the media, so return null
			return null;
		}

		// For the save to sd card info:
		// http://stackoverflow.com/a/3551906/1601953
		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/suspent/images");
		dir.mkdirs();
		File mediaFile;
		mImageFilepath = dir + "/IMG_" + mUniqueStamp + ".jpg";

		if (type == MEDIA_TYPE_IMAGE) {
			// Create a media file name
			mediaFile = new File(mImageFilepath);
		} else {
			return null;
		}
		return mediaFile;
	}

	public class MyCountdown extends CountDownTimer {
		public MyCountdown(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			mCamera.setPreviewCallback(null);
			mCamera.takePicture(shutterCallback, null, mPicture);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			mCaptureButton.setText("" + millisUntilFinished / 1000);
			// some script here
		}
	}

	class MyRecorder extends MediaRecorder implements MediaRecorder.OnInfoListener {

		@Override
		public void onInfo(MediaRecorder mr, int what, int extra) {
			switch (what) {
			case MEDIA_RECORDER_INFO_MAX_DURATION_REACHED:
				stopRecording();
				final Intent intent = new Intent(getApplicationContext(), SuspentReview.class);
				intent.putExtra(IMAGE_FILEPATH_KEY, mImageFilepath);
				intent.putExtra(AUDIO_FILEPATH_KEY, mAudioFilepath);
				startActivity(intent);
				mCaptureButton.setClickable(true);
				break;
			case MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED:
			case MEDIA_RECORDER_INFO_UNKNOWN:
				break;
			default:
				break;
			}
		}
	}

	private final ShutterCallback shutterCallback = new ShutterCallback() {
		public void onShutter() {
			// AudioManager mgr = (AudioManager)
			// getSystemService(Context.AUDIO_SERVICE);
			// mgr.playSoundEffect(AudioManager.FLAG_PLAY_SOUND);
		}
	};
}


text:
export class Country
{
    Id:number;
    Code:number;
    Name:string;

    constructor(){}

}