text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LeanCloud.Realtime.Internal;
using LeanCloud;
using LeanCloud.Storage.Internal;
using System.Collections;
using LeanCloud.Core.Internal;

namespace LeanCloud.Realtime
{
    /// <summary>
    /// 对话
    /// </summary>
    public class AVIMConversation : IEnumerable<KeyValuePair<string, object>>
    {

        private DateTime? updatedAt;

        private DateTime? createdAt;

        private DateTime? lastMessageAt;

        private AVObject convState;

        internal readonly Object mutex = new Object();
        //private readonly IDictionary<string, object> estimatedData = new Dictionary<string, object>();

        internal AVIMClient _currentClient;

        IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>
    .GetEnumerator()
        {
            lock (mutex)
            {
                return ((IEnumerable<KeyValuePair<string, object>>)convState).GetEnumerator();
            }
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            lock (mutex)
            {
                return ((IEnumerable<KeyValuePair<string, object>>)convState).GetEnumerator();
            }
        }
        virtual public object this[string key]
        {
            get
            {
                return convState[key];
            }
            set
            {
                convState[key] = value;
            }
        }
        public ICollection<string> Keys
        {
            get
            {
                lock (mutex)
                {
                    return convState.Keys;
                }
            }
        }

        internal IDictionary<string, object> EncodeAttributes()
        {
            var currentOperations = convState.StartSave();
            var jsonToSave = AVObject.ToJSONObjectForSaving(currentOperations);
            return jsonToSave;
        }
        internal void MergeFromPushServer(IDictionary<string, object> json)
        {
            if (json.Keys.Contains("cdate"))
            {
                createdAt = DateTime.Parse(json["cdate"].ToString());
                updatedAt = DateTime.Parse(json["cdate"].ToString());
                json.Remove("cdate");
            }
            if (json.Keys.Contains("lm"))
            {
                var ts = double.Parse(json["lm"].ToString());
                updatedAt = ts.UnixTimeStampSeconds();
                lastMessageAt = ts.UnixTimeStampSeconds();
                json.Remove("lm");
            }
            if (json.Keys.Contains("c"))
            {
                Creator = json["c"].ToString();
                json.Remove("c");
            }
            if (json.Keys.Contains("m"))
            {
                MemberIds = json["m"] as IList<string>;
                json.Remove("m");
            }
            if (json.Keys.Contains("mu"))
            {
                MuteMemberIds = json["mu"] as IList<string>;
                json.Remove("mu");
            }
            if (json.Keys.Contains("tr"))
            {
                IsTransient = bool.Parse(json["tr"].ToString());
                json.Remove("tr");
            }
            if (json.Keys.Contains("sys"))
            {
                IsSystem = bool.Parse(json["sys"].ToString());
                json.Remove("sys");
            }
            if (json.Keys.Contains("cid"))
            {
                ConversationId = json["cid"].ToString();
                json.Remove("cid");
            }

            if (json.Keys.Contains("name"))
            {
                Name = json["name"].ToString();
                json.Remove("name");
            }
            if (json.Keys.Contains("attr"))
            {

            }
        }

        /// <summary>
        /// 当前的AVIMClient,一个对话理论上只存在一个AVIMClient。
        /// </summary>
        public AVIMClient CurrentClient
        {
            get
            {
                return _currentClient;
            }
            set
            {
                _currentClient = value;
            }
        }
        /// <summary>
        /// 对话的唯一ID
        /// </summary>
        public string ConversationId { get; internal set; }

        /// <summary>
        /// 对话在全局的唯一的名字
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 对话中存在的 Client 的 Id 列表
        /// </summary>
        public IList<string> MemberIds { get; internal set; }

        /// <summary>
        /// 对该对话静音的成员列表
        /// <remarks>
        /// 对该对话设置了静音的成员,将不会收到离线消息的推送。
        /// </remarks>
        /// </summary>
        public IList<string> MuteMemberIds { get; internal set; }

        /// <summary>
        /// 对话的创建者
        /// </summary>
        public string Creator { get; private set; }

        /// <summary>
        /// 是否为聊天室
        /// </summary>
        public bool IsTransient { get; internal set; }

        /// <summary>
        /// 是否系统对话
        /// </summary>
        public bool IsSystem { get; internal set; }

        /// <summary>
        /// 对话创建的时间
        /// </summary>
        public DateTime? CreatedAt
        {
            get
            {
                DateTime? nullable;
                lock (this.mutex)
                {
                    nullable = this.createdAt;
                }
                return nullable;
            }
            private set
            {
                lock (this.mutex)
                {
                    this.createdAt = value;
                }
            }
        }

        /// <summary>
        /// 对话更新的时间
        /// </summary>
        public DateTime? UpdatedAt
        {
            get
            {
                DateTime? nullable;
                lock (this.mutex)
                {
                    nullable = this.updatedAt;
                }
                return nullable;
            }
            private set
            {
                lock (this.mutex)
                {
                    this.updatedAt = value;
                }
            }
        }

        public DateTime? LastMessageAt
        {
            get
            {
                DateTime? nullable;
                lock (this.mutex)
                {
                    nullable = this.lastMessageAt;
                }
                return nullable;
            }
            private set
            {
                lock (this.mutex)
                {
                    this.lastMessageAt = value;
                }
            }
        }

        /// <summary>
        /// 对话的自定义属性
        /// </summary>
        [System.Obsolete("不再推荐使用,请使用 AVIMConversation[key] = value,新版的 ConversationQuery 不再支持查询 Attributes 字段的内部属性。")]
        public IDictionary<string, object> Attributes
        {
            get
            {
                return fetchedAttributes.Merge(pendingAttributes);
            }
            private set
            {
                Attributes = value;
            }
        }
        internal IDictionary<string, object> fetchedAttributes;
        internal IDictionary<string, object> pendingAttributes;

        /// <summary>
        /// 已知 id,在本地构建一个 AVIMConversation 对象
        /// </summary>
        public AVIMConversation(string id)
            : this(null, null, null, null, null, false, false, null)
        {
            this.ConversationId = id;
        }

        /// <summary>
        /// AVIMConversation Build 驱动器
        /// </summary>
        /// <param name="source"></param>
        /// <param name="name"></param>
        /// <param name="members"></param>
        /// <param name="isTransient"></param>
        /// <param name="attributes"></param>
        internal AVIMConversation(AVIMConversation source = null,
            string name = null,
            string creator = null,
            IList<string> members = null,
            IList<string> muteMembers = null,
            bool isTransient = false,
            bool isSystem = false,
            IDictionary<string, object> attributes = null)
        {
            convState = source != null ? source.convState : new AVObject("_Conversation");
            this.Name = source?.Name;
            this.MemberIds = source?.MemberIds;
            this.Creator = source?.Creator;
            this.MuteMemberIds = source?.MuteMemberIds;

            if (!string.IsNullOrEmpty(name))
            {
                this.Name = name;
            }
            if (!string.IsNullOrEmpty(creator))
            {
                this.Creator = creator;
            }
            if (members != null)
            {
                this.MemberIds = members;
            }
            if (muteMembers != null)
            {
                this.MuteMemberIds = muteMembers;
            }

            this.IsTransient = isTransient;
            this.IsSystem = isSystem;
        }

        #region 属性操作
        public Task SaveAsync()
        {
            var cmd = new ConversationCommand()
               .Generate(this);

            var convCmd = cmd.Option("update")
                .AppId(AVClient.CurrentConfiguration.ApplicationId)
                .PeerId(this.CurrentClient.Id);

            return AVIMClient.AVCommandRunner.RunCommandAsync(convCmd);

        }
        #endregion

        ///// <summary>
        ///// 向该对话发送普通的文本消息。
        ///// </summary>
        ///// <param name="textContent">文本消息的内容,一般就是一个不超过5KB的字符串。</param>
        ///// <returns></returns>
        //public Task<Tuple<bool, AVIMTextMessage>> SendTextMessageAsync(AVIMTextMessage textMessage)
        //{
        //    return SendMessageAsync<AVIMTextMessage>(textMessage);
        //}

        /// <summary>
        /// 向该对话发送消息。
        /// </summary>
        /// <param name="avMessage"></param>
        /// <returns></returns>
        public Task<AVIMMessage> SendMessageAsync(AVIMMessage avMessage)
        {
            if (this.CurrentClient == null) throw new Exception("当前对话未指定有效 AVIMClient,无法发送消息。");
            if (this.CurrentClient.State != AVIMClient.Status.Connecting) throw new Exception("未能连接到服务器,无法发送消息。");
            return this.CurrentClient.SendMessageAsync(this, avMessage);
        }

        /// <summary>
        /// 从本地构建一个对话
        /// </summary>
        /// <param name="convId">对话的 objectId</param>
        /// <param name="client"></param>
        /// <returns></returns>
        public static AVIMConversation CreateWithoutData(string convId, AVIMClient client)
        {
            return new AVIMConversation()
            {
                ConversationId = convId,
                CurrentClient = client
            };
        }

        /// <summary>
        /// 设置自定义属性
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        [System.Obsolete("不再推荐使用,请使用 AVIMConversation[key] = value,新版的 ConversationQuery 不再支持查询 attr 字段的内部属性。")]
        public void Attribute(string key, object value)
        {
            if (pendingAttributes == null)
            {
                pendingAttributes = new Dictionary<string, object>();
            }
            pendingAttributes[key] = value;
        }

        #region 成员操作相关接口
        /// <summary>
        /// CurrentClient 主动加入到对话中
        /// <para>签名操作</para>
        /// </summary>
        /// <returns></returns>
        public Task<bool> JoinAsync()
        {
            return AddMembersAsync(CurrentClient.Id);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        public Task<bool> AddMembersAsync(string clientId)
        {
            var cmd = new ConversationCommand()
                .ConId(this.ConversationId)
                .Member(clientId)
                .Option("add")
                .AppId(AVClient.CurrentConfiguration.ApplicationId)
                .PeerId(clientId);
            var memberList = new List<string>() { clientId };
            return CurrentClient.AttachSignature(cmd, CurrentClient.SignatureFactory.CreateConversationSignature(this.ConversationId, CurrentClient.Id, memberList, "invite")).OnSuccess(_ =>
            {
                return AVIMClient.AVCommandRunner.RunCommandAsync(cmd).OnSuccess(t =>
                {
                    return t.Result.Item2.ContainsKey("added");
                });
            }).Unwrap();
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
from braintree.attribute_getter import AttributeGetter
from braintree.configuration import Configuration
from braintree.risk_data import RiskData

class CreditCardVerification(AttributeGetter):

    class Status(object):
        """
        Constants representing transaction statuses. Available statuses are:

        * braintree.CreditCardVerification.Status.Failed
        * braintree.CreditCardVerification.Status.GatewayRejected
        * braintree.CreditCardVerification.Status.ProcessorDeclined
        * braintree.CreditCardVerification.Status.Unrecognized
        * braintree.CreditCardVerification.Status.Verified
        """

        Failed                 = "failed"
        GatewayRejected        = "gateway_rejected"
        ProcessorDeclined      = "processor_declined"
        Unrecognized           = "unrecognized"
        Verified               = "verified"

    def __init__(self, gateway, attributes):
        AttributeGetter.__init__(self, attributes)
        if "processor_response_code" not in attributes:
            self.processor_response_code = None
        if "processor_response_text" not in attributes:
            self.processor_response_text = None

        if "risk_data" in attributes:
            self.risk_data = RiskData(attributes["risk_data"])
        else:
            self.risk_data = None

    @staticmethod
    def find(verification_id):
        return Configuration.gateway().verification.find(verification_id)

    @staticmethod
    def search(*query):
        return Configuration.gateway().verification.search(*query)

    def __eq__(self, other):
        if not isinstance(other, CreditCardVerification):
            return False
        return self.id == other.id


text:
Puppet Community module for Corosync
============================

[![Build Status](https://travis-ci.org/puppet-community/puppet-corosync.png?branch=master)](https://travis-ci.org/puppet-community/puppet-community-corosync)

Corosync is a cluster stack written as a reimplementation of all the core
functionalities required by openais.  Meant to provide 100% correct operation
during failures or partitionable networks.

Most famous for being the cluster stack used by Pacemaker to support n-code
clusters that can respond to node and resource level events.

Basic usage
-----------

*To install and configure Corosync*

```puppet
class { 'corosync':
  enable_secauth    => true,
  authkey           => '/var/lib/puppet/ssl/certs/ca.pem',
  bind_address      => $ipaddress,
  multicast_address => '239.1.1.2',
}
```

*To enable Pacemaker*

```puppet
corosync::service { 'pacemaker':
  version => '0',
}
```

Configuring primitives
------------------------

The resources that Corosync will manage can be referred to as a primitive.
These are things like virtual IPs or services like drbd, nginx, and apache.

*To assign a VIP to a network interface to be used by Nginx*

```puppet
cs_primitive { 'nginx_vip':
  primitive_class => 'ocf',
  primitive_type  => 'IPaddr2',
  provided_by     => 'heartbeat',
  parameters      => { 'ip' => '172.16.210.100', 'cidr_netmask' => '24' },
  operations      => { 'monitor' => { 'interval' => '10s' } },
}
```

*Make Corosync manage and monitor the state of Nginx using a custom OCF agent*

```puppet
cs_primitive { 'nginx_service':
  primitive_class => 'ocf',
  primitive_type  => 'nginx_fixed',
  provided_by     => 'pacemaker',
  operations      => {
    'monitor' => { 'interval' => '10s', 'timeout' => '30s' },
    'start'   => { 'interval' => '0', 'timeout' => '30s', 'on-fail' => 'restart' }
  },
  require         => Cs_primitive['nginx_vip'],
}
```

*Make Corosync manage and monitor the state of Apache using a LSB agent*

```puppet
cs_primitive { 'apache_service':
  primitive_class => 'lsb',
  primitive_type  => 'apache2',
  provided_by     => 'heartbeat',
  operations      => {
    'monitor' => { 'interval' => '10s', 'timeout' => '30s' },
    'start'   => { 'interval' => '0', 'timeout' => '30s', 'on-fail' => 'restart' }
  },
  require         => Cs_primitive['apache2_vip'],
}
```

Note: Operations with the same names should be declared as an Array. Example:
```puppet
cs_primitive { 'pgsql_service':
  primitive_class => 'ocf',
  primitive_type  => 'pgsql',
  provided_by     => 'heartbeat',
  operations      => {
    'monitor' => [
      { 'interval' => '10s', 'timeout' => '30s' },
      { 'interval' => '5s', 'timeout' => '30s', 'role' => 'Master' },
    ],
    'start'   => { 'interval' => '0', 'timeout' => '30s', 'on-fail' => 'restart' }
  },
}
```

Configuring locations
-----------------------

Locations determine on which nodes primitive resources run.

```puppet
cs_location { 'nginx_service_location':
  primitive => 'nginx_service',
  node_name => 'hostname',
  score     => 'INFINITY'
}
```
Configuring colocations
-----------------------

Colocations keep primitives together.  Meaning if a vip moves to web02 from web01
because web01 just hit the dirt it will drag the nginx service with it.

```puppet
cs_colocation { 'vip_with_service':
  primitives => [ 'nginx_vip', 'nginx_service' ],
}
```

Configuring migration or state order
------------------------------------

Colocation defines that a set of primitives must live together on the same node
but order definitions will define the order of which each primitive is started.  If
Nginx is configured to listen only on our vip we definitely want the vip to be
migrated to a new node before nginx comes up or the migration will fail.

```puppet
cs_order { 'vip_before_service':
  first   => 'nginx_vip',
  second  => 'nginx_service',
  require => Cs_colocation['vip_with_service'],
}
```

Configuring cloned resources
----------------------------

Cloned resources should be active on multiple hosts at the same time. You can
clone any existing resource provided the resource agent supports it.

```puppet
cs_clone { 'nginx_service-clone' :
  ensure    => present,
  primitive => 'nginx_service',
  clone_max => 3,
  require   => Cs_primitive['nginx_service'],
}
```

Corosync Properties
------------------
A few global settings can be changed with the "cs_property" section.

Disable STONITH if required.
```puppet
cs_property { 'stonith-enabled' :
  value   => 'false',
}
```

Change quorum policy
```
cs_property { 'no-quorum-policy' :
  value   => 'ignore',
}
```

Resource defaults
-----------------
A few global settings can be changed with the "cs_rsc_defaults" section.

Don't move resources.
```puppet
cs_rsc_defaults { 'resource-stickiness' :
  value => 'INFINITY',
}
```

Dependencies
------------

Tested and built on Debian 6 using backports so version 1.4.2 of Corosync is validated
to function.

Notes
-----

This module doesn't abstract away everything about managing Corosync but makes setup
and automation easier.  Things that are currently outstanding...

 * Needs a lot more tests.
 * There is already a handful of bugs that need to be worked out.
 * Plus a other things since Corosync and Pacemaker do a lot.

We suggest you at least go read the [Clusters from Scratch](http://www.clusterlabs.org/doc/en-US/Pacemaker/1.1/html-single/Clusters_from_Scratch) document
from Cluster Labs.  It will help you out a lot when understanding how all the pieces
fall together a point you in the right direction when Corosync fails unexpectedly.

A simple but complete manifest example can be found on [Cody Herriges' Github](https://github.com/ody/ha-demo), plus
there are more incomplete examples spread across the [Puppet Labs Github](https://github.com/puppetlabs).

Contributors
------------

  * [See Github](https://github.com/puppet-community/puppet-community-corosync/graphs/contributors)

Copyright and License
---------------------

Copyright (C) 2012 [Puppet Labs](https://www.puppetlabs.com/) Inc

Puppet Labs can be contacted at: info@puppetlabs.com

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
package com.caul.modules.account;

import com.caul.core.mybatis.QueryParamAdapter;
import org.apache.commons.lang.StringUtils;

/**
 * Created by BlueDream on 2016-03-21.
 */
public class AccountQueryParam extends QueryParamAdapter {

    private String accountName;
    private String qq;
    private String mobile;
    private Integer sendState;//派送状态(未派送,已派送,已拒绝)
    private Boolean arbitrage;//是否套利

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public String getQq() {
        return qq;
    }

    public void setQq(String qq) {
        this.qq = qq;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getSendState() {
        return sendState;
    }

    public void setSendState(Integer sendState) {
        this.sendState = sendState;
    }

    public Boolean getArbitrage() {
        return arbitrage;
    }

    public void setArbitrage(Boolean arbitrage) {
        this.arbitrage = arbitrage;
    }

    public boolean isEmpty() {
        return StringUtils.isEmpty(getAccountName())
                && StringUtils.isEmpty(getQq())
                && StringUtils.isEmpty(getMobile())
                && getSendState() == null
                && getArbitrage() == null;
    }
}


text:
define(function (require) {

    'use strict';

    var Light = require('../Light');

    /**
     * @constructor qtek.light.Sphere
     * @extends {qtek.Light}
     */
    var SphereLight = Light.derive(
    /** @lends qtek.light.Sphere# */
    {
        /**
         * @type {number}
         */
        range: 100,

        /**
         * @type {number}
         */
        radius: 5
    }, {

        type: 'SPHERE_LIGHT',

        uniformTemplates: {
            sphereLightPosition: {
                type: '3f',
                value: function(instance) {
                    return instance.getWorldPosition()._array;
                }
            },
            sphereLightRange: {
                type: '1f',
                value: function(instance) {
                    return instance.range;
                }
            },
            sphereLightRadius: {
                type: '1f',
                value: function(instance) {
                    return instance.radius;
                }
            },
            sphereLightColor: {
                type: '3f',
                value: function(instance) {
                    var color = instance.color;
                    var intensity = instance.intensity;
                    return [color[0]*intensity, color[1]*intensity, color[2]*intensity];
                }
            }
        }
    });

    return SphereLight;
});


text:
<?php

namespace Google\Service\CloudSearch;

class MatchInfo extends \Google\Collection
{
  protected $collection_key = 'matchingImageReferenceKey';
  /**
   * @var string[]
   */
  public $matchingImageReferenceKey;

  /**
   * @param string[]
   */
  public function setMatchingImageReferenceKey($matchingImageReferenceKey)
  {
    $this->matchingImageReferenceKey = $matchingImageReferenceKey;
  }
  /**
   * @return string[]
   */
  public function getMatchingImageReferenceKey()
  {
    return $this->matchingImageReferenceKey;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(MatchInfo::class, 'Google_Service_CloudSearch_MatchInfo');


text:
FOUNDATION_EXPORT double TranslatioVersionNumber;
FOUNDATION_EXPORT const unsigned char TranslatioVersionString[];


text:
from django.conf.urls import patterns  # noqa
from django.conf.urls import url  # noqa

from openstack_dashboard.dashboards.admin.instances import views
from openstack_dashboard.dashboards.project.instances \
    import views as project_views

INSTANCES = r'^(?P<instance_id>[^/]+)/%s$'

urlpatterns = patterns('openstack_dashboard.dashboards.admin.instances.views',
    url(r'^$', views.AdminIndexView.as_view(), name='index'),
    url(INSTANCES % 'update', views.AdminUpdateView.as_view(), name='update'),
    url(INSTANCES % 'detail',
        project_views.DetailView.as_view(), name='detail'),
    url(INSTANCES % 'console', 'console', name='console'),
    url(INSTANCES % 'vnc', 'vnc', name='vnc'),
    url(INSTANCES % 'spice', 'spice', name='spice'),
    url(INSTANCES % 'live_migrate', views.LiveMigrateView.as_view(),
        name='live_migrate'),
)


text:
using System;
using SFA.DAS.CommitmentsV2.Types;

namespace SFA.DAS.CommitmentsV2.Domain.Extensions
{
    public static class OriginatorExtensions
    {
        public static Party ToParty(this Originator originator)
        {
            switch (originator)
            {
                case Originator.Employer:
                    return Party.Employer;
                case Originator.Provider:
                    return Party.Provider;
                default:
                    throw new ArgumentException($"Unable to map Originator {originator} to Party");
            }
        }
    }
}


text:
import React from 'react';

import { Anchor, Box, Header, Menu, ResponsiveContext } from 'grommet';
import { Grommet as GrommetIcon, Menu as MenuIcon } from 'grommet-icons';

export const Responsive = () => (
  // Uncomment <Grommet> lines when using outside of storybook
  // <Grommet theme={...}>
  <Header background="light-4" pad="medium" height="xsmall">
    <Anchor
      href="https://tools.grommet.io/"
      icon={<GrommetIcon color="brand" />}
      label="Grommet Tools"
    />
    <ResponsiveContext.Consumer>
      {(size) =>
        size === 'small' ? (
          <Box justify="end">
            <Menu
              a11yTitle="Navigation Menu"
              dropProps={{ align: { top: 'bottom', right: 'right' } }}
              icon={<MenuIcon color="brand" />}
              items={[
                {
                  label: <Box pad="small">Grommet.io</Box>,
                  href: 'https://v2.grommet.io/',
                },
                {
                  label: <Box pad="small">Feedback</Box>,
                  href: 'https://github.com/grommet/grommet/issues',
                },
              ]}
            />
          </Box>
        ) : (
          <Box justify="end" direction="row" gap="medium">
            <Anchor href="https://v2.grommet.io/" label="Grommet.io" />
            <Anchor
              href="https://github.com/grommet/grommet/issues"
              label="Feedback"
            />
          </Box>
        )
      }
    </ResponsiveContext.Consumer>
  </Header>
  // </Grommet>
);

export default {
  title: 'Layout/Header/Responsive',
};


text:
module.exports = [
  { name: 'Login', params: ['Username', 'Secret'] },
  { name: 'CoreShowChannels', params: [] },
  { name: 'Ping', params: [] },
  { name: 'Hangup', params: [] },
  { name: 'CoreStatus', params: [] },
  { name: 'Status', params: [] },
  { name: 'DahdiShowChannels', params: [] },
  { name: 'CoreSettings', params: [] },
  { name: 'ListCommands', params: [] },
  { name: 'Logoff', params: [] },
  { name: 'AbsoluteTimeout', params: [] },
  { name: 'SipShowPeer', params: [] },
  { name: 'SipShowRegistry', params: [] },
  { name: 'SipQualifyPeer', params: [] },
  { name: 'SipPeers', params: [] },
  { name: 'AgentLogoff', params: [] },
  { name: 'Agents', params: [] },
  { name: 'AttendedTransfer', params: [] },
  { name: 'ChangeMonitor', params: [] },
  { name: 'Command', params: [] },
  { name: 'CreateConfig', params: [] },
  { name: 'DahdiDialOffHook', params: [] },
  { name: 'DahdiDndOff', params: [] },
  { name: 'DahdiDndOn', params: [] },
  { name: 'DahdiHangup', params: [] },
  { name: 'DahdiRestart', params: [] },
  { name: 'DbDel', params: [] },
  { name: 'DbDeltree', params: [] },
  { name: 'DbGet', params: [] },
  { name: 'DbPut', params: [] },
  { name: 'ExtensionState', params: [] },
  { name: 'GetConfig', params: ['Filename'] },
  { name: 'GetConfigJson', params: ['Filename'] },
  { name: 'GetVar', params: [] },
  { name: 'JabberSend', params: [] },
  { name: 'ListCategories', params: [] },
  { name: 'PauseMonitor', params: [] },
  { name: 'UnpauseMonitor', params: [] },
  { name: 'StopMonitor', params: [] },
  { name: 'LocalOptimizeAway', params: [] },
  { name: 'SetVar', params: [] },
  { name: 'Reload', params: [] },
  { name: 'PlayDtmf', params: [] },
  { name: 'Park', params: [] },
  { name: 'ParkedCalls', params: [] },
  {
    name: 'Monitor',
    params: ['format', 'mix'],
    defaults: { format: 'wav', mix: true },
  },
  { name: 'ModuleCheck', params: [] },
  { name: 'ModuleLoad', params: ['LoadType'], defaults: { LoadType: 'Load' } },
  {
    name: 'ModuleUnload',
    params: ['LoadType'],
    defaults: { LoadType: 'Unload' },
  },
  {
    name: 'ModuleReload',
    params: ['LoadType'],
    defaults: { LoadType: 'record' },
  },
  { name: 'MailboxCount', params: [] },
  { name: 'MailboxStatus', params: [] },
  { name: 'VoicemailUsersList', params: [] },
  { name: 'Redirect', params: [] },
  { name: 'Bridge', params: [] },
  { name: 'ShowDialPlan', params: [] },
  { name: 'SendText', params: [] },
  { name: 'Queues', params: [] },
  {
    name: 'QueuePause',
    params: ['Interface', 'Paused', 'Queue', 'Reason'],
    optional: ['Queue', 'Reason'],
    defaults: { Paused: true },
  },
  { name: 'QueueSummary', params: [] },
  { name: 'QueueRule', params: [] },
  { name: 'QueueStatus', params: [] },
  { name: 'QueueReset', params: [] },
  { name: 'QueueRemove', params: ['Interface', 'Queue'] },
  { name: 'Originate', params: [] },
  { name: 'QueueAdd', params: ['Interface', 'Queue'] },
  { name: 'QueueLog', params: [] },
  { name: 'MeetmeList', params: ['Conference'], optional: ['Conference'] },
  { name: 'MeetmeMute', params: ['Meetme', 'Usernum'] },
  { name: 'MeetmeUnmute', params: ['Meetme', 'Usernum'] },
  { name: 'ConfbridgeListRooms', params: [] },
  { name: 'ConfbridgeList', params: ['Conference'] },
  { name: 'ConfbridgeKick', params: ['Conference', 'Channel'] },
  { name: 'ConfbridgeLock', params: ['Conference'] },
  { name: 'ConfbridgeUnlock', params: ['Conference'] },
  { name: 'ConfbridgeMute', params: ['Conference', 'Channel'] },
  { name: 'ConfbridgeUnmute', params: ['Conference', 'Channel'] },
  { name: 'AGI', params: ['Channel', 'Command', 'CommandId'] },
  { name: 'BlindTransfer', params: ['Channel', 'Context', 'Extension'] },
  { name: 'SIPpeerstatus' },
  { name: 'BridgeList' },
  { name: 'BridgeInfo' },
];


text:
<resources>

    <string name="app_name">VimTouch Plugins</string>

</resources>


text:
using RevistaUFO.Helpers;
using RevistaUFO.Models;
using RevistaUFO.PetaPoco;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Web;

namespace RevistaUFO.Controllers
{
    /// <summary>
    /// Summary description for MemberLoginSurfaceController
    /// </summary>
    public class EventRegistrationSurfaceController : Umbraco.Web.Mvc.SurfaceController
    {
        readonly UmbracoHelper umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
        static Database _db = null;
        readonly IPublishedContent home = null;
        readonly Smtp email;
        public EventRegistrationSurfaceController()
        {
            home = umbracoHelper.TypedContentAtRoot().First();
            _db = ApplicationContext.DatabaseContext.Database;
            email = new Smtp();
        }

        [HttpGet]
        [OutputCache(Duration = 24 * 60 * 60, VaryByParam = "none")]
        public JsonResult AllEvents()
        {
            /*[{ "date": "1337594400000", "type": "meeting", "title": "Project A meeting", "description": "Lorem Ipsum dolor set", "url": "http://www.event1.com/" }]*/

            var events = umbracoHelper.TypedContentAtRoot().First().Descendants("List_Events").FirstOrDefault().Descendants("Event_Main");
            List<EventCalendarItem> eventos = new List<EventCalendarItem>();
            foreach (var e in events)
                eventos.Add(new EventCalendarItem
                {
                    title = e.GetPropertyValue<string>("eventName"),
                    description = e.GetPropertyValue<string>("Event_LongDescription"),
                    url = e.Url,
                    LongDate = e.GetPropertyValue<DateTime>("eventStartDate")
                });
            //Cache.Insert("EventCalendar", eventos, null, DateTime.Now.AddMinutes(1d), Cache.NoSlidingExpiration);
            return Json(eventos, JsonRequestBehavior.AllowGet);

        }
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        [ActionName("Register")]
        public ActionResult RegisterForEventPost(EventRegistrationModel form)
        {
            if (ModelState.IsValid)
            {
                var evento = umbracoHelper.Content(form.EventId);
                //cupons not enabled yet
                form.Coupon = "";
                form.IpAddress = Request.UserHostAddress;
                form.RefCode = evento.GetPropertyValue<string>("EventReferenceCode") + (Latest(form.EventId) + 1);

                var done = NewRegister(form);

                if (done != null)
                {
                    string qr = HttpUtility.HtmlEncode(string.Format("nome:{0};inscricao:{1};refCode:{2}", done.Fullname, done.RegistrationNumber, form.RefCode));
                    string payLink = evento.Parent.UrlWithDomain() + done.PaymentMethod.ToString() + "?session=" + done.Session;

                    string message = evento.GetPropertyValue<string>("EventConfirmationEmail")
                        .Replace("##NAME##", done.Fullname)
                        .Replace("##EMAIL##", done.Email1)
                        .Replace("##ID##", qr)
                        .Replace("##PAYLINK##", payLink)
                        .Replace("##DATE##", DateTime.Now.ToShortDateString())
                        .Replace("##EVENTNAME##", evento.Name)
                        .Replace("##IPADDRESS##", form.IpAddress)
                        .Replace("##VIEWURL##", evento.Parent.UrlWithDomain() + "InscricaoConcluida?session=" + done.Session)
                        .Replace("##REFCODE##", form.RefCode);

                    SendRegistrationConfirmation(done.Email1, "Inscrição para o " + evento.Name, message);
                    TempData["registrationInfo"] = done;

                    if (done.PaymentMethod != PaymentMethod.Free)
                    {
                        switch (done.PaymentMethod)
                        {
                            case PaymentMethod.PayPal:
                                break;
                            case PaymentMethod.PagSeguro:
                                return Redirect(evento.Parent.Url + "PagSeguro?session=" + done.Session);
                            case PaymentMethod.Free: //nothing to pay
                                break;
                            default: //nothing to pay
                                break;
                        }
                    }
                }
            }
            else
            {
                TempData["Status"] = "Erro no formulário de inscrição, tente novamente";
                TempData["formdata"] = form;
            }
            return CurrentUmbracoPage();
        }

        bool PayWithPagSeguro()
        {
            return false;
        }
        bool PayWithPayPal()
        {
            return false;
        }
        long Latest(int eventId)
        {
            long? scalar = _db.ExecuteScalar<long>("select max(RegistrationNumber) from EventRegistrations where eventID = @0", eventId);
            if (scalar.HasValue) return scalar.Value;
            return 1;
        }
        EventRegistrationModel NewRegister(EventRegistrationModel registration)
        {
            //get total price from system to avoid price hacking
            string total = registration.PopulateTotal();

            var newRegistration = new EventRegistration
            {
                EventAddOns = registration.AddOns,
                Coupon = registration.Coupon,
                EventId = registration.EventId,
                PaymentMethod = (int)registration.PaymentMethod,
                TotalPaid = total.ToString(CultureInfo.InvariantCulture),
                Session = Guid.NewGuid().ToString(),
                RegistrationDescription = "Pagamento pendente",
                CreatedOn = DateTime.UtcNow,
                IpAddress = registration.IpAddress,
                RefCode = registration.RefCode,
                Paid = registration.Paid
            };

            var registrationUser = new EventRegistrationUser
            {
                Fullname = registration.Fullname,
                Email1 = registration.Email1,
                Email2 = registration.Email2,
                HomePhone = registration.Phone1,
                CellPhone = registration.Phone2,
                PostalCode = registration.Postal,
                Address = registration.Address,
                Address2 = registration.Address2,
                City = registration.City,
                Number = registration.Number,
                Neighborhood = registration.Neighborhood,
                State = registration.State,
                Document = registration.Document
            };

            var done = _db.Insert(newRegistration);

            //Assign a registration ID
            var registrationNumber = Latest(registration.EventId) + 1;
            newRegistration.RegistrationNumber = registrationNumber;
            int updated = _db.Update(newRegistration);

            //Assing foreign key
            registrationUser.RegistrationId = int.Parse(done.ToString());
            var user = _db.Insert(registrationUser);

            registration.Session = newRegistration.Session;
            registration.RegistrationNumber = newRegistration.RegistrationNumber;

            return registration;
        }

        public bool SendRegistrationConfirmation(string emailAddress, string subject, string template)
        {
            var emailMessage = template;
            SetupSmtp();
            email.To = emailAddress;
            email.ToName = emailAddress;
            email.Subject = subject;
            email.Message = email.UsingTemplate(emailMessage,
                new
                {
                    Website = "Site Revista UFO",
                    Email = emailAddress
                });

            return email.Send();
        }

        void SetupSmtp()
        {
            email.Hostname = home.GetPropertyValue<string>("hostname");
            email.Port = home.GetPropertyValue<int>("port");
            email.Username = home.GetPropertyValue<string>("username");
            email.Password = home.GetPropertyValue<string>("password");
            email.UseSSL = home.GetPropertyValue<bool>("useSSL");
            email.From = home.GetPropertyValue<string>("from");
            email.FromName = home.GetPropertyValue<string>("fromName");
        }
    }
}


text:
<?php

namespace AuthBucket\Push\Tests\ServiceType;

use AuthBucket\Push\Model\MessageInterface;
use AuthBucket\Push\Model\ServiceInterface;
use AuthBucket\Push\ServiceType\ServiceTypeHandlerInterface;

class BarServiceTypeHandler implements ServiceTypeHandlerInterface
{
    public function send(ServiceInterface $service, MessageInterface $message)
    {
    }
}


text:
from flaky import flaky
import numpy
from numpy.testing import assert_array_almost_equal
from keras import backend as K
from keras.initializers import Constant
from keras.layers import Embedding, Input
from keras.models import Model
from keras import activations

from deep_qa.tensors.backend import apply_feed_forward
from deep_qa.layers.tuple_matchers import ThresholdTupleMatcher
from ...common.test_case import DeepQaTestCase

class TestThresholdTupleMatcher(DeepQaTestCase):
    def setUp(self):
        super(TestThresholdTupleMatcher, self).setUp()
        self.num_slots = 3
        self.num_words = 5
        self.embed_dimension = 4
        self.tuple1_input = Input(shape=(self.num_slots, self.num_words, self.embed_dimension), dtype='float32',
                                  name="input_tuple1")
        self.tuple2_input = Input(shape=(self.num_slots, self.num_words, self.embed_dimension), dtype='float32',
                                  name="input_tuple2")
        self.num_hidden_layers = 1
        self.hidden_layer_width = 2
        self.hidden_layer_activation = 'linear'

        # tuple1 shape: (batch size, num_slots, num_words, embed_dimension)
        self.tuple1 = numpy.random.rand(1, self.num_slots, self.num_words, self.embed_dimension)
        # tuple2 shape: (batch size, num_slots, num_words, embed_dimension)
        self.tuple2 = numpy.random.rand(1, self.num_slots, self.num_words, self.embed_dimension)
        # cause some dimensions to have identical embeddings (i.e. cosine similarity of 1)
        self.tuple1[0, 1, 1, :] = numpy.ones(4)
        self.tuple1[0, 2, 0, :] = numpy.ones(4)

        self.tuple2[0, 1, 0, :] = numpy.ones(4)
        self.tuple2[0, 2, 3, :] = numpy.ones(4)
        self.tuple2[0, 2, 4, :] = numpy.ones(4)
        # This should result in 1 matched word in slot 1, and two in slot 2
        # So the normalized overlaps should be (0, 1/5,  2/5)

    @flaky
    def test_general_case(self):
        match_layer = ThresholdTupleMatcher({"type": "cosine_similarity"},
                                            self.num_hidden_layers,
                                            self.hidden_layer_width,
                                            initialization=Constant(.999),
                                            hidden_layer_activation=self.hidden_layer_activation)
        output = match_layer([self.tuple1_input, self.tuple2_input])
        model = Model([self.tuple1_input, self.tuple2_input], output)

        # Get the initial weights for use in testing
        layer_nn = match_layer.hidden_layer_weights

        # Testing general unmasked case.
        desired_overlap = K.variable(numpy.asarray([[0, 1/5, 2/5]]))
        # Desired_overlap gets fed into the inner NN.
        neural_network_feed_forward = apply_feed_forward(desired_overlap, layer_nn,
                                                         activations.get(match_layer.hidden_layer_activation))
        # Apply the final activation function.
        desired_result = activations.get(match_layer.final_activation)(K.dot(neural_network_feed_forward,
                                                                             match_layer.score_layer))
        result = model.predict([self.tuple1, self.tuple2])
        assert_array_almost_equal(result, K.eval(desired_result))

    def test_returns_masks_correctly(self):
        # Test when one tuple is all padding.
        # Here, since tuple2 is all padding, we want to return a mask value of 0 for this pair
        # tuple1 shape: (batch size, num_slots, num_words, embed_dimension)
        tuple1 = K.variable(self.tuple1)
        mask1 = K.variable(numpy.ones((1, self.num_slots, self.num_words)))
        tuple2 = K.variable(self.tuple2)
        mask2 = K.variable(numpy.zeros((1, self.num_slots, self.num_words)))
        calculated_mask_exclude = K.eval(
                ThresholdTupleMatcher({"type": "cosine_similarity"},
                                      self.num_hidden_layers,
                                      self.hidden_layer_width,
                                      hidden_layer_activation=self.hidden_layer_activation)
                .compute_mask([tuple1, tuple2], [mask1, mask2]))
        assert_array_almost_equal(calculated_mask_exclude, numpy.array([[0]], dtype='int32'))
        assert calculated_mask_exclude.shape == (1, 1,)

        # Test when tuple2 is valid.
        # Here, since tuple2 is valid, we want to return a mask value of 1 for this pair
        new_mask = numpy.ones((1, self.num_slots, self.num_words))
        new_mask[:, :, 1] = 0
        mask2 = K.variable(new_mask)

        calculated_mask_include = K.eval(
                ThresholdTupleMatcher({"type": "cosine_similarity"},
                                      self.num_hidden_layers,
                                      self.hidden_layer_width,
                                      hidden_layer_activation=self.hidden_layer_activation)
                .compute_mask([tuple1, tuple2], [mask1, mask2]))
        assert_array_almost_equal(calculated_mask_include, numpy.array([[1]], dtype='int32'))
        assert calculated_mask_include.shape == (1, 1,)

    def test_handles_input_masks_correctly(self):
        num_slots = 3
        num_words = 5
        embed_dimension = 4
        tuple1_word_input = Input(shape=(num_slots, num_words), dtype='int32', name="input_tuple1")
        tuple2_word_input = Input(shape=(num_slots, num_words), dtype='int32', name="input_tuple2")

        embedding = Embedding(10, embed_dimension, mask_zero=True)
        embedded_masked_tuple1 = embedding(tuple1_word_input)
        embedded_masked_tuple2 = embedding(tuple2_word_input)

        match_layer = ThresholdTupleMatcher({"type": "cosine_similarity"},
                                            self.num_hidden_layers,
                                            self.hidden_layer_width,
                                            initialization=Constant(.999),
                                            hidden_layer_activation=self.hidden_layer_activation)
        output = match_layer([embedded_masked_tuple1, embedded_masked_tuple2])
        mask_model = Model([tuple1_word_input, tuple2_word_input], output)

        # Assign tuple1 to be all 4's and tuple2 to be all 3's so we can control lexical overlap
        tuple1_words = numpy.ones((1, num_slots, num_words)) * 4
        tuple2_words = numpy.ones((1, num_slots, num_words)) * 3
        # Add a set of matching zeros to slot 1 in each tuple1 -- but shouldn't "match" because it's padding
        tuple1_words[:, 1, :] = numpy.zeros(num_words)
        tuple2_words[:, 1, :] = numpy.zeros(num_words)

        # Get the initial weights for use in testing
        layer_nn = match_layer.hidden_layer_weights

        # Testing general unmasked case.
        desired_overlap = K.variable(numpy.asarray([[0, 0, 0]]))
        # Desired_overlap gets fed into the inner NN.
        neural_network_feed_forward = apply_feed_forward(desired_overlap, layer_nn,
                                                         activations.get(match_layer.hidden_layer_activation))
        # Apply the final activation function.
        desired_result = activations.get(match_layer.final_activation)(K.dot(neural_network_feed_forward,
                                                                             match_layer.score_layer))
        result = mask_model.predict([tuple1_words, tuple2_words])
        assert_array_almost_equal(result, K.eval(desired_result))


text:
package analyzer

import (
	"gopkg.in/src-d/go-mysql-server.v0/sql"
	"gopkg.in/src-d/go-mysql-server.v0/sql/plan"
)

func shouldParallelize(node sql.Node) bool {
	// Do not try to parallelize index operations.
	switch node.(type) {
	case *plan.CreateIndex, *plan.DropIndex, *plan.Describe:
		return false
	default:
		return true
	}
}

func parallelize(ctx *sql.Context, a *Analyzer, node sql.Node) (sql.Node, error) {
	if a.Parallelism <= 1 || !node.Resolved() {
		return node, nil
	}

	proc, ok := node.(*plan.QueryProcess)
	if (ok && !shouldParallelize(proc.Child)) || !shouldParallelize(node) {
		return node, nil
	}

	node, err := node.TransformUp(func(node sql.Node) (sql.Node, error) {
		if !isParallelizable(node) {
			return node, nil
		}

		return plan.NewExchange(a.Parallelism, node), nil
	})

	if err != nil {
		return nil, err
	}

	return node.TransformUp(removeRedundantExchanges)
}

// removeRedundantExchanges removes all the exchanges except for the topmost
// of all.
func removeRedundantExchanges(node sql.Node) (sql.Node, error) {
	exchange, ok := node.(*plan.Exchange)
	if !ok {
		return node, nil
	}

	e := &protectedExchange{exchange}
	return e.TransformUp(func(node sql.Node) (sql.Node, error) {
		if exchange, ok := node.(*plan.Exchange); ok {
			return exchange.Child, nil
		}
		return node, nil
	})
}

func isParallelizable(node sql.Node) bool {
	var ok = true
	var tableSeen bool
	var lastWasTable bool

	plan.Inspect(node, func(node sql.Node) bool {
		if node == nil {
			return true
		}

		lastWasTable = false
		if plan.IsBinary(node) {
			ok = false
			return false
		}

		switch node.(type) {
		// These are the only unary nodes that can be parallelized. Any other
		// unary nodes will not.
		case *plan.Filter,
			*plan.Project,
			*plan.TableAlias,
			*plan.Exchange:
		case sql.Table:
			lastWasTable = true
			tableSeen = true
		default:
			ok = false
			return false
		}

		return true
	})

	return ok && tableSeen && lastWasTable
}

// protectedExchange is a placeholder node that protects a certain exchange
// node from being removed during transformations.
type protectedExchange struct {
	*plan.Exchange
}

// TransformUp transforms the child with the given transform function but it
// will not call the transform function with the new instance. Instead of
// another protectedExchange, it will return an Exchange.
func (e *protectedExchange) TransformUp(f sql.TransformNodeFunc) (sql.Node, error) {
	child, err := e.Child.TransformUp(f)
	if err != nil {
		return nil, err
	}

	return plan.NewExchange(e.Parallelism, child), nil
}


text:
package uk.ac.ebi.pride.archive.px.writer;

import uk.ac.ebi.pride.archive.px.model.*;
import uk.ac.ebi.pride.data.exception.SubmissionFileException;
import uk.ac.ebi.pride.data.model.Submission;

import java.io.File;
import java.io.IOException;

/**
 * @author Suresh Hewapathirana
 */
public interface MessageWriter {

    public String formatversion = null;

    File createIntialPxXml(File submissionSummaryFile, File outputDirectory, String pxAccession, String datasetPathFragment, String pxSchemaVersion) throws SubmissionFileException, IOException;
    void addChangeLogEntry(ProteomeXchangeDataset pxXML, String message);
    Publication getPublication(Long pmid);
    Publication getPublicationDoi(String doi);
    KeywordList getKeywordList(Submission submissionSummary);
    ModificationList getModificationList(Submission submissionSummary);
    InstrumentList getInstrumentList(Submission submissionSummary);
    SpeciesList getSpeciesList(Submission submissionSummary);
    File createIntialPxXml(Submission submissionSummary, File outputDirectory, String pxAccession, String datasetPathFragment, String pxSchemaVersion)throws IOException;
}


text:
package org.openshift.ping.server;

import org.jgroups.Channel;

/**
 * @author Ales Justin
 */
public interface Server {
    public static final String CLUSTER_NAME = "CLUSTER_NAME";
    public void start(Channel channel) throws Exception;
    public void stop(Channel channel);
    public Channel getChannel(String clusterName);
}


text:
'use strict';
import { AppRegistry } from 'react-native';
import Example from './Example';
AppRegistry.registerComponent('Example', () => Example);


text:
package org.apache.ignite.internal.processors.cache.transactions;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.TestRecordingCommunicationSpi;
import org.apache.ignite.internal.processors.affinity.AffinityAssignment;
import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionExchangeId;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionSupplyMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsFullMessage;
import org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionTopology;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearLockRequest;
import org.apache.ignite.internal.processors.cache.distributed.near.GridNearTxPrepareRequest;
import org.apache.ignite.internal.util.GridConcurrentSkipListSet;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteBiPredicate;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.transactions.Transaction;
import org.apache.ignite.transactions.TransactionConcurrency;
import org.apache.ignite.transactions.TransactionIsolation;
import org.junit.Test;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
import static org.apache.ignite.internal.processors.cache.distributed.dht.topology.GridDhtPartitionState.OWNING;
import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC;
import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC;
import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ;
import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE;

/**
 */
public class TxCrossCacheMapOnInvalidTopologyTest extends GridCommonAbstractTest {
    /** Partitions count. */
    private static final int PARTS_CNT = 32;

    /** Cache 1. */
    private static final String CACHE1 = DEFAULT_CACHE_NAME;

    /** Cache 2. */
    private static final String CACHE2 = DEFAULT_CACHE_NAME + "2";

    /** */
    private static final int MB = 1024 * 1024;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        cfg.setCommunicationSpi(new TestRecordingCommunicationSpi());
        cfg.setCacheConfiguration(cacheConfiguration(CACHE1), cacheConfiguration(CACHE2).setRebalanceOrder(10));

        cfg.setDataStorageConfiguration(new DataStorageConfiguration().setPageSize(1024).
            setDefaultDataRegionConfiguration(new DataRegionConfiguration().
                setInitialSize(100 * MB).setMaxSize(100 * MB)));

        return cfg;
    }

    /**
     * @param name Name.
     */
    protected CacheConfiguration<Object, Object> cacheConfiguration(String name) {
        CacheConfiguration<Object, Object> ccfg = new CacheConfiguration<>(name);

        ccfg.setAtomicityMode(TRANSACTIONAL);
        ccfg.setBackups(2);
        ccfg.setWriteSynchronizationMode(FULL_SYNC);
        ccfg.setAffinity(new RendezvousAffinityFunction(false, PARTS_CNT));

        return ccfg;
    }

    /**
     *
     */
    @Test
    public void testCrossCacheTxMapOnInvalidTopologyPessimistic() throws Exception {
        doTestCrossCacheTxMapOnInvalidTopology(PESSIMISTIC, REPEATABLE_READ);
    }

    /**
     *
     */
    @Test
    public void testCrossCacheTxMapOnInvalidTopologyOptimistic() throws Exception {
        doTestCrossCacheTxMapOnInvalidTopology(OPTIMISTIC, REPEATABLE_READ);
    }

    /**
     *
     */
    @Test
    public void testCrossCacheTxMapOnInvalidTopologyOptimisticSerializable() throws Exception {
        doTestCrossCacheTxMapOnInvalidTopology(OPTIMISTIC, SERIALIZABLE);
    }

    /**
     * Test scenario: cross-cache tx is started when node is left in the middle of rebalance, first cache is rebalanced
     * and second is partially rebalanced.
     *
     * First cache map request will trigger client compatible remap for pessimistic txs,
     * second cache map request should use new topology version.
     *
     * For optimistic tx remap is enforced if more than one mapping in transaction or all enlisted caches have compatible
     * assignments.
     *
     * Success: tx is finished on ideal topology version over all mapped nodes.
     *
     * @param concurrency Concurrency.
     * @param isolation Isolation.
     */
    private void doTestCrossCacheTxMapOnInvalidTopology(TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception {
        try {
            IgniteEx crd = startGrid(0);
            IgniteEx g1 = startGrid(1);

            awaitPartitionMapExchange();

            IgniteEx client = startClientGrid("client");
            assertNotNull(client.cache(CACHE1));
            assertNotNull(client.cache(CACHE2));

            try (IgniteDataStreamer<Object, Object> streamer = crd.dataStreamer(CACHE1)) {
                // Put 500 keys per partition.
                for (int k = 0; k < PARTS_CNT * 500; k++)
                    streamer.addData(k, new byte[10]);
            }

            try (IgniteDataStreamer<Object, Object> streamer = crd.dataStreamer(CACHE2)) {
                // Put 500 keys per partition.
                for (int k = 0; k < PARTS_CNT * 500; k++)
                    streamer.addData(k, new byte[10]);
            }

            TestRecordingCommunicationSpi crdSpi = TestRecordingCommunicationSpi.spi(crd);

            final AffinityTopologyVersion joinVer = new AffinityTopologyVersion(4, 0);
            AffinityTopologyVersion leftVer = new AffinityTopologyVersion(5, 0);
            AffinityTopologyVersion idealVer = new AffinityTopologyVersion(5, 1);

            AtomicReference<Set<Integer>> full = new AtomicReference<>();

            GridConcurrentSkipListSet<Integer> leftVerParts = new GridConcurrentSkipListSet<>();

            crdSpi.blockMessages((node, m) -> {
                if (m instanceof GridDhtPartitionSupplyMessage) {
                    GridDhtPartitionSupplyMessage msg = (GridDhtPartitionSupplyMessage)m;

                    // Allow full rebalance for cache 1 and system cache.
                    if (msg.groupId() != CU.cacheId(CACHE2))
                        return false;

                    // Allow only first batch for cache 2.
                    if (msg.topologyVersion().equals(joinVer)) {
                        if (full.get() == null) {
                            Map<Integer, Long> last = U.field(msg, "last");

                            full.set(last.keySet());

                            return false;
                        }

                        return true;
                    }

                    if (msg.topologyVersion().equals(leftVer)) {
                        Map<Integer, Long> last = U.field(msg, "last");

                        leftVerParts.addAll(last.keySet());

                        return true;
                    }
                } else if (m instanceof GridDhtPartitionsFullMessage) {
                    GridDhtPartitionsFullMessage msg = (GridDhtPartitionsFullMessage)m;

                    // Delay full message for ideal topology switch.
                    GridDhtPartitionExchangeId exchId = msg.exchangeId();

                    if (exchId != null && exchId.topologyVersion().equals(idealVer))
                        return true;
                }

                return false;
            });

            TestRecordingCommunicationSpi g1Spi = TestRecordingCommunicationSpi.spi(g1);
            g1Spi.blockMessages((node, msg) -> {
                if (msg instanceof GridDhtPartitionSupplyMessage) {
                    GridDhtPartitionSupplyMessage m = (GridDhtPartitionSupplyMessage)msg;

                    return m.groupId() == CU.cacheId(CACHE2);
                }

                return false;
            });

            startGrid(2);

            crdSpi.waitForBlocked();
            g1Spi.waitForBlocked();

            // Wait partial owning.
            assertTrue("Timed out while waiting for rebalance", GridTestUtils.waitForCondition(() -> {
                // Await full rebalance for cache 2.
                GridDhtPartitionTopology top0 = grid(2).cachex(CACHE1).context().topology();

                for (int p = 0; p < PARTS_CNT; p++) {
                    if (top0.localPartition(p).state() != OWNING)
                        return false;
                }

                // Await partial rebalance for cache 1.
                GridDhtPartitionTopology top1 = grid(2).cachex(CACHE2).context().topology();

                for (Integer part : full.get()) {
                    if (top1.localPartition(part).state() != OWNING)
                        return false;
                }

                return true;
            }, 10_000));

            // At this point cache 1 is fully rebalanced and cache 2 is partially rebalanced.
            // Stop supplier in the middle of rebalance.
            g1.close();

            // Wait for topologies and calculate required partitions.
            grid(0).cachex(CACHE1).context().affinity().affinityReadyFuture(leftVer).get();
            grid(2).cachex(CACHE1).context().affinity().affinityReadyFuture(leftVer).get();
            grid(0).cachex(CACHE2).context().affinity().affinityReadyFuture(leftVer).get();
            grid(2).cachex(CACHE2).context().affinity().affinityReadyFuture(leftVer).get();

            AffinityAssignment assignment0 = grid(0).cachex(CACHE1).context().affinity().assignment(leftVer);
            AffinityAssignment assignment = grid(0).cachex(CACHE2).context().affinity().assignment(leftVer);

            // Search for a partition with incompatible assignment.
            int stablePart = -1; // Partition for cache1 which is mapped for both late and ideal topologies to the same primary.
            int movingPart = -1; // Partition for cache2 which is mapped for both late and ideal topologies on different primaries.

            for (int p = 0; p < assignment0.assignment().size(); p++) {
                List<ClusterNode> curr = assignment.assignment().get(p);
                List<ClusterNode> ideal = assignment.idealAssignment().get(p);

                if (curr.equals(ideal) && curr.get(0).order() == 1) {
                    stablePart = p;

                    break;
                }
            }

            assertFalse(stablePart == -1);

            for (int p = 0; p < assignment.assignment().size(); p++) {
                List<ClusterNode> curr = assignment.assignment().get(p);
                List<ClusterNode> ideal = assignment.idealAssignment().get(p);

                if (!curr.equals(ideal) && curr.get(0).order() == 1) {
                    movingPart = p;

                    break;
                }
            }

            assertFalse(movingPart == -1);

            TestRecordingCommunicationSpi.spi(client).blockMessages(new IgniteBiPredicate<ClusterNode, Message>() {
                @Override public boolean apply(ClusterNode node, Message msg) {
                    if (concurrency == PESSIMISTIC)
                        return msg instanceof GridNearLockRequest;
                    else
                        return msg instanceof GridNearTxPrepareRequest;
                }
            });

            final int finalStablePart = stablePart;
            final int finalMovingPart = movingPart;

            IgniteInternalFuture<?> txFut = multithreadedAsync(() -> {
                try (Transaction tx = client.transactions().txStart(concurrency, isolation)) {
                    client.cache(CACHE1).put(finalStablePart, 0); // Will map on crd(order=1).

                    // Next request will remap to ideal topology, but it's not ready on other node except crd.
                    client.cache(CACHE2).put(finalMovingPart, 0);

                    tx.commit();
                }
            }, 1, "tx-thread");

            // Wait until all missing supply messages are blocked.
            assertTrue(GridTestUtils.waitForCondition(() -> leftVerParts.size() == PARTS_CNT - full.get().size(), 5_000));

            // Delay first lock request on late topology.
            TestRecordingCommunicationSpi.spi(client).waitForBlocked();

            // At this point only supply messages should be blocked.
            // Unblock to continue rebalance and trigger ideal topology switch.
            crdSpi.stopBlock(true, null, false, true);

            // Wait until ideal topology is ready on crd.
            crd.context().cache().context().exchange().affinityReadyFuture(idealVer).get(10_000);

            // Other node must wait for full message.
            assertFalse(GridTestUtils.waitForCondition(() ->
                grid(2).context().cache().context().exchange().affinityReadyFuture(idealVer).isDone(), 1_000));

            // Map on unstable topology (PME is in progress on other node).
            TestRecordingCommunicationSpi.spi(client).stopBlock();

            // Capture local transaction.
            IgniteInternalTx tx0 = client.context().cache().context().tm().activeTransactions().iterator().next();

            // Expected behavior: tx must hang (both pessimistic and optimistic) because topology is not ready.
            try {
                txFut.get(3_000);

                fail("TX must not complete");
            }
            catch (IgniteFutureTimeoutCheckedException e) {
                // Expected.
            }

            crdSpi.stopBlock();

            txFut.get();

            // Check transaction map version. Should be mapped on ideal topology.
            assertEquals(tx0.topologyVersionSnapshot(), idealVer);

            awaitPartitionMapExchange();

            checkFutures();
        }
        finally {
            stopAllGrids();
        }
    }
}


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
from django.db.models.deletion import SET_NULL

DJSTRIPE_SUBSCRIBER_MODEL = getattr(settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL)

def on_subscriber_delete_purge_customers(collector, field, sub_objs, using):
    """ Ensure that all customers attached to subscriber are purged on deletion. """
    for obj in sub_objs:
        obj.purge()

    SET_NULL(collector, field, sub_objs, using)

class Migration(migrations.Migration):

    dependencies = [
        ('djstripe', '0018_field_docs'),
    ]

    operations = [
        migrations.AlterField(
            model_name='customer',
            name='subscriber',
            field=models.OneToOneField(null=True, on_delete=on_subscriber_delete_purge_customers, to=DJSTRIPE_SUBSCRIBER_MODEL),
        ),
    ]


text:
from google.cloud import datastream_v1

def sample_create_route():
    # Create a client
    client = datastream_v1.DatastreamClient()

    # Initialize request argument(s)
    route = datastream_v1.Route()
    route.display_name = "display_name_value"
    route.destination_address = "destination_address_value"

    request = datastream_v1.CreateRouteRequest(
        parent="parent_value",
        route_id="route_id_value",
        route=route,
    )

    # Make the request
    operation = client.create_route(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

# [END datastream_v1_generated_Datastream_CreateRoute_sync]


text:
"""This example illustrates how to download a report file."""

import argparse
import io
import os
import sys

import dfareporting_utils
from googleapiclient import http
from oauth2client import client

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
    'report_id', type=int,
    help='The ID of the report to get a file for')
argparser.add_argument(
    'file_id', type=int,
    help='The ID of the file to get')

# Chunk size to use when downloading report files. Defaults to 32MB.
CHUNK_SIZE = 32 * 1024 * 1024

def main(argv):
  # Retrieve command line arguments.
  flags = dfareporting_utils.get_arguments(argv, __doc__, parents=[argparser])

  # Authenticate and construct service.
  service = dfareporting_utils.setup(flags)

  report_id = flags.report_id
  file_id = flags.file_id

  try:
    # Retrieve the file metadata.
    report_file = service.files().get(reportId=report_id,
                                      fileId=file_id).execute()

    if report_file['status'] == 'REPORT_AVAILABLE':
      # Prepare a local file to download the report contents to.
      out_file = io.FileIO(generate_file_name(report_file), mode='wb')

      # Create a get request.
      request = service.files().get_media(reportId=report_id, fileId=file_id)

      # Create a media downloader instance.
      # Optional: adjust the chunk size used when downloading the file.
      downloader = http.MediaIoBaseDownload(out_file, request,
                                            chunksize=CHUNK_SIZE)

      # Execute the get request and download the file.
      download_finished = False
      while download_finished is False:
        _, download_finished = downloader.next_chunk()

      print('File %s downloaded to %s'
            % (report_file['id'], os.path.realpath(out_file.name)))

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')

def generate_file_name(report_file):
  """Generates a report file name based on the file metadata."""
  # If no filename is specified, use the file ID instead.
  file_name = report_file['fileName'] or report_file['id']
  extension = '.csv' if report_file['format'] == 'CSV' else '.xml'
  return file_name + extension

if __name__ == '__main__':
  main(sys.argv)


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/bg"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/iv_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="53dp"
        android:src="@mipmap/btn_add" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:lineSpacingExtra="11dp"
        android:text="@string/no_device_tip"
        android:textColor="@color/c323232"
        android:textSize="@dimen/size_32" />

</LinearLayout>


text:
import click

from alertaclient.utils import action_progressbar, build_query

@click.command('unshelve', short_help='Un-shelve alerts')
@click.option('--ids', '-i', metavar='ID', multiple=True, help='List of alert IDs (can use short 8-char id)')
@click.option('--query', '-q', 'query', metavar='QUERY', help='severity:"warning" AND resource:web')
@click.option('--filter', '-f', 'filters', metavar='FILTER', multiple=True, help='KEY=VALUE eg. serverity=warning resource=web')
@click.option('--text', help='Message associated with status change')
@click.pass_obj
def cli(obj, ids, query, filters, text):
    """Set alert status to 'open'."""
    client = obj['client']
    if ids:
        total = len(ids)
    else:
        if query:
            query = [('q', query)]
        else:
            query = build_query(filters)
        total, _, _ = client.get_count(query)
        ids = [a.id for a in client.get_alerts(query)]

    action_progressbar(client, 'unshelve', ids, label=f'Un-shelving {total} alerts', text=text)


text:
/*
Allocore Example: Parallel thread computation

Description:
This example shows how to spawn multiple threads to perform a calculation-
computing the mean of an array. The task is broken into individual work units
that compute the sum of a unique sub-interval of the entire array. When the
individual workers are done, their results are combined into the final result.

Author:
Lance Putnam, 1/2012
*/

#include <stdio.h>
#include "allocore/system/al_Thread.hpp"
using namespace al;

// The function each worker thread will execute
struct Func{

	void operator()(){
		printf("Summing indices %u to %u ...\n", ival[0], ival[1]-1);
		for(unsigned i=ival[0]; i<ival[1]; ++i) sum += data[i];
	}

	unsigned ival[2];		// processing interval
	double sum = 0.;		// final result
	const double * data;	// read-only data
};

int main(){
	int Nthreads = 7;			// number of worker threads
	const unsigned N = 100000;	// size of our array
	double data[N];

	// Fill array with polynomial
	for(unsigned i=0; i<N; ++i){
		double f = double(i)/N;
		data[i] = 1 - f*f;
	}

	Threads<Func> threads(Nthreads);

	// Setup worker thread summation intervals
	for(int i=0; i<Nthreads; ++i){
		threads.getInterval(threads.function(i).ival, i, N);
		threads.function(i).data = data;
	}

	// Compute in parallel
	// By default, the threads join the main thread when finished
	threads.start();

	// Combine worker results
	double sumPll = 0;
	for(int i=0; i<Nthreads; ++i){
		sumPll += threads.function(i).sum;
	}

	// Compute serially for verification
	double sumSer = 0;
	for(unsigned i=0; i<N; ++i){
		sumSer += data[i];
	}

	printf("Correct : %g\n", sumSer/N);
	printf("Computed: %g\n", sumPll/N);
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>SSD1306 OLED display driver: SSD1306_RECT Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

SSD1306 OLED display driver
    1.8.2

This library is developed to control SSD1306/SSD1331/SSD1351/IL9163/PCD8554 RGB i2c/spi LED displays

Public Attributes |
List of all members

SSD1306_RECT Struct Reference

#include <nano_gfx_types.h>

Public Attributes

uint8_t 	left

 	left

uint8_t 	top

 	top

uint8_t 	right

 	right

uint8_t 	bottom

 	bottom

Detailed Description

Rectangle region. not used now

Definition at line 129 of file nano_gfx_types.h.

The documentation for this struct was generated from the following file:

nano_gfx_types.h

<address class="footer">
Generated by

 1.8.13
</address>


text:
.red{
    color: #f00;
}
.SELECTBOX{
    width: 260px;
    height: 19px;
    overflow: hidden;
    border: 1px solid #ccc;
    padding: 1px 1px 0;
    margin: 0;
    background: #fff;
    position: relative;
    font-size: 12px;
}

.SELECTBOX-active{
    overflow: visible;
}

.SELECTBOX .SELECTLabel{
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 0 0 0 3px;
    margin: 0;
    line-height: 18px;
    color: #444;
    margin-right: 20px;
    cursor: pointer;
}

.SELECTBOX .SELECTIcon{
    position: absolute;
    display: block;
    right: 1px;
    top: 1px;
    width: 17px;
    height: 18px;
    background: url(http://p5.qhimg.com/d/inn/6ec56c0d/sel-aro.png) no-repeat;
    overflow: hidden;
    padding: 0;
    margin: 0;
    font-size: 0;
    line-height: 0;
    float: right;
}

.SELECTBOX:hover .SELECTIcon{
    background-position: 0 -18px;
}

.SELECTBOX-disabled{
    border: 1px solid #ddd;
    background: #f0f0f0;
}

.SELECTBOX-disabled .SELECTLabel{
    color: #666;
    cursor: default;
}

.SELECTBOX-disabled:hover .SELECTIcon{
    background-position: 0 0;
}

.SELECTBOX-disabled .SELECTIcon{
    filter: alpha(opacity=70);
    opacity: 0.7;
}

.SELECTListBox{
    display: none;
    background: #fff;
    width: 100%;
    border: 1px solid #ccc;
    position: absolute;
    left: -1px;
    top: 19px;
    overflow-x: auto;
}

.SELECTListBox ul{
    list-style: none;
    padding: 0;
    margin: 0;
    max-height: 200px;
    overflow-y: scroll;
}

.SELECTListBox li{
    padding: 0;
    vertical-align: middle;
    float: none;
    display:block;
}

.SELECTListBox li label{
    padding: 4px 8px;
    display: block !important;
}
.SELECTListBox li input{
   margin: 0 3px 0 0;
   vertical-align: -3px;
}
.SELECTClose{
    /*background: #eee;*/
    border-top: 1px solid #ccc;
    text-align: right;
    padding: 2px 10px;
}
/*.SELECTListBox .tree_wrap{
    padding-top: 4px!important;
}*/


text:
using System.Text;

namespace Nancy
{
    using System;
    using System.Linq;

    /// <summary>
    /// A buffer that is used to locate a HTTP multipart/form-data boundary in a stream.
    /// </summary>
    public class HttpMultipartBuffer
    {
        private readonly byte[] boundaryAsBytes;
        private readonly byte[] closingBoundaryAsBytes;
        private readonly byte[] buffer;
        private int position;

        /// <summary>
        /// Initializes a new instance of the <see cref="HttpMultipartBuffer"/> class.
        /// </summary>
        /// <param name="boundaryAsBytes">The boundary as a byte-array.</param>
        /// <param name="closingBoundaryAsBytes">The closing boundary as byte-array</param>
        public HttpMultipartBuffer(byte[] boundaryAsBytes, byte[] closingBoundaryAsBytes)
        {
            this.boundaryAsBytes = boundaryAsBytes;
            this.closingBoundaryAsBytes = closingBoundaryAsBytes;
            this.buffer = new byte[this.boundaryAsBytes.Length];
        }

        /// <summary>
        /// Gets a value indicating whether the buffer contains the same values as the boundary.
        /// </summary>
        /// <value><see langword="true"/> if buffer contains the same values as the boundary; otherwise, <see langword="false"/>.</value>
        public bool IsBoundary
        {
            get { return this.buffer.SequenceEqual(this.boundaryAsBytes); }
        }
        public bool IsClosingBoundary
        {
            get { return this.buffer.SequenceEqual(this.closingBoundaryAsBytes); }
        }
        /// <summary>
        /// Gets a value indicating whether this buffer is full.
        /// </summary>
        /// <value><see langword="true"/> if buffer is full; otherwise, <see langword="false"/>.</value>
        public bool IsFull
        {
            get { return this.position.Equals(this.buffer.Length); }
        }

        /// <summary>
        /// Gets the number of bytes that can be stored in the buffer.
        /// </summary>
        /// <value>The number of bytes that can be stored in the buffer.</value>
        public int Length
        {
            get { return this.buffer.Length; }
        }

        /// <summary>
        /// Resets the buffer so that inserts happens from the start again.
        /// </summary>
        /// <remarks>This does not clear any previously written data, just resets the buffer position to the start. Data that is inserted after Reset has been called will overwrite old data.</remarks>
        public void Reset()
        {
            this.position = 0;
        }

        /// <summary>
        /// Inserts the specified value into the buffer and advances the internal position.
        /// </summary>
        /// <param name="value">The value to insert into the buffer.</param>
        /// <remarks>This will throw an <see cref="ArgumentOutOfRangeException"/> is you attempt to call insert more times then the <see cref="Length"/> of the buffer and <see cref="Reset"/> was not invoked.</remarks>
        public void Insert(byte value)
        {
            this.buffer[this.position++] = value;
        }
    }
}