text:
angular
	.module('app')
	.controller('historyCtrl', ['$scope', 'Items', '$http', function($scope, Items, $http){
			$scope.title = "Shipping History";
			$scope.items = Items.get().then(function(data) {
				$scope.items = data;
			});

	}]);


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Api\V2010\Account\Queue;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceContext;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;

class MemberContext extends InstanceContext {
    /**
     * Initialize the MemberContext
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param string $accountSid The SID of the Account that created the
     *                           resource(s) to fetch
     * @param string $queueSid The SID of the Queue in which to find the members
     * @param string $callSid The Call SID of the resource(s) to fetch
     * @return \Twilio\Rest\Api\V2010\Account\Queue\MemberContext
     */
    public function __construct(Version $version, $accountSid, $queueSid, $callSid) {
        parent::__construct($version);

        // Path Solution
        $this->solution = array(
            'accountSid' => $accountSid,
            'queueSid' => $queueSid,
            'callSid' => $callSid,
        );

        $this->uri = '/Accounts/' . \rawurlencode($accountSid) . '/Queues/' . \rawurlencode($queueSid) . '/Members/' . \rawurlencode($callSid) . '.json';
    }

    /**
     * Fetch a MemberInstance
     *
     * @return MemberInstance Fetched MemberInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function fetch() {
        $params = Values::of(array());

        $payload = $this->version->fetch(
            'GET',
            $this->uri,
            $params
        );

        return new MemberInstance(
            $this->version,
            $payload,
            $this->solution['accountSid'],
            $this->solution['queueSid'],
            $this->solution['callSid']
        );
    }

    /**
     * Update the MemberInstance
     *
     * @param string $url The absolute URL of the Queue resource
     * @param array|Options $options Optional Arguments
     * @return MemberInstance Updated MemberInstance
     * @throws TwilioException When an HTTP error occurs.
     */
    public function update($url, $options = array()) {
        $options = new Values($options);

        $data = Values::of(array('Url' => $url, 'Method' => $options['method'], ));

        $payload = $this->version->update(
            'POST',
            $this->uri,
            array(),
            $data
        );

        return new MemberInstance(
            $this->version,
            $payload,
            $this->solution['accountSid'],
            $this->solution['queueSid'],
            $this->solution['callSid']
        );
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->solution as $key => $value) {
            $context[] = "$key=$value";
        }
        return '[Twilio.Api.V2010.MemberContext ' . \implode(' ', $context) . ']';
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<meta charset="utf-8" />
<title>input type=text Two nested forms with one input each and submit at the end</title>

	Click the submit button below.  Nothing should happen.

<form action="../../../../res/null_post.rb" method="post">

		<input name="test" type="text" value="foo" />

	<form action="../../../../res/return_multiple_post.rb" method="post">

			<input name="test2" type="text" value="bar" />

	</form>

		<input type="submit" name="submit" />

</form>


text:
'use strict';

/**
 * Module dependencies.
 */
var	thinky = require('../utils/thinky'),
	type = thinky.type,
	r = thinky.r,
	crypto = require('crypto');

/**
 * User Schema
 */
var User = thinky.createModel('User',{
	firstName: type.string(),
	lastName: type.string(),
	displayName: type.string(),
	email: type.string().email(),
	username: type.string(),
	password: type.string(),
	salt: type.string(),
	provider: type.string(),
	providerData: {},
	additionalProvidersData: {},
	roles: type.string().enum(['user','admin']),
	updated: type.date(),
	created: type.date().default(r.now),
	resetPasswordToken: type.string(),
	resetPasswordExpires: type.date(),
	id: type.string()
},{init : true});

/**
 * Create instance method for hashing a password
 */
User.define.hashPassword = function(password) {
    if (this.salt && password) {
        return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
    } else {
        return password;
    }
};

/**
 * Create instance method for authenticating user
 */
User.define.authenticate = function(password) {
    return this.password === this.hashPassword(password);
};

/*User.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }

    next();
});*/

/**
 * Find possible not used username
 */
User.defineStatic.findUniqueUsername = function(username, suffix, callback) {
    var _this = this;
    var possibleUsername = username + (suffix || '');

    _this.get({
        username: possibleUsername
    }, function(err, user) {
        if (!err) {
            if (!user) {
                callback(possibleUsername);
            } else {
                return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
            }
        } else {
            callback(null);
        }
    });
};

module.exports = User;


text:
#ifndef __LTFS_LOCKING_NEW_H__
#define __LTFS_LOCKING_NEW_H__

#ifdef __cplusplus
extern "C" {
#endif

#ifdef mingw_PLATFORM
	#error "New locking system is required on Windows"
#else /* ! mingw_PLATFORM */

#include <pthread.h>
#include <execinfo.h> /* For backtrace() */
#include <unistd.h>

/* Use struct for checking wrong usage of ltfs_mutex and ltfs_thread_mutex by compliter */
typedef struct {
	pthread_mutex_t lock;
} ltfs_mutex_t;

typedef pthread_mutexattr_t ltfs_mutexattr_t;

enum {
	LTFS_THREAD_PROCESS_SHARED = PTHREAD_PROCESS_SHARED,
	LTFS_THREAD_PROCESS_PRIVATE = PTHREAD_PROCESS_PRIVATE
};

static inline void backtrace_info(void)
{
	void *address[50];
	char **funcs = NULL;
	size_t back_num, i;

	back_num = backtrace(address, 50);
	funcs = backtrace_symbols( address, back_num);

	for(i = 0; i < back_num; ++i)  {
		if (funcs && funcs[i])
			ltfsmsg(LTFS_INFO, 17193I, (int)i, address[i], funcs[i]);
		else
			ltfsmsg(LTFS_INFO, 17194I, (int)i, address[i]);
	}

	if (funcs) free(funcs);

	return;
}

static inline int ltfs_mutex_init(ltfs_mutex_t *mutex)
{
	return pthread_mutex_init(&mutex->lock, NULL);
}

static inline int ltfs_mutex_init_attr(ltfs_mutex_t *mutex, ltfs_mutexattr_t *attr)
{
	return pthread_mutex_init(&mutex->lock, attr);
}

static inline int ltfs_mutex_destroy(ltfs_mutex_t *mutex)
{
	return pthread_mutex_destroy(&mutex->lock);
}

static inline int ltfs_mutex_lock(ltfs_mutex_t *mutex)
{
	return pthread_mutex_lock(&mutex->lock);
}

static inline int ltfs_mutex_unlock(ltfs_mutex_t *mutex)
{
	return pthread_mutex_unlock(&mutex->lock);
}

static inline int ltfs_mutex_trylock(ltfs_mutex_t *mutex)
{
	return pthread_mutex_trylock(&mutex->lock);
}

static inline int ltfs_mutexattr_init(ltfs_mutexattr_t *attr)
{
	return pthread_mutexattr_init(attr);
}

static inline int ltfs_mutexattr_destroy(ltfs_mutexattr_t *attr)
{
	return pthread_mutexattr_destroy(attr);
}

static inline int ltfs_mutexattr_setpshared(ltfs_mutexattr_t *attr,
											int pshared)
{
#ifdef __NetBSD__
	abort(); /* Not implemented */
#else
	return pthread_mutexattr_setpshared(attr, pshared);
#endif
}

typedef struct MultiReaderSingleWriter {
	ltfs_mutex_t     exclusive_mutex;
	pthread_rwlock_t rw_lock;
	uint32_t         writer; //if there is a write lock acquired
	uint32_t         long_lock;
} MultiReaderSingleWriter;

static inline int
init_mrsw(MultiReaderSingleWriter *mrsw)
{
	int ret;

	mrsw->writer = 0;
	mrsw->long_lock = 0;
	ret = ltfs_mutex_init(&mrsw->exclusive_mutex);
	if (ret)
		return -ret;

	ret = pthread_rwlock_init(&mrsw->rw_lock, NULL);
	if (ret) {
		ltfs_mutex_destroy(&mrsw->exclusive_mutex);
		return -ret;
	}

	return 0;
}

static inline void
destroy_mrsw(MultiReaderSingleWriter *mrsw)
{
	pthread_rwlock_destroy(&mrsw->rw_lock);
	ltfs_mutex_destroy(&mrsw->exclusive_mutex);
}

static inline bool
try_acquirewrite_mrsw(MultiReaderSingleWriter *mrsw)
{
	int err;
	err = ltfs_mutex_trylock(&mrsw->exclusive_mutex);
	if (err)
		return false;

	err = pthread_rwlock_trywrlock(&mrsw->rw_lock);
	if (err) {
		ltfs_mutex_unlock(&mrsw->exclusive_mutex);
		return false;
	}
	mrsw->writer=1;
	return true;
}

static inline void
acquirewrite_mrsw(MultiReaderSingleWriter *mrsw)
{
	ltfs_mutex_lock(&mrsw->exclusive_mutex);
	pthread_rwlock_wrlock(&mrsw->rw_lock);
	mrsw->writer=1;
	mrsw->long_lock=0;
}

static inline void
acquirewrite_mrsw_long(MultiReaderSingleWriter *mrsw)
{
	ltfs_mutex_lock(&mrsw->exclusive_mutex);
	pthread_rwlock_wrlock(&mrsw->rw_lock);
	mrsw->writer=1;
	mrsw->long_lock=1;
}

static inline void
releasewrite_mrsw(MultiReaderSingleWriter *mrsw)
{
	mrsw->writer=0;
	mrsw->long_lock=0;
	pthread_rwlock_unlock(&mrsw->rw_lock);
	ltfs_mutex_unlock(&mrsw->exclusive_mutex);
}

static inline void
acquireread_mrsw(MultiReaderSingleWriter *mrsw)
{
	ltfs_mutex_lock(&mrsw->exclusive_mutex);
	mrsw->long_lock=0;
	ltfs_mutex_unlock(&mrsw->exclusive_mutex);

	pthread_rwlock_rdlock(&mrsw->rw_lock);
}

static inline int
acquireread_mrsw_short(MultiReaderSingleWriter *mrsw)
{
	int ret = 0;
	//struct timespec tv = {0, 100000000};

	if (mrsw->long_lock)
		return -1;

	while(1) {
		ret = ltfs_mutex_trylock(&mrsw->exclusive_mutex);
		if (! ret)
			break;
		if (mrsw->long_lock)
			return -1;
		/*
		 * Wait 1 sec to avoid busy loop.
		 * This kind of busy loop consumes CPU resource
		 */
		sleep(1);
	}
	ltfs_mutex_unlock(&mrsw->exclusive_mutex);

	pthread_rwlock_rdlock(&mrsw->rw_lock);

	return 0;
}

static inline void
releaseread_mrsw(MultiReaderSingleWriter *mrsw)
{
	pthread_rwlock_unlock(&mrsw->rw_lock);
}

static inline void
release_mrsw(MultiReaderSingleWriter *mrsw)
{
	if(mrsw->writer) {
		//If there is a writer, and we hold a lock, we must be the writer.
		releasewrite_mrsw(mrsw);
	} else {
		releaseread_mrsw(mrsw);
	}
}

//downgrades a write lock to a read lock
static inline void
writetoread_mrsw(MultiReaderSingleWriter *mrsw)
{
	// This thread owns write protection meaning that
	// there are no threads that own read protection.

	// This means:
	// 1) read_count is currently 0 AND all threads requesting read and write protection
	//    are blocked on write_exclusive_mutex
	// 2) There may threads requesting read protection that got through the write_exclusive_mutex gate
	//    before this thread successfully got write protection.
	//    At most, one of this set of threads has gotten through the read_count_mutex gate, and may
	//    have already bumped read_count to 1, or is in the process of bumping read_count to 1. This
	//    thread may or may not be blocked on reading_mutex, but is following that code path.

	// Unset the writer flag before allowing any readers in.
	mrsw->writer = 0;
	mrsw->long_lock = 0;

	// Replace acquired write lock to a read lock
	pthread_rwlock_unlock(&mrsw->rw_lock);
	pthread_rwlock_rdlock(&mrsw->rw_lock);

	//Release the write_exclusive_mutex, to allow others to write protect, and additional readers in.
	ltfs_mutex_unlock(&mrsw->exclusive_mutex);
}
#endif /* mingw_PLATFORM */

#ifdef __cplusplus
}
#endif

#endif /* __LTFS_LOCKING_NEW_H__ */


text:
(function($) {
  $.fn.fn = function() {
    var self = this;
    var extension = arguments[0], name = arguments[0];
    if (typeof name == "string") {
      return apply(self, name, $.makeArray(arguments).slice(1, arguments.length));
    } else {
      $.each(extension, function(key, value) {
        define(self, key, value);
      });
      return self;
    }
  };
  function define(self, name, fn) {
    self.data(namespacedName(name), fn);
  };
  function apply(self, name, args) {
    var result;
    self.each(function(i, item) {
      var fn = $(item).data(namespacedName(name));
      if (fn) result = fn.apply(item, args)
      else throw(name + " is not defined");
    });

    return result;
  };
  function namespacedName(name) {
    return 'fn.' + name;
  }
})(jQuery);


text:
<?php

use Symfony\Component\HttpFoundation\Request;

/**
 * @var \Symfony\Component\ClassLoader\ClassLoader
 */
$loader = require __DIR__.'/../app/autoload.php';
include_once __DIR__.'/../app/bootstrap.php.cache';

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();

if ($_SERVER['REMOTE_ADDR'] === '144.217.203.53') {
    Request::setTrustedProxies([$_SERVER['REMOTE_ADDR']]);
    // force all trusted header names
    Request::setTrustedHeaderName(Request::HEADER_FORWARDED, '');
    Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_REAL_IP');
    Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, '');
    Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, '');
    Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, '');
}

$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);


text:
module Data.BERT
  ( module Data.BERT.Types
  , module Data.BERT.Term
  , module Data.BERT.Packet
  ) where

import Data.BERT.Types
import Data.BERT.Term
import Data.BERT.Packet


text:
=begin
#BillForward REST API

#No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

OpenAPI spec version: 1.0.0

Generated by: https://github.com/swagger-api/swagger-codegen.git
Swagger Codegen version: 2.2.3-SNAPSHOT

=end

require 'spec_helper'
require 'json'

# Unit tests for Bfwd::FixedtermdefinitionsApi
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'FixedtermdefinitionsApi' do
  before do
    # run before each test
    @instance = Bfwd::FixedtermdefinitionsApi.new
  end

  after do
    # run after each test
  end

  describe 'test an instance of FixedtermdefinitionsApi' do
    it 'should create an instance of FixedtermdefinitionsApi' do
      expect(@instance).to be_instance_of(Bfwd::FixedtermdefinitionsApi)
    end
  end

  # unit tests for create_fixed_term_definition
  # Create
  # {\"nickname\":\"Create a new fixed term definition\",\"request\":\"createFixedTermDefinitionRequest.html\",\"response\":\"createFixedTermDefinitionResponse.html\"}
  # @param fixed_term_definiton The fixed-term-definition object to be updated.
  # @param [Hash] opts the optional parameters
  # @return [FixedTermDefinitionPagedMetadata]
  describe 'create_fixed_term_definition test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  # unit tests for update_fixed_term_definition
  # Update
  # {\"nickname\":\"Update a fixed-term definition\",\"request\":\"updateFixedTermDefinitionRequest.html\",\"response\":\"updateFixedTermDefinitionResponse.html\"}
  # @param fixed_term_definiton The fixed-term-definition object to be updated.
  # @param [Hash] opts the optional parameters
  # @return [FixedTermDefinitionPagedMetadata]
  describe 'update_fixed_term_definition test' do
    it "should work" do
      # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

end


text:
/*
    Game_of_life.cpp :
                      main project file.
*/
#include "Board.h"
#include "Form1.h"
#include "../../../common/utility/get_default_num_threads.h"

#define WIN32_LEAN_AND_MEAN

#ifndef _CONSOLE
#include <windows.h>
#else
#include <iostream>
#include <sstream>
#include <time.h>
#include "Evolution.h"

#define BOARD_SQUARE_SIZE 2

int low;                            //! lower range limit of threads
int high;                           //! high range limit of threads
double execution_time;              //! time for game of life iterations
#endif

Board::Board(int width, int height, int squareSize, LabelPtr counter)
: m_width(width), m_height(height), m_squareSize(squareSize), m_counter(counter)
{
#ifndef _CONSOLE
    InitializeComponent();
    DoubleBuffered = true;

    this->Width = m_squareSize*width;
    this->Height = m_squareSize*height;
#endif
    m_matrix = new Matrix();
    m_matrix->width = width;
    m_matrix->height = height;
    m_matrix->data = new char[width*height];
    memset(m_matrix->data, 0, width*height);
#ifndef _CONSOLE
    m_occupiedBrush = gcnew SolidBrush(Color::Black);
    m_freeBrush = gcnew SolidBrush(Color::LightGray);

    m_graphics = CreateGraphics();
    m_bmp = gcnew Bitmap(Width, Height);
    m_mem_dc = Graphics::FromImage(m_bmp);
#endif
}

Board::~Board()
{
#ifndef _CONSOLE
    if (components)
    {
        delete components;
    }
#endif
    delete[] m_matrix->data;
    delete m_matrix;
}

void Board::seed(int s)
{
    srand(s);
    for (int j=0; j<m_height; j++)
    {
        for (int i=0; i<m_width; i++)
        {
            int x = rand()/(int)(((unsigned)RAND_MAX + 1) / 100);
            m_matrix->data[i+j*m_width] = x>75? 1: 0;               // 25% occupied
        }
    }
#ifndef _CONSOLE
    Invalidate();
#endif
}

void Board::seed( const BoardPtr src )
{
            memcpy(m_matrix->data, src->m_matrix->data, m_height*m_width);
#ifndef _CONSOLE
    Invalidate();
#endif
}

#ifndef _CONSOLE
void Board::draw(Graphics^ g)
{
    m_mem_dc->FillRectangle(m_freeBrush, Drawing::Rectangle(0, 0, m_width*m_squareSize, m_height*m_squareSize));
    for (int j=0; j<m_height; j++)
    {
        for (int i=0; i<m_width; i++)
        {
            if ( m_matrix->data[i+j*m_width] )
            {
                m_mem_dc->FillRectangle(m_occupiedBrush, Drawing::Rectangle(i*m_squareSize, j*m_squareSize, m_squareSize, m_squareSize));
            }
        }
    }
    g->DrawImage(m_bmp, 0, 0);
}

void Board::OnPaint(PaintEventArgs^ e)
{
    draw(e->Graphics);
}

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Enabling Windows XP visual effects before any controls are created
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false);

    // Create the main window and run it
    Application::Run(gcnew Form1());
    return 0;
}
#else

//! Print usage of this program
void PrintUsage()
{
    printf("Usage: gol [M[:N] -t execution_time]\nM and N are a range of numbers of threads to be used.\nexecution_time is a time (in sec) for execution game_of_life iterations\n");
    printf("Default values:\nM:\t\tautomatic\nN:\t\tM\nexecution_time:\t10\n");
}

//! Parse command line
bool ParseCommandLine(int argc, char * argv [])
{
    char* s = argv[1];
    char* end;
    //! command line without parameters
    if(argc == 1)
    {
        low = utility::get_default_num_threads();
        high = low;
        execution_time = 5;
        return true;
    }
    //! command line with parameters
    if(argc != 4)
    {
        PrintUsage();
        return false;
    }
    if(std::string("-t") != argv[argc-2])
    //! process M[:N] parameter
    high = strtol(s,&end,0);
    low = strtol(s,&end,0);
    switch( *end )
    {
        case ':':
            high = strtol(end+1,0,0);
            break;
        case '\0':
            break;
        default:
            PrintUsage();
            return false;
    }
    if (high < low)
    {
        std::cout << "Set correct range. Current range: " << low << ":" << high << std::endl;
        PrintUsage();
        return false;

    }
    //! process execution_time parameter
    execution_time = strtol(argv[argc-1],&end,0);
    return true;
}

int main( int argc, char* argv[] )
{
    if(!ParseCommandLine( argc, argv ))
        return 1;
    SequentialEvolution* m_seq;
    ParallelEvolution* m_par;
    Board* m_board1;
    Board* m_board2;
    int* count = NULL;

    int boardWidth = 300;
    int boardHeight = 300;

    m_board1 = new Board(boardWidth, boardHeight, BOARD_SQUARE_SIZE, count);
    m_board2 = new Board(boardWidth, boardHeight, BOARD_SQUARE_SIZE, count);

    time_t now = time(NULL);
    printf("Generate Game of life board\n");
    m_board1->seed((int)now);
    m_board2->seed(m_board1);

    m_seq = new SequentialEvolution(m_board1->m_matrix, m_board1);
    m_seq->Run(execution_time, 1);
    delete m_seq;

    m_par = new ParallelEvolution(m_board2->m_matrix, m_board2);
    for( int p = low; p <= high; ++p )
    {
        m_par->Run(execution_time, p);
    }
    delete m_par;

    delete m_board1;
    delete m_board2;
    return 0;
}
#endif


text:
package gp.math.jahuwaldt.jatex.latexeditor;

import javax.swing.text.DefaultEditorKit;
import javax.swing.text.ViewFactory;

/**
 * View is responsible for rendering a particular Element, and EditorKit is responsible
 * for a ViewFactory that is able to decide what View should be created based on an
 * Element.
 *
 *
  Modified by:  Joseph A. Huwaldt

 *
 * @author Jess Thrysoee, 2006
 * @version May 10, 2013
 */
public class LatexEditorKit extends DefaultEditorKit {

    private LatexStyleContext styleContext;

    /**
     * Get the MIME type of the data that this kit represents support for. This kit
     * supports the type
     * text/latex.
     */
    @Override
    public String getContentType() {
        return "text/latex";
    }

    /**
     * Fetches a factory that is suitable for producing views of any models that are
     * produced by this kit.
     *
     * @return the view factory
     */
    @Override
    public final ViewFactory getViewFactory() {
        if (styleContext == null) {
            styleContext = new LatexStyleContext();
        }
        return styleContext;
    }
}


text:
<form>
    <field>
        <id>list.enabled</id>
        Enabled
        <type>checkbox</type>
        <help>This will enable or disable the list.</help>
    </field>
    <field>
        <id>list.name</id>
        Name
        <type>text</type>
        <help>Set the name for this signatures.</help>
    </field>
    <field>
        <id>list.link</id>
        URL
        <type>text</type>
        <help>URL of the signature database.</help>
    </field>
</form>


text:
import abc
import argparse
import enum
import functools
import numbers
import sys
from dataclasses import dataclass
from itertools import chain

__author__ = "Nicola Coretti"
__email__ = "nico.coretti@gmail.com"

class AbstractCrcRegister(metaclass=abc.ABCMeta):
    """
    Abstract base class / Interface a crc register needs to implement.

    Workflow:
        1. The Crc-Register needs to be initialized.    1 time     (init)
        2. Data is feed into the crc register.          1..n times (update)
        3. Final result is calculated.                  1 time     (digest)
    """

    @abc.abstractmethod
    def init(self):
        """
        Initializes the crc register.
        """

    @abc.abstractmethod
    def update(self, data):
        """
        Feeds the provided data into the crc register.

        :param bytes data: a bytes like object or ann object which can be converted to a bytes
                     like object using the built in bytes() function.
        :return: the current value of the crc register.
        """

    @abc.abstractmethod
    def digest(self):
        """
        Final crc checksum will be calculated.

        :return: the final crc checksum.
        :rtype: int.
        """

    @abc.abstractmethod
    def reverse(self):
        """
        Calculates the reversed value of the crc register.

        :return: the the reversed value of the crc register.
        """

@dataclass(frozen=True)
class Configuration:
    """
    A Configuration provides all settings necessary to determine the concrete
    implementation of a specific crc algorithm/register.
    """

    width: int
    polynomial: int
    init_value: int = 0
    final_xor_value: int = 0
    reverse_input: bool = False
    reverse_output: bool = False

class CrcRegisterBase(AbstractCrcRegister):
    """
    Implements the common crc algorithm, assuming a user of this base
    class will provide an overwrite for the _process_byte method.
    """

    def __init__(self, configuration):
        """
        Create a new CrcRegisterBase.

        :param configuration: used for the crc algorithm.
        """
        if isinstance(configuration, enum.Enum):
            configuration = configuration.value
        self._topbit = 1 << (configuration.width - 1)
        self._bitmask = 2**configuration.width - 1
        self._config = configuration
        self._register = configuration.init_value & self._bitmask

    def __len__(self):
        """
        Returns the length (width) of the register.

        :return: the register size/width in bytes.
        """
        return self._config.width // 8

    def __getitem__(self, index):
        """
        Gets a single byte of the register.

        :param index: byte which shall be returned.
        :return: the byte at the specified index.
        :raises IndexError: if the index is out of bounce.
        """
        if index >= (self._config.width / 8) or index < 0:
            raise IndexError
        shift_offset = index * 8
        return (self.register & (0xFF << shift_offset)) >> shift_offset

    def init(self):
        """
        See AbstractCrcRegister.init
        """
        self.register = self._config.init_value

    def update(self, data):
        """
        See AbstractCrcRegister.update
        """
        for byte in data:
            byte = Byte(byte)
            if self._config.reverse_input:
                byte = byte.reversed()
            self._register = self._process_byte(byte)
        return self.register

    @abc.abstractmethod
    def _process_byte(self, byte):
        """
        Processes an entire byte feed to the crc register.

        :param byte: the byte which shall be processed by the crc register.
        :return: the new value of the crc register will have after the byte have been processed.
        """

    def digest(self):
        """
        See AbstractCrcRegister.digest
        """
        if self._config.reverse_output:
            self.register = self.reverse()
        return self.register ^ self._config.final_xor_value

    def reverse(self):
        """
        See AbstractCrcRegister.digest
        """
        index = 0
        reversed_value = 0
        for byte in reversed(self):
            reversed_value += int(Byte(byte).reversed()) << index
            index += 8
        return reversed_value

    def _is_division_possible(self):
        return (self.register & self._topbit) > 0

    @property
    def register(self):
        return self._register & self._bitmask

    @register.setter
    def register(self, value):
        self._register = value & self._bitmask

class CrcRegister(CrcRegisterBase):
    """
    Simple crc register, which will process one bit at the time.

    .. note:

        If performance is an important issue for the crc calculation use a table
        based register.
    """

    def _process_byte(self, byte):
        """
        See CrcRegisterBase._process_byte
        """
        self.register ^= int(byte) << (self._config.width - 8)
        for _ in byte:
            if self._is_division_possible():
                self.register = (self.register << 1) ^ self._config.polynomial
            else:
                self.register <<= 1
        return self.register

class TableBasedCrcRegister(CrcRegisterBase):
    """
    Lookup table based crc register.

    .. note::

        this register type will be much faster than a simple bit by bit based crc register.
        (e.g. CrcRegister)
    """

    def __init__(self, configuration):
        """
        Creates a new table based crc register.

        :param configuration: used for the crc algorithm.

        :attention: creating a table based register initially might take some extra time, due to the
                    fact that some lookup tables need to be calculated/initialized .
        """
        super().__init__(configuration)
        if isinstance(configuration, enum.Enum):
            configuration = configuration.value
        self._lookup_table = create_lookup_table(
            configuration.width, configuration.polynomial
        )

    def _process_byte(self, byte):
        """
        See CrcRegisterBase._process_byte
        """
        index = int(byte) ^ (self.register >> (self._config.width - 8))
        self.register = self._lookup_table[index] ^ (self.register << 8)
        return self.register

class Byte(numbers.Number):
    BIT_LENGTH = 8
    BIT_MASK = 0xFF

    def __init__(self, value=0x00):
        self._value = value & Byte.BIT_MASK

    def __add__(self, other):
        if not isinstance(other, Byte):
            other = Byte(other)
        return Byte(self.value + other.value)

    def __radd__(self, other):
        return self + other

    def __iadd__(self, other):
        result = self + other
        self.value = result.value
        return self

    def __eq__(self, other):
        if not isinstance(other, Byte):
            raise TypeError("unsupported operand")
        return self.value == other.value

    def __hash__(self):
        return hash(self.value)

    def __len__(self):
        return Byte.BIT_LENGTH

    def __getitem__(self, index):
        if index >= Byte.BIT_LENGTH or index < 0:
            raise IndexError
        return (self.value & (1 << index)) >> index

    def __int__(self):
        return self.value

    @property
    def value(self):
        return self._value & Byte.BIT_MASK

    @value.setter
    def value(self, value):
        self._value = value & Byte.BIT_MASK

    def reversed(self):
        value = 0
        index = 0
        for bit in reversed(self):
            value += bit << index
            index += 1
        return Byte(value)

@functools.lru_cache()
def create_lookup_table(width, polynomial):
    """
    Creates a crc lookup table.

    :param int width: of the crc checksum.
    :parma int polynomial: which is used for the crc calculation.
    """
    config = Configuration(width=width, polynomial=polynomial)
    crc_register = CrcRegister(config)
    lookup_table = []
    for index in range(0, 256):
        crc_register.init()
        data = bytes((index).to_bytes(1, byteorder="big"))
        crc_register.update(data)
        lookup_table.append(crc_register.digest())
    return lookup_table

class CrcCalculator:
    def __init__(self, configuration, table_based=False):
        """
        Creates a new CrcCalculator.

        :param configuration: for the crc algorithm.
        :param table_based: if true a tables based register will be used for the calculations.

        :attention: initializing a table based calculator might take some extra time, due to the
                    fact that the lookup table need to be initialized.
        """
        if table_based:
            self._crc_register = TableBasedCrcRegister(configuration)
        else:
            self._crc_register = CrcRegister(configuration)

    def calculate_checksum(self, data):
        self._crc_register.init()
        self._crc_register.update(data)
        return self._crc_register.digest()

    def verify_checksum(self, data, expected_checksum):
        return self.calculate_checksum(data) == expected_checksum

@enum.unique
class Crc8(enum.Enum):
    CCITT = Configuration(
        width=8,
        polynomial=0x07,
        init_value=0x00,
        final_xor_value=0x00,
        reverse_input=False,
        reverse_output=False,
    )

    SAEJ1850 = Configuration(
        width=8,
        polynomial=0x1D,
        init_value=0x00,
        final_xor_value=0x00,
        reverse_input=False,
        reverse_output=False,
    )

    AUTOSAR = Configuration(
        width=8,
        polynomial=0x2F,
        init_value=0xFF,
        final_xor_value=0xFF,
        reverse_input=False,
        reverse_output=False,
    )

    BLUETOOTH = Configuration(
        width=8,
        polynomial=0xA7,
        init_value=0x00,
        final_xor_value=0x00,
        reverse_input=True,
        reverse_output=True,
    )

    MAXIM_DOW = Configuration(
        width=8,
        polynomial=0x31,
        init_value=0,
        final_xor_value=0,
        reverse_input=True,
        reverse_output=True,
    )

@enum.unique
class Crc16(enum.Enum):
    CCITT = Configuration(
        width=16,
        polynomial=0x1021,
        init_value=0x0000,
        final_xor_value=0x0000,
        reverse_input=False,
        reverse_output=False,
    )

    GSM = Configuration(
        width=16,
        polynomial=0x1021,
        init_value=0x0000,
        final_xor_value=0xFFFF,
        reverse_input=False,
        reverse_output=False,
    )

    PROFIBUS = Configuration(
        width=16,
        polynomial=0x1DCF,
        init_value=0xFFFF,
        final_xor_value=0xFFFF,
        reverse_input=False,
        reverse_output=False,
    )

@enum.unique
class Crc32(enum.Enum):
    CRC32 = Configuration(
        width=32,
        polynomial=0x04C11DB7,
        init_value=0xFFFFFFFF,
        final_xor_value=0xFFFFFFFF,
        reverse_input=True,
        reverse_output=True,
    )

    AUTOSAR = Configuration(
        width=32,
        polynomial=0xF4ACFB13,
        init_value=0xFFFFFFFF,
        final_xor_value=0xFFFFFFFF,
        reverse_input=True,
        reverse_output=True,
    )

    BZIP2 = Configuration(
        width=32,
        polynomial=0x04C11DB7,
        init_value=0xFFFFFFFF,
        final_xor_value=0xFFFFFFFF,
        reverse_input=False,
        reverse_output=False,
    )

    POSIX = Configuration(
        width=32,
        polynomial=0x04C11DB7,
        init_value=0x00000000,
        final_xor_value=0xFFFFFFFF,
        reverse_input=False,
        reverse_output=False,
    )

@enum.unique
class Crc64(enum.Enum):
    CRC64 = Configuration(
        width=64,
        polynomial=0x42F0E1EBA9EA3693,
        init_value=0x0000000000000000,
        final_xor_value=0x0000000000000000,
        reverse_input=False,
        reverse_output=False,
    )

CRC_TYPES = {
    Crc8.__name__: Crc8,
    Crc16.__name__: Crc16,
    Crc32.__name__: Crc32,
    Crc64.__name__: Crc64,
}

def argument_parser():
    into_int = functools.partial(int, base=0)
    program = "crc"
    description = "A set of crc checksum related command line tools."
    parser = argparse.ArgumentParser(
        prog=program,
        description=description,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    subparsers = parser.add_subparsers()

    table_command = subparsers.add_parser(
        "table", help="Generates lookup tables for various crc algorithm settings"
    )
    table_command.add_argument(
        "width",
        metavar="<width>",
        type=into_int,
        help="width of the crc algorithm, common width's are 8, 16, 32, 64",
    )
    table_command.add_argument(
        "polynomial",
        metavar="<polynomial>",
        type=into_int,
        help="hex value of the polynomial used for calculating the crc table",
    )
    table_command.set_defaults(func=table)

    checksum_command = subparsers.add_parser(
        "checksum", help="Calculate checksum(s) for the specified input(s)"
    )
    checksum_command.add_argument(
        "inputs",
        nargs="*",
        type=argparse.FileType("rb"),
        default=[sys.stdin.buffer],
        help="who will be feed into the crc calculation",
    )
    checksum_command.add_argument(
        "-c",
        "--category",
        choices=list(CRC_TYPES),
        default=Crc8.__name__,
        help="of crc algorithms which shall be used for calculation",
    )
    checksum_command.set_defaults(func=checksum)

    return parser

def _generate_template(width):
    return f"0x{{:0{(width + 3) // 4}X}}"

def table(args):
    if not (args.width and args.polynomial):
        return False
    columns = 8
    width = args.width
    polynomial = args.polynomial
    lookup_table = create_lookup_table(width, polynomial)
    template = _generate_template(width)
    rows = (lookup_table[i : i + columns] for i in range(0, len(lookup_table), columns))
    print("\n".join((" ".join((template.format(value) for value in r)) for r in rows)))
    return True

def checksum(args):
    category = CRC_TYPES[args.category]
    data = bytearray(chain.from_iterable(src.read() for src in args.inputs))
    for algorithm in sorted(category, key=str):
        print(
            "{name}: 0x{result:X}".format(
                name=f"{algorithm}".split(".")[1],
                result=CrcCalculator(algorithm, True).calculate_checksum(data),
            )
        )
    return True

def main(argv=None):
    parser = argument_parser()
    args = parser.parse_args(argv)
    if "func" in args:
        exit_code = 0 if args.func(args) else -1
        sys.exit(exit_code)
    else:
        parser.print_help()
        sys.exit(-1)

if __name__ == "__main__":
    main()


text:
<?php
namespace frontend\modules\publication\models;

use Yii;
use yii\base\Model;
use common\models\Publication;
use common\models\RecevoirPubl;
use \common\models\Communaute;
use common\models\AppartenirComm;
use common\models\User;
use common\models\Fichier;
use common\models\FichierAssocPubl;

/**
 * PostForm is the model behind the post form.
 */
class PostForm extends Model
{
    public $content;
    public $file;
    public $idComm;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['content', 'required', 'message'=>'Ce champ est obligatoire'],
          /**  ['content', 'required', 'when'=>  function($model){ return empty($mdel->file); },
                                                         'whenClient'=>'function(attribute, value){ '
                    . 'alert(  $("#post-form").children(":file").val());'
                    . 'return $("#post-form").children(":file").val() == ""; }'
                                                         ,'skipOnEmpty'=>false, 'skipOnError'=>false, 'message'=>'Choisissez un domaine'

                            ],
           **
           */
            ['file', 'file'],
            [['idComm'], 'integer']
        ];
    }
    /**
     * This function handle the post by inserting submitted datas  in the database
     * @return Null|Publication the active Record created
     */

    public function post(){
        $publ = new Publication();

        /**  insert the new post in table 'publication' **/
        //$publ->idAuteur = Yii::$app->user->identity->id;

         $publ->id_comm = $this->idComm;
        $publ->contenu = $this->content;
        $publ->date_post = date("y-m-d H:i:s");
        $isValidComm = (!empty(Communaute::find()->where(['id_comm'=>$this->idComm])->scalar()) ) ;
         if($isValidComm){
            if($publ->save()){
                //handle file submittion
                 if(!empty($this->file)){
                    //  Insert file data in the database
                    $idFile = (Fichier::find()->select(['max(id_fichier)'])->scalar())+1;
                    $file = new Fichier();
                    $file->nom = 'publ_'.date("YmdHis").'_'.$idFile.'.'.$this->file->extension;
                    $file->statut = 'publication';
                    $file->save();
                    // insert in table fichier_assoc_publ
                    $publFile = new FichierAssocPubl();
                    $publFile->id_publ = Publication::find()->select(['max(id_publ)'])->scalar();
                    $publFile->id_fichier = $idFile;
                    $publFile->save();
                    // save the file in frontend/web/uploads
                    $this->file->saveAs('uploads/'.$file->nom);
                }

                // That is the current publication id
                $idPubl = Publication::find()->select('id_publ')->orderBy('id_publ DESC')->scalar();
                /** Select members of the concerned community **/
                $members = AppartenirComm::find()->select(['id_user'])->where(['id_comm'=>$this->idComm])->all();

                foreach ($members as $member){
                    $recPubl = new RecevoirPubl();
                    $recPubl->id_publ = $idPubl;
                    $recPubl->id_user = $member->id_user;
                    $recPubl->nouveau = 'oui';
                    if (!$recPubl->save()){
                        return Null;
                    }
                }

                return $publ;
            }
        }
        return Null;

    }

}


text:
//
// Copyright (c) 2009-2010 Shawn Singh, Mubbasir Kapadia, Petros Faloutsos, Glenn Reinman
// See license.txt for complete license.
//

#ifndef __STEERLIB_SIMULATION_METRICS_COLLECTOR_H__
#define __STEERLIB_SIMULATION_METRICS_COLLECTOR_H__

/// @file SimulationMetricsCollector.h
/// @brief Declares the SteerLib::SimulationMetricsCollector class

#include <vector>
#include "Globals.h"
#include "benchmarking/AgentMetricsCollector.h"
#include "griddatabase/GridDatabase2D.h"
#include "recfileio/RecFileIO.h"
#include "interfaces/AgentInterface.h"

#ifdef _WIN32
// on win32, there is an unfortunate conflict between exporting symbols for a
// dynamic/shared library and STL code.  A good document describing the problem
// in detail is http://www.unknownroad.com/rtfm/VisualStudio/warningC4251.html
// the "least evil" solution is just to simply ignore this warning.
#pragma warning( push )
#pragma warning( disable : 4251 )
#endif

namespace SteerLib {

	/**
	 * @brief Functionality for collecting all metrics of a simulation, including an AgentMetricsCollector for each agent.
	 *
	 * @todo
	 *    - add more documentation for this class
	 */
    class STEERLIB_API SimulationMetricsCollector
	{
	public:
	    SimulationMetricsCollector( const std::vector<SteerLib::AgentInterface*> & agents);
	    ~SimulationMetricsCollector();

		void reset();
		void update(SteerLib::GridDatabase2D * gridDB, const std::vector<SteerLib::AgentInterface*> & updatedAgents, float currentTimeStamp, float timePassedSinceLastFrame);

	    AgentMetricsCollector * getAgentCollector(unsigned int agentIndex) { return _agentCollectors[agentIndex]; }
	    unsigned int getNumAgents() { return _agentCollectors.size(); }

		void printCurrentMetrics(unsigned int agentIndex, std::ostream & out);

	protected:
	    void _resetEnvironmentMetrics();
	    void _updateAgentMetrics(SteerLib::GridDatabase2D * gridDB, const std::vector<SteerLib::AgentInterface*> & updatedAgents, float currentTimeStamp, float timePassedSinceLastFrame);
	    void _updateEnvironmentMetrics(SteerLib::GridDatabase2D * gridDB, float currentTimeStamp, float timePassedSinceLastFrame);

	    std::vector<AgentMetricsCollector*> _agentCollectors;
	    EnvironmentMetrics _environmentMetrics;

	};

} // end namespace SteerLib

#ifdef _WIN32
#pragma warning( pop )
#endif

#endif


text:
package ru.job4j.mapforbank;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Bank realisation.
 */
public class Bank {
    /**
     * Variable that referring to a Map collection of Users.
     */
    private Map<User, List<Account>> userListMap;

    /**
     * Constructor.
     */
    public Bank() {
        this.userListMap = new LinkedHashMap<>();
    }

    /**
     * Method add an User.
     *
     * @param user user to add
     */
    public void addUser(User user) {
        this.userListMap.put(user, new ArrayList<>());
    }

    /**
     * Method remove an User.
     *
     * @param user user to delete
     */
    public void deleteUser(User user) {
        if (this.userListMap.containsKey(user)) {
            this.userListMap.remove(user);
        }
    }

    /**
     * Method add an Account to User.
     *
     * @param user    user whom account add
     * @param account account add
     */
    public void addAccountToUser(User user, Account account) {
        if (this.userListMap.containsKey(user)) {
            this.userListMap.get(user).add(account);
        }
    }

    /**
     * Method delete an Account to User.
     *
     * @param user    user whom account delete
     * @param account account delete
     */
    public void deleteAccountFromUser(User user, Account account) {
        if (this.userListMap.containsKey(user)) {
            this.userListMap.get(user).remove(account);
        }
    }

    /**
     * Method lists all accounts of User.
     *
     * @param user user
     * @return List Accounts
     */
    public List<Account> getUserAccounts(User user) {
        List<Account> accounts = new ArrayList<>();
        if (this.userListMap.containsKey(user)) {
            accounts = this.userListMap.get(user);
        }
        return accounts;
    }

    /**
     * Method transferring of money from account of one User to account of another User.
     *
     * @param srcUser    source User
     * @param srcAccount source Account
     * @param dstUser    dest User
     * @param dstAccount dest Account
     * @param amount     value to be transferred
     * @return true if transaction was successful - false otherwise
     */
    public boolean transferMoney(User srcUser, Account srcAccount, User dstUser, Account dstAccount, double amount) {
        boolean result = false;

        if (this.userListMap.get(srcUser).contains(srcAccount)) {

            for (Account account : this.userListMap.get(srcUser)) {
                if (account.equals(srcAccount)) {
                    if (account.getValue() >= amount) {
                        for (Account account1 : this.userListMap.get(dstUser)) {
                            if (account1.equals(dstAccount)) {
                                account.setValue(account.getValue() - amount);
                                account1.setValue(account1.getValue() + amount);
                                result = true;
                            }
                        }
                    } else {
                        result = false;
                    }
                }
            }
        } else {

            result = false;

        }
        return result;
    }

    /**
     *
     * @return userListMap
     */
    public Map<User, List<Account>> getUserListMap() {
        return userListMap;
    }
}


text:
package org.apache.shindig.gadgets.parse.caja;

import com.google.caja.lexer.*;
import com.google.caja.parser.html.DomParser;
import com.google.caja.reporting.MessageQueue;
import com.google.caja.reporting.SimpleMessageQueue;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.http.HttpResponse;
import org.apache.shindig.gadgets.parse.GadgetHtmlParser;
import org.apache.shindig.gadgets.parse.HtmlSerialization;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;

/**
 * Simple html parser based on caja.
 */
public class VanillaCajaHtmlParser extends GadgetHtmlParser {
  private final boolean needsDebugData;

  @Inject
  public VanillaCajaHtmlParser(DOMImplementation documentFactory,
                               @Named("vanillaCajaParser.needsDebugData")
                               boolean needsDebugData) {
    super(documentFactory);
    this.needsDebugData = needsDebugData;
  }

  @Override
  public Document parseDom(String source) throws GadgetException {
    // TODO: Add support for caching the DOM after evaluation.
    return parseDomImpl(source);
  }

  private DomParser getDomParser(String source, final MessageQueue mq) throws ParseException {
    InputSource is = InputSource.UNKNOWN;
    HtmlLexer lexer = new HtmlLexer(CharProducer.Factory.fromString(source, is));
    TokenQueue<HtmlTokenType> tokenQueue = new TokenQueue<HtmlTokenType>(
        lexer, is);
    DomParser parser = new DomParser(tokenQueue, /** asXml */ false, mq);

    parser.setDomImpl(documentFactory);
    parser.setNeedsDebugData(needsDebugData);
    return parser;
  }

  @Override
  protected Document parseDomImpl(String source) throws GadgetException {
    MessageQueue mq = new SimpleMessageQueue();
    try {
      DomParser parser = getDomParser(source, mq);
      Document doc = parser.parseDocument().getOwnerDocument();

      VanillaCajaHtmlSerializer serializer = new VanillaCajaHtmlSerializer();
      HtmlSerialization.attach(doc, serializer, null);
      return doc;
    } catch (ParseException e) {
      throw new GadgetException(GadgetException.Code.HTML_PARSE_ERROR,
          e.getCajaMessage().toString(), HttpResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (NullPointerException e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e);
    }
  }

  @Override
  protected DocumentFragment parseFragmentImpl(String source)
      throws GadgetException {
    throw new UnsupportedOperationException("Use parseDom instead.");
  }
}


text:
extern void	zip_rtu(void);
extern void	zip_halt(void);
extern void	zip_idle(void);
extern void	zip_syscall(void);
extern void	zip_restore_context(int *);
extern void	zip_save_context(int *);
extern int	zip_bitrev(int v);
extern unsigned	zip_cc(void);
extern unsigned	zip_ucc(void);

extern	void	save_context(int *);
extern	void	restore_context(int *);
extern	int	syscall(int,int,int,int);

#ifndef	NULL
#define	NULL	((void *)0)
#endif

#define	ASMFNSTR(A)	"\t.section\t.text\n\t.global\t" A "\n\t.type\t" A ",@function\n" A ":\n"

#endif


text:
/*This file contains general theme styles*/

*{padding:0; margin:0;}

/*==Default styles for HTML 4==*/

html, address,
blockquote,
body, dd, div,
dl, dt, fieldset, form,
frame, frameset,
h1, h2, h3, h4,
h5, h6, noframes,
ol, p, ul, center,
dir, hr, menu, pre   { display: block; unicode-bidi: embed }
fieldset		{border:none;}
li              { display: list-item; list-style:none;}
head            { display: none }
table           { display: table }
tr              { display: table-row }
thead           { display: table-header-group }
tbody           { display: table-row-group }
tfoot           { display: table-footer-group }
col             { display: table-column }
colgroup        { display: table-column-group }
td, th          { display: table-cell }
caption         { display: table-caption }
th              { font-weight: bolder; text-align: center }
caption         { text-align: center }
body            { margin: 0px }
h1              { font-size: 2em; margin: .67em 0 }
h2              { font-size: 1.5em; margin: .75em 0 }
h3              { font-size: 1.17em; margin: .83em 0 }
h4, p,
blockquote, ul,
fieldset, form,
ol, dl, dir,
menu            { margin: 1em 0 }
h5              { font-size: .83em; margin: 1.5em 0 }
h6              { font-size: .75em; margin: 1.67em 0 }
h1, h2, h3, h4,
h5, h6, b,
strong          { font-weight: bolder }
blockquote      { margin-left: 40px; margin-right: 40px }
i, cite, em,
var, address    { font-style: italic }
pre, tt, code,
kbd, samp       { font-family: monospace }
pre             { white-space: pre }
button, textarea,
input, select   { display: inline; }
big             { font-size: 1.17em }
small, sub, sup { font-size: .83em }
sub             { vertical-align: sub }
sup             { vertical-align: super }
table           { border-spacing: 2px; }
thead, tbody,
tfoot           { vertical-align: middle }
td, th, tr      { vertical-align: inherit }
s, strike, del  { text-decoration: line-through }
hr              { border: 1px inset }
ol, ul, dir,
menu, dd        { margin-left: 0px }
ol              { list-style-type: decimal }
ol ul, ul ol,
ul ul, ol ol    { margin-top: 0; margin-bottom: 0 }
u, ins          { text-decoration: underline }
br:before       { content: "\A"; white-space: pre-line }
center          { text-align: center }
:link, :visited { text-decoration: none }
:focus          { outline: none }

a, a img, a:hover, a:active, a:focus{
	outline:0;
	outline:none;
	border:none;}

/* Begin bidirectionality settings (do not change) */
BDO[DIR="ltr"]  { direction: ltr; unicode-bidi: bidi-override }
BDO[DIR="rtl"]  { direction: rtl; unicode-bidi: bidi-override }

*[DIR="ltr"]    { direction: ltr; unicode-bidi: embed }
*[DIR="rtl"]    { direction: rtl; unicode-bidi: embed }

@media print {
  h1            { page-break-before: always }
  h1, h2, h3,
  h4, h5, h6    { page-break-after: avoid }
  ul, ol, dl    { page-break-before: avoid }
}

/*===============FORMS===================*/

label{
	display:inline;}

/* Form validation */
input.invalid,
textarea.invalid{
	border: 1px solid #ff0000 !important;
	}

label.invalid { color: #ff0000 !important; }

form.form-validate dl dt{
	float:left;
	width:12em;
	}

form.form-validate dl dd{
	display: block;
    margin-bottom: 1em;
    overflow: hidden;
}

form.form-validate legend{
	padding:0 1em;
	font-weight:bold;
	}

.checkbox{
position:relative;
top:2px;
margin:0 2px;
}

/*=================Lists==================*/

ul li{
	list-style:none;}

/* Caption fixes */
.img_caption .left {
        float: left;
        margin-right: 1em;
}

.img_caption .right {
        float: right;
        margin-left: 1em;
}

.img_caption .left p {
        clear: left;
        text-align: center;
}

.img_caption .right p {
        clear: right;
        text-align: center;
}

.img_caption  {
	text-align: center!important;
}

.img_caption.none {
	margin-left:auto;
	margin-right:auto;
}

/* Calendar */
a img.calendar {
	width: 16px;
	height: 16px;
	margin-left: 3px;
	background: url(../images/calendar.png) no-repeat;
	cursor: pointer;
	vertical-align: middle;
}

/*==========MAIN LAYOUT==========*/

#left-col,
#right-col,
#content{
	float:left;
	}

/* Tooltips */
.tip {
   background-color: #fff;
   border: 1px #ccc solid;
   padding: 5px;
   font-family: Arial, Helvetica, sans-serif;
   font-size: 11px;
   position:relative;
   z-index:50;
}

.tip-title {
	font-weight: bold;
}

/*===========BLOG LAYOUT=========*/

.items-row .item{
	float:left;}

.items-row.cols-1 .item{
	width:100%;
}

.items-row.cols-2 .item{
	width:50%;
}

.items-row.cols-3 .item{
	width:33%;
}

.items-row.cols-4 .item{
	width:25%;
}

.items-row.cols-5 .item{
	width:20%;
}

.items-row.cols-6 .item{
	width:16%;
}

.item-content, .item .system-unpublished{
	padding:0 1em;}

span.row-separator{
	clear:both;
	visibility:none;
	height:0px;
	line-height:0px;
	display:block;
	}

/*============ARTICLES DETAILS=======*/

dl.article-info{
	font-style:italic;
	}
dl.article-info dt.article-info-term{
	display:none;}

dl.article-info dd{
	margin-left:1em;}

.item-page{
	position:relative;
	}

ul.actions{
	position:absolute;
	right:0;
	top:0;}

.blog .items-leading > div,
.blog .items-row .item,
.blog-featured .items-leading,
.blog-featured .items-row .item
{
	position:relative;}

/*===Articles Archive===*/

.archive .filter-search select#month{
	width:5em;}
.archive .filter-search select#year{
	width:5em;}
.archive .filter-search select#limit{
	width:3em;}

/*===Category List===*/

table.category{
	width:100%;}

table.category th.list-title{
	width:60%;
	}

table.category th.list-author{
	width:30%;
	}

table.category th.list-hits{
	width:10%;
	}

td.list-author,
td.list-hits{
	text-align:center;}

/*===========ACTION ICONS============*/

ul.actions{
float:right;
margin-left:0;
padding-right:1em;
}

ul.actions li{
display:inline;}

ul.actions li img{
	float:none;}

/*===========Articles Edit============*/

#editor-xtd-buttons {
    padding-top: 10px;
}

.button2-left, .button2-left div {
    float: left;
}
.button2-left a, .button2-left button, .button2-left span{
    color: #333333;
    cursor: pointer;
    display: block;
    float: left;
    font-size: 1em;
    height: 22px;
    line-height: 22px;
	text-decoration:none;
}

.button2-left .page a, .button2-right .page a, .button2-left .page span, .button2-right .page span, .button2-left .blank a, .button2-right .blank a, .button2-left .blank span, .button2-right .blank span, .button2-left .blank button, .button2-right .blank button {
    padding: 0 6px;
}

.button2-left a:hover, .button2-left button:hover, .button2-left button:hover {
    color: #0B55C4;
    text-decoration: none;
}
.button2-left a, .button2-left span, .button2-left button {
    padding: 0 24px 0 6px;
}

.button2-left {
    background: url("../images/system/j_button2_left.png") no-repeat scroll 0 0 transparent;
    float: left;
    margin-right: 10px;
}

.button2-left .image {
    background: url("../images/system/j_button2_image.png") no-repeat scroll 100% 0 transparent;
}
.button2-left .readmore {
    background: url("../images/system/j_button2_readmore.png") no-repeat scroll 100% 0 transparent;
}
.button2-left .pagebreak {
    background: url("../images/system/j_button2_pagebreak.png") no-repeat scroll 100% 0 transparent;
}
.button2-left .blank {
    background: url("../images/system/j_button2_blank.png") no-repeat scroll 100% 0 transparent;
}
.button2-left .article {
    background: url("../images/system/j_button2_readmore.png") no-repeat scroll 100% 0 transparent;
}

.edit fieldset{
	border:1px solid #ccc;
	padding:0 2em 2em 2em;}

.edit fieldset legend{
	font-weight:bold;
	padding:0 1em;
	margin-left:1em;}

.edit label
{
	width:10em;
	display:block;
	float:left;
	}

.edit .formelm{
	margin:1em 0;
	overflow:hidden;
	clear:both;}

.edit  select{
	width:183px;
	}
#jform_publish_up_img,
#jform_publish_down_img{
	left: 5px;
    position: relative;
    top: 4px;
}

.edit fieldset{
	position:relative;}

.edit .formelm-area{
	margin-top:1em;}

.edit .formelm-buttons{
	 position: absolute;
    right: 3em;
    top: 0.7em;
}

label#jform_description-lbl{
	float:none;}

/*========COMPONENT PAGES==========*/

	/*====COM_USER===*/

	/*===Login page===*/

div.login ul{
	margin-left:0;
	}

div.login ul li{
	list-style:none;
	}

div.login-fields{
	    margin: 0.5em 0;}

div.login-fields label{
	display: block;
    width: 10em;
	float:left;
	}

div.login-fields input{
	width:15em;}

p#form-login-remember input#modlgn-remember{
	display:inline;
	width:20px;
	position:relative;
	top:2px;}

	/*===Logout page===*/

	/*===Reset password page===*/

	/*===Reset username page===*/

	/*===Registration page====*/

#member-registration fieldset dl dt.first{
	float:none;}

	/*===Profile page====*/

div.profile fieldset#users-profile-core,
div.profile fieldset#users-profile-custom{
	border:1px solid #CCC;
	padding:1em;
	}

div.profile fieldset legend{
	padding:0 0.5em;}

div.profile fieldset dl{
	overflow:hidden;}

div.profile fieldset dt{
	display:block;
	width:10em;
	float:left;}

	/*===Profile Edit page===*/

form#member-profile fieldset{
	border:1px solid #ccc;
	margin-bottom:1em;
	padding:1em;
	}

	/*===Single Contact page====*/

/*slider*/

#contact-slider .panel h3.pane-toggler{
	background:url(../images/slider_plus.png) top right no-repeat;
	}

#contact-slider .panel h3.pane-toggler-down{
	background:url(../images/slider_minus.png) top right no-repeat;
}

input#jform_contact_email_copy{
	position:relative;
	top:2px;}

.contact span.jicons-icons{
	float:left;
	width:30px;
	}

.contact #contact-address{
	float:right;
	width:40%;}

.contact .contact-form{
	float:left;
	width:60%;}

	/*===Featured Contacts page====*/

table.category td.item-num,
table.category td.item-position,
table.category td.item-phone,
table.category td.item-suburb,
table.category td.item-state,
table.category td.item-state{
	text-align:center;
	}

/*=========Search Results Page=========*/

form#searchForm fieldset{
border:1px solid #ccc;
padding:1em;
}

form#searchForm .ordering-box{
margin-top:0.5em;}

.phrases-box input,
#searchForm .only input{
	position:relative;
	top:2px;}

.phrases-box label,
#searchForm .only label{
	padding-right:1em;}

.ordering-box select{
	width:9em;}

.search-results .result-title{
	font-weight:bold;
	margin-bottom:0.5em;
	}

.search-results .result-category,
.search-results .result-created{
	font-style:italic;
	}

.search-results .result-created{
	margin-bottom:2em;
	}

.search-results .result-text{
	margin:0.5em 0;}

.search-results

.search-results
.search-results
.search-results

/*=========Footer Page navigation=======*/

ul.pagenav{
	overflow:hidden;
	margin-left:0;}

ul.pagenav li{
	list-style:none;}

ul.pagenav li.pagenav-prev{
	float:left;}
ul.pagenav li.pagenav-next{
	float:right;
}

div.pagination{
	overflow:hidden;}

p.counter{
	text-align:center;}

div.pagination ul{
	overflow:hidden;
	text-align:center;
	}

div.pagination ul li{
	float:none;
	display:inline;
	padding:0 0.5em;
	list-style:none;
	}

/*=========System Messages=========*/

.error{
	padding:0px;
	}

.error h2{
    color:#000 !important;
	font-size:1.4em !important;
	text-transform:uppercase;
	padding:0 0 0 0px !important
}

#system-message{
	margin:1em 0;
	border-left:0;
	border-right:0;
}

#system-message dt{
	font-weight: bold;
}
#system-message dd{
	margin: 0 0 1em 0;
	font-weight: bold;
	text-indent: 0px;
	padding:0
}
#system-message dd ul{
	color: #000;
	list-style: none;
	padding: 0px;
}
#system-message dd ul li{
	line-height:1.5em
}

/* System Standard Messages */
#system-message dt.message {
	position:absolute;
	top:-2000px;
	left:-3000px;
}

#system-message dd.message  ul{
	background: #fff  url(../images/system/notice-info.png) no-repeat;
	padding-left:2em;
	padding: 1em 1em 1em 2em;
	border-top: 2px solid #90B203;
	border-bottom: 2px solid #90B203;
}

#system-message dd.message ul li{background:none !important}

/* System Error Messages */
#system-message dt.error {
	position:absolute;
	top:-2000px;
	left:-3000px;
}

#system-message dd.error ul
{
	background:#fff url(../images/system/notice-alert.png) no-repeat ;
	padding-left:2em;
	padding: 1em 1em 1em 2em;
    border-top: 2px solid #990000;
    border-bottom: 2px solid #990000;
}

/* System Notice Messages */
#system-message dt.notice {
	position:absolute;
	top:-2000px;
	left:-3000px;
}

#system-message dd.notice  ul
{
		background:#fff url(../images/system/notice-note.png) no-repeat ;
	padding-left:2em;
	padding: 1em 1em 1em 2em;
	    border-top: 2px solid #FAA528;
	    border-bottom: 2px solid #FAA528;
}
#system-message dd.notice ul { color: #000;margin:10px 0 }

#system-message {
    margin-bottom: 0px;
    padding: 0;
}

#system-message dt {
    font-weight: bold;
}

#system-message dd {
    font-weight: bold;
    padding: 0;
}


text:
"""
Test for EPMD connector.
"""

from twisted.internet.defer import Deferred
from twisted.internet.error import ConnectionDone
from twisted.internet import address
from twisted.test.proto_helpers import StringTransportWithDisconnection

from twotp.term import Node
from twotp.epmd import PortMapperProtocol, PersistentPortMapperFactory
from twotp.epmd import OneShotPortMapperFactory, NodeNotFound

from twotp.test.test_client import DummyClientFactory
from twotp.test.util import TestCase

class DummyPortMapperFactory(object):
    """
    Fake EPMD factory for tests.
    """

    def __init__(self):
        """
        Create a deferred to be fired later.
        """
        self._connectDeferred = Deferred()

class PortMapperProtocolTestCase(TestCase):
    """
    Tests for L{PortMapperProtocol}.
    """

    def setUp(self):
        """
        Create a protocol instance linked with a L{DummyPortMapperFactory}.
        """
        self.proto = PortMapperProtocol()
        self.proto.factory = DummyPortMapperFactory()
        self.transport = StringTransportWithDisconnection()
        self.proto.makeConnection(self.transport)
        self.transport.protocol = self.proto

    def test_alive2Response(self):
        """
        Test an successful alive2 response.
        """
        def cb(res):
            self.assertEqual(res, 1)
        self.proto.factory._connectDeferred.addCallback(cb)
        self.proto.dataReceived("y")
        self.proto.dataReceived("\x00")
        self.proto.dataReceived("\x00\x01")
        return self.proto.factory._connectDeferred

    def test_alive2ResponseError(self):
        """
        Test an erroneous alive2 response.
        """
        def eb(res):
            res.trap(ValueError)
        self.proto.factory._connectDeferred.addErrback(eb)
        self.proto.dataReceived("y\x01\x00\x01")
        return self.proto.factory._connectDeferred

    def test_alive2Request(self):
        """
        Test data sent by an alive2 request.
        """
        self.proto.alive2Request(1234, 77, (1, 2), "foo@bar")
        self.assertEqual(
            self.transport.value(),
            "\x00\x14x\x04\xd2M\x00\x00\x01\x00\x02\x00\x07foo@bar\x00\x00")

    def test_port2Response(self):
        """
        Test an successful port2 response.
        """
        d = Deferred()
        d.addCallback(self.assertEqual, Node(9, 77, 1, (5, 5), "bar", ""))
        self.proto.deferred = d
        self.proto.dataReceived("w")
        self.proto.dataReceived("\x00")
        self.proto.dataReceived("\x00\x09M\x01\x00\x05\x00\x05\x00\x03bar\x00")
        self.assertEqual(self.proto.received, "")
        return d

    def test_port2ResponseWithExtra(self):
        """
        Test an successful port2 response, with extra data.
        """
        d = Deferred()
        d.addCallback(
            self.assertEqual, Node(9, 77, 1, (5, 5), "bar", "spam"))
        self.proto.deferred = d
        self.proto.dataReceived(
            "w\x00\x00\x09M\x01\x00\x05\x00\x05\x00\x03bar\x00\x04spam")
        self.assertEqual(self.proto.received, "")
        return d

    def test_port2ResponseNodeNotFound(self):
        """
        Test a port2 not found response: the response deferred should be fired
        with a L{NodeNotFound} exception.
        """
        d = Deferred()
        self.proto.deferred = d
        self.proto.dataReceived("w\x01")
        self.assertEqual(self.proto.received, "")
        return self.assertFailure(d, NodeNotFound)

    def test_port2Request(self):
        """
        Test data sent by a port2 request.
        """
        d = Deferred()
        self.proto.portPlease2Request(d, "egg@spam")
        self.assertEqual(self.transport.value(), "\x00\tzegg@spam")
        self.assertEqual(self.proto.deferred, d)

    def test_names(self):
        """
        Test successful names request and response.
        """
        d = Deferred()
        d.addCallback(self.assertEqual, [("foo", 1234), ("egg", 4321)])
        self.proto.namesRequest(d)
        self.assertEqual(self.transport.value(), "\x00\x01n")
        self.proto.dataReceived("\x00\x00\x00\x01")
        self.proto.dataReceived("name %s at port %s\n" % ("foo", 1234))
        self.proto.dataReceived("name %s at port %s\n" % ("egg", 4321))
        self.transport.loseConnection()
        return d

    def test_dump(self):
        """
        Test successful dump request and response.
        """
        d = Deferred()
        d.addCallback(
            self.assertEqual, {"active": [("foo", 1234, 3)],
                               "old": [("egg", 4321, 2)]})
        self.proto.dumpRequest(d)
        self.assertEqual(self.transport.value(), "\x00\x01d")
        self.proto.dataReceived("\x00\x00\x00\x01")
        self.proto.dataReceived(
            "active name    <%s> at port %s, fd = %s\n\x00" % ("foo", 1234, 3))
        self.proto.dataReceived(
            "old/unused name, <%s>, at port %s, fd = %s\n\x00" % ("egg",
                                                                  4321, 2))
        self.transport.loseConnection()
        return d

    def test_kill(self):
        """
        Test successful kill request and response.
        """
        d = Deferred()
        d.addCallback(self.assertEqual, "OK")
        self.proto.killRequest(d)
        self.assertEqual(self.transport.value(), "\x00\x01k")
        self.proto.dataReceived("OK")
        self.transport.loseConnection()
        return d

    def test_invalidKillResponse(self):
        """
        Test a kill request with an invalid response.
        """
        d = Deferred()
        self.proto.killRequest(d)
        self.assertEqual(self.transport.value(), "\x00\x01k")
        self.proto.dataReceived("Wrong")
        self.transport.loseConnection()
        return self.assertFailure(d, ValueError)

    def test_connectionLostWithPendingDeferred(self):
        """
        Test that connectionLost errbacks the action deferred if present.
        """
        d = Deferred()
        self.proto.deferred = d
        self.transport.loseConnection()
        return self.assertFailure(d, ConnectionDone)

    def test_unhandledRequest(self):
        """
        When a unhandled data is received, the protocol should log a
        C{RuntimeError}.
        """
        self.proto.dataReceived("Wrong")
        errors = self.flushLoggedErrors()
        self.assertEqual(len(errors), 1)
        errors[0].trap(RuntimeError)

class DummyPort(object):
    """
    A dummy L{twisted.internet.tcp.Port} object.
    """

    def __init__(self, portNumber):
        """
        @param portNumber: the port which is used as listening address.
        @type portNumber: C{int}.
        """
        self.portNumber = portNumber

    def getHost(self):
        """
        Return a fake host.
        """
        return address.IPv4Address(
            "TCP", *(("127.0.0.1", self.portNumber) + ("INET",)))

class TestablePPMF(PersistentPortMapperFactory):
    """
    A L{PersistentPortMapperFactory} without socket operations.
    """

    def __init__(self, nodeName, cookie):
        """
        Initialization: forward call and create attributes to save future
        calls.
        """
        PersistentPortMapperFactory.__init__(self, nodeName, cookie)
        self.connect = []
        self.listen = []

    def listenTCP(self, portNumber, factory):
        """
        A fake listenTCP.
        """
        self.listen.append((portNumber, factory))
        p = DummyPort(portNumber)
        return p

    def connectTCP(self, host, port, factory):
        """
        A fake connectTCP.
        """
        self.connect.append((host, port, factory))

class PersistentPortMapperFactoryTestCase(TestCase):
    """
    Tests for L{PersistentPortMapperFactory}.
    """

    def setUp(self):
        """
        Create a factory to be used in the tests.
        """
        self.factory = TestablePPMF("foo@bar", "test_cookie")

    def test_publish(self):
        """
        Test publish: this should create a server, and connect to the EPMD.
        """
        d = self.factory.publish()
        self.assertEqual(self.factory.listen[0][0], 0)
        self.assertIsInstance(self.factory.listen[0][1],
                              self.factory.nodeFactoryClass)
        self.assertEqual(self.factory.connect[0][:2], ("127.0.0.1", 4369))
        self.assertIdentical(self.factory.connect[0][2], self.factory)
        self.factory._connectDeferred.callback(2)

        def cb(ign):
            self.assertEqual(self.factory.listen[0][1].creation, 2)

        return d.addCallback(cb)

    def test_connection(self):
        """
        On connection, the EPMD client should send an ALIVE2 request.
        """
        self.factory.nodePortNumber = 1234
        transport = StringTransportWithDisconnection()
        proto = self.factory.buildProtocol(("127.0.01", 4369))
        proto.makeConnection(transport)
        transport.protocol = proto
        self.assertEqual(
            transport.value(),
            "\x00\x10x\x04\xd2H\x00\x00\x05\x00\x05\x00\x03foo\x00\x00")

class TestableOSPMF(OneShotPortMapperFactory):
    """
    A L{OneShotPortMapperFactory} without socket operations.
    """

    def __init__(self, nodeName, cookie, host="127.0.0.1"):
        """
        Initialization: forward call and create attributes to save future
        calls.
        """
        OneShotPortMapperFactory.__init__(self, nodeName, cookie, host=host)
        self.connect = []

    def connectTCP(self, host, port, factory):
        """
        A fake connectTCP.
        """
        self.connect.append((host, port, factory))

class OneShotPortMapperFactoryTestCase(TestCase):
    """
    Tests for L{OneShotPortMapperFactory}
    """

    def setUp(self):
        """
        Create a factory to be used in the tests.
        """
        self.factory = TestableOSPMF("foo@bar", "test_cookie")

    def test_portPlease2(self):
        """
        L{OneShotPortMapperFactory.portPlease2Request} should create a
        connection to a new host, and set its initial action to
        B{portPlease2Request} with the nodeName given.
        """
        d = self.factory.portPlease2Request("egg@spam")
        transport = StringTransportWithDisconnection()
        proto = self.factory.buildProtocol(("127.0.01", 4369))
        proto.makeConnection(transport)
        transport.protocol = proto
        self.assertEqual(transport.value(), "\x00\tzegg@spam")
        self.assertEqual(
            self.factory.connect, [("127.0.0.1", 4369, self.factory)])
        proto.dataReceived(
            "w\x00\x00\x09M\x01\x00\x05\x00\x05\x00\x03bar\x00")
        return d.addCallback(self.assertEqual,
                             Node(9, 77, 1, (5, 5), "bar", ""))

    def test_connectToNode(self):
        """
        L{OneShotPortMapperFactory.connectToNode} should return a L{Deferred}
        that will be called back with the instance of the protocol connected
        to the erlang node.
        """
        clientFactory = DummyClientFactory()
        self.factory.nodeFactoryClass = lambda a, b, c: clientFactory
        d = self.factory.connectToNode("egg@spam")
        transport = StringTransportWithDisconnection()
        proto = self.factory.buildProtocol(("127.0.01", 4369))
        proto.makeConnection(transport)
        transport.protocol = proto
        self.assertEqual(transport.value(), "\x00\x04zegg")
        self.assertEqual(
            self.factory.connect, [("127.0.0.1", 4369, self.factory)])
        proto.dataReceived(
            "w\x00\x00\x09M\x01\x00\x05\x00\x05\x00\x03bar\x00")
        clientProto = object()
        clientFactory._connectDeferred.callback(clientProto)
        self.assertEqual(
            self.factory.connect,
            [("127.0.0.1", 4369, self.factory),
             ("127.0.0.1", 9, clientFactory)])
        return d.addCallback(self.assertIdentical, clientProto)

    def test_connectToNodeInCache(self):
        """
        If a previous client is present in the cache of the factory,
        L{OneShotPortMapperFactory.connectToNode} should directly return it.
        """
        clientProto = object()
        self.factory._nodeCache["egg"] = clientProto
        d = self.factory.connectToNode("egg@spam")
        return d.addCallback(self.assertIdentical, clientProto)

    def test_connectionLostCleanCache(self):
        """
        When a connectionLost is forwarded from a client factory, it should
        remove the client from the cache.
        """
        clientProto1 = object()
        clientProto2 = object()
        self.factory._nodeCache["spam@egg"] = clientProto1
        self.factory._nodeCache["foo@bar"] = clientProto2
        clientFactory = DummyClientFactory()
        self.factory.onConnectionLost(clientFactory)
        self.assertEqual(self.factory._nodeCache, {"foo@bar": clientProto2})

    def test_names(self):
        """
        L{OneShotPortMapperFactory.names} should return a L{Deferred} that
        will be called back when the names request is complete.
        """
        d = self.factory.names()
        transport = StringTransportWithDisconnection()
        proto = self.factory.buildProtocol(("127.0.01", 4369))
        proto.makeConnection(transport)
        transport.protocol = proto
        self.assertEqual(transport.value(), "\x00\x01n")
        proto.dataReceived("\x00\x00\x00\x01")
        proto.dataReceived("name %s at port %s\n" % ("foo", 1234))
        transport.loseConnection()
        return d.addCallback(self.assertEqual, [("foo", 1234)])

    def test_dump(self):
        """
        L{OneShotPortMapperFactory.dump} should return a L{Deferred} that
        will be called back when the dump request is complete.
        """
        d = self.factory.dump()
        transport = StringTransportWithDisconnection()
        proto = self.factory.buildProtocol(("127.0.01", 4369))
        proto.makeConnection(transport)
        transport.protocol = proto
        self.assertEqual(transport.value(), "\x00\x01d")
        proto.dataReceived("\x00\x00\x00\x01")
        proto.dataReceived(
            "active name    <%s> at port %s, fd = %s\n\x00" % ("foo", 1234, 3))
        transport.loseConnection()
        return d.addCallback(
            self.assertEqual, {"active": [("foo", 1234, 3)], "old": []})

    def test_kill(self):
        """
        L{OneShotPortMapperFactory.kill} should return a L{Deferred} that
        will be called back when the kill request is complete.
        """
        d = self.factory.kill()
        transport = StringTransportWithDisconnection()
        proto = self.factory.buildProtocol(("127.0.01", 4369))
        proto.makeConnection(transport)
        transport.protocol = proto
        self.assertEqual(transport.value(), "\x00\x01k")
        proto.dataReceived("OK")
        transport.loseConnection()
        return d.addCallback(self.assertEqual, "OK")


text:
export = isElevated;

declare function isElevated(): Promise<boolean>;