text:
// MapData.cs
// Introduced: 2015-04-14
// Last edited: 2015-05-13
// Edited by:
// Pontus Magnusson
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using Synced.MapNameSpace;
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;

namespace Synced.MapNamespace
{
    [Serializable]
    [XmlRoot("MapData")]
    public class MapData
    {
        List<MapObjectData> _objects;

        [XmlElement(typeof(PlayerStartData))]
        [XmlElement(typeof(CrystalSpawnData))]
        [XmlElement(typeof(BorderData))]
        [XmlElement(typeof(GoalData))]
        [XmlElement(typeof(MapObjectData))]
        public List<MapObjectData> Objects
        {
            get { return _objects; }
            set { _objects = value; }
        }

        // TODO Temporary ctor for first map file // TODO: had to comment everything
        public MapData()
        {
            _objects = new List<MapObjectData>();

            #region Players
            _objects.Add(new PlayerStartData()
            {
                TexturePath = "",
                drawingLevel = 3,
                PlayerIndex = PlayerIndex.One,
                Position = new Vector2(400, 400),
                Position2 = new Vector2(400, 450),
                Rotation = 0,
            });
            _objects.Add(new PlayerStartData()
            {
                TexturePath = "",
                drawingLevel = 3,
                PlayerIndex = PlayerIndex.Two,
                Position = new Vector2(1920 - 400, 400),
                Position2 = new Vector2(1920 - 400, 450),
                Rotation = 0,
            });
            _objects.Add(new PlayerStartData()
            {
                TexturePath = "",
                drawingLevel = 3,
                PlayerIndex = PlayerIndex.Three,
                Position = new Vector2(400, 1080 - 400),
                Position2 = new Vector2(400, 1080 - 450),
                Rotation = 0,
            });
            _objects.Add(new PlayerStartData()
            {
                TexturePath = "",
                drawingLevel = 3,
                PlayerIndex = PlayerIndex.Four,
                Position = new Vector2(1920 - 400, 1080 - 400),
                Position2 = new Vector2(1920 - 400, 1080 - 450),
                Rotation = 0,
            });
            #endregion

            #region Crystals
            _objects.Add(new CrystalSpawnData()
            {
                TexturePath = "GameObjects/Crystal",
                drawingLevel = 3,
                Position = new Vector2(1920 / 2, 1080 / 2),
                IsStart = true,
            });
            _objects.Add(new CrystalSpawnData()
            {
                TexturePath = "GameObjects/Crystal",
                drawingLevel = 3,
                Position = new Vector2(1920 / 2, 1080 / 2),
                IsStart = false,
            });
            _objects.Add(new CrystalSpawnData()
            {
                TexturePath = "GameObjects/Crystal",
                drawingLevel = 3,
                Position = new Vector2(1920 / 2, 1080 / 2),
                IsStart = false,
            });
            _objects.Add(new CrystalSpawnData()
            {
                TexturePath = "GameObjects/Crystal",
                drawingLevel = 3,
                Position = new Vector2(1920 / 2, 1080 / 2),
                IsStart = false,
            });
            _objects.Add(new CrystalSpawnData()
            {
                TexturePath = "GameObjects/Crystal",
                drawingLevel = 3,
                Position = new Vector2(1920 / 2, 1080 / 2),
                IsStart = false,
            });
            #endregion

            #region Map
            _objects.Add(new MapObjectData()
            {
                Position = new Vector2(129, 111),
                TexturePath = "Maps/Paper/background",
                drawingLevel = 1,
            });
            _objects.Add(new BorderData()
            {
                Position = new Vector2(1920 / 2, 1080 / 2),
                TexturePath = "Maps/Paper/Frame2",
                drawingLevel = 3,
            });
            #endregion

            #region Goals
            _objects.Add(new GoalData()
            {
                Position = new Vector2(300, 1080 / 2),
                TexturePath = "Maps/Paper/Goal",
                Texture2Path = "GameObjects/GoalBorder",
                drawingLevel = 3,
                Direction = GoalDirections.West,
            });
            _objects.Add(new GoalData()
            {
                Position = new Vector2(1920 - 300, 1080 / 2),
                TexturePath = "GameObjects/Goal",
                Texture2Path = "GameObjects/GoalBorder",
                drawingLevel = 3,
                Direction = GoalDirections.East,
            });
            #endregion
        }
    }
}


text:
require 'spec_helper'

describe NetSuite::Records::JournalEntryLineList do
  let(:list) { NetSuite::Records::JournalEntryLineList.new }

  it 'has a custom_fields attribute' do
    expect(list.lines).to be_kind_of(Array)
  end

  describe '#to_record' do
    before do
      list.lines << NetSuite::Records::JournalEntryLine.new(:memo => 'This is a memo')
    end

    it 'can represent itself as a SOAP record' do
      record =
        {
          'tranGeneral:line' => [{
            'tranGeneral:memo' => 'This is a memo'
          }]
        }
      expect(list.to_record).to eql(record)
    end
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?php
defined('BASEPATH') OR exit('No direct access allowed');

/**
*
*/
class User extends CI_Controller
{

	function profile()
	{
		$data['username'] = $this->session->userdata('username');
		$data['level'] = $this->session->userdata('level');

		$username = $this->session->userdata('username');
		$this->load->model("User_model");

		$data['result'] = $this->User_model->readsingle("username = '$username'");
		$data['view'] = "user_page/profile";
		$this->load->view('index', $data);
	}

	function user_lomba()
	{
		$data['username'] = $this->session->userdata('username');
		$data['level'] = $this->session->userdata('level');

		$this->load->model("user_model");

		$username = $this->session->userdata('username');

		$data['result'] = $this->user_model->read();
		$data['dataHolder'] = $this->user_model->readHolder("username = '$username' ");
		$data['dataKategori'] = $this->user_model->readKategori();

		$data['view'] = "user_page/list_lomba";

		$this->load->view('index', $data);
	}

	// function tambahLomba(){
	// 	$this->load->model("user_model");

	// 	$data['dataHolder'] = $this->user_model->readHolder();
	// 	$data['dataKategori'] = $this->user_model->readKategori();

	// 	$data['view'] = "user_page/list_lomba";
	// 	$this->load->view("index", $data);
	// }

	function do_tambah(){
		$path = "";
		$config['upload_path']          = './gambar';
		$config['allowed_types']        = 'gif|jpg|png';

		if (!is_dir('./gambar')) {
			mkdir('./gambar', 0777, TRUE);
		}

		$this->load->library('upload', $config);

		if (!$this->upload->do_upload('poster')){
			echo $this->upload->display_errors();
			echo "mantap";
		}else{
			$data = $this->upload->data();
			$path = $data['file_name'];
		}
		$arraydata = array (
			"id_kategori" => $this->input->post("id_kategori"),
			"id_holder" => $this->input->post("id_holder"),
			"nama_lomba" => $this->input->post("nama_lomba"),
			"deskripsi" => $this->input->post("deskripsi"),
			"tgl_pendaftaran" => $this->input->post("tgl_pendaftaran"),
			"tgl_pengumpulan" => $this->input->post("tgl_pengumpulan"),
			"link" => $this->input->post("link"),
			"poster" => $path
		);
		$this->load->model("user_model");
		$this->user_model->create($arraydata);

		redirect("user/user_lomba");
	}
}


text:
ansible-docker-demo
===================

A simple ansible project for demonstrating how to build a docker image. Read the article - [Building docker images with ansible](http://victorlin.me/posts/2014/08/11/building-docker-image-with-ansible)

Run the demo
============

To run this demo, you need to install ansible and [vagrant](http://www.vagrantup.com) with vbguest plugin. Then

```
vagrant up
```

Then, let's build the image, here you run

```
ansible-playbook \
  -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory \
  -u vagrant --private-key=~/.vagrant.d/insecure_private_key \
  playbooks/hellobaby.yml
```

It will prompt you which version and interation number to build like this

```
hellobaby_version [1.0.0]:
hellobaby_iteration [1]:
```

Just press enter twice to use the default value. Have a break, it should be done pretty soon.


text:
package org.keycloak.testsuite.model;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientTemplateModel;
import org.keycloak.models.ModelException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.models.utils.RepresentationToModel;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ProtocolMapperRepresentation;
import org.keycloak.services.managers.ClientManager;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * @author Stian Thorgersen
 */
public class ClientModelTest extends AbstractModelTest {
    private ClientModel client;
    private RealmModel realm;

    @Before
    @Override
    public void before() throws Exception {
        super.before();

        realm = realmManager.createRealm("original");
        client = realm.addClient("application");
        client.setName("Application");
        client.setDescription("Description");
        client.setBaseUrl("http://base");
        client.setManagementUrl("http://management");
        client.setClientId("app-name");
        client.addRole("role-1");
        client.addRole("role-2");
        client.addRole("role-3");
        client.addDefaultRole("role-1");
        client.addDefaultRole("role-2");

        client.addRedirectUri("redirect-1");
        client.addRedirectUri("redirect-2");

        client.addWebOrigin("origin-1");
        client.addWebOrigin("origin-2");

        client.registerNode("node1", 10);
        client.registerNode("10.20.30.40", 50);

        client.updateClient();
    }

    @Test
    public void testClientRoleRemovalAndClientScope() throws Exception {
        // Client "from" has a role.  Assign this role to a scope to client "scoped".  Delete the role and make sure
        // cache gets cleared
        ClientModel from = realm.addClient("from");
        RoleModel role = from.addRole("clientRole");
        String roleId = role.getId();
        ClientModel scoped = realm.addClient("scoped");
        String idOfClient = scoped.getId();
        scoped.setFullScopeAllowed(false);
        scoped.addScopeMapping(role);
        commit();
        realm = session.realms().getRealmByName("original");
        scoped = realm.getClientByClientId("scoped");
        from = realm.getClientByClientId("from");
        role = session.realms().getRoleById(roleId, realm);
        from.removeRole(role);
        commit();
        realm = session.realms().getRealmByName("original");
        scoped = realm.getClientByClientId("scoped");
        Set<RoleModel> scopeMappings = scoped.getScopeMappings();
        Assert.assertEquals(0, scopeMappings.size());  // used to throw an NPE

    }

    @Test
    public void testClientRoleRemovalAndClientScopeSameTx() throws Exception {
        // Client "from" has a role.  Assign this role to a scope to client "scoped".  Delete the role and make sure
        // cache gets cleared
        ClientModel from = realm.addClient("from");
        RoleModel role = from.addRole("clientRole");
        String roleId = role.getId();
        ClientModel scoped = realm.addClient("scoped");
        String idOfClient = scoped.getId();
        scoped.setFullScopeAllowed(false);
        scoped.addScopeMapping(role);
        commit();
        realm = session.realms().getRealmByName("original");
        scoped = realm.getClientByClientId("scoped");
        from = realm.getClientByClientId("from");
        role = session.realms().getRoleById(roleId, realm);
        from.removeRole(role);
        Set<RoleModel> scopeMappings = scoped.getScopeMappings();
        Assert.assertEquals(0, scopeMappings.size());  // used to throw an NPE

    }

    @Test
    public void testRealmRoleRemovalAndClientScope() throws Exception {
        // Client "from" has a role.  Assign this role to a scope to client "scoped".  Delete the role and make sure
        // cache gets cleared
        RoleModel role = realm.addRole("clientRole");
        String roleId = role.getId();
        ClientModel scoped = realm.addClient("scoped");
        String idOfClient = scoped.getId();
        scoped.setFullScopeAllowed(false);
        scoped.addScopeMapping(role);
        commit();
        realm = session.realms().getRealmByName("original");
        scoped = realm.getClientByClientId("scoped");
        role = session.realms().getRoleById(roleId, realm);
        realm.removeRole(role);
        commit();
        realm = session.realms().getRealmByName("original");
        scoped = realm.getClientByClientId("scoped");
        Set<RoleModel> scopeMappings = scoped.getScopeMappings();
        Assert.assertEquals(0, scopeMappings.size());  // used to throw an NPE

    }

    @Test
    public void testCircularClientScopes() throws Exception {
        ClientModel scoped1 = realm.addClient("scoped");
        RoleModel role1 = scoped1.addRole("role1");
        ClientModel scoped2 = realm.addClient("scoped2");
        RoleModel role2 = scoped2.addRole("role2");
        scoped1.addScopeMapping(role2);
        scoped2.addScopeMapping(role1);
        commit();
        realm = session.realms().getRealmByName("original");

        // this hit the circular cache and failed with a stack overflow
        scoped1 = realm.getClientByClientId("scoped");

    }

    @Test
    public void persist() {
        RealmModel persisted = realmManager.getRealm(realm.getId());

        ClientModel actual = persisted.getClientByClientId("app-name");
        assertEquals(client, actual);
    }

    @Test
    public void json() {
        ClientRepresentation representation = ModelToRepresentation.toRepresentation(client);
        representation.setId(null);
        for (ProtocolMapperRepresentation protocolMapper : representation.getProtocolMappers()) {
            protocolMapper.setId(null);
        }

        RealmModel realm = realmManager.createRealm("copy");
        ClientModel copy = RepresentationToModel.createClient(session, realm, representation, true);

        assertEquals(client, copy);
    }

    @Test
    public void testAddApplicationWithId() {
        client = realm.addClient("app-123", "application2");
        commit();
        client = realmManager.getRealm(realm.getId()).getClientById("app-123");
        Assert.assertNotNull(client);
    }

    @Test
    public void testCannotRemoveBoundClientTemplate() {
        ClientModel client = realm.addClient("templatized");
        ClientTemplateModel template = realm.addClientTemplate("template");
        client.setClientTemplate(template);
        commit();
        realm = realmManager.getRealmByName("original");
        try {
            realm.removeClientTemplate(template.getId());
            Assert.fail();
        } catch (ModelException e) {

        }
        realm.removeClient(client.getId());
        realm.removeClientTemplate(template.getId());
        commit();
    }

    public static void assertEquals(ClientModel expected, ClientModel actual) {
        Assert.assertEquals(expected.getClientId(), actual.getClientId());
        Assert.assertEquals(expected.getName(), actual.getName());
        Assert.assertEquals(expected.getDescription(), actual.getDescription());
        Assert.assertEquals(expected.getBaseUrl(), actual.getBaseUrl());
        Assert.assertEquals(expected.getManagementUrl(), actual.getManagementUrl());
        Assert.assertEquals(expected.getDefaultRoles(), actual.getDefaultRoles());

        Assert.assertTrue(expected.getRedirectUris().containsAll(actual.getRedirectUris()));
        Assert.assertTrue(expected.getWebOrigins().containsAll(actual.getWebOrigins()));
        Assert.assertTrue(expected.getRegisteredNodes().equals(actual.getRegisteredNodes()));
    }

    public static void assertEquals(List<RoleModel> expected, List<RoleModel> actual) {
        Assert.assertEquals(expected.size(), actual.size());
        Iterator<RoleModel> exp = expected.iterator();
        Iterator<RoleModel> act = actual.iterator();
        while (exp.hasNext()) {
            Assert.assertEquals(exp.next().getName(), act.next().getName());
        }
    }

}


text:
*Mob Rewards*, a Minecraft Bukkit plugin.

Reward your players for killing mobs.

Requires: Vault

Please see the [Bukkit Dev](http://dev.bukkit.org/server-mods/mobrewards/)
page for more info.

A full list of releases (with JARs attached) can be found [here](https://github.com/vxnick/mobrewards/releases).


text:
from collections import defaultdict, Counter
from enum import Enum
from timeit import default_timer as timer
import re, argparse

# global dictionary of words (key: length, value: list of words)
lenDict = defaultdict(list)

#class State(Enum):
#    PLAYING = auto()
#    WON = auto()
#    LOSS = auto()
#
#class Result(Enum):
#    GUESS_EXISTS = auto()
#    GUESS_DNE = auto()
#    ERROR = auto()

class State(Enum):
    PLAYING = 1
    WON = 2
    LOSS = 3

class Result(Enum):
    GUESS_EXISTS = 4
    GUESS_DNE = 5
    ERROR = 6

# represents the status of the game
class Game:
    def __init__(self, inWord):
        self._word = list(inWord)
        self._curr = ['.'] * len(inWord)     # some list that represents a regex object
        self._fail = []                      # some list of failed letters
        self._guessed = []                   # some list of guessed letters
        self._state = State.PLAYING

    # guess a certain letter.
    # updates fail or curr accordingly
    def guess_letter(self, guess):
        if guess in self._guessed:
            print "YOU HAVE ALREADY GUESSED THIS LETTER"
            return Result.ERROR
        if self._state is not State.PLAYING:
            print "GAME OVER"
            return Result.ERROR

        self._guessed.append(guess)
        found = False

        for counter, letter in enumerate(self._word):
            if letter is guess:
                self._curr[counter] = guess
                found = True

        if found is False:
            self._fail.append(guess)
            if len(self._fail) >= 7:
                self._state = State.LOSS
                print "YOU HAVE FAILED IN GUESSING THE WORD:", "".join(self._word)
            return Result.GUESS_DNE
        else:
            if '.' not in self._curr:
                self._state = State.WON
                #print "YOU HAVE SUCCEEDED IN GUESSING THE WORD:", "".join(self._word)
            return Result.GUESS_EXISTS

    def __str__(self):
        return "Word: {0}; Curr: {1}; Fail: {2}; Guessed: {3}".format("".join(self._word), "".join(self._curr), self._fail, self._guessed)

# read text input dictionary, get lenDict.
# note: same working folder
def readDictionary():
    text_file = open('words_50000.txt', 'r')
    lines = text_file.read().splitlines()
    for word in lines:
        l = len(word)
        lenDict[l].append(word)

# iterate through lenDict, find most common letter
def findNextGuess(guessed, dic):
    count = Counter()
    for words in dic:
          for letters in set(words):
              count[letters]+=1
    for guess in count.most_common():
        if guess[0] not in guessed:
            return guess[0]

# run regex match on current list to trim possible solutions list
def trimPoss(curr, poss, missed=None):
    if missed is None:
        pattern = "^" + "".join(curr) + "$"
        searchRegex = re.compile(pattern).search
        return [l for l in poss for m in (searchRegex(l),) if m]
    else:
        return [word for word in poss if missed not in word]

# number of possibilities is less than the number guesses,
# guess words, we will win.
# note: using this function actually makes the overall running time slower.
def guessWords(game, poss):
    for word in poss:
        if word == "".join(game._word):
            game._state = State.WON
            return True
        else:
            game._guessed.append(word)
            if len(game._guessed) >= 7:
                game._state = State.LOSS
                return False

# Hangman solver
def solve(word):
    game = Game(word)
    poss = lenDict[len(game._word)]

    while game._state is State.PLAYING:
        guess = findNextGuess(game._guessed, poss)
        res = game.guess_letter(guess)

        if res is Result.GUESS_EXISTS:
            poss = trimPoss(game._curr, poss)
            # de facto game won
            # this branch is not used because it will increase the running time
            # if len(poss) <= 7-len(game._guessed):
            #     guessWords(game, poss)
            #     break
        elif res is Result.GUESS_DNE:
            poss = trimPoss(game._curr, poss, guess)
        else:
            break
    return game._state

# prints statistics as outlined by requirements
def printStats(time, correct, total):
    print "Number of words tested:", total_words
    print "Number of words guessed correctly:", correct
    print "Correct Guesses (%):", float(correct)/total * 100
    print "Time to run:", time

# main function
if __name__ == "__main__":
    # saves to global variable so we only read the file once
    readDictionary()

    # parser for optional string input that solves a specific word
    # if argument does not exist, run through whole dictionary.
    parser = argparse.ArgumentParser(description='Hangman Solver.')
    parser.add_argument('-w', default=None, help='Specific input for Hangman.')
    args = parser.parse_args()

    if args.w is not None:
        solve(args.w)
    else:
        total_words = 0
        correct_words = 0
        start = timer()
        for k, v in lenDict.iteritems():
            for i in v:
                total_words += 1
                if solve(i) is State.WON:
                    correct_words += 1
        end = timer()
        printStats(end - start, correct_words, total_words)


text:
using System.Collections.Generic;

namespace Lithogen.Core.Interfaces
{
    public interface IPartialCache
    {
        /// <summary>
        /// Loads all the text files from the partials folder.
        /// </summary>
        void Load();

        /// <summary>
        /// Flushes all files from the cache.
        /// </summary>
        int Flush();

        /// <summary>
        /// Returns the number of text files loaded in the cache.
        /// </summary>
        int Count { get; }

        /// <summary>
        /// The set of files that are currently cached.
        /// </summary>
        IEnumerable<ITextFile> Files { get; }

        /// <summary>
        /// Given a partial name, returns the matching partial template based on
        /// the files in the cache.
        /// </summary>
        /// <param name="partialName">The name of the partial.</param>
        /// <param name="relativeTo">Filename to resolve relative to.</param>
        /// <returns>TextFile object containing the body of the template.</returns>
        ITextFile ResolvePartial(string partialName, string relativeTo);
    }
}


text:
namespace eprosima {
namespace fastrtps {
namespace rtps {
namespace security {

bool parse_domain_id_set(tinyxml2::XMLElement* root, Domains& domains);

}
}
}
}

#endif // __SECURITY_ACCESSCONTROL_COMMON_H__


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.34014
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Netcached.Client.Netcached.Server.NetcachedServer.Adapter {

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(ConfigurationName="Netcached.Server.NetcachedServer.Adapter.INetcachedServer")]
    public interface INetcachedServer {

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/INetcachedServer/Set", ReplyAction="http://tempuri.org/INetcachedServer/SetResponse")]
        bool Set(string key, byte[] data, int priority);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/INetcachedServer/Set", ReplyAction="http://tempuri.org/INetcachedServer/SetResponse")]
        System.Threading.Tasks.Task<bool> SetAsync(string key, byte[] data, int priority);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/INetcachedServer/Delete", ReplyAction="http://tempuri.org/INetcachedServer/DeleteResponse")]
        bool Delete(string key);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/INetcachedServer/Delete", ReplyAction="http://tempuri.org/INetcachedServer/DeleteResponse")]
        System.Threading.Tasks.Task<bool> DeleteAsync(string key);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/INetcachedServer/Get", ReplyAction="http://tempuri.org/INetcachedServer/GetResponse")]
        byte[] Get(string key);

        [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/INetcachedServer/Get", ReplyAction="http://tempuri.org/INetcachedServer/GetResponse")]
        System.Threading.Tasks.Task<byte[]> GetAsync(string key);
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public interface INetcachedServerChannel : Netcached.Server.NetcachedServer.Adapter.INetcachedServer, System.ServiceModel.IClientChannel {
    }

    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
    public partial class NetcachedServerClient : System.ServiceModel.ClientBase<Netcached.Server.NetcachedServer.Adapter.INetcachedServer>, Netcached.Server.NetcachedServer.Adapter.INetcachedServer {

        public NetcachedServerClient() {
        }

        public NetcachedServerClient(string endpointConfigurationName) :
                base(endpointConfigurationName) {
        }

        public NetcachedServerClient(string endpointConfigurationName, string remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public NetcachedServerClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
                base(endpointConfigurationName, remoteAddress) {
        }

        public NetcachedServerClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
                base(binding, remoteAddress) {
        }

        public bool Set(string key, byte[] data, int priority = 0) {
            return base.Channel.Set(key, data, priority);
        }

        public System.Threading.Tasks.Task<bool> SetAsync(string key, byte[] data, int priority = 0) {
            return base.Channel.SetAsync(key, data, priority);
        }

        public bool Delete(string key) {
            return base.Channel.Delete(key);
        }

        public System.Threading.Tasks.Task<bool> DeleteAsync(string key) {
            return base.Channel.DeleteAsync(key);
        }

        public byte[] Get(string key) {
            return base.Channel.Get(key);
        }

        public System.Threading.Tasks.Task<byte[]> GetAsync(string key) {
            return base.Channel.GetAsync(key);
        }
    }
}


text:
<?php

namespace PHPExiftool\Driver\Tag\MXF;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class SpeedChangeEffectFlag extends AbstractTag
{

    protected $Id = '060e2b34.0101.0101.05300503.00000000';

    protected $Name = 'SpeedChangeEffectFlag';

    protected $FullName = 'MXF::Main';

    protected $GroupName = 'MXF';

    protected $g0 = 'MXF';

    protected $g1 = 'MXF';

    protected $g2 = 'Video';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Speed Change Effect Flag';

}


text:
package com.intellij.application.options.codeStyle.arrangement.ui;

import javax.annotation.Nonnull;

import javax.swing.*;

/**
 * @author Denis Zhdanov
 * @since 11/12/12 12:34 PM
 */
public interface ArrangementEditorAware {

  @Nonnull
  JComponent getComponent();
}


text:
"""
Base test suite for extension arrays.

These tests are intended for third-party libraries to subclass to validate
that their extension arrays and dtypes satisfy the interface. Moving or
renaming the tests should not be done lightly.

Libraries are expected to implement a few pytest fixtures to provide data
for the tests. The fixtures may be located in either

* The same module as your test class.
* A ``conftest.py`` in the same directory as your test class.

The full list of fixtures may be found in the ``conftest.py`` next to this
file.

.. code-block:: python

   import pytest
   from pandas.tests.extension.base import BaseDtypeTests

   @pytest.fixture
   def dtype():
       return MyDtype()

   class TestMyDtype(BaseDtypeTests):
       pass

Your class ``TestDtype`` will inherit all the tests defined on
``BaseDtypeTests``. pytest's fixture discover will supply your ``dtype``
wherever the test requires it. You're free to implement additional tests.

All the tests in these modules use ``self.assert_frame_equal`` or
``self.assert_series_equal`` for dataframe or series comparisons. By default,
they use the usual ``pandas.testing.assert_frame_equal`` and
``pandas.testing.assert_series_equal``. You can override the checks used
by defining the staticmethods ``assert_frame_equal`` and
``assert_series_equal`` on your base test class.

"""
from .casting import BaseCastingTests  # noqa
from .constructors import BaseConstructorsTests  # noqa
from .dtype import BaseDtypeTests  # noqa
from .getitem import BaseGetitemTests  # noqa
from .groupby import BaseGroupbyTests  # noqa
from .interface import BaseInterfaceTests  # noqa
from .io import BaseParsingTests  # noqa
from .methods import BaseMethodsTests  # noqa
from .missing import BaseMissingTests  # noqa
from .ops import (  # noqa
    BaseArithmeticOpsTests,
    BaseComparisonOpsTests,
    BaseOpsUtil,
    BaseUnaryOpsTests,
)
from .printing import BasePrintingTests  # noqa
from .reduce import (  # noqa
    BaseBooleanReduceTests,
    BaseNoReduceTests,
    BaseNumericReduceTests,
)
from .reshaping import BaseReshapingTests  # noqa
from .setitem import BaseSetitemTests  # noqa


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.05.18 at 05:13:02 PM MST
//

package eml.ecoinformatics_org.literature_2_1;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import eml.ecoinformatics_org.party_2_1.ResponsibleParty;

/**
 *
Java class for Article complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="Article">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="journal" type="{eml://ecoinformatics.org/resource-2.1.1}NonEmptyStringType"/>
 *         <element name="volume" type="{eml://ecoinformatics.org/resource-2.1.1}NonEmptyStringType" minOccurs="0"/>
 *         <element name="issue" type="{eml://ecoinformatics.org/resource-2.1.1}NonEmptyStringType" minOccurs="0"/>
 *         <element name="pageRange" type="{eml://ecoinformatics.org/resource-2.1.1}NonEmptyStringType" minOccurs="0"/>
 *         <element name="publisher" type="{eml://ecoinformatics.org/party-2.1.1}ResponsibleParty" minOccurs="0"/>
 *         <element name="publicationPlace" type="{eml://ecoinformatics.org/resource-2.1.1}NonEmptyStringType" minOccurs="0"/>
 *         <element name="ISSN" type="{eml://ecoinformatics.org/resource-2.1.1}NonEmptyStringType" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Article", propOrder = {
    "journal",
    "volume",
    "issue",
    "pageRange",
    "publisher",
    "publicationPlace",
    "issn"
})
public class Article {

    @XmlElement(required = true)
    protected String journal;
    protected String volume;
    protected String issue;
    protected String pageRange;
    protected ResponsibleParty publisher;
    protected String publicationPlace;
    @XmlElement(name = "ISSN")
    protected String issn;

    /**
     * Gets the value of the journal property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getJournal() {
        return journal;
    }

    /**
     * Sets the value of the journal property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setJournal(String value) {
        this.journal = value;
    }

    /**
     * Gets the value of the volume property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVolume() {
        return volume;
    }

    /**
     * Sets the value of the volume property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVolume(String value) {
        this.volume = value;
    }

    /**
     * Gets the value of the issue property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIssue() {
        return issue;
    }

    /**
     * Sets the value of the issue property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIssue(String value) {
        this.issue = value;
    }

    /**
     * Gets the value of the pageRange property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPageRange() {
        return pageRange;
    }

    /**
     * Sets the value of the pageRange property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPageRange(String value) {
        this.pageRange = value;
    }

    /**
     * Gets the value of the publisher property.
     *
     * @return
     *     possible object is
     *     {@link ResponsibleParty }
     *
     */
    public ResponsibleParty getPublisher() {
        return publisher;
    }

    /**
     * Sets the value of the publisher property.
     *
     * @param value
     *     allowed object is
     *     {@link ResponsibleParty }
     *
     */
    public void setPublisher(ResponsibleParty value) {
        this.publisher = value;
    }

    /**
     * Gets the value of the publicationPlace property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPublicationPlace() {
        return publicationPlace;
    }

    /**
     * Sets the value of the publicationPlace property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPublicationPlace(String value) {
        this.publicationPlace = value;
    }

    /**
     * Gets the value of the issn property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getISSN() {
        return issn;
    }

    /**
     * Sets the value of the issn property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setISSN(String value) {
        this.issn = value;
    }

}


text:
import RSVP from 'rsvp';
import { computed } from '@ember/object';
import { inject as service } from '@ember/service';
import { later, cancel, scheduleOnce, next } from '@ember/runloop';
import { isPresent, typeOf, isEmpty, isNone } from '@ember/utils';
import { A } from '@ember/array';
import { getOwner } from '@ember/application';
import { warn } from '@ember/debug';
import Ember from 'ember';
import BaseStore from './base';
import objectsAreEqual from '../utils/objects-are-equal';

const persistingProperty = function(beforeSet = function() {}) {
  return computed({
    get(key) {
      return this.get(`_${key}`);
    },
    set(key, value) {
      beforeSet.apply(this, [key, value]);
      this.set(`_${key}`, value);
      scheduleOnce('actions', this, this.rewriteCookie);
      return value;
    }
  });
};

/**
  Session store that persists data in a cookie.

  By default the cookie session store uses a session cookie that expires and is
  deleted when the browser is closed. The cookie expiration period can be
  configured by setting the
  {{#crossLink "CookieStore/cookieExpirationTime:property"}}{{/crossLink}}
  property. This can be used to implement "remember me" functionality that will
  either store the session persistently or in a session cookie depending on
  whether the user opted in or not:

  ```js
  // app/controllers/login.js
  export default Ember.Controller.extend({
    rememberMe: computed({
      get(key) {
        return false;
      },
      set(key, value) {
        let expirationTime = value ? (14 * 24 * 60 * 60) : null;
        this.set('session.store.cookieExpirationTime', expirationTime);
        return value;
      }
    })
  });
  ```

  __Applications that use FastBoot must use this session store by defining the
  application session store like this:__

  ```js
  // app/session-stores/application.js
  import CookieStore from 'ember-simple-auth/session-stores/cookie';

  export default CookieStore.extend();
  ```

  @class CookieStore
  @module ember-simple-auth/session-stores/cookie
  @extends BaseStore
  @public
*/
export default BaseStore.extend({
  _syncDataTimeout: null,
  _renewExpirationTimeout: null,

  /**
    The domain to use for the cookie, e.g., "example.com", ".example.com"
    (which includes all subdomains) or "subdomain.example.com". If not
    explicitly set, the cookie domain defaults to the domain the session was
    authenticated on.

    @property cookieDomain
    @type String
    @default null
    @public
  */
  _cookieDomain: null,
  cookieDomain: persistingProperty(),

  /**
    The name of the cookie.

    @property cookieName
    @type String
    @default ember_simple_auth-session
    @public
  */
  _cookieName: 'ember_simple_auth-session',
  cookieName: persistingProperty(function() {
    this._oldCookieName = this._cookieName;
  }),

  /**
    The path to use for the cookie, e.g., "/", "/something".

    @property cookiePath
    @type String
    @default '/'
    @public
  */
  _cookiePath: '/',
  cookiePath: persistingProperty(),

  /**
    The expiration time for the cookie in seconds. A value of `null` will make
    the cookie a session cookie that expires and gets deleted when the browser
    is closed.

    The recommended minimum value is 90 seconds. If your value is less than
    that, the cookie may expire before its expiration time is extended
    (expiration time is extended every 60 seconds).

    @property cookieExpirationTime
    @default null
    @type Integer
    @public
  */
  _cookieExpirationTime: null,
  cookieExpirationTime: persistingProperty(function(key, value) {
    // When nulling expiry time on purpose, we need to clear the cached value.
    // Otherwise, `_calculateExpirationTime` will reuse it.
    if (isNone(value)) {
      this.get('_cookies').clear(`${this.get('cookieName')}-expiration_time`);
    } else if (value < 90) {
      warn('The recommended minimum value for `cookieExpirationTime` is 90 seconds. If your value is less than that, the cookie may expire before its expiration time is extended (expiration time is extended every 60 seconds).', false, { id: 'ember-simple-auth.cookieExpirationTime' });
    }
  }),

  _cookies: service('cookies'),

  _fastboot: computed(function() {
    let owner = getOwner(this);

    return owner && owner.lookup('service:fastboot');
  }),

  _secureCookies: computed(function() {
    if (this.get('_fastboot.isFastBoot')) {
      return this.get('_fastboot.request.protocol') === 'https';
    }

    return window.location.protocol === 'https:';
  }).volatile(),

  _isPageVisible: computed(function() {
    if (this.get('_fastboot.isFastBoot')) {
      return false;
    } else {
      const visibilityState = typeof document !== 'undefined' ? document.visibilityState || 'visible' : false;
      return visibilityState === 'visible';
    }
  }).volatile(),

  init() {
    this._super(...arguments);

    let cachedExpirationTime = this._read(`${this.get('cookieName')}-expiration_time`);
    if (cachedExpirationTime) {
      this.set('cookieExpirationTime', parseInt(cachedExpirationTime, 10));
    }

    if (!this.get('_fastboot.isFastBoot')) {
      next(() => {
        this._syncData().then(() => {
          this._renewExpiration();
        });
      });
    } else {
      this._renew();
    }
  },

  /**
    Persists the `data` in the cookie.

    @method persist
    @param {Object} data The data to persist
    @return {Ember.RSVP.Promise} A promise that resolves when the data has successfully been persisted and rejects otherwise.
    @public
  */
  persist(data) {
    this._lastData = data;
    data = JSON.stringify(data || {});
    let expiration = this._calculateExpirationTime();
    this._write(data, expiration);
    return RSVP.resolve();
  },

  /**
    Returns all data currently stored in the cookie as a plain object.

    @method restore
    @return {Ember.RSVP.Promise} A promise that resolves with the data currently persisted in the store when the data has been restored successfully and rejects otherwise.
    @public
  */
  restore() {
    let data = this._read(this.get('cookieName'));
    if (isEmpty(data)) {
      return RSVP.resolve({});
    } else {
      return RSVP.resolve(JSON.parse(data));
    }
  },

  /**
    Clears the store by deleting the cookie.

    @method clear
    @return {Ember.RSVP.Promise} A promise that resolves when the store has been cleared successfully and rejects otherwise.
    @public
  */
  clear() {
    this._write('', 0);
    this._lastData = {};
    return RSVP.resolve();
  },

  _read(name) {
    return this.get('_cookies').read(name) || '';
  },

  _calculateExpirationTime() {
    let cachedExpirationTime = this._read(`${this.get('cookieName')}-expiration_time`);
    cachedExpirationTime = cachedExpirationTime ? new Date().getTime() + cachedExpirationTime * 1000 : null;
    return this.get('cookieExpirationTime') ? new Date().getTime() + this.get('cookieExpirationTime') * 1000 : cachedExpirationTime;
  },

  _write(value, expiration) {
    let cookieOptions = {
      domain: this.get('cookieDomain'),
      expires: isEmpty(expiration) ? null : new Date(expiration),
      path: this.get('cookiePath'),
      secure: this.get('_secureCookies')
    };
    if (this._oldCookieName) {
      A([this._oldCookieName, `${this._oldCookieName}-expiration_time`]).forEach((oldCookie) => {
        this.get('_cookies').clear(oldCookie);
      });
      delete this._oldCookieName;
    }
    this.get('_cookies').write(this.get('cookieName'), value, cookieOptions);
    if (!isEmpty(expiration)) {
      let expirationCookieName = `${this.get('cookieName')}-expiration_time`;
      let cachedExpirationTime = this.get('_cookies').read(expirationCookieName);
      this.get('_cookies').write(expirationCookieName, this.get('cookieExpirationTime') || cachedExpirationTime, cookieOptions);
    }
  },

  _syncData() {
    return this.restore().then((data) => {
      if (!objectsAreEqual(data, this._lastData)) {
        this._lastData = data;
        this.trigger('sessionDataUpdated', data);
      }
      if (!Ember.testing) {
        cancel(this._syncDataTimeout);
        this._syncDataTimeout = later(this, this._syncData, 500);
      }
    });
  },

  _renew() {
    return this.restore().then((data) => {
      if (!isEmpty(data) && data !== {}) {
        data = typeOf(data) === 'string' ? data : JSON.stringify(data || {});
        let expiration = this._calculateExpirationTime();
        this._write(data, expiration);
      }
    });
  },

  _renewExpiration() {
    if (!Ember.testing) {
      cancel(this._renewExpirationTimeout);
      this._renewExpirationTimeout = later(this, this._renewExpiration, 60000);
    }
    if (this.get('_isPageVisible')) {
      return this._renew();
    } else {
      return RSVP.resolve();
    }
  },

  rewriteCookie() {
    // if `cookieName` has not been renamed, `oldCookieName` will be nil
    const cookieName = this._oldCookieName || this._cookieName;
    const data = this._read(cookieName);
    if (isPresent(data)) {
      const expiration = this._calculateExpirationTime();
      this._write(data, expiration);
    }
  },
});


text:
extern crate vec_map;

use std::marker::PhantomData;
use std::fmt;
use std::ops::{Index, IndexMut};
use std::iter::{Iterator, DoubleEndedIterator};
use vec_map::VecMap;
use std::hash::{Hash, Hasher};
use std::mem;

const INITIAL_CAPACITY: usize = 10;

#[derive(PartialOrd, Ord)]
pub struct TypedHandle<T> {
    index: usize,
    version: usize,
    phantom: PhantomData<T>
}

impl<T> TypedHandle<T> {
    pub fn new(index: usize, version: usize) -> TypedHandle<T> {
        TypedHandle {
            index: index,
            version: version,
            phantom: PhantomData
        }
    }

    #[inline]
    pub fn index(&self) -> usize {
        self.index
    }

    #[inline]
    pub fn version(&self) -> usize {
        self.version
    }
}

impl<T> Copy for TypedHandle<T> {}
impl<T> Clone for TypedHandle<T> {
    fn clone(&self) -> TypedHandle<T> { *self }
}

impl<T> Eq for TypedHandle<T> {}
impl<T> PartialEq for TypedHandle<T> {
    fn eq(&self, rhs: &TypedHandle<T>) -> bool {
        return self.index == rhs.index && self.version == rhs.version;
    }
}

impl<T> fmt::Debug for TypedHandle<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("TypedHandle")
           .field("index", &self.index)
           .field("version", &self.version)
           .finish()
    }
}

impl<T> Hash for TypedHandle<T> {
    fn hash<H>(&self, state: &mut H)
        where H: Hasher
    {
        state.write_usize(self.index);
        state.write_usize(self.version);
    }
}

struct HandleEntry<T> {
    pub version: usize,
    pub inner: Option<T>
}

impl<T> HandleEntry<T> {
    fn new() -> HandleEntry<T> {
        HandleEntry {
            version: 0,
            inner: None
        }
    }
}

pub struct HandleMap<T> {
    next_index: usize,
    availables: Vec<usize>,
    entries: VecMap<HandleEntry<T>>
}

impl<T> HandleMap<T> {
    pub fn new() -> HandleMap<T> {
        HandleMap {
            next_index: 0,
            availables: Vec::with_capacity(INITIAL_CAPACITY),
            entries: VecMap::new()
        }
    }

    pub fn with_capacity(capacity: usize) -> HandleMap<T> {
        HandleMap {
            next_index: 0,
            availables: Vec::with_capacity(INITIAL_CAPACITY),
            entries: VecMap::with_capacity(capacity)
        }
    }

    pub fn insert(&mut self, value: T) -> TypedHandle<T> {
        let index = self.find_available();

        let entry = &mut self.entries[index];
        entry.inner = Some(value);
        TypedHandle::new(index, entry.version)
    }

    #[inline]
    fn find_available(&mut self) -> usize {
        let index = match self.availables.pop() {
            Some(index) => index,
            None => {
                let next = self.next_index + 1;
                mem::replace(&mut self.next_index, next)
            }
        };

        if self.entries.len() <= index {
            self.entries.insert(index, HandleEntry::new());
        }

        index
    }

    pub fn insert_with<F>(&mut self, func: F) -> TypedHandle<T>
        where F: FnOnce(TypedHandle<T>) -> T
    {
        let index = self.find_available();

        let entry = &mut self.entries[index];
        let handle = TypedHandle::new(index, entry.version);
        entry.inner = Some(func(handle));

        handle
    }

    pub fn remove(&mut self, handle: TypedHandle<T>) -> Option<T> {
        let index = handle.index;
        let entry = &mut self.entries[index];
        assert_eq!(entry.version, handle.version);
        assert!(entry.inner.is_some());

        entry.version += 1;
        self.availables.push(index);
        entry.inner.take()
    }

    pub fn clear(&mut self) {
        self.next_index = 0;
        self.availables.clear();
        self.entries.clear();
    }

    pub fn capacity(&self) -> usize {
        self.entries.capacity()
    }

    pub fn is_valid(&self, handle: TypedHandle<T>) -> bool {
        let entry = &self.entries[handle.index];

        entry.version == handle.version && entry.inner.is_some()
    }

    pub fn get(&self, handle: TypedHandle<T>) -> Option<&T> {
        let entry = &self.entries[handle.index];

        if entry.version == handle.version {
            return entry.inner.as_ref();
        }
        None
    }

    pub fn get_mut(&mut self, handle: TypedHandle<T>) -> Option<&mut T> {
        let entry = &mut self.entries[handle.index];

        if entry.version == handle.version {
            return entry.inner.as_mut();
        }
        None
    }

    pub fn iter<'a>(&'a self) -> Iter<'a, T> {
        Iter {
            iter: self.entries.iter()
        }
    }

    pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
        IterMut {
            iter: self.entries.iter_mut()
        }
    }
}

impl<T> Index<TypedHandle<T>> for HandleMap<T> {
    type Output = T;

    #[inline]
    fn index(&self, handle: TypedHandle<T>) -> &Self::Output {
        self.get(handle).unwrap()
    }
}

impl<T> IndexMut<TypedHandle<T>> for HandleMap<T> {
    #[inline]
    fn index_mut(&mut self, handle: TypedHandle<T>) -> &mut Self::Output {
        self.get_mut(handle).unwrap()
    }
}

impl<'a, T> IntoIterator for &'a HandleMap<T> {
    type Item = (TypedHandle<T>, &'a T);
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut HandleMap<T> {
    type Item = (TypedHandle<T>, &'a mut T);
    type IntoIter = IterMut<'a, T>;

    fn into_iter(self) -> IterMut<'a, T> {
        self.iter_mut()
    }
}

macro_rules! iterator {
    (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
        impl<'a, T> Iterator for $name<'a, T> {
            type Item = $elem;

            #[inline]
            fn next(&mut self) -> Option<$elem> {
                while let Some((index, entry)) = self.iter.next() {
                    if entry.inner.is_some() {
                        return Some((TypedHandle::new(index, entry.version),
                                entry.inner$(. $getter())+.unwrap()));
                    }
                }
                None
            }

            #[inline]
            fn size_hint(&self) -> (usize, Option<usize>) {
                self.iter.size_hint()
            }
        }
    }
}

macro_rules! double_ended_iterator {
    (impl $name:ident -> $elem:ty, $($getter:ident),+) => {
        impl<'a, T> DoubleEndedIterator for $name<'a, T> {
            #[inline]
            fn next_back(&mut self) -> Option<$elem> {
                while let Some((index, entry)) = self.iter.next_back() {
                    if entry.inner.is_some() {
                        return Some((TypedHandle::new(index, entry.version),
                                entry.inner$(. $getter())+.unwrap()));
                    }
                }
                None
            }
        }
    }
}

pub struct Iter<'a, T: 'a> {
    iter: vec_map::Iter<'a, HandleEntry<T>>
}

iterator! { impl Iter -> (TypedHandle<T>, &'a T), as_ref }
double_ended_iterator! { impl Iter -> (TypedHandle<T>, &'a T), as_ref }

pub struct IterMut<'a, T: 'a> {
    iter: vec_map::IterMut<'a, HandleEntry<T>>
}

iterator! { impl IterMut -> (TypedHandle<T>, &'a mut T), as_mut }
double_ended_iterator! { impl IterMut -> (TypedHandle<T>, &'a mut T), as_mut }

#[cfg(test)]
mod test {
    use super::*;

    const DUMMY_VALUE: usize = 5;

    #[test]
    fn insert() {
        let mut map = HandleMap::new();

        let handle = map.insert(DUMMY_VALUE);

        assert_eq!(DUMMY_VALUE, map[handle]);
    }

    #[test]
    fn remove() {
        let mut map = HandleMap::new();

        let handle = map.insert(DUMMY_VALUE);
        map.remove(handle);

        assert_eq!(map.is_valid(handle), false);
    }

    #[test]
    fn access_after_remove() {
        let mut map = HandleMap::new();

        let handle = map.insert(DUMMY_VALUE);
        map.remove(handle);

        assert_eq!(map.get(handle).is_none(), true)
    }

    #[test]
    fn access_with_old_handle() {
        let mut map = HandleMap::new();

        let handle = map.insert(DUMMY_VALUE);
        map.remove(handle);
        map.insert(DUMMY_VALUE);

        assert_eq!(map.get(handle).is_none(), true)
    }

    #[test]
    #[should_panic]
    fn remove_with_old_handle() {
        let mut map = HandleMap::new();
        let handle = map.insert(DUMMY_VALUE);
        map.remove(handle);
        map.remove(handle);
    }
}


text:
title: Layout Strategies
page_title: Layout Strategies - WinForms TreeMap Control
description: Check our Layout Strategies documentation article for the RadTreeMap WinForms control.
slug: treemap-layout-strategies
tags: treemap, layout, strategies, algorithms
published: True
position: 4
---

# Layout Strategies

By the end of this help topic, you will learn about the Layout Strategies which are responsible for data tiling in the RadTreeMap control. *Treemap* algorithms represent hierarchical data sets via recursive subdivision of the initial rectangle. The area of each rectangle in the treemap is proportional to the size of that particular node.

>note Layout Strategies are always applied to child nodes.

Currently there are two Layout Strategies to visualize the data:

### Squarified

It creates rectangles with best aspect ratio:

![treemap-layout-strategies 001](images/treemap-layout-strategies001.png)

{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=Squarified}}
{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=Squarified}}

````C#

SquarifiedAlgorithm squarifiedAlgorithm = new SquarifiedAlgorithm();
this.radTreeMap1.Algorithm = squarifiedAlgorithm;

````
````VB.NET
SquarifiedAlgorithm squarifiedAlgorithm = new SquarifiedAlgorithm();
this.radTreeMap1.Algorithm = squarifiedAlgorithm;

````

{{endregion}}

>note The default layout is Squarified.

### Slice and Dice

It creates rectangles with high aspect ratio and displays them sorted either horizontally or vertically:

![treemap-layout-strategies 002](images/treemap-layout-strategies002.png)

For the **Slice and Dice** algorithm you can specify **Orientation** (*Horizontal*, *Vertical* or *Smart*) and **SortDirection** (*Ascending* or *Descending*):

{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=HorizontalSliceDice}}
{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=HorizontalSliceDice}}

````C#

SliceDiceAlgorithm sliceDiceAlgorithm = new SliceDiceAlgorithm();
sliceDiceAlgorithm.Orientation = SliceDiceOrientation.Horizontal;
sliceDiceAlgorithm.SortDirection = ListSortDirection.Descending;
this.radTreeMap1.Algorithm = sliceDiceAlgorithm;

````
````VB.NET

Dim sliceDiceAlgorithm As SliceDiceAlgorithm = New SliceDiceAlgorithm()
sliceDiceAlgorithm.Orientation = SliceDiceOrientation.Horizontal
sliceDiceAlgorithm.SortDirection = System.ComponentModel.ListSortDirection.Descending
Me.radTreeMap1.Algorithm = sliceDiceAlgorithm

````

{{endregion}}

Setting the **Orientation** to *Smart* means that the algorithm will automatically choose the most appropriate orientation depending on your data and the available space.

{{source=..\SamplesCS\TreeMap\TreeMapGettingStarted.cs region=SmartSliceDice}}
{{source=..\SamplesVB\TreeMap\TreeMapGettingStarted.vb region=SmartSliceDice}}

````C#

SliceDiceAlgorithm sliceDiceAlgorithmSmart = new SliceDiceAlgorithm();
sliceDiceAlgorithmSmart.Orientation = SliceDiceOrientation.Smart;
this.radTreeMap1.Algorithm = sliceDiceAlgorithmSmart;

````
````VB.NET

Dim sliceDiceAlgorithmSmart As SliceDiceAlgorithm = New SliceDiceAlgorithm()
sliceDiceAlgorithmSmart.Orientation = SliceDiceOrientation.Smart
Me.radTreeMap1.Algorithm = sliceDiceAlgorithmSmart

````

{{endregion}}

#### Vertical Slice and Dice

![treemap-layout-strategies 003](images/treemap-layout-strategies003.png)

# See Also

* [Structure]({%slug treemap-structure%})

* [Getting Started]({%slug winforms-treemap-getting-started%})


text:
/* 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.
 */
package org.camunda.bpm.engine.impl.cmmn.operation;

import static org.camunda.bpm.engine.impl.util.ActivityBehaviorUtil.getActivityBehavior;

import org.camunda.bpm.engine.impl.cmmn.behavior.CmmnActivityBehavior;
import org.camunda.bpm.engine.impl.cmmn.execution.CmmnExecution;
import org.camunda.bpm.engine.impl.cmmn.model.CmmnActivity;
import org.camunda.bpm.engine.impl.core.operation.AbstractEventAtomicOperation;

/**
 * @author Roman Smirnov
 *
 */
public abstract class AbstractCmmnEventAtomicOperation extends AbstractEventAtomicOperation<CmmnExecution> implements CmmnAtomicOperation {

  protected CmmnActivity getScope(CmmnExecution execution) {
    return execution.getActivity();
  }

  public boolean isAsync(CmmnExecution execution) {
    return false;
  }

  protected final void eventNotificationsCompleted(CmmnExecution execution) {
    repetition(execution);
    preTransitionNotification(execution);
    performTransitionNotification(execution);
    postTransitionNotification(execution);
  }

  protected void repetition(CmmnExecution execution) {
    CmmnActivityBehavior behavior = getActivityBehavior(execution);
    behavior.repeat(execution, getEventName());
  }

  protected void preTransitionNotification(CmmnExecution execution) {

  }

  protected void performTransitionNotification(CmmnExecution execution) {
    String eventName = getEventName();

    CmmnExecution parent = execution.getParent();

    if (parent != null) {
      parent.handleChildTransition(execution, eventName);
    }
  }

  protected void postTransitionNotification(CmmnExecution execution) {
    // noop
  }

}


text:
var UserConfig = require('./userConfig')
var Url = require('url')
var librarian = require('../librarian/librarian')
var apiUtil = require('@xervo/api-util')
var apiClient

var userConfig = new UserConfig()

userConfig.load()

if (userConfig.data && userConfig.data.api_uri) {
  var url = Url.parse(userConfig.data.api_uri)

  if (url.protocol === 'https:') {
    librarian.init(url.hostname, url.port || 443, true)
  } else {
    librarian.init(url.hostname, url.port || 80, false)
  }

  var api = url.parse(userConfig.data.api_uri)
  apiClient = apiUtil({
    protocol: api.protocol,
    hostname: api.hostname,
    version: 'v2',
    token: userConfig.data.apiKey
  })
} else {
  librarian.init('api.xervo.io', 443, true)

  apiClient = apiUtil({
    protocol: 'https',
    hostname: 'api.xervo.io',
    version: 'v2',
    token: userConfig.data ? userConfig.data.apiKey : null
  })
}

module.exports = {
  librarian: librarian,
  apiUtil: apiClient,
  userConfig: new UserConfig()
}


text:
namespace prerender {

NoStatePrefetchProcessorImpl::NoStatePrefetchProcessorImpl(
    int render_process_id,
    int render_frame_id,
    const url::Origin& initiator_origin,
    mojo::PendingReceiver<blink::mojom::NoStatePrefetchProcessor> receiver,
    std::unique_ptr<NoStatePrefetchProcessorImplDelegate> delegate)
    : render_process_id_(render_process_id),
      render_frame_id_(render_frame_id),
      initiator_origin_(initiator_origin),
      delegate_(std::move(delegate)) {
  receiver_.Bind(std::move(receiver));
  receiver_.set_disconnect_handler(base::BindOnce(
      &NoStatePrefetchProcessorImpl::Abandon, base::Unretained(this)));
}

NoStatePrefetchProcessorImpl::~NoStatePrefetchProcessorImpl() = default;

// static
void NoStatePrefetchProcessorImpl::Create(
    content::RenderFrameHost* frame_host,
    mojo::PendingReceiver<blink::mojom::NoStatePrefetchProcessor> receiver,
    std::unique_ptr<NoStatePrefetchProcessorImplDelegate> delegate) {
  // NoStatePrefetchProcessorImpl is a self-owned object. This deletes itself on
  // the mojo disconnect handler.
  new NoStatePrefetchProcessorImpl(frame_host->GetProcess()->GetID(),
                                   frame_host->GetRoutingID(),
                                   frame_host->GetLastCommittedOrigin(),
                                   std::move(receiver), std::move(delegate));
}

void NoStatePrefetchProcessorImpl::Start(
    blink::mojom::PrerenderAttributesPtr attributes) {
  if (!initiator_origin_.opaque() &&
      !content::ChildProcessSecurityPolicy::GetInstance()
           ->CanAccessDataForOrigin(render_process_id_, initiator_origin_)) {
    receiver_.ReportBadMessage("NSPPI_INVALID_INITIATOR_ORIGIN");
    // The above ReportBadMessage() closes |receiver_| but does not trigger its
    // disconnect handler, so we need to call the handler explicitly
    // here to do some necessary work.
    Abandon();
    return;
  }

  // Start() must be called only one time.
  if (link_trigger_id_) {
    receiver_.ReportBadMessage("NSPPI_START_TWICE");
    // The above ReportBadMessage() closes |receiver_| but does not trigger its
    // disconnect handler, so we need to call the handler explicitly
    // here to do some necessary work.
    Abandon();
    return;
  }

  auto* render_frame_host =
      content::RenderFrameHost::FromID(render_process_id_, render_frame_id_);
  if (!render_frame_host)
    return;

  auto* link_manager = GetNoStatePrefetchLinkManager();
  if (!link_manager)
    return;

  DCHECK(!link_trigger_id_);
  link_trigger_id_ = link_manager->OnStartLinkTrigger(
      render_process_id_,
      render_frame_host->GetRenderViewHost()->GetRoutingID(),
      std::move(attributes), initiator_origin_);
}

void NoStatePrefetchProcessorImpl::Cancel() {
  if (!link_trigger_id_)
    return;
  auto* link_manager = GetNoStatePrefetchLinkManager();
  if (link_manager)
    link_manager->OnCancelLinkTrigger(*link_trigger_id_);
}

void NoStatePrefetchProcessorImpl::Abandon() {
  if (link_trigger_id_) {
    auto* link_manager = GetNoStatePrefetchLinkManager();
    if (link_manager)
      link_manager->OnAbandonLinkTrigger(*link_trigger_id_);
  }
  delete this;
}

NoStatePrefetchLinkManager*
NoStatePrefetchProcessorImpl::GetNoStatePrefetchLinkManager() {
  auto* render_frame_host =
      content::RenderFrameHost::FromID(render_process_id_, render_frame_id_);
  if (!render_frame_host)
    return nullptr;
  return delegate_->GetNoStatePrefetchLinkManager(
      render_frame_host->GetProcess()->GetBrowserContext());
}

}  // namespace prerender


text:
void raise_io_codec_error(VM* vm, const char* who, int operation, const char* message, scm_obj_t io, scm_obj_t ch) {
  vm->backtrace_seek();
  scm_symbol_t arg1 = make_symbol(vm->m_heap, who);
  scm_string_t arg2 = make_string(vm->m_heap, message);

  switch (operation) {
    case SCM_PORT_OPERATION_ENCODE: {
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-encoding-error"), 4, arg1, arg2, io, ch);
    } break;
    case SCM_PORT_OPERATION_DECODE: {
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-decoding-error"), 3, arg1, arg2, io);
    } break;
    default:
      fatal("%s:%u wrong port operation code", __FILE__, __LINE__);
  }
}

void raise_io_error(VM* vm, const char* who, int operation, const char* message, int err, scm_obj_t io, scm_obj_t filename) {
  vm->backtrace_seek();
  scm_symbol_t arg1 = make_symbol(vm->m_heap, who);
  scm_string_t arg2;
  char buf[256];
  if (err) {
    snprintf(buf, sizeof(buf), "%s (%d)", message, err);
    arg2 = make_string(vm->m_heap, buf);
  } else {
    arg2 = make_string(vm->m_heap, message);
  }
  switch (operation) {
    case SCM_PORT_OPERATION_OPEN: {
      switch (err) {
        case ENOENT:
          vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-file-does-not-exist-error"), 3, arg1, arg2, filename);
          break;
        case EEXIST:
          vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-file-already-exists-error"), 3, arg1, arg2, filename);
          break;
        case EROFS:
        case EISDIR:
        case ETXTBSY:
          vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-file-is-read-only-error"), 3, arg1, arg2, filename);
          break;
        case EACCES:
          vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-file-protection-error"), 3, arg1, arg2, filename);
          break;
        default:
          vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-error"), 3, arg1, arg2, filename);
          break;
      }
    } break;
    case SCM_PORT_OPERATION_READ: {
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-read-error"), 3, arg1, arg2, io);
    } break;
    case SCM_PORT_OPERATION_WRITE: {
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-write-error"), 3, arg1, arg2, io);
    } break;
    case SCM_PORT_OPERATION_SEEK: {
      scm_obj_t pos = int64_to_integer(vm->m_heap, ((scm_port_t)io)->mark);
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-invalid-position-error"), 4, arg1, arg2, io, pos);
    } break;
    case SCM_SOCKET_OPERATION_OPEN: {
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-error"), 2, arg1, arg2);
    } break;
    case SCM_PORT_OPERATION_CLOSE:
    case SCM_PORT_OPERATION_STAT:
    case SCM_PORT_OPERATION_SELECT: {
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-error"), 3, arg1, arg2, io);
    } break;
    case SCM_SOCKET_OPERATION_READ:
    case SCM_SOCKET_OPERATION_WRITE:
    case SCM_SOCKET_OPERATION_ACCEPT: {
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-error"), 3, arg1, arg2, io);
      break;
    }
    default:
      fatal("%s:%u wrong port operation code", __FILE__, __LINE__);
  }
}

void raise_io_filesystem_error(VM* vm, const char* who, const char* message, int err, scm_obj_t old_filename, scm_obj_t new_filename) {
  vm->backtrace_seek();
  scm_symbol_t arg1 = make_symbol(vm->m_heap, who);
  scm_string_t arg2;
  char buf[256];
  if (err) {
    snprintf(buf, sizeof(buf), "%s (%d)", message, err);
    arg2 = make_string(vm->m_heap, buf);
  } else {
    arg2 = make_string(vm->m_heap, message);
  }
  switch (err) {
    case ENOENT:
    case EISDIR:
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-file-does-not-exist-error"), 3, arg1, arg2, old_filename);
      break;
    case EEXIST:
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-file-already-exists-error"), 3, arg1, arg2, new_filename);
      break;
    default:
      vm->apply_scheme(vm->lookup_system_closure(".@raise-i/o-error"), 4, arg1, arg2, old_filename, new_filename);
      break;
  }
}


text: <!DOCTYPE html>


text:
source math.lib

function help {
	echo "--fib and number for fibonacci"
	echo "--fac and number for factorial"
	echo "--pri and number to know is this number prime"
	echo "--help for call help"
}

case "$1" in
	--help)	help;;
	--fib)	fib $2;;
	--fac)	fac $2;;
	--pri)	isPrime $2;;
	*) 	echo "Wrong parametres! --help for help";;
esac

exit 0


text:
/**
 * This code was donated by Dan Vulpe https://github.com/dvulpe/atmosphere-ws-pubsub
 */
package org.atmosphere.samples.pubsub.config.protocol;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.atmosphere.config.service.WebSocketProtocolService;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResourceImpl;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.samples.pubsub.config.SpringApplicationContext;
import org.atmosphere.samples.pubsub.dto.BaseCommand;
import org.atmosphere.samples.pubsub.dto.Command;
import org.atmosphere.samples.pubsub.dto.EmptyCommand;
import org.atmosphere.samples.pubsub.services.ChatService;
import org.atmosphere.websocket.WebSocket;
import org.atmosphere.websocket.WebSocketProcessor;
import org.atmosphere.websocket.WebSocketProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

@WebSocketProtocolService
public class DelegatingWebSocketProtocol implements WebSocketProtocol {

    public static final Logger LOG = LoggerFactory.getLogger(DelegatingWebSocketProtocol.class);

    @Override
    public void configure(AtmosphereConfig atmosphereConfig) {
        // nothing needed
    }

    @Override
    public List<AtmosphereRequest> onMessage(WebSocket webSocket, String message) {
        if (webSocket.resource() == null) {
            return null;
        }
        AtmosphereResourceImpl resource = (AtmosphereResourceImpl) webSocket.resource();
        resource.suspend();

        ChatService chatService = SpringApplicationContext.getBean(ChatService.class);
        ObjectMapper mapper = SpringApplicationContext.getBean(ObjectMapper.class);
        Command command = readCommand(message, mapper);
        command.setResource(resource);
        chatService.execute(command);
        return null;
    }

    private Command readCommand(String s, ObjectMapper mapper) {
        Command command = new EmptyCommand();
        try {
            command = mapper.readValue(s, BaseCommand.class);
        } catch (IOException e) {
            LOG.error("Exception converting JSON:", e);
        }
        return command;
    }

    @Override
    public List<AtmosphereRequest> onMessage(WebSocket webSocket, byte[] bytes, int offset, int length) {
        return onMessage(webSocket, new String(bytes, offset, length));
    }

    @Override
    public void onOpen(WebSocket webSocket) {
        LOG.debug("opened web socket connection {}", webSocket);
    }

    @Override
    public void onClose(WebSocket webSocket) {
        LOG.debug("closing web socket connection {}", webSocket);
    }

    @Override
    public void onError(WebSocket webSocket, WebSocketProcessor.WebSocketException e) {
        LOG.error("error on websocket connection {}", e);
    }
}


text:
PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
STOPBITS_ONE, STOPBITS_TWO = (1, 2)
FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5,6,7,8)

PARITY_NAMES = {
    PARITY_NONE: 'None',
    PARITY_EVEN: 'Even',
    PARITY_ODD:  'Odd',
    PARITY_MARK: 'Mark',
    PARITY_SPACE:'Space',
}

XON  = chr(17)
XOFF = chr(19)

#Python < 2.2.3 compatibility
try:
    True
except:
    True = 1
    False = not True

class SerialException(Exception):
    """Base class for serial port related exceptions."""

portNotOpenError = SerialException('Port not open')

class SerialTimeoutException(SerialException):
    """Write timeouts give an exception"""

writeTimeoutError = SerialTimeoutException("Write timeout")

class FileLike(object):
    """An abstract file like class.

    This class implements readline and readlines based on read and
    writelines based on write.
    This class is used to provide the above functions for to Serial
    port objects.

    Note that when the serial port was opened with _NO_ timeout that
    readline blocks until it sees a newline (or the specified size is
    reached) and that readlines would never return and therefore
    refuses to work (it raises an exception in this case)!
    """

    def read(self, size): raise NotImplementedError
    def write(self, s): raise NotImplementedError

    def readline(self, size=None, eol='\n'):
        """read a line which is terminated with end-of-line (eol) character
        ('\n' by default) or until timeout"""
        line = ''
        while 1:
            c = self.read(1)
            if c:
                line += c   #not very efficient but lines are usually not that long
                if c == eol:
                    break
                if size is not None and len(line) >= size:
                    break
            else:
                break
        return line

    def readlines(self, sizehint=None, eol='\n'):
        """read a list of lines, until timeout
        sizehint is ignored"""
        if self.timeout is None:
            raise ValueError, "Serial port MUST have enabled timeout for this function!"
        lines = []
        while 1:
            line = self.readline(eol=eol)
            if line:
                lines.append(line)
                if line[-1] != eol:    #was the line received with a timeout?
                    break
            else:
                break
        return lines

    def xreadlines(self, sizehint=None):
        """just call readlines - here for compatibility"""
        return self.readlines()

    def writelines(self, sequence):
        for line in sequence:
            self.write(line)

    def flush(self):
        """flush of file like objects"""
        pass

    # iterator for e.g. "for line in Serial(0): ..." usage
    def next(self):
        line = self.readline()
        if not line: raise StopIteration
        return line

    def __iter__(self):
        return self

class SerialBase(FileLike):
    """Serial port base class. Provides __init__ function and properties to
       get/set port settings."""

    #default values, may be overriden in subclasses that do not support all values
    BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
                 19200,38400,57600,115200,230400,460800,500000,576000,921600,
                 1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000)
    BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
    PARITIES  = (PARITY_NONE, PARITY_EVEN, PARITY_ODD)
    STOPBITS  = (STOPBITS_ONE, STOPBITS_TWO)

    def __init__(self,
                 port = None,           #number of device, numbering starts at
                                        #zero. if everything fails, the user
                                        #can specify a device string, note
                                        #that this isn't portable anymore
                                        #port will be opened if one is specified
                 baudrate=9600,         #baudrate
                 bytesize=EIGHTBITS,    #number of databits
                 parity=PARITY_NONE,    #enable parity checking
                 stopbits=STOPBITS_ONE, #number of stopbits
                 timeout=None,          #set a timeout value, None to wait forever
                 xonxoff=0,             #enable software flow control
                 rtscts=0,              #enable RTS/CTS flow control
                 writeTimeout=None,     #set a timeout for writes
                 dsrdtr=None,           #None: use rtscts setting, dsrdtr override if true or false
                 interCharTimeout=None  #Inter-character timeout, None to disable
                 ):
        """Initialize comm port object. If a port is given, then the port will be
           opened immediately. Otherwise a Serial port object in closed state
           is returned."""

        self._isOpen   = False
        self._port     = None           #correct value is assigned below trough properties
        self._baudrate = None           #correct value is assigned below trough properties
        self._bytesize = None           #correct value is assigned below trough properties
        self._parity   = None           #correct value is assigned below trough properties
        self._stopbits = None           #correct value is assigned below trough properties
        self._timeout  = None           #correct value is assigned below trough properties
        self._writeTimeout = None       #correct value is assigned below trough properties
        self._xonxoff  = None           #correct value is assigned below trough properties
        self._rtscts   = None           #correct value is assigned below trough properties
        self._dsrdtr   = None           #correct value is assigned below trough properties
        self._interCharTimeout = None   #correct value is assigned below trough properties

        #assign values using get/set methods using the properties feature
        self.port     = port
        self.baudrate = baudrate
        self.bytesize = bytesize
        self.parity   = parity
        self.stopbits = stopbits
        self.timeout  = timeout
        self.writeTimeout = writeTimeout
        self.xonxoff  = xonxoff
        self.rtscts   = rtscts
        self.dsrdtr   = dsrdtr
        self.interCharTimeout = interCharTimeout

        if port is not None:
            self.open()

    def isOpen(self):
        """Check if the port is opened."""
        return self._isOpen

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -

    #TODO: these are not realy needed as the is the BAUDRATES etc attribute...
    #maybe i remove them before the final release...

    def getSupportedBaudrates(self):
        return [(str(b), b) for b in self.BAUDRATES]

    def getSupportedByteSizes(self):
        return [(str(b), b) for b in self.BYTESIZES]

    def getSupportedStopbits(self):
        return [(str(b), b) for b in self.STOPBITS]

    def getSupportedParities(self):
        return [(PARITY_NAMES[b], b) for b in self.PARITIES]

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -

    def setPort(self, port):
        """Change the port. The attribute portstr is set to a string that
           contains the name of the port."""

        was_open = self._isOpen
        if was_open: self.close()
        if port is not None:
            if type(port) in [type(''), type(u'')]:       #strings are taken directly
                self.portstr = port
            else:
                self.portstr = self.makeDeviceName(port)
        else:
            self.portstr = None
        self._port = port
        if was_open: self.open()

    def getPort(self):
        """Get the current port setting. The value that was passed on init or using
           setPort() is passed back. See also the attribute portstr which contains
           the name of the port as a string."""
        return self._port

    port = property(getPort, setPort, doc="Port setting")

    def setBaudrate(self, baudrate):
        """Change baudrate. It raises a ValueError if the port is open and the
        baudrate is not possible. If the port is closed, then tha value is
        accepted and the exception is raised when the port is opened."""
        #~ if baudrate not in self.BAUDRATES: raise ValueError("Not a valid baudrate: %r" % baudrate)
        try:
            self._baudrate = int(baudrate)
        except TypeError:
            raise ValueError("Not a valid baudrate: %r" % (baudrate,))
        else:
            if self._isOpen:  self._reconfigurePort()

    def getBaudrate(self):
        """Get the current baudrate setting."""
        return self._baudrate

    baudrate = property(getBaudrate, setBaudrate, doc="Baudrate setting")

    def setByteSize(self, bytesize):
        """Change byte size."""
        if bytesize not in self.BYTESIZES: raise ValueError("Not a valid byte size: %r" % (bytesize,))
        self._bytesize = bytesize
        if self._isOpen: self._reconfigurePort()

    def getByteSize(self):
        """Get the current byte size setting."""
        return self._bytesize

    bytesize = property(getByteSize, setByteSize, doc="Byte size setting")

    def setParity(self, parity):
        """Change parity setting."""
        if parity not in self.PARITIES: raise ValueError("Not a valid parity: %r" % (parity,))
        self._parity = parity
        if self._isOpen: self._reconfigurePort()

    def getParity(self):
        """Get the current parity setting."""
        return self._parity

    parity = property(getParity, setParity, doc="Parity setting")

    def setStopbits(self, stopbits):
        """Change stopbits size."""
        if stopbits not in self.STOPBITS: raise ValueError("Not a valid stopbit size: %r" % (stopbits,))
        self._stopbits = stopbits
        if self._isOpen: self._reconfigurePort()

    def getStopbits(self):
        """Get the current stopbits setting."""
        return self._stopbits

    stopbits = property(getStopbits, setStopbits, doc="Stopbits setting")

    def setTimeout(self, timeout):
        """Change timeout setting."""
        if timeout is not None:
            if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
            try:
                timeout + 1     #test if it's a number, will throw a TypeError if not...
            except TypeError:
                raise ValueError("Not a valid timeout: %r" % (timeout,))

        self._timeout = timeout
        if self._isOpen: self._reconfigurePort()

    def getTimeout(self):
        """Get the current timeout setting."""
        return self._timeout

    timeout = property(getTimeout, setTimeout, doc="Timeout setting for read()")

    def setWriteTimeout(self, timeout):
        """Change timeout setting."""
        if timeout is not None:
            if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
            try:
                timeout + 1     #test if it's a number, will throw a TypeError if not...
            except TypeError:
                raise ValueError("Not a valid timeout: %r" % timeout)

        self._writeTimeout = timeout
        if self._isOpen: self._reconfigurePort()

    def getWriteTimeout(self):
        """Get the current timeout setting."""
        return self._writeTimeout

    writeTimeout = property(getWriteTimeout, setWriteTimeout, doc="Timeout setting for write()")

    def setXonXoff(self, xonxoff):
        """Change XonXoff setting."""
        self._xonxoff = xonxoff
        if self._isOpen: self._reconfigurePort()

    def getXonXoff(self):
        """Get the current XonXoff setting."""
        return self._xonxoff

    xonxoff = property(getXonXoff, setXonXoff, doc="Xon/Xoff setting")

    def setRtsCts(self, rtscts):
        """Change RtsCts flow control setting."""
        self._rtscts = rtscts
        if self._isOpen: self._reconfigurePort()

    def getRtsCts(self):
        """Get the current RtsCts flow control setting."""
        return self._rtscts

    rtscts = property(getRtsCts, setRtsCts, doc="RTS/CTS flow control setting")

    def setDsrDtr(self, dsrdtr=None):
        """Change DsrDtr flow control setting."""
        if dsrdtr is None:
            #if not set, keep backwards compatibility and follow rtscts setting
            self._dsrdtr = self._rtscts
        else:
            #if defined independently, follow its value
            self._dsrdtr = dsrdtr
        if self._isOpen: self._reconfigurePort()

    def getDsrDtr(self):
        """Get the current DsrDtr flow control setting."""
        return self._dsrdtr

    dsrdtr = property(getDsrDtr, setDsrDtr, "DSR/DTR flow control setting")

    def setInterCharTimeout(self, interCharTimeout):
        """Change inter-character timeout setting."""
        if interCharTimeout is not None:
            if interCharTimeout < 0: raise ValueError("Not a valid timeout: %r" % interCharTimeout)
            try:
                interCharTimeout + 1     #test if it's a number, will throw a TypeError if not...
            except TypeError:
                raise ValueError("Not a valid timeout: %r" % interCharTimeout)

        self._interCharTimeout = interCharTimeout
        if self._isOpen: self._reconfigurePort()

    def getInterCharTimeout(self):
        """Get the current inter-character timeout setting."""
        return self._interCharTimeout

    interCharTimeout = property(getInterCharTimeout, setInterCharTimeout, doc="Inter-character timeout setting for read()")

    #  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -

    def __repr__(self):
        """String representation of the current port settings and its state."""
        return "%s<id=0x%x, open=%s>(port=%r, baudrate=%r, bytesize=%r, parity=%r, stopbits=%r, timeout=%r, xonxoff=%r, rtscts=%r, dsrdtr=%r)" % (
            self.__class__.__name__,
            id(self),
            self._isOpen,
            self.portstr,
            self.baudrate,
            self.bytesize,
            self.parity,
            self.stopbits,
            self.timeout,
            self.xonxoff,
            self.rtscts,
            self.dsrdtr,
        )

if __name__ == '__main__':
    s = SerialBase()
    print s.portstr
    print s.getSupportedBaudrates()
    print s.getSupportedByteSizes()
    print s.getSupportedParities()
    print s.getSupportedStopbits()
    print s


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu)  2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <boost/metaparse/v1/accept.hpp>
#include <boost/metaparse/v1/is_error.hpp>
#include <boost/metaparse/v1/get_position.hpp>
#include <boost/metaparse/v1/get_result.hpp>
#include <boost/metaparse/v1/get_remaining.hpp>

#include <boost/mpl/eval_if.hpp>

namespace boost
{
  namespace metaparse
  {
    namespace v1
    {
      template <class P, class StateP, class BackwardOp>
      struct foldr_start_with_parser
      {
      private:
        template <class Res, class Rem>
        struct apply_unchecked1 :
          accept<
            typename BackwardOp::template apply<
              typename get_result<Rem>::type,
              typename get_result<Res>::type
            >::type,
            typename get_remaining<Rem>::type,
            typename get_position<Rem>::type
          >
        {};

        template <class Res>
        struct apply_unchecked;
      public:
        typedef foldr_start_with_parser type;

        template <class S, class Pos>
        struct apply :
          boost::mpl::eval_if<
            typename is_error<typename P::template apply<S, Pos> >::type,
            typename StateP::template apply<S, Pos>,
            apply_unchecked<typename P::template apply<S, Pos> >
          >
        {};
      private:
        template <class Res>
        struct apply_unchecked
        {
        private:
          typedef
            typename foldr_start_with_parser::template apply<
              typename get_remaining<Res>::type,
              typename get_position<Res>::type
            >
            parsed_remaining;
        public:
          typedef
            typename boost::mpl::eval_if<
              typename is_error<parsed_remaining>::type,
              parsed_remaining,
              apply_unchecked1<Res, parsed_remaining>
            >::type
            type;
        };
      };
    }
  }
}

#endif


text: export * from "./import.component";