text:
_Note_: if you're looking for the `winrm` command-line tool, this has been splitted from this project and is available at [winrm-cli](https://github.com/masterzen/winrm-cli)

This is a Go library to execute remote commands on Windows machines through
the use of WinRM/WinRS.

_Note_: this library doesn't support domain users (it doesn't support GSSAPI nor Kerberos). It's primary target is to execute remote commands on EC2 windows machines.

[![Build Status](https://travis-ci.org/masterzen/winrm.svg?branch=master)](https://travis-ci.org/masterzen/winrm)
[![Coverage Status](https://coveralls.io/repos/masterzen/winrm/badge.png)](https://coveralls.io/r/masterzen/winrm)

## Contact

- Bugs: https://github.com/masterzen/winrm/issues

## Getting Started
WinRM is available on Windows Server 2008 and up. This project natively supports basic authentication for local accounts, see the steps in the next section on how to prepare the remote Windows machine for this scenario. The authentication model is pluggable, see below for an example on using Negotiate/NTLM authentication (e.g. for connecting to vanilla Azure VMs).

### Preparing the remote Windows machine for Basic authentication
This project supports only basic authentication for local accounts (domain users are not supported). The remote windows system must be prepared for winrm:

_For a PowerShell script to do what is described below in one go, check [Richard Downer's blog](http://www.frontiertown.co.uk/2011/12/overthere-control-windows-from-java/)_

On the remote host, a PowerShell prompt, using the __Run as Administrator__ option and paste in the following lines:

		winrm quickconfig
		y
		winrm set winrm/config/service/Auth '@{Basic="true"}'
		winrm set winrm/config/service '@{AllowUnencrypted="true"}'
		winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="1024"}'

__N.B.:__ The Windows Firewall needs to be running to run this command. See [Microsoft Knowledge Base article #2004640](http://support.microsoft.com/kb/2004640).

__N.B.:__ Do not disable Negotiate authentication as the `winrm` command itself uses this for internal authentication, and you risk getting a system where `winrm` doesn't work anymore.

__N.B.:__ The `MaxMemoryPerShellMB` option has no effects on some Windows 2008R2 systems because of a WinRM bug. Make sure to install the hotfix described [Microsoft Knowledge Base article #2842230](http://support.microsoft.com/kb/2842230) if you need to run commands that uses more than 150MB of memory.

For more information on WinRM, please refer to the online documentation at Microsoft's DevCenter.

### Building the winrm go and executable

You can build winrm from source:

```sh
git clone https://github.com/masterzen/winrm
cd winrm
make
```

_Note_: this winrm code doesn't depend anymore on [Gokogiri](https://github.com/moovweb/gokogiri) which means it is now in pure Go.

_Note_: you need go 1.5+. Please check your installation with

```
go version
```

## Command-line usage

For command-line usage check the [winrm-cli project](https://github.com/masterzen/winrm-cli)

## Library Usage

**Warning the API might be subject to change.**

For the fast version (this doesn't allow to send input to the command) and it's using HTTP as the transport:

```go
package main

import (
	"github.com/masterzen/winrm"
	"os"
)

endpoint := winrm.NewEndpoint(host, 5986, false, false, nil, nil, nil, 0)
client, err := winrm.NewClient(endpoint, "Administrator", "secret")
if err != nil {
	panic(err)
}
client.Run("ipconfig /all", os.Stdout, os.Stderr)
```

or
```go
package main
import (
  "github.com/masterzen/winrm"
  "fmt"
  "os"
)

endpoint := winrm.NewEndpoint("localhost", 5985, false, false, nil, nil, nil, 0)
client, err := winrm.NewClient(endpoint,"Administrator", "secret")
if err != nil {
	panic(err)
}

_, err := client.RunWithInput("ipconfig", os.Stdout, os.Stderr, os.Stdin)
if err != nil {
	panic(err)
}

```

By passing a TransportDecorator in the Parameters struct it is possible to use different Transports (e.g. NTLM)

```go
package main
import (
  "github.com/masterzen/winrm"
  "fmt"
  "os"
)

endpoint := winrm.NewEndpoint("localhost", 5985, false, false, nil, nil, nil, 0)

params := DefaultParameters
params.TransportDecorator = func() Transporter { return &ClientNTLM{} }

client, err := NewClientWithParameters(endpoint, "test", "test", params)
if err != nil {
	panic(err)
}

_, err := client.RunWithInput("ipconfig", os.Stdout, os.Stderr, os.Stdin)
if err != nil {
	panic(err)
}

```

For a more complex example, it is possible to call the various functions directly:

```go
package main

import (
  "github.com/masterzen/winrm"
  "fmt"
  "bytes"
  "os"
)

stdin := bytes.NewBufferString("ipconfig /all")
endpoint := winrm.NewEndpoint("localhost", 5985, false, false,nil, nil, nil, 0)
client , err := winrm.NewClient(endpoint, "Administrator", "secret")
if err != nil {
	panic(err)
}
shell, err := client.CreateShell()
if err != nil {
  panic(err)
}
var cmd *winrm.Command
cmd, err = shell.Execute("cmd.exe")
if err != nil {
  panic(err)
}

go io.Copy(cmd.Stdin, stdin)
go io.Copy(os.Stdout, cmd.Stdout)
go io.Copy(os.Stderr, cmd.Stderr)

cmd.Wait()
shell.Close()
```

For using HTTPS authentication with x 509 cert without checking the CA
```go
	package main

	import (
		"github.com/masterzen/winrm"
		"os"
		"io/ioutil"
	)

	clientCert, err := ioutil.ReadFile("path/to/cert")
	if err != nil {
		panic(err)
	}

	clientKey, err := ioutil.ReadFile("path/to/key")
	if err != nil {
		panic(err)
	}

	winrm.DefaultParameters.TransportDecorator = func() winrm.Transporter {
		// winrm https module
		return &winrm.ClientAuthRequest{}
	}

	endpoint := winrm.NewEndpoint(host, 5986, false, false, clientCert, clientKey, nil, 0)
	client, err := winrm.NewClient(endpoint, "Administrator", ""
	if err != nil {
		panic(err)
	}
	client.Run("ipconfig /all", os.Stdout, os.Stderr)
```

## Developing on WinRM

If you wish to work on `winrm` itself, you'll first need [Go](http://golang.org)
installed (version 1.5+ is _required_). Make sure you have Go properly installed,
including setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH).

For some additional dependencies, Go needs [Mercurial](http://mercurial.selenic.com/)
and [Bazaar](http://bazaar.canonical.com/en/) to be installed.
Winrm itself doesn't require these, but a dependency of a dependency does.

Next, clone this repository into `$GOPATH/src/github.com/masterzen/winrm` and
then just type `make`.

You can run tests by typing `make test`.

If you make any changes to the code, run `make format` in order to automatically
format the code according to Go standards.

When new dependencies are added to winrm you can use `make updatedeps` to
get the latest and subsequently use `make` to compile.


text:
"""Convert data2vec checkpoint."""

import argparse
import os
import pathlib

import fairseq
import torch
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import Data2VecTextConfig, Data2VecTextForMaskedLM, Data2VecTextForSequenceClassification
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)

# IMPORTANT: In order for this script to run, please make sure to download the dictionary: `dict.txt` from wget https://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz
# File copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_text.py
from transformers.models.data2vec.data2vec_text import Data2VecTextModel
from transformers.utils import logging

if version.parse(fairseq.__version__) < version.parse("0.9.0"):
    raise Exception("requires fairseq >= 0.9.0")

logging.set_verbosity_info()
logger = logging.get_logger(__name__)

SAMPLE_TEXT = "Hello world! cécé herlolip"

def convert_data2vec_checkpoint_to_pytorch(
    data2vec_checkpoint_path: str, pytorch_dump_folder_path: str, classification_head: bool
):
    """
    Copy/paste/tweak data2vec's weights to our BERT structure.
    """
    data2vec_checkpoint_dir, data2vec_checkpoint_file_name = os.path.split(data2vec_checkpoint_path)
    data2vec = Data2VecTextModel.from_pretrained(
        data2vec_checkpoint_dir, checkpoint_file=data2vec_checkpoint_file_name
    )
    data2vec.eval()  # disable dropout
    data2vec_model = data2vec.models[0]
    data2vec_sent_encoder = data2vec_model.encoder.sentence_encoder
    config = Data2VecTextConfig(
        vocab_size=data2vec_sent_encoder.embed_tokens.num_embeddings,
        hidden_size=data2vec_model.args.encoder_embed_dim,
        num_hidden_layers=data2vec_model.args.encoder_layers,
        num_attention_heads=data2vec_model.args.encoder_attention_heads,
        intermediate_size=data2vec_model.args.encoder_ffn_embed_dim,
        max_position_embeddings=514,
        type_vocab_size=1,
        layer_norm_eps=1e-5,  # PyTorch default used in fairseq
    )
    if classification_head:
        config.num_labels = data2vec.model.classification_heads["mnli"].out_proj.weight.shape[0]
    print("Our BERT config:", config)

    model = Data2VecTextForSequenceClassification(config) if classification_head else Data2VecTextForMaskedLM(config)
    model.eval()

    # Now let's copy all the weights.
    # Embeddings
    model.data2vec_text.embeddings.word_embeddings.weight = data2vec_sent_encoder.embed_tokens.weight
    model.data2vec_text.embeddings.position_embeddings.weight = data2vec_sent_encoder.embed_positions.weight
    model.data2vec_text.embeddings.token_type_embeddings.weight.data = torch.zeros_like(
        model.data2vec_text.embeddings.token_type_embeddings.weight
    )  # just zero them out b/c data2vec doesn't use them.
    model.data2vec_text.embeddings.LayerNorm.weight = data2vec_sent_encoder.layernorm_embedding.weight
    model.data2vec_text.embeddings.LayerNorm.bias = data2vec_sent_encoder.layernorm_embedding.bias

    for i in range(config.num_hidden_layers):
        # Encoder: start of layer
        layer: BertLayer = model.data2vec_text.encoder.layer[i]
        data2vec_layer: TransformerSentenceEncoderLayer = data2vec_sent_encoder.layers[i]

        # self attention
        self_attn: BertSelfAttention = layer.attention.self
        assert data2vec_layer.self_attn.k_proj.weight.data.shape == torch.Size(
            (config.hidden_size, config.hidden_size)
        ), (
            "Shape for data2vec_layer.self_attn.k_proj.weight.data should be"
            f" {torch.Size((config.hidden_size, config.hidden_size))}"
        )
        assert data2vec_layer.self_attn.q_proj.weight.data.shape == torch.Size(
            (config.hidden_size, config.hidden_size)
        ), (
            "Shape for data2vec_layer.self_attn.q_proj.weight.data should be"
            f" {torch.Size((config.hidden_size, config.hidden_size))}"
        )
        assert data2vec_layer.self_attn.v_proj.weight.data.shape == torch.Size(
            (config.hidden_size, config.hidden_size)
        ), (
            "Shape for data2vec_layer.self_attn.v_proj.weight.data should be"
            f" {torch.Size((config.hidden_size, config.hidden_size))}"
        )

        self_attn.query.weight.data = data2vec_layer.self_attn.q_proj.weight
        self_attn.query.bias.data = data2vec_layer.self_attn.q_proj.bias
        self_attn.key.weight.data = data2vec_layer.self_attn.k_proj.weight
        self_attn.key.bias.data = data2vec_layer.self_attn.k_proj.bias
        self_attn.value.weight.data = data2vec_layer.self_attn.v_proj.weight
        self_attn.value.bias.data = data2vec_layer.self_attn.v_proj.bias

        # self-attention output
        self_output: BertSelfOutput = layer.attention.output
        assert (
            self_output.dense.weight.shape == data2vec_layer.self_attn.out_proj.weight.shape
        ), f"Shape for self_output.dense.weight should be {data2vec_layer.self_attn.out_proj.weight.shape}"
        self_output.dense.weight = data2vec_layer.self_attn.out_proj.weight
        self_output.dense.bias = data2vec_layer.self_attn.out_proj.bias
        self_output.LayerNorm.weight = data2vec_layer.self_attn_layer_norm.weight
        self_output.LayerNorm.bias = data2vec_layer.self_attn_layer_norm.bias

        # intermediate
        intermediate: BertIntermediate = layer.intermediate
        assert (
            intermediate.dense.weight.shape == data2vec_layer.fc1.weight.shape
        ), f"Shape for intermediate.dense.weight should be {data2vec_layer.fc1.weight.shape}"
        intermediate.dense.weight = data2vec_layer.fc1.weight
        intermediate.dense.bias = data2vec_layer.fc1.bias

        # output
        bert_output: BertOutput = layer.output
        assert (
            bert_output.dense.weight.shape == data2vec_layer.fc2.weight.shape
        ), f"Shape for bert_output.dense.weight should be {data2vec_layer.fc2.weight.shape}"
        bert_output.dense.weight = data2vec_layer.fc2.weight
        bert_output.dense.bias = data2vec_layer.fc2.bias
        bert_output.LayerNorm.weight = data2vec_layer.final_layer_norm.weight
        bert_output.LayerNorm.bias = data2vec_layer.final_layer_norm.bias
        # end of layer

    if classification_head:
        model.classifier.dense.weight = data2vec.model.classification_heads["mnli"].dense.weight
        model.classifier.dense.bias = data2vec.model.classification_heads["mnli"].dense.bias
        model.classifier.out_proj.weight = data2vec.model.classification_heads["mnli"].out_proj.weight
        model.classifier.out_proj.bias = data2vec.model.classification_heads["mnli"].out_proj.bias
    else:
        # LM Head
        model.lm_head.dense.weight = data2vec_model.encoder.lm_head.dense.weight
        model.lm_head.dense.bias = data2vec_model.encoder.lm_head.dense.bias
        model.lm_head.layer_norm.weight = data2vec_model.encoder.lm_head.layer_norm.weight
        model.lm_head.layer_norm.bias = data2vec_model.encoder.lm_head.layer_norm.bias
        model.lm_head.decoder.weight = data2vec_model.encoder.lm_head.weight
        model.lm_head.decoder.bias = data2vec_model.encoder.lm_head.bias

    # Let's check that we get the same results.
    input_ids: torch.Tensor = data2vec.encode(SAMPLE_TEXT).unsqueeze(0)  # batch of size 1

    our_output = model(input_ids)[0]
    if classification_head:
        their_output = data2vec.model.classification_heads["mnli"](data2vec.extract_features(input_ids))
    else:
        their_output = data2vec_model(input_ids)[0]
    print(our_output.shape, their_output.shape)
    max_absolute_diff = torch.max(torch.abs(our_output - their_output)).item()
    print(f"max_absolute_diff = {max_absolute_diff}")  # ~ 1e-7
    success = torch.allclose(our_output, their_output, atol=1e-3)
    print("Do both models output the same tensors?", "🔥" if success else "💩")
    if not success:
        raise Exception("Something went wRoNg")

    pathlib.Path(pytorch_dump_folder_path).mkdir(parents=True, exist_ok=True)
    print(f"Saving model to {pytorch_dump_folder_path}")
    model.save_pretrained(pytorch_dump_folder_path)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        "--checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
    )
    parser.add_argument(
        "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
    )
    parser.add_argument(
        "--classification_head", action="store_true", help="Whether to convert a final classification head."
    )
    args = parser.parse_args()
    convert_data2vec_checkpoint_to_pytorch(
        args.checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
    )

redpajama_set_name: RedPajamaGithub


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import sinon from 'sinon';

module(
  'Integration | Component | willDestroyParent hook runs in the correct order',
  function (hooks) {
    setupRenderingTest(hooks);

    test('top-level parent and two children', async function (assert) {
      let parentSpy = (this.parentSpy = sinon.spy());
      let childSpy = (this.childSpy = sinon.spy());
      this.show = true;

      await render(hbs`
      {{#if this.show}}
        <Root @willDestroyParent={{this.parentSpy}} as |Node|>
          <Node @willDestroyParent={{this.childSpy}}/>
          <Node @willDestroyParent={{this.childSpy}}/>
        </Root>
      {{/if}}
    `);

      this.set('show', false);

      assert.ok(
        parentSpy.calledOnce,
        'parent willDestroyParent was called once'
      );
      assert.ok(
        childSpy.calledTwice,
        'child willDestroyParent was called twice'
      );
      assert.ok(
        childSpy.calledBefore(parentSpy),
        'child was called before parent'
      );
    });

    test('top-level parent and two children after if', async function (assert) {
      let parentSpy = (this.parentSpy = sinon.spy());
      let childSpy = (this.childSpy = sinon.spy());
      let childParentSpy = (this.childParentSpy = sinon.spy());
      this.showChild = this.showParentChild = this.show = true;

      await render(hbs`
      {{#if this.show}}
        <Root @willDestroyParent={{this.parentSpy}} as |Node|>
          <Node @willDestroyParent={{this.childSpy}}/>
          <Node @willDestroyParent={{this.childSpy}}/>
          {{#if this.showParentChild}}
            <Node @willDestroyParent={{this.childParentSpy}} as |Node|>
              {{#if this.showChild}}
                <Node @willDestroyParent={{this.childSpy}}/>
              {{/if}}
              <Node @willDestroyParent={{this.childSpy}}/>
            </Node>
          {{/if}}
        </Root>
      {{/if}}
    `);

      this.set('showChild', false);

      assert.notOk(
        parentSpy.called,
        'parent willDestroyParent was never called'
      );
      assert.notOk(
        childParentSpy.called,
        'child-parent willDestroyParent was never called'
      );
      assert.ok(childSpy.calledOnce, 'child willDestroyParent was called once');

      childSpy.resetHistory();
      this.set('showChild', true);
      this.set('showParentChild', false);

      assert.notOk(
        parentSpy.called,
        'parent willDestroyParent was never called'
      );
      assert.ok(
        childParentSpy.calledOnce,
        'child-parent willDestroyParent was called once'
      );
      assert.ok(
        childSpy.calledTwice,
        'child willDestroyParent was called twice'
      );
      assert.ok(
        childSpy.calledBefore(childParentSpy),
        'child was called before child-parent'
      );

      childSpy.resetHistory();
      childParentSpy.resetHistory();
      this.set('showChild', true);
      this.set('showParentChild', true);
      this.set('show', false);

      assert.ok(
        parentSpy.calledOnce,
        'parent willDestroyParent was called once'
      );
      assert.ok(
        childParentSpy.calledOnce,
        'child-parent willDestroyParent was called once'
      );
      assert.strictEqual(
        childSpy.callCount,
        4,
        'child willDestroyParent was called 4 times'
      );
      assert.ok(
        childSpy.calledBefore(childParentSpy),
        'child was called before child-parent'
      );
      assert.ok(
        childParentSpy.calledBefore(parentSpy),
        'child-parent was called before parent'
      );
    });
  }
);


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TimeKeeping")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TimeKeeping")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("448cbd50-477c-4875-b0e2-30b48fd92765")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
ES5Harness.registerTest( {

    id: "15.4.4.15-8-b-i-28",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.15/15.4.4.15-8-b-i-28.js",

    description: "Array.prototype.lastIndexOf - side-effects are visible in subsequent iterations on an Array",

    test: function testcase() {

        var preIterVisible = false;
        var arr = [];

        Object.defineProperty(arr, "2", {
            get: function () {
                preIterVisible = true;
                return false;
            },
            configurable: true
        });

        Object.defineProperty(arr, "1", {
            get: function () {
                if (preIterVisible) {
                    return true;
                } else {
                    return false;
                }
            },
            configurable: true
        });

        return arr.lastIndexOf(true) === 1;
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.lastIndexOf) && fnExists(Object.defineProperty) && fnSupportsArrayIndexGettersOnArrays();
    }

});


text:
<?php

namespace GoogleUrl;

use GoogleUrl\ProxyInterface;

/**
 * Description of ProxyPool
 *
 * @author bob
 */
interface ProxyAccessAdapter {

    /**
     * Find the proxy with the shortest time for next usage
     *
     */
    public function findShortestTimeProxy();

    /**
     * Find a proxy that is available for querying now
     */
    public function findAvailableProxy();

    /**
     *
     * @param \GoogleUrl\ProxyInterface $proxy
     */
    public function acquireProxyLock(ProxyInterface $proxy);
    public function releaseProxyLock(ProxyInterface $proxy);
    public function proxyUsed(ProxyInterface $proxy);

    public function setProxy(ProxyInterface $proxy);
    public function removeProxy(ProxyInterface $proxy);

    public function hasProxy(SimpleProxyInterface $p);

}


text:
def stub_ticket_mailer_secrets
  # TODO
#  Rails.application.secrets.stub!(ticket_mailer: {
#    address: 'myprovider.com',
#    port: 587,
#    authentication: 'plain',
#    enable_starttls_auto: true,
#    user_name: 'test',
#    password: 'test',
#  })
end


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var platform_browser_1 = require('@angular/platform-browser');
var dive_log_component_1 = require('./dive-log.component');
var content_filter_pipe_1 = require('./content-filter.pipe');
var DiveLogModule = (function () {
    function DiveLogModule() {
    }
    DiveLogModule = __decorate([
        core_1.NgModule({
            imports: [platform_browser_1.BrowserModule],
            declarations: [
                dive_log_component_1.DiveLogComponent,
                content_filter_pipe_1.ContentFilterPipe
            ]
        }),
        __metadata('design:paramtypes', [])
    ], DiveLogModule);
    return DiveLogModule;
}());
exports.DiveLogModule = DiveLogModule;
//# sourceMappingURL=dive-log.module.js.map


text:
using PaintTracker.Core.DependencyInterfaces;
using System.Threading.Tasks;

namespace PaintTracker.Core.Services
{
    public class DialogService
    {
        IProgressDialog _progressDialog;

        public DialogService(IProgressDialog progressDialog)
        {
            _progressDialog = progressDialog;
        }

        public void DisplayAlert(string title, string message)
        {
            App.Current.MainPage.DisplayAlert(title, message, "OK");
        }

        public async Task<bool> DisplayAlertAsync(string title, string message) =>
            await App.Current.MainPage.DisplayAlert(title, message, "OK", "Cancel");

        public async Task<string> DisplayActionSheetAsync(string title, string message, string[] buttons) =>
            await App.Current.MainPage.DisplayActionSheet(title, message, null, buttons);

        public void ShowProgressDialog(string title, string message)
        {
            _progressDialog.Show(title, message);
        }

        public void HideProgressDialog()
        {
            _progressDialog.Hide();
        }
    }
}


text:
var debug = require('debug')('HAPServer');
var crypto = require("crypto");
var srp = require("srp");
var url = require("url");
var inherits = require('util').inherits;
var ed25519 = require("ed25519");
var hkdf = require("./util/hkdf");
var tlv = require("./util/tlv");
var encryption = require("./util/encryption")
var EventEmitter = require('events').EventEmitter;
var EventedHTTPServer = require("./util/eventedhttp").EventedHTTPServer;
var once = require('./util/once').once;

'use strict';

module.exports = {
  HAPServer: HAPServer
}

/**
 * The actual HAP server that iOS devices talk to.
 *
 * Notes
 * -----
 * It turns out that the IP-based version of HomeKit's HAP protocol operates over a sort of pseudo-HTTP.
 * Accessories are meant to host a TCP socket server that initially behaves exactly as an HTTP/1.1 server.
 * So iOS devices will open up a long-lived connection to this server and begin issuing HTTP requests.
 * So far, this conforms with HTTP/1.1 Keepalive. However, after the "pairing" process is complete, the
 * connection is expected to be "upgraded" to support full-packet encryption of both HTTP headers and data.
 * This encryption is NOT SSL. It is a customized ChaCha20+Poly1305 encryption layer.
 *
 * Additionally, this "HTTP Server" supports sending "event" responses at any time without warning. The iOS
 * device simply keeps the connection open after it's finished with HTTP request/response traffic, and while
 * the connection is open, the server can elect to issue "EVENT/1.0 200 OK" HTTP-style responses. These are
 * typically sent to inform the iOS device of a characteristic change for the accessory (like "Door was Unlocked").
 *
 * See eventedhttp.js for more detail on the implementation of this protocol.
 *
 * @event 'listening' => function() { }
 *        Emitted when the server is fully set up and ready to receive connections.
 *
 * @event 'identify' => function(callback(err)) { }
 *        Emitted when a client wishes for this server to identify itself before pairing. You must call the
 *        callback to respond to the client with success.
 *
 * @event 'pair' => function(username, publicKey, callback(err)) { }
 *        This event is emitted when a client completes the "pairing" process and exchanges encryption keys.
 *        Note that this does not mean the "Add Accessory" process in iOS has completed. You must call the
 *        callback to complete the process.
 *
 * @event 'verify' => function() { }
 *        This event is emitted after a client successfully completes the "verify" process, thereby authenticating
 *        itself to an Accessory as a known-paired client.
 *
 * @event 'unpair' => function(username, callback(err)) { }
 *        This event is emitted when a client has requested us to "remove their pairing info", or basically to unpair.
 *        You must call the callback to complete the process.
 *
 * @event 'accessories' => function(callback(err, accessories)) { }
 *        This event is emitted when a client requests the complete representation of Accessory data for
 *        this Accessory (for instance, what services, characteristics, etc. are supported) and any bridged
 *        Accessories in the case of a Bridge Accessory. The listener must call the provided callback function
 *        when the accessory data is ready. We will automatically JSON.stringify the data.
 *
 * @event 'get-characteristics' => function(data, events, callback(err, characteristics)) { }
 *        This event is emitted when a client wishes to retrieve the current value of one or more characteristics.
 *        The listener must call the provided callback function when the values are ready. iOS clients can typically
 *        wait up to 10 seconds for this call to return. We will automatically JSON.stringify the data (which must
 *        be an array) and wrap it in an object with a top-level "characteristics" property.
 *
 * @event 'set-characteristics' => function(data, events, callback(err)) { }
 *        This event is emitted when a client wishes to set the current value of one or more characteristics and/or
 *        subscribe to one or more events. The 'events' param is an initially-empty object, associated with the current
 *        connection, on which you may store event registration keys for later processing. The listener must call
 *        the provided callback when the request has been processed.
 */

function HAPServer(accessoryInfo, accessoryController) {
  this.accessoryInfo = accessoryInfo;
  this.allowInsecureRequest = false;

  // internal server that does all the actual communication
  this._httpServer = new EventedHTTPServer();
  this._httpServer.on('listening', this._onListening.bind(this));
  this._httpServer.on('request', this._onRequest.bind(this));
  this._httpServer.on('encrypt', this._onEncrypt.bind(this));
  this._httpServer.on('decrypt', this._onDecrypt.bind(this));

  // so iOS is very reluctant to actually disconnect HAP connections (as in, sending a FIN packet).
  // For instance, if you turn off wifi on your phone, it will not close the connection, instead
  // it will leave it open and hope that it's still valid when it returns to the network. And Node,
  // by itself, does not ever "discover" that the connection has been closed behind it, until a
  // potentially very long system-level socket timeout (like, days). To work around this, we have
  // invented a manual "keepalive" mechanism where we send "empty" events perodicially, such that
  // when Node attempts to write to the socket, it discovers that it's been disconnected after
  // an additional one-minute timeout (this timeout appears to be hardcoded).
  this._keepAliveTimerID = setInterval(this._onKeepAliveTimerTick.bind(this), 1000 * 60 * 10); // send keepalive every 10 minutes
}

inherits(HAPServer, EventEmitter);

HAPServer.handlers = {
  '/identify': '_handleIdentify',
  '/pair-setup': '_handlePair',
  '/pair-verify': '_handlePairVerify',
  '/pairings': '_handlePairings',
  '/accessories': '_handleAccessories',
  '/characteristics': '_handleCharacteristics'
}

// Various "type" constants for HAP's TLV encoding.
HAPServer.Types = {
  REQUEST_TYPE: 0x00,
  USERNAME: 0x01,
  SALT: 0x02,
  PUBLIC_KEY: 0x03,
  PASSWORD_PROOF: 0x04,
  ENCRYPTED_DATA: 0x05,
  SEQUENCE_NUM: 0x06,
  ERROR_CODE: 0x07,
  PROOF: 0x0a
}

// Error codes and the like, guessed by packet inspection
HAPServer.Codes = {
  INVALID_REQUEST: 0x02,
  INVALID_SIGNATURE: 0x04
}

// Status codes for underlying HAP calls
HAPServer.Status = {
  SUCCESS: 0,
  INSUFFICIENT_PRIVILEGES: -70401,
  SERVICE_COMMUNICATION_FAILURE: -70402,
  RESOURCE_BUSY: -70403,
  READ_ONLY_CHARACTERISTIC: -70404,
  WRITE_ONLY_CHARACTERISTIC: -70405,
  NOTIFICATION_NOT_SUPPORTED: -70406,
  OUT_OF_RESOURCE: -70407,
  OPERATION_TIMED_OUT: -70408,
  RESOURCE_DOES_NOT_EXIST: -70409,
  INVALID_VALUE_IN_REQUEST: -70410
}

HAPServer.prototype.listen = function(port) {
  this._httpServer.listen(port);
}

HAPServer.prototype._onKeepAliveTimerTick = function() {
  // send out a "keepalive" event which all connections automatically sign up for once pairVerify is
  // completed. The event contains no actual data, so iOS devices will simply ignore it.
  this.notifyClients('keepalive', {characteristics: []});
}

/**
 * Notifies connected clients who have subscribed to a particular event.
 *
 * @param event {string} - the name of the event (only clients who have subscribed to this name will be notified)
 * @param data {object} - the object containing the event data; will be JSON.stringify'd automatically
 */
HAPServer.prototype.notifyClients = function(event, data, excludeEvents) {
  // encode notification data as JSON, set content-type, and hand it off to the server.
  this._httpServer.sendEvent(event, JSON.stringify(data), "application/hap+json", excludeEvents);
}

HAPServer.prototype._onListening = function() {
  this.emit('listening');
}

// Called when an HTTP request was detected.
HAPServer.prototype._onRequest = function(request, response, session, events) {

  debug("[%s] HAP Request: %s %s", this.accessoryInfo.username, request.method, request.url);

  // collect requst data, if any
  var requestData = Buffer("");
  request.on('data', function(data) { requestData = Buffer.concat([requestData, data]); });
  request.on('end', function() {

    // parse request.url (which can contain querystring, etc.) into components, then extract just the path
    var pathname = url.parse(request.url).pathname;

    // all request data received; now process this request
    for (var path in HAPServer.handlers)
      if (new RegExp('^'+path+'/?$').test(pathname)) { // match exact string and allow trailing slash
        this[HAPServer.handlers[path]](request, response, session, events, requestData);
        return;
      }

    // nobody handled this? reply 404
    debug("[%s] WARNING: Handler for %s not implemented", this.accessoryInfo.username, request.url);
    response.writeHead(404, "Not found", {'Content-Type': 'text/html'});
    response.end();

  }.bind(this));
}

HAPServer.prototype._onEncrypt = function(data, encrypted, session) {

  // instance of HAPEncryption (created in handlePairVerifyStepOne)
  var enc = session.encryption;

  // if accessoryToControllerKey is not empty, then encryption is enabled for this connection. However, we'll
  // need to be careful to ensure that we don't encrypt the last few bytes of the response from handlePairVerifyStepTwo.
  // Since all communication calls are asynchronous, we could easily receive this 'encrypt' event for those bytes.
  // So we want to make sure that we aren't encrypting data until we have *received* some encrypted data from the
  // client first.
  if (enc && enc.accessoryToControllerKey.length > 0 && enc.controllerToAccessoryCount.value > 0) {
    encrypted.data = encryption.layerEncrypt(data, enc.accessoryToControllerCount, enc.accessoryToControllerKey);
  }
}

HAPServer.prototype._onDecrypt = function(data, decrypted, session) {

  // possibly an instance of HAPEncryption (created in handlePairVerifyStepOne)
  var enc = session.encryption;

  // if controllerToAccessoryKey is not empty, then encryption is enabled for this connection.
  if (enc && enc.controllerToAccessoryKey.length > 0) {
    decrypted.data = encryption.layerDecrypt(data, enc.controllerToAccessoryCount, enc.controllerToAccessoryKey);
  }
}

/**
 * Unpaired Accessory identification.
 */

HAPServer.prototype._handleIdentify = function(request, response, session, events, requestData) {
  // /identify only works if the accesory is not paired
  if (!this.allowInsecureRequest && this.accessoryInfo.paired()) {
    response.writeHead(400, {"Content-Type": "application/hap+json"});
    response.end(JSON.stringify({status:HAPServer.Status.INSUFFICIENT_PRIVILEGES}));

    return;
  }

  this.emit('identify', once(function(err) {

    if (!err) {
      debug("[%s] Identification success", this.accessoryInfo.username);
      response.writeHead(204);
      response.end();
    }
    else {
      debug("[%s] Identification error: %s", this.accessoryInfo.username, err.message);
      response.writeHead(500);
      response.end();
    }

  }.bind(this)));
}

/**
 * iOS <-> Accessory pairing process.
 */

HAPServer.prototype._handlePair = function(request, response, session, events, requestData) {
  // Can only be directly paired with one iOS device
  if (!this.allowInsecureRequest && this.accessoryInfo.paired()) {
    response.writeHead(403);
    response.end();

    return;
  }

  var objects = tlv.decode(requestData);
  var sequence = objects[HAPServer.Types.SEQUENCE_NUM][0]; // value is single byte with sequence number

  if (sequence == 0x01)
    this._handlePairStepOne(request, response, session);
  else if (sequence == 0x03)
    this._handlePairStepTwo(request, response, session, objects);
  else if (sequence == 0x05)
    this._handlePairStepThree(request, response, session, objects);
}

// M1 + M2
HAPServer.prototype._handlePairStepOne = function(request, response, session) {
  debug("[%s] Pair step 1/5", this.accessoryInfo.username);

  var salt = crypto.randomBytes(16);
  var srpParams = srp.params["3072"];

  srp.genKey(32, function (error, key) {

    // create a new SRP server
    var srpServer = new srp.Server(srpParams, Buffer(salt), Buffer("Pair-Setup"), Buffer(this.accessoryInfo.pincode), key);
    var srpB = srpServer.computeB();

    // attach it to the current TCP session
    session.srpServer = srpServer;

    response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
    response.end(tlv.encode(
      HAPServer.Types.SEQUENCE_NUM, 0x02,
      HAPServer.Types.SALT, salt,
      HAPServer.Types.PUBLIC_KEY, srpB
    ));

  }.bind(this));
}

// M3 + M4
HAPServer.prototype._handlePairStepTwo = function(request, response, session, objects) {
  debug("[%s] Pair step 2/5", this.accessoryInfo.username);

  var A = objects[HAPServer.Types.PUBLIC_KEY]; // "A is a public key that exists only for a single login session."
  var M1 = objects[HAPServer.Types.PASSWORD_PROOF]; // "M1 is the proof that you actually know your own password."

  // pull the SRP server we created in stepOne out of the current session
  var srpServer = session.srpServer;
  srpServer.setA(A);

  try {
    srpServer.checkM1(M1);
  }
  catch (err) {
    // most likely the client supplied an incorrect pincode.
    debug("[%s] Error while checking pincode: %s", this.accessoryInfo.username, err.message);

    response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
    response.end(tlv.encode(
      HAPServer.Types.SEQUENCE_NUM, 0x04,
      HAPServer.Types.ERROR_CODE, HAPServer.Codes.INVALID_REQUEST
    ));

    return;
  }

  // "M2 is the proof that the server actually knows your password."
  var M2 = srpServer.computeM2();

  response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
  response.end(tlv.encode(
    HAPServer.Types.SEQUENCE_NUM, 0x04,
    HAPServer.Types.PASSWORD_PROOF, M2
  ));
}

// M5-1
HAPServer.prototype._handlePairStepThree = function(request, response, session, objects) {
  debug("[%s] Pair step 3/5", this.accessoryInfo.username);

  // pull the SRP server we created in stepOne out of the current session
  var srpServer = session.srpServer;

  var encryptedData = objects[HAPServer.Types.ENCRYPTED_DATA];

  var messageData = Buffer(encryptedData.length - 16);
  var authTagData = Buffer(16);

  encryptedData.copy(messageData, 0, 0, encryptedData.length - 16);
  encryptedData.copy(authTagData, 0, encryptedData.length - 16, encryptedData.length);

  var S_private = srpServer.computeK();
  var encSalt = Buffer("Pair-Setup-Encrypt-Salt");
  var encInfo = Buffer("Pair-Setup-Encrypt-Info");

  var outputKey = hkdf.HKDF("sha512", encSalt, S_private, encInfo, 32);

  var plaintextBuffer = Buffer(messageData.length);
  encryption.verifyAndDecrypt(outputKey, Buffer("PS-Msg05"), messageData, authTagData, null, plaintextBuffer);

  // decode the client payload and pass it on to the next step
  var M5Packet = tlv.decode(plaintextBuffer);

  var clientUsername = M5Packet[HAPServer.Types.USERNAME];
  var clientLTPK = M5Packet[HAPServer.Types.PUBLIC_KEY];
  var clientProof = M5Packet[HAPServer.Types.PROOF];
  var hkdfEncKey = outputKey;

  this._handlePairStepFour(request, response, session, clientUsername, clientLTPK, clientProof, hkdfEncKey);
}

// M5-2
HAPServer.prototype._handlePairStepFour = function(request, response, session, clientUsername, clientLTPK, clientProof, hkdfEncKey) {
  debug("[%s] Pair step 4/5", this.accessoryInfo.username);

  var S_private = session.srpServer.computeK();
  var controllerSalt = Buffer("Pair-Setup-Controller-Sign-Salt");
  var controllerInfo = Buffer("Pair-Setup-Controller-Sign-Info");
  var outputKey = hkdf.HKDF("sha512", controllerSalt, S_private, controllerInfo, 32);

  var completeData = Buffer.concat([outputKey, clientUsername, clientLTPK]);

  if (!ed25519.Verify(completeData, clientProof, clientLTPK)) {
    debug("[%s] Invalid signature", this.accessoryInfo.username);

    response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
    response.end(tlv.encode(
      HAPServer.Types.SEQUENCE_NUM, 0x06,
      HAPServer.Types.ERROR_CODE, HAPServer.Codes.INVALID_REQUEST
    ));

    return;
  }

  this._handlePairStepFive(request, response, session, clientUsername, clientLTPK, hkdfEncKey);
}

// M5 - F + M6
HAPServer.prototype._handlePairStepFive = function(request, response, session, clientUsername, clientLTPK, hkdfEncKey) {
  debug("[%s] Pair step 5/5", this.accessoryInfo.username);

  var S_private = session.srpServer.computeK();
  var accessorySalt = Buffer("Pair-Setup-Accessory-Sign-Salt");
  var accessoryInfo = Buffer("Pair-Setup-Accessory-Sign-Info");
  var outputKey = hkdf.HKDF("sha512", accessorySalt, S_private, accessoryInfo, 32);

  var serverLTPK = this.accessoryInfo.signPk;
  var usernameData = Buffer(this.accessoryInfo.username);

  var material = Buffer.concat([outputKey, usernameData, serverLTPK]);
  var privateKey = Buffer(this.accessoryInfo.signSk);

  var serverProof = ed25519.Sign(material, privateKey);

  var message = tlv.encode(
    HAPServer.Types.USERNAME, usernameData,
    HAPServer.Types.PUBLIC_KEY, serverLTPK,
    HAPServer.Types.PROOF, serverProof
  );

  var ciphertextBuffer = Buffer(Array(message.length));
  var macBuffer = Buffer(Array(16));
  encryption.encryptAndSeal(hkdfEncKey, Buffer("PS-Msg06"), message, null, ciphertextBuffer, macBuffer);

  // finally, notify listeners that we have been paired with a client
  this.emit('pair', clientUsername.toString(), clientLTPK, once(function(err) {

    if (err) {
      debug("[%s] Error adding pairing info: %s", this.accessoryInfo.username, err.message);
      response.writeHead(500, "Server Error");
      response.end();
      return;
    }

    // send final pairing response to client
    response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
    response.end(tlv.encode(
      HAPServer.Types.SEQUENCE_NUM, 0x06,
      HAPServer.Types.ENCRYPTED_DATA, Buffer.concat([ciphertextBuffer,macBuffer])
    ));
  }));
}

/**
 * iOS <-> Accessory pairing verification.
 */

HAPServer.prototype._handlePairVerify = function(request, response, session, events, requestData) {
  // Don't allow pair-verify without being paired first
  if (!this.allowInsecureRequest && !this.accessoryInfo.paired()) {
    response.writeHead(403);
    response.end();

    return;
  }

  var objects = tlv.decode(requestData);
  var sequence = objects[HAPServer.Types.SEQUENCE_NUM][0]; // value is single byte with sequence number

  if (sequence == 0x01)
    this._handlePairVerifyStepOne(request, response, session, objects);
  else if (sequence == 0x03)
    this._handlePairVerifyStepTwo(request, response, session, events, objects);
}

HAPServer.prototype._handlePairVerifyStepOne = function(request, response, session, objects) {
  debug("[%s] Pair verify step 1/2", this.accessoryInfo.username);

  var clientPublicKey = objects[HAPServer.Types.PUBLIC_KEY]; // Buffer

  // generate new encryption keys for this session
  var secretKey = encryption.generateCurve25519SecretKey();
  var publicKey = encryption.generateCurve25519PublicKeyFromSecretKey(secretKey);
  var sharedSec = encryption.generateCurve25519SharedSecKey(secretKey, clientPublicKey);

  var usernameData = Buffer(this.accessoryInfo.username);
  var material = Buffer.concat([publicKey, usernameData, clientPublicKey]);
  var privateKey = Buffer(this.accessoryInfo.signSk);
  var serverProof = ed25519.Sign(material, privateKey);

  var encSalt = Buffer("Pair-Verify-Encrypt-Salt");
  var encInfo = Buffer("Pair-Verify-Encrypt-Info");

  var outputKey = hkdf.HKDF("sha512", encSalt, sharedSec, encInfo, 32).slice(0,32);

  // store keys in a new instance of HAPEncryption
  var enc = new HAPEncryption();
  enc.clientPublicKey = clientPublicKey;
  enc.secretKey = secretKey;
  enc.publicKey = publicKey;
  enc.sharedSec = sharedSec;
  enc.hkdfPairEncKey = outputKey;

  // store this in the current TCP session
  session.encryption = enc;

  // compose the response data in TLV format
  var message = tlv.encode(
    HAPServer.Types.USERNAME, usernameData,
    HAPServer.Types.PROOF, serverProof
  );

  // encrypt the response
  var ciphertextBuffer = Buffer(Array(message.length));
  var macBuffer = Buffer(Array(16));
  encryption.encryptAndSeal(outputKey, Buffer("PV-Msg02"), message, null, ciphertextBuffer, macBuffer);

  response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
  response.end(tlv.encode(
    HAPServer.Types.SEQUENCE_NUM, 0x02,
    HAPServer.Types.ENCRYPTED_DATA, Buffer.concat([ciphertextBuffer, macBuffer]),
    HAPServer.Types.PUBLIC_KEY, publicKey
  ));
}

HAPServer.prototype._handlePairVerifyStepTwo = function(request, response, session, events, objects) {
  debug("[%s] Pair verify step 2/2", this.accessoryInfo.username);

  var encryptedData = objects[HAPServer.Types.ENCRYPTED_DATA];

  var messageData = Buffer(encryptedData.length - 16);
  var authTagData = Buffer(16);
  encryptedData.copy(messageData, 0, 0, encryptedData.length - 16);
  encryptedData.copy(authTagData, 0, encryptedData.length - 16, encryptedData.length);

  var plaintextBuffer = Buffer(messageData.length);

  // instance of HAPEncryption (created in handlePairVerifyStepOne)
  var enc = session.encryption;

  if (!encryption.verifyAndDecrypt(enc.hkdfPairEncKey, Buffer("PV-Msg03"), messageData, authTagData, null, plaintextBuffer)) {
    debug("[%s] M3: Invalid signature", this.accessoryInfo.username);

    response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
    response.end(tlv.encode(
      HAPServer.Types.ERROR_CODE, HAPServer.Codes.INVALID_REQUEST
    ));

    return;
  }

  var decoded = tlv.decode(plaintextBuffer);
  var clientUsername = decoded[HAPServer.Types.USERNAME];
  var proof = decoded[HAPServer.Types.PROOF];

  var material = Buffer.concat([enc.clientPublicKey, clientUsername, enc.publicKey]);

  // since we're paired, we should have the public key stored for this client
  var clientPublicKey = this.accessoryInfo.getClientPublicKey(clientUsername.toString());

  // if we're not actually paired, then there's nothing to verify - this client thinks it's paired with us but we
  // disagree. Respond with invalid request (seems to match HomeKit Accessory Simulator behavior)
  if (!clientPublicKey) {
    debug("[%s] Client %s attempting to verify, but we are not paired; rejecting client", this.accessoryInfo.username, clientUsername);

    response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
    response.end(tlv.encode(
      HAPServer.Types.ERROR_CODE, HAPServer.Codes.INVALID_REQUEST
    ));

    return;
  }

  if (!ed25519.Verify(material, proof, clientPublicKey)) {
    debug("[%s] Client %s provided an invalid signature", this.accessoryInfo.username, clientUsername);

    response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
    response.end(tlv.encode(
      HAPServer.Types.ERROR_CODE, HAPServer.Codes.INVALID_REQUEST
    ));

    return;
  }

  debug("[%s] Client %s verification complete", this.accessoryInfo.username, clientUsername);

  response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
  response.end(tlv.encode(
    HAPServer.Types.SEQUENCE_NUM, 0x04
  ));

  // now that the client has been verified, we must "upgrade" our pesudo-HTTP connection to include
  // TCP-level encryption. We'll do this by adding some more encryption vars to the session, and using them
  // in future calls to onEncrypt, onDecrypt.

  var encSalt = new Buffer("Control-Salt");
  var infoRead = new Buffer("Control-Read-Encryption-Key");
  var infoWrite = new Buffer("Control-Write-Encryption-Key");

  enc.accessoryToControllerKey = hkdf.HKDF("sha512", encSalt, enc.sharedSec, infoRead, 32);
  enc.controllerToAccessoryKey = hkdf.HKDF("sha512", encSalt, enc.sharedSec, infoWrite, 32);

  // Our connection is now completely setup. We now want to subscribe this connection to special
  // "keepalive" events for detecting when connections are closed by the client.
  events['keepalive'] = true;
}

/**
 * Pair add/remove
 */

HAPServer.prototype._handlePairings = function(request, response, session, events, requestData) {

  // Only accept /pairing request if there is a secure session
  if (!this.allowInsecureRequest && !session.encryption) {
    response.writeHead(401, {"Content-Type": "application/hap+json"});
    response.end(JSON.stringify({status:HAPServer.Status.INSUFFICIENT_PRIVILEGES}));

    return;
  }

  var objects = tlv.decode(requestData);
  var requestType = objects[HAPServer.Types.REQUEST_TYPE][0]; // value is single byte with request type

  if (requestType == 3) {

    // technically we're already paired and communicating securely if the client is able to call /pairings at all!
    // but maybe the client wants to change their public key? so we'll emit 'pair' like we just paired again

    debug("[%s] Adding pairing info for client", this.accessoryInfo.username);
    var clientUsername = objects[HAPServer.Types.USERNAME];
    var clientLTPK = objects[HAPServer.Types.PUBLIC_KEY];

    this.emit('pair', clientUsername.toString(), clientLTPK, once(function(err) {

      if (err) {
        debug("[%s] Error adding pairing info: %s", this.accessoryInfo.username, err.message);
        response.writeHead(500, "Server Error");
        response.end();
        return;
      }

      response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
      response.end(tlv.encode(HAPServer.Types.SEQUENCE_NUM, 0x02));

    }.bind(this)));
  }
  else if (requestType == 4) {

    debug("[%s] Removing pairing info for client", this.accessoryInfo.username);
    var clientUsername = objects[HAPServer.Types.USERNAME];

    this.emit('unpair', clientUsername.toString(), once(function(err) {

      if (err) {
        debug("[%s] Error removing pairing info: %s", this.accessoryInfo.username, err.message);
        response.writeHead(500, "Server Error");
        response.end();
        return;
      }

      response.writeHead(200, {"Content-Type": "application/pairing+tlv8"});
      response.end(tlv.encode(HAPServer.Types.SEQUENCE_NUM, 0x02));

    }.bind(this)));
  }
}

/*
 * Handlers for all after-pairing communication, or the bulk of HAP.
 */

// Called when the client wishes to fetch all data regarding our published Accessories.
HAPServer.prototype._handleAccessories = function(request, response, session, events, requestData) {
  if (!this.allowInsecureRequest && !session.encryption) {
    response.writeHead(401, {"Content-Type": "application/hap+json"});
    response.end(JSON.stringify({status:HAPServer.Status.INSUFFICIENT_PRIVILEGES}));

    return;
  }

  // call out to listeners to retrieve the latest accessories JSON
  this.emit('accessories', once(function(err, accessories) {

    if (err) {
      debug("[%s] Error getting accessories: %s", this.accessoryInfo.username, err.message);
      response.writeHead(500, "Server Error");
      response.end();
      return;
    }

    response.writeHead(200, {"Content-Type": "application/hap+json"});
    response.end(JSON.stringify(accessories));
  }));
}

// Called when the client wishes to get or set particular characteristics
HAPServer.prototype._handleCharacteristics = function(request, response, session, events, requestData) {
  if (!this.allowInsecureRequest && !session.encryption) {
    response.writeHead(401, {"Content-Type": "application/hap+json"});
    response.end(JSON.stringify({status:HAPServer.Status.INSUFFICIENT_PRIVILEGES}));

    return;
  }

  if (request.method == "GET") {

    // Extract the query params from the URL which looks like: /characteristics?id=1.9,2.14,...
    var parseQueryString = true;
    var query = url.parse(request.url, parseQueryString).query; // { id: '1.9,2.14' }

    if(query == undefined || query.id == undefined) {
      response.writeHead(500);
      response.end();
      return;
    }

    var sets = query.id.split(','); // ["1.9","2.14"]
    var data = []; // [{aid:1,iid:9},{aid:2,iid:14}]

    for (var i in sets) {
      var ids = sets[i].split('.'); // ["1","9"]
      var aid = parseInt(ids[0]); // accessory ID
      var iid = parseInt(ids[1]); // instance ID (for characteristic)
      data.push({aid:aid,iid:iid});
    }

    this.emit('get-characteristics', data, events, function(err, characteristics) {

      if (!characteristics && !err)
        err = new Error("characteristics not supplied by the get-characteristics event callback");

      if (err) {
        debug("[%s] Error getting characteristics: %s", this.accessoryInfo.username, err.stack);

        // rewrite characteristics array to include error status for each characteristic requested
        characteristics = [];
        for (var i in data) {
          characteristics.push({
            aid: data[i].aid,
            iid: data[i].iid,
            status: HAPServer.Status.SERVICE_COMMUNICATION_FAILURE
          });
        }
      }

      // 207 is "multi-status" since HomeKit may be requesting multiple things and any one can fail independently
      response.writeHead(207, {"Content-Type": "application/hap+json"});
      response.end(JSON.stringify({characteristics:characteristics}));

    }.bind(this));
  }
  else if (request.method == "PUT") {
    if (!session.encryption) {
      if (!request.headers || (request.headers && request.headers["authorization"] !== this.accessoryInfo.pincode)) {
        response.writeHead(401, {"Content-Type": "application/hap+json"});
        response.end(JSON.stringify({status:HAPServer.Status.INSUFFICIENT_PRIVILEGES}));

        return;
      }
    }

    if(requestData.length == 0) {
      response.writeHead(400, {"Content-Type": "application/hap+json"});
      response.end(JSON.stringify({status:HAPServer.Status.INVALID_VALUE_IN_REQUEST}));

      return;
    }

    // requestData is a JSON payload like { characteristics: [ { aid: 1, iid: 8, value: true, ev: true } ] }
    var data = JSON.parse(requestData.toString()).characteristics; // pull out characteristics array

    // call out to listeners to retrieve the latest accessories JSON
    this.emit('set-characteristics', data, events, once(function(err, characteristics) {

      if (err) {
        debug("[%s] Error setting characteristics: %s", this.accessoryInfo.username, err.message);

        // rewrite characteristics array to include error status for each characteristic requested
        characteristics = [];
        for (var i in data) {
          characteristics.push({
            aid: data[i].aid,
            iid: data[i].iid,
            status: HAPServer.Status.SERVICE_COMMUNICATION_FAILURE
          });
        }
      }

      // 207 is "multi-status" since HomeKit may be setting multiple things and any one can fail independently
      response.writeHead(207, {"Content-Type": "application/hap+json"});
      response.end(JSON.stringify({characteristics:characteristics}));

    }.bind(this)));
  }
}

/**
 * Simple struct to hold vars needed to support HAP encryption.
 */

function HAPEncryption() {
  // initialize member vars with null-object values
  this.clientPublicKey = new Buffer(0);
  this.secretKey = new Buffer(0);
  this.publicKey = new Buffer(0);
  this.sharedSec = new Buffer(0);
  this.hkdfPairEncKey = new Buffer(0);
  this.accessoryToControllerCount = { value: 0 };
  this.controllerToAccessoryCount = { value: 0 };
  this.accessoryToControllerKey = new Buffer(0);
  this.controllerToAccessoryKey = new Buffer(0);
}


text:
<?php
/**
 * @file
 * Responsive Green theme implementation to display regions.
 */
?>
<?php if (!empty($content)): ?>
<div class="<?php print $classes; ?>">
  <?php print $content; ?>
</div>
<?php endif; ?> <!-- /.region -->


text:
(async function() {
  TestRunner.addResult(`Tests that non-standard mixed-cased properties are displayed in the Styles pane.\n`);
  await TestRunner.loadLegacyModule('elements'); await TestRunner.loadTestModule('elements_test_runner');
  await TestRunner.showPanel('elements');
  await TestRunner.loadHTML(`

    `);

  ElementsTestRunner.selectNodeAndWaitForStylesWithComputed('nested', step1);

  async function step1() {
    await ElementsTestRunner.dumpSelectedElementStyles();
    TestRunner.completeTest();
  }
})();


text:
require File.join(File.dirname(__FILE__), '..', 'spec_helper.rb')

describe  "/stork-forum/" do

  before(:all) do
    mount_slice
  end

  describe "GET /" do

    before(:each) do
      @response = request("/stork-forum/")
    end

    it "should be successful" do
      @response.status.should be_successful
    end

    # This is just an example of what you can do
    # You can also use the other webrat methods to click links,
    # fill up forms etc...
    it "should render the default slice layout" do
      @response.should have_tag(:h1, :content => "StorkForum Slice")
      @response.should have_selector("div#container div#main")
      @response.should have_xpath("//div[@id='container']/div[@id='main']")
    end

  end

end


text:
{% extends "layout.html" %}

{% block page_title %}
  Apprenticeships
{% endblock %}

{% block content %}

{% include "includes/phase_banner_alpha.html" %}
{% include "includes/secondary-nav-provider.html" %}

      {% include "includes/breadcrumbs/register-back.html" %}

Choose training

Choose the training course that your apprentices will be taking - you'll have the option to add more courses later.

                <form id="checkTrainingForm" action="add-an-apprenticeship/training-list">
                    <input id="checkTrainingSource" name="source" type="hidden" value="employer" />
                    <fieldset>
                      <legend class="visuallyhidden">Enter the name of the framework or standard.</legend>

                            Apprenticeship training course
                        Search for the training by course name or code

                            <input class="form-control" id="search-for-training" type="text" style="width:90%">

                      </fieldset>
                </form>

       <input class="button" id="saveAndContinue" type="button" onclick="whereNow()" value="Continue">

Previous courses

Bulk upload  apprentices to a course you've used previously:

                            Mechatronics engineer, level 3

                            Mechatronics engineer, level 4

                            Bakery assistant, level 1

{% endblock %}


text:
Lightweight wrapper aroound storekit for easy In-App Purchases. Will be refactored soon to use completion blocks!

## Installation using Cocoapods
```
pod 'BDGInAppPurchase'
```


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Geomicons</title>
  <meta name="author" content="Jxnblk">
  <meta name="description" content="Open Source Icons for The Web">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="docs/assets/favicon.png">
  <link rel="stylesheet" href="http://d2v52k3cl9vedd.cloudfront.net/basscss/4.1.3/base.min.css">
  <link rel="stylesheet" href="docs/assets/base.min.css">

Geomicons

Open Source Icons for the Web

          Github

Fast, Plain & Simple

Smaller than similar webfonts and with fewer network requests than other solutions, Geomicons Open is built from the ground up for performance. Designed on a grid for pixel-precision at standard sizes, each icon is hand-coded to avoid the extra bloat from traditional vector drawing applications.

Getting Started

Download the source or grab Geomicons Open from one of these sources:

git clone https://github.com/jxnblk/geomicons-open.git

npm install geomicons-open

<link rel="stylesheet" href="http://d2v52k3cl9vedd.cloudfront.net/geomicons/0.2.0/geomicons.min.js">

Add a data-icon attribute with the name of the icon to inject.

<span class="js-geomicon" data-icon="heart"></span>

      Pass a nodelist to the Geomicons.inject() method.

<script>
  var icons = document.querySelectorAll('.js-geomicon');
  Geomicons.inject(icons);
</script>

Style with CSS

<style>
  .geomicon { width: 1em; height: 1em; }
  .red { color: red }
</style>
<span class="js-geomicon geomicon red" data-id="heart"></span>

Or, if you’re just using one or two, copy and paste the SVG code from the icons on this page.

Learn More

Download and learn more about how to use Geomicons on Github.

    View on Github

Other Geomicons Products

Geomicons Squared

Symbolset Webfont with a Friendly Demeanor

Geomicons Wired

The Original Outlined Icons

            Tweet

            Made with love by
            Jxnblk

    Toast Test


text:
#region Usings

using System;
using System.Collections.Generic;

#endregion

namespace de.ahzf.Styx
{

    /// <summary>
    /// Emits the path that the traverser has taken up to this object.
    /// In other words, it uses the Path property of the previous pipe
    /// to emit the transformation stages.
    /// </summary>
    /// <typeparam name="S">The type of the consuming objects.</typeparam>
    public class PathPipe<S> : AbstractPipe<S, IEnumerable<Object>>, IEndPipe<IEnumerable<Object>>
    {

        #region MoveNext()

        /// <summary>
        /// Advances the enumerator to the next element of the collection.
        /// </summary>
        /// <returns>
        /// True if the enumerator was successfully advanced to the next
        /// element; false if the enumerator has passed the end of the
        /// collection.
        /// </returns>
        public override Boolean MoveNext()
        {

            if (_InternalEnumerator == null)
                return false;

            if (_InternalEnumerator is IPipe)
            {

                if (_InternalEnumerator.MoveNext())
                {
                    _CurrentElement = ((IPipe) _InternalEnumerator).Path;
                    return true;
                }

                return false;

            }

            else
                throw new NoSuchElementException("The source of this pipe was not a pipe!");

        }

        #endregion

    }

}


text:
require('../spec_helper');

let SolveHelper;

describe('SolveHelper', () => {
  beforeEach(() => {
    SolveHelper = require('helpers/solve_helper');
  });

  describe('#computeWeight', () => {
    describe('when the coef is an element', () => {
      it('computes the correct molecular weight', () => {
        expect(SolveHelper.computeWeight('C', 0)).toEqual('12.0000000');
        expect(SolveHelper.computeWeight('C', 7)).toEqual('11.9961598');
      });
    });

    describe('when the coef is a molecule', () => {
      it('computes the correct molecular weight', () => {
        expect(SolveHelper.computeWeight('C6H12O6', 0)).toEqual('180.063390');
        expect(SolveHelper.computeWeight('C6H12O6', -4)).toEqual('180.065584');
      });
    });

    describe('when the coef is a fragment', () => {
      it('computes the correct molecular weight', () => {
        expect(SolveHelper.computeWeight('tBuPy', 0)).toEqual('135.104799');
        expect(SolveHelper.computeWeight('tBuPy', -4)).toEqual('135.106993');
      });
    });

    describe('when the coef is not valid', () => {
      it('returns null', () => {
        expect(SolveHelper.computeWeight('s', 0)).toEqual(null);
        expect(SolveHelper.computeWeight('s', 7)).toEqual(null);
      });
    });
  });

  describe('#parseNumeric', () => {
    it('strips nonnumeric characters from strings (but leaves them as strings)', () => {
      expect(SolveHelper.parseNumeric('123')).toEqual('123');
      expect(SolveHelper.parseNumeric('-123')).toEqual('-123');
      expect(SolveHelper.parseNumeric('a12b3c')).toEqual('123');
      expect(SolveHelper.parseNumeric('1.23')).toEqual('1.23');
    });
  });

  describe('#solveDisabled', () => {
    it('is true if solving is true', () => {
      expect(SolveHelper.solveDisabled(true, [{weight: 5}], 3, 0.02)).toEqual(true);
    });

    it('is true if rows is empty', () => {
      expect(SolveHelper.solveDisabled(false, [], 3, 0.02)).toEqual(true);
    });

    it('is true if there is a row with no weight', () => {
      expect(SolveHelper.solveDisabled(false, [{weight: null}], 3, 0.02)).toEqual(true);
      expect(SolveHelper.solveDisabled(false, [{id: '1', weight: 0}], 3, 0.02)).toEqual(true);
    });

    it('is true if total mass is zero or not set', () => {
      expect(SolveHelper.solveDisabled(false, [{weight: 5}], 0, 0.02)).toEqual(true);
      expect(SolveHelper.solveDisabled(false, [{weight: 5}], '', 0.02)).toEqual(true);
    });

    it('is true if max error is not set', () => {
      expect(SolveHelper.solveDisabled(false, [{weight: 5}], 3, '')).toEqual(true);
    });

    it('is false if max error is zero', () => {
      expect(SolveHelper.solveDisabled(false, [{weight: 5}], 3, 0)).toEqual(false);
    });

    it('is false if max error is nonzero', () => {
      expect(SolveHelper.solveDisabled(false, [{weight: 5}], 3, 0.02)).toEqual(false);
    });
  });

  describe('#numCombinations', () => {
    it('calculates the max number of combinations of elements (not considering the target weight)', () => {
      expect(SolveHelper.numCombinations([
        {weight: '350.54435', range: {min: '2', max: '6'}},
        {weight: '234.23', range: {min: '0', max: '3.2'}},
        {weight: '47', range: {min: '0', max: '4'}},
        {weight: '12.34', range: {min: '1', max: '10'}}
      ])).toEqual(1000);
    });
  });

  describe('#formatRows', () => {
    it('parses string data into floats and ints', () => {
      expect(SolveHelper.formatRows([
        {weight: '350.54435', range: {min: '2', max: '6'}},
        {weight: '234.23', range: {min: '0', max: '3.2'}},
        {weight: '47', range: {min: '0', max: '4'}},
        {weight: '12.34', range: {min: '1', max: '10'}}
      ])).toEqual([
        {weight: 350.54435, range: {min: 2, max: 6}},
        {weight: 234.23, range: {min: 0, max: 3}},
        {weight: 47, range: {min: 0, max: 4}},
        {weight: 12.34, range: {min: 1, max: 10}}
      ]);
    });
  });
});


text:
<!DOCTYPE HTML>

  <title>Test for Content Security Policy "no eval" base restriction</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />


text:
class ApplicationController
  def setup_classTree!
    self.class_tree = ClassTreeNode.classTreeNodesWithHashTree(Manager.instance.namespace)
    @classTreeController.addObserver(self,
       forKeyPath: 'selectionIndexPaths',
          options: NSKeyValueObservingOptionNew,
          context: nil
    )
  end
end


text:
let assert = require('chai').assert;
let restify = require('restify');
let async = require('async');

import { Descriptor } from 'pip-services-commons-node';
import { ConfigParams } from 'pip-services-commons-node';
import { References } from 'pip-services-commons-node';

import { HeartbeatRestService } from '../../src/status/HeartbeatRestService';

var restConfig = ConfigParams.fromTuples(
    "connection.protocol", "http",
    "connection.host", "localhost",
    "connection.port", 3000
);

suite('HeartbeatRestService', ()=> {
    let service: HeartbeatRestService;
    let rest: any;

    suiteSetup((done) => {
        service = new HeartbeatRestService();
        service.configure(restConfig);

        service.open(null, done);
    });

    suiteTeardown((done) => {
        service.close(null, done);
    });

    setup(() => {
        let url = 'http://localhost:3000';
        rest = restify.createJsonClient({ url: url, version: '*' });
    });

    test('Status', (done) => {
        rest.get('/heartbeat',
            (err, req, res, result) => {
                assert.isNull(err);

                assert.isNotNull(result);

                done();
            }
        );
    });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<ldswebml type="image" uri="/media-library/images/motherhood#teens-homework-244472" xml:lang="eng" locale="eng" status="publish">
  <search-meta>
      <uri-title its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">teens-homework-244472</uri-title>
      <source>teens-homework-244472</source>
      <publication-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</publication-type>
      <media-type its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">image</media-type>
      <publication value="ldsorg">LDS.org</publication>
      <publication-date value="2012-04-09">2012-04-09</publication-date>
      <title/>
      <description/>
      <collections>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">global-search</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">media</collection>
          <collection its:translate="no" xmlns:its="http://www.w3.org/2005/11/its">images</collection>
      </collections>
      <subjects>
          <subject>children</subject>
          <subject>family</subject>
          <subject>families</subject>
          <subject>parents</subject>
          <subject>mothers</subject>
          <subject>teaching</subject>
          <subject>learning</subject>
          <subject>talking</subject>
          <subject>kitchen</subject>
          <subject>tables</subject>
          <subject>homework</subject>
          <subject>helping</subject>
          <subject>teenagers</subject>
      </subjects>
  </search-meta>
  <no-search>
      <path>http://media.ldscdn.org/images/media-library/motherhood/teens-homework-244472-gallery.jpg</path>
      <images>
          http://media.ldscdn.org/images/media-library/motherhood/teens-homework-244472-thumbnail.jpg
      </images>
          <download-urls>
              <download-url>
                  Mobile
                  <size>144 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/motherhood/teens-homework-244472-mobile.jpg</path>
              </download-url>
              <download-url>
                  Tablet
                  <size>162 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/motherhood/teens-homework-244472-tablet.jpg</path>
              </download-url>
              <download-url>
                  Print
                  <size>359 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/motherhood/teens-homework-244472-print.jpg</path>
              </download-url>
              <download-url>
                  Wallpaper
                  <size>761 KB</size>
                  <path>http://media.ldscdn.org/images/media-library/motherhood/teens-homework-244472-wallpaper.jpg</path>
              </download-url>
          </download-urls>
  </no-search>
<ldse-meta its:translate="no" xmlns="http://lds.org/code/lds-edit" xmlns:its="http://www.w3.org/2005/11/its"><document id="teens-homework-244472" locale="eng" uri="/media-library/images/motherhood#teens-homework-244472" status="publish" site="ldsorg" source="chq" words="120" tgp="0.4196"/><created username="lds-edit" userid=""/><last-modified date="2012-05-10T12:26:23.573084-06:00" username="lds-edit" userid=""/></ldse-meta></ldswebml>


text:
/**
 * Built-in Report API plug-ins.
 */
package com.asakusafw.runtime.report;


text:
default['firewall']['windows']['defaults'] = {
  policy: {
    input: 'blockinbound',
    output: 'allowoutbound',
  },
}


text:
<?php
namespace accounting\clients\web\controllers;

use accounting\aplication\ModifyAccountName;
use accounting\aplication\ViewAccount;

class ModifyAccountController extends BaseController
{
	public function execute($request, $response)
	{
		$usecase = new ModifyAccountName($this->getRepository('account'), $this->getIdsGenerator('account'));
		$usecase->execute($request["id"], $request["name"]);

		$usecase = new ViewAccount($this->getRepository('account'), $this->getIdsGenerator('account'));
		$result = $usecase->execute($request['id']);
		$this->render("modify-account", $result);
	}
}


text:
 /
public interface OMEventMacroFilter {
    /**
     * @param listOfEvents a list of events that are currently going to be
     *        displayed in the GUI.
     * @return a filtered list of events that pass the criteria set by this
     *         filter.
     */
    public List<OMEvent> getMacroFilteredList(List<OMEvent> listOfEvents);
}


text:
package helpers

import play.api.mvc.{ActionBuilder, WrappedRequest, Request, ActionTransformer}
import scala.concurrent.Future

trait ConditionalLayout {

  class ConditionalLayoutRequest[A](
    val requiresLayout: Boolean,
    request: Request[A]) extends WrappedRequest[A](request)

  object ConditionalLayoutAction extends ActionBuilder[ConditionalLayoutRequest] with ActionTransformer[Request, ConditionalLayoutRequest] {
    override protected def transform[A](request: Request[A]) = Future.successful {
      val layoutRequired = request.headers.get("X-PJAX") != Some("true")
      new ConditionalLayoutRequest[A](requiresLayout = layoutRequired, request)
    }
  }

}


text:
class GreenBlockExplodeBmp : public WoopsiGfx::BitmapWrapper {
public:
	GreenBlockExplodeBmp();
};

#endif


text:
using System;
using System.Collections.Generic;
using System.IO;

namespace Nezaboodka.Ndef
{
    public abstract class AbstractNdefReader : INdefReader
    {
        private NdefDataSet BufferDataSet;
        protected NdefObject BufferObject; // TODO: Eliminate protected
        private List<NdefObject> fObjectPath;
        private int fObjectLevel;

        // Public

        public NdefDataSet CurrentDataSet { get; private set; }
        public NdefObject CurrentObject { get; private set; }
        public NdefElement CurrentElement { get { return CurrentObject.CurrentElement; } }
        public Func<string, string> SubstituteObjectKey { get; set; }

        protected AbstractNdefReader()
        {
            BufferDataSet = new NdefDataSet();
            BufferDataSet.IsImplicit = true;
            BufferObject = new NdefObject();
            fObjectPath = new List<NdefObject>();
            fObjectPath.Add(null); // root
            CurrentDataSet = new NdefDataSet();
            CurrentObject = new NdefObject();
        }

        protected abstract bool MoveToNextLine();

        public virtual bool MoveToNextDataSet()
        {
            bool result = true;
            if (CurrentDataSet.IsEndOfDataSet)
                CurrentDataSet.Clear();
            if (IsBufferEmpty)
                result = MoveToNextLine();
            if (BufferDataSet.Header != null || BufferDataSet.IsImplicit)
            {
                CurrentDataSet.Header = Take(ref BufferDataSet.Header);
                CurrentDataSet.IsImplicit = Take(ref BufferDataSet.IsImplicit);
                CurrentDataSet.IsStartOfDataSet = Take(ref BufferDataSet.IsStartOfDataSet);
                CurrentDataSet.IsEndOfDataSet = Take(ref BufferDataSet.IsEndOfDataSet);
            }
            return result;
        }

        public virtual bool MoveToNextObject()
        {
            if (CurrentObject.IsEndOfObject)
                CurrentObject = SwitchToParentObject();
            else if (fObjectPath.Count > fObjectLevel + 1 && fObjectPath[fObjectLevel + 1] != null && fObjectPath[fObjectLevel + 1].IsStartOfObject)
                CurrentObject = SwitchToNestedObject();
            if (IsBufferEmpty)
                MoveToNextLine();
            if (!BufferObject.Header.IsEmpty)
            {
                bool isListItem = Take(ref BufferObject.Header.IsListItem);
                string typeName = Take(ref BufferObject.Header.TypeName);
                NdefObjectKind kind = Take(ref BufferObject.Header.Kind);
                string number = Take(ref BufferObject.Header.Number);
                string key = Take(ref BufferObject.Header.Key);
                InitializeNestedObject(isListItem, typeName, kind, number, key);
                CurrentObject = SwitchToNestedObject();
            }
            return !CurrentObject.Header.IsEmpty;
        }

        public virtual bool MoveToNextElement()
        {
            bool result = CurrentObject.IsBackFromNestedObject;
            if (!result)
            {
                if (IsBufferEmpty)
                {
                    if (CurrentElement.Value.AsStream != null)
                    {
                        CurrentElement.Value.AsStream.Close();
                        CurrentObject.CurrentElement.Value.AsStream = null;
                    }
                    MoveToNextLine();
                }
                result = BufferObject.CurrentElement.Field.Name != null ||
                    !BufferObject.CurrentElement.Value.IsUndefined;
                if (result)
                {
                    CurrentObject.CurrentElement = Take(ref BufferObject.CurrentElement);
                    NdefObject nestedObject = CurrentObject.CurrentElement.Value.AsNestedObjectToDeserialize;
                    if (nestedObject != null)
                    {
                        BufferObject.Header.TypeName = nestedObject.Header.TypeName;
                        BufferObject.Header.Kind = nestedObject.Header.Kind;
                        BufferObject.Header.Number = nestedObject.Header.Number;
                        BufferObject.Header.Key = nestedObject.Header.Key;
                    }
                }
            }
            else
                CurrentObject.IsBackFromNestedObject = false;
            return result;
        }

        // Protected

        protected virtual bool IsBufferEmpty
        {
            get
            {
                return
                    !CurrentDataSet.IsEndOfDataSet &&
                    BufferDataSet.Header == null &&
                    !CurrentObject.IsEndOfObject &&
                    BufferObject.Header.IsEmpty &&
                    BufferObject.CurrentElement.Field.Name == null &&
                    BufferObject.CurrentElement.Value.IsUndefined;
            }
        }

        protected void PutDataSetStartToBuffer(string header)
        {
            if (BufferDataSet.Header == null)
            {
                if (CurrentDataSet.IsEndOfDataSet || CurrentDataSet.Header == null)
                {
                    BufferDataSet.Header = header;
                    BufferDataSet.IsImplicit = false;
                    BufferDataSet.IsStartOfDataSet = true;
                }
                else
                {
                    if (IsBufferEmpty)
                        throw new FormatException("data set cannot be nested");
                    else
                        throw new FormatException("cannot read value: buffer is full");
                }
            }
            else
                throw new FormatException("cannot read data set: buffer is full");
        }

        protected void PutDataSetEndOrExtensionToBuffer(bool isExtension)
        {
            bool isBufferEmpty = !CurrentDataSet.IsEndOfDataSet &&
                BufferObject.CurrentElement.Field.Name == null &&
                BufferObject.CurrentElement.Value.IsUndefined;
            if (isBufferEmpty)
            {
                if (isExtension)
                    BufferDataSet.Header = CurrentDataSet.Header;
                else
                    CurrentDataSet.IsEndOfDataSet = true;
            }
            else
                throw new FormatException("cannot write end of data set: buffer is full");
        }

        protected void PutObjectStartToBuffer(bool isListItem, string type, NdefObjectKind kind,
            string number, string key)
        {
            if (BufferObject.Header.IsEmpty)
            {
                if (SubstituteObjectKey != null)
                    key = SubstituteObjectKey(key);
                if (!CurrentObject.IsEndOfObject && !CurrentObject.Header.IsEmpty)
                {
                    if (BufferObject.CurrentElement.Value.IsUndefined)
                    {
                        //if (isList && string.IsNullOrEmpty(type) && string.IsNullOrEmpty(key) &&
                        //    string.IsNullOrEmpty(BufferObject.CurrentFieldOrListItem.FieldName))
                        //    throw new FormatException("cannot read list item: current object is not a list");
                        BufferObject.CurrentElement.Field.Kind = NdefFieldKind.SetOrAdd;
                        BufferObject.CurrentElement.Value.AsNestedObjectToDeserialize =
                            InitializeNestedObject(isListItem, type, kind, number, key);
                        if (BufferObject.CurrentElement.Value.Kind != NdefValueKind.Object)
                            throw new ArgumentException("cannot put value to the buffer as a nested object");
                    }
                    else
                        throw new FormatException("cannot read value: buffer is full");
                }
                else
                {
                    BufferObject.Header.TypeName = type;
                    BufferObject.Header.Kind = kind;
                    BufferObject.Header.Number = number;
                    BufferObject.Header.Key = key;
                }
            }
            else
                throw new FormatException("cannot read object: buffer is full");
        }

        protected void PutObjectEndToBuffer()
        {
            bool isBufferEmpty = !CurrentObject.IsEndOfObject &&
                BufferObject.CurrentElement.Field.Name == null &&
                BufferObject.CurrentElement.Value.IsUndefined;
            if (isBufferEmpty)
                CurrentObject.IsEndOfObject = true;
            else
                throw new FormatException("cannot write end of object: buffer is full");
        }

        protected void PutFieldNameToBuffer(string name)
        {
            if (BufferObject.CurrentElement.Field.Name == null)
            {
                BufferObject.CurrentElement.Field.Number = -1; // not implemented yet
                BufferObject.CurrentElement.Field.Name = name;
            }
            else
                throw new FormatException("cannot read field: buffer is full");
        }

        protected void PutListItemToBuffer(bool removed)
        {
            if (CurrentObject.Header.Kind == NdefObjectKind.List)
            {
                if (BufferObject.CurrentElement.Value.IsUndefined)
                {
                    BufferObject.CurrentElement.Field.Kind = removed ? NdefFieldKind.Remove : NdefFieldKind.SetOrAdd;
                    if (BufferObject.CurrentElement.Value.Kind == NdefValueKind.Object)
                        throw new ArgumentException("cannot put object or list to the buffer as an item");
                }
                else
                    throw new FormatException("cannot read value: buffer is full");
            }
            else
                throw new FormatException("cannot read list item: current object is not a list");
        }

        protected void PutValueToBuffer(string explicitTypeName, string scalar, string number, string key)
        {
            if (BufferObject.CurrentElement.Value.IsUndefined)
            {
                if (SubstituteObjectKey != null)
                    key = SubstituteObjectKey(key);
                BufferObject.CurrentElement.Value.ActualSerializableTypeName = explicitTypeName;
                BufferObject.CurrentElement.Value.AsScalar = scalar;
                BufferObject.CurrentElement.Value.AsObjectNumber = number;
                BufferObject.CurrentElement.Value.AsObjectKey = key;
                if (BufferObject.CurrentElement.Value.Kind == NdefValueKind.Object)
                    throw new ArgumentException("cannot put object or list to the buffer");
            }
            else
                throw new FormatException("cannot read value: buffer is full");
        }

        protected void PutStreamToBuffer(Stream stream)
        {
            BufferObject.CurrentElement.Value.AsStream = stream;
        }

        protected void PutCommentToBuffer(string comment)
        {
            BufferObject.CurrentElement.Comment = comment;
        }

        // Internal

        private NdefObject InitializeNestedObject(bool isListItem, string typeName, NdefObjectKind kind,
            string number, string key)
        {
            while (fObjectPath.Count <= fObjectLevel + 1)
                fObjectPath.Add(null);
            var result = new NdefObject();
            result.Header.IsListItem = isListItem;
            result.Header.TypeName = typeName;
            result.Header.Kind = kind;
            result.Header.Number = number;
            result.Header.Key = key;
            result.Parent = fObjectPath[fObjectLevel]; // CurrentObject
            result.IsStartOfObject = true;
            fObjectPath[fObjectLevel + 1] = result;
            return result;
        }

        private NdefObject SwitchToNestedObject()
        {
            BufferObject.Clear();
            if (fObjectLevel > 0)
                fObjectPath[fObjectLevel].IsStartOfObject = false;
            fObjectLevel++;
            NdefObject result = fObjectPath[fObjectLevel];
            return result;
        }

        private NdefObject SwitchToParentObject()
        {
            fObjectPath[fObjectLevel] = null;
            fObjectLevel--;
            NdefObject result = fObjectPath[fObjectLevel];
            if (result != null)
                result.IsBackFromNestedObject = true;
            else
                result = new NdefObject();
            return result;
        }

        private T Take<T>(ref T variable)
        {
            var result = variable;
            variable = default(T);
            return result;
        }
    }
}


text:
package de.arthurkaul.archref.services.types;

import java.util.Collection;

import de.arthurkaul.archref.model.types.NodeType;;

/********************************************************************************************************************************************************************************************************
 *
 * @interface - NodeTypeInterface - Interface for the NodeTypes define all Methods which should be implemented by this interface.
 *
 * @author - Arthur Kaul
 *
 *******************************************************************************************************************************************************************************************************/
public interface NodeTypeInterface {

	Collection<NodeType> findAllNodeTypes();

	NodeType findById(long id);

	NodeType create(NodeType nodeType);

	NodeType update(NodeType nodeType);

	void delete(long id);

	void deleteAllNodeTypes();

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package chat.data.model.conversion;

import chat.data.model.Contact;
import chat.database.beans.User;

/**
 *
 * @author sharno
 */
public class Converter {
    static public Contact fromUserToContact (User user) {
        Contact c = new Contact();

        c.setBirthdate(user.getBdate());
        c.setEmail(user.getEmail());
        c.setFname(user.getFname());
        c.setLname(user.getLname());
        c.setGender((int) user.getGender());
        c.setId((int) user.getIduser());
        c.setPass(user.getPassword());
        c.setStatus((int) user.getStatus());
        return c;
    }
}