text:
package org.camunda.bpm.engine.rest.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.identity.Group;
import org.camunda.bpm.engine.identity.GroupQuery;
import org.camunda.bpm.engine.rest.GroupRestService;
import org.camunda.bpm.engine.rest.dto.CountResultDto;
import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto;
import org.camunda.bpm.engine.rest.dto.identity.GroupDto;
import org.camunda.bpm.engine.rest.dto.identity.GroupQueryDto;
import org.camunda.bpm.engine.rest.exception.InvalidRequestException;
import org.camunda.bpm.engine.rest.sub.identity.GroupResource;
import org.camunda.bpm.engine.rest.sub.identity.impl.GroupResourceImpl;
import org.camunda.bpm.engine.rest.util.PathUtil;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.List;

import static org.camunda.bpm.engine.authorization.Authorization.ANY;
import static org.camunda.bpm.engine.authorization.Permissions.CREATE;
import static org.camunda.bpm.engine.authorization.Resources.GROUP;

/**
 * @author Daniel Meyer
 *
 */
public class GroupRestServiceImpl extends AbstractAuthorizedRestResource implements GroupRestService {

  public GroupRestServiceImpl(String engineName, final ObjectMapper objectMapper) {
    super(engineName, GROUP, ANY, objectMapper);
  }

  public GroupResource getGroup(String id) {
    id = PathUtil.decodePathParam(id);
    return new GroupResourceImpl(getProcessEngine().getName(), id, relativeRootResourcePath, getObjectMapper());
  }

  public List<GroupDto> queryGroups(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
    GroupQueryDto queryDto = new GroupQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
    return queryGroups(queryDto, firstResult, maxResults);
  }

  public List<GroupDto> queryGroups(GroupQueryDto queryDto, Integer firstResult, Integer maxResults) {

    queryDto.setObjectMapper(getObjectMapper());
    GroupQuery query = queryDto.toQuery(getProcessEngine());

    List<Group> resultList;
    if(firstResult != null || maxResults != null) {
      resultList = executePaginatedQuery(query, firstResult, maxResults);
    } else {
      resultList = query.list();
    }

    return GroupDto.fromGroupList(resultList);
  }

  public CountResultDto getGroupCount(UriInfo uriInfo) {
    GroupQueryDto queryDto = new GroupQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
    return getGroupCount(queryDto);
  }

  protected CountResultDto getGroupCount(GroupQueryDto queryDto) {
    GroupQuery query = queryDto.toQuery(getProcessEngine());
    long count = query.count();
    return new CountResultDto(count);
  }

  public void createGroup(GroupDto groupDto) {
    final IdentityService identityService = getIdentityService();

    if(identityService.isReadOnly()) {
      throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only.");
    }

    Group newGroup = identityService.newGroup(groupDto.getId());
    groupDto.update(newGroup);
    identityService.saveGroup(newGroup);

  }

  public ResourceOptionsDto availableOperations(UriInfo context) {

    final IdentityService identityService = getIdentityService();

    UriBuilder baseUriBuilder = context.getBaseUriBuilder()
        .path(relativeRootResourcePath)
        .path(GroupRestService.PATH);

    ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();

    // GET /
    URI baseUri = baseUriBuilder.build();
    resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");

    // GET /count
    URI countUri = baseUriBuilder.clone().path("/count").build();
    resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");

    // POST /create
    if(!identityService.isReadOnly() && isAuthorized(CREATE)) {
      URI createUri = baseUriBuilder.clone().path("/create").build();
      resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
    }

    return resourceOptionsDto;
  }

  // utility methods //////////////////////////////////////

  protected List<Group> executePaginatedQuery(GroupQuery query, Integer firstResult, Integer maxResults) {
    if (firstResult == null) {
      firstResult = 0;
    }
    if (maxResults == null) {
      maxResults = Integer.MAX_VALUE;
    }
    return query.listPage(firstResult, maxResults);
  }

  protected IdentityService getIdentityService() {
    return getProcessEngine().getIdentityService();
  }

}


text:
import threading
from functools import wraps
from django.utils.importlib import import_module

from shrubbery.authentication.exceptions import AuthenticationError, Http403
from shrubbery.conf import settings

_authentication_contexts = None

def get_authentication_contexts():
    global _authentication_contexts
    if _authentication_contexts is None:
        _authentication_contexts = []
        for path in settings['shrubbery.authentication'].CONTEXTS:
            module_name, name = path.rsplit('.', 1)
            module = import_module(module_name)
            context = getattr(module, name)
            _authentication_contexts.append(context)
    return _authentication_contexts

class Sudo(object):
    def __init__(self, auth, user):
        self.auth = auth
        self.user = user
        self.base_user = None

    def __enter__(self):
        self.base_user = self.auth.user
        self.auth.user = self.user

    def __exit__(self, *exc):
        self.auth.user = self.base_user

    def __call__(self, func):
        @wraps(func)
        def decorated(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return decorated

_unset = object()

class AuthenticationContext(object):
    def __init__(self, root=None, anonymous=None, session_key=None):
        self.root = root
        self.anonymous = anonymous
        self.stack = threading.local()
        if not session_key:
            session_key = "%s.user-id" % self.__class__.__name__
        self.session_key = session_key
        self.user = self.anonymous

    def sudo(self, user=_unset):
        if user is _unset:
            user = self.root
        return Sudo(self, user)

    def is_anonymous(self, user):
        return user is self.anonymous

    def login(self, request, user):
        self.set_user(request, user)

    def logout(self, request):
        self.set_user(request, self.anonymous)

    def get_user_id(self, user):
        raise NotImplemented()

    def get_user_by_id(self, id):
        raise NotImplemented()

    def set_user(self, request, user=_unset):
        if user is not _unset:
            self.user = user
        if self.user:
            request.session[self.session_key] = self.get_user_id(self.user)
        elif self.session_key in request.session:
            del request.session[self.session_key]

    def get_user(self, request):
        if self.session_key in request.session:
            try:
                return self.get_user_by_id(request.session[self.session_key])
            except (AuthenticationError, ValueError) as e:
                pass
        return self.anonymous

    def _set_user(self, user):
        self.stack.user = user

    def _get_user(self):
        if callable(self.stack.user):
            self.stack.user = self.stack.user()
        return self.stack.user

    def _del_user(self):
        self.stack.user = self.anonymous

    user = property(_get_user, _set_user, _del_user)

    def required(self, func=None):
        if not func:
            return self.required
        @wraps(func)
        def _decorated(*args, **kwargs):
            if self.is_anonymous(self.user):
                raise Http403()
            return func(*args, **kwargs)
        return _decorated

class ModelAuthenticationContext(AuthenticationContext):
    def __init__(self, **kwargs):
        if 'queryset' in kwargs:
            self.queryset = kwargs.pop('queryset')
        super(ModelAuthenticationContext, self).__init__(**kwargs)

    def get_user_id(self, user):
        return user.pk

    def get_user_by_id(self, user_id):
        try:
            return self.queryset.get(pk=user_id)
        except self.queryset.model.DoesNotExist:
            raise ValueError("invalid user id: %s" % user_id)

redpajama_set_name: RedPajamaGithub


text:
My first steps to IntelliJ IDEA 13 IDE guided by HelloWorld tutorial available [here](http://www.jetbrains.com/idea/webhelp/creating-and-running-your-first-java-application.html)

Keyboard shortcuts:

* `⌘ + n` — Search classes
* `⌃ + n` — Generators (like new package or java class)
* `⌥ + enter` - Show intention actions and quick-fixes
* `⌘ + F9` - build project (make it!)
* `⌘ + ⇧ + f10` - run  project
* `⌘ + +` & `⌘ + -` — Fold/Unfold the code
* `⇧ + Enter` - starts a new line keeping the previous line intact.

Live Templates:
* `psvm + tab` - `public static void main()` scaffold
* `sout + tab` - `system.out.println()`


text:
"""users and values joiner tables

Revision ID: 16c38836d489
Revises: 16c93656a0de
Create Date: 2015-07-21 12:24:33.077367

"""

# revision identifiers, used by Alembic.
revision = '16c38836d489'
down_revision = '16c93656a0de'
branch_labels = None
depends_on = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.create_table(
        'post_users',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('user', sa.String(64), nullable=False),
        sa.Column('post_id', sa.Integer, nullable=False))

    op.create_table(
        'post_values',
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('value', sa.String(64), nullable=False),
        sa.Column('post_id', sa.Integer, nullable=False))

    post_users_table = sa.sql.table('post_users',
        sa.Column('user', sa.String(64), nullable=False),
        sa.Column('post_id', sa.Integer, nullable=False))

    post_values_table = sa.sql.table('post_values',
        sa.Column('value', sa.String(64), nullable=False),
        sa.Column('post_id', sa.Integer, nullable=False))

    conn = op.get_bind()
    results = conn.execute("SELECT id, user, value FROM posts").fetchall()

    p_u = [{'post_id': r[0], 'user': r[1]} for r in results]
    p_v = [{'post_id': r[0], 'value': r[2]} for r in results]

    op.bulk_insert(post_users_table, p_u)
    op.bulk_insert(post_values_table, p_v)

def downgrade():
    op.drop_table('post_users')
    op.drop_table('post_values')


text:
using namespace azule;

Q_DECLARE_METATYPE(azule::Entity*)
Q_DECLARE_METATYPE(azule::Component*)

struct TreeWidgetEntity::Impl
{
	ScopedConnection connection;
};

TreeWidgetEntity::TreeWidgetEntity(QWidget* parent) : QTreeWidget(parent)
{
	ObjectFactoryRegister(azule::GUIComponent);

	qRegisterMetaType<azule::Entity*>();
	qRegisterMetaType<azule::Component*>();

	this->pimpl->connection = EventQueue::Instance().addEventHandler([this](Event* x) {
		auto evt = dynamic_cast<EntityEvent*>(x);

		if(evt != nullptr)
		{
			switch(evt->getType())
			{
				case EntityEvent::Type::EntityAdded:
					this->addEntity(evt->getEntity());
					break;

				case EntityEvent::Type::EntityRemoved:
					this->removeEntity(evt->getEntity());
					break;

				case EntityEvent::Type::ComponentAdded:
					this->addComponent(evt->getEntity(), evt->Component);
					break;

				case EntityEvent::Type::ComponentRemoved:
					this->removeComponent(evt->getEntity(), evt->Component);
					break;

				default:
					break;
			}
		}
	});

	this->connect(this, &QTreeWidget::itemChanged, this, [this](QTreeWidgetItem* item) {
		if(item->type() == ItemType::Entity)
		{
			auto entity = item->data(0, Qt::UserRole).value<azule::Entity*>();

			if(entity != nullptr)
			{
				auto gui = entity->addComponent<GUIComponent>();
				gui->ID = item->text(0).toStdString();
			}
		}
	});

	this->connect(this, &QTreeWidget::itemClicked, this, [this](QTreeWidgetItem* item) {
		if(item->type() == ItemType::Component)
		{
			auto component = item->data(0, Qt::UserRole).value<azule::Component*>();
			Application::Instance()->componentSelected(component);
		}
	});

	const auto manager = Application::Instance()->getEngine().getChild<EntityDatabase>();

	if(manager != nullptr)
	{
		const auto& entities = manager->getChildren<azule::Entity>();

		for(const auto& entity : entities)
		{
			this->addEntity(entity.get());
		}
	}
}

TreeWidgetEntity::~TreeWidgetEntity()
{
}

void TreeWidgetEntity::addEntity(azule::Entity* x)
{
	// Block the item changed signal until after we've fully added the entity node along with
	// its component nodes.
	QSignalBlocker block(this);
	auto item = new QTreeWidgetItem(this, ItemType::Entity);
	item->setText(0, "Entity");
	item->setData(0, Qt::UserRole, QVariant::fromValue(x));
	item->setIcon(0, QIcon(":icons/pawn.png"));
	item->setFlags(item->flags() | Qt::ItemFlag::ItemIsEditable);

	auto components = x->getChildren<azule::Component>();

	for(const auto& component : components)
	{
		this->addComponent(item, component.get());
	}
}

void TreeWidgetEntity::removeEntity(azule::Entity* x)
{
	delete this->findItem(x);
}

void TreeWidgetEntity::addComponent(azule::Entity* e, azule::Component* c)
{
	auto item = this->findItem(e);

	if(item != nullptr)
	{
		this->addComponent(item, c);
	}
}

void TreeWidgetEntity::addComponent(QTreeWidgetItem* item, azule::Component* c)
{
	const auto componentItem = new QTreeWidgetItem(item, ItemType::Component);
	componentItem->setText(0, QString::fromStdString(c->getID()));
	componentItem->setData(0, Qt::UserRole, QVariant::fromValue(c));
	item->setExpanded(true);
}

void TreeWidgetEntity::removeComponent(azule::Entity* e, azule::Component* c)
{
	delete this->findItem(e, c);
}

QTreeWidgetItem* TreeWidgetEntity::findItem(azule::Entity* x)
{
	for(auto i = 0; i < this->topLevelItemCount(); i++)
	{
		auto item = this->topLevelItem(i);

		if(item->data(0, Qt::UserRole).value<azule::Entity*>() == x)
		{
			return item;
		}
	}

	return nullptr;
}

QTreeWidgetItem* TreeWidgetEntity::findItem(azule::Entity* e, azule::Component* c)
{
	auto item = this->findItem(e);

	if(item != nullptr)
	{
		for(auto i = 0; i < item->childCount(); i++)
		{
			auto child = item->child(i);

			if(child->text(0) == QString::fromStdString(c->getID()))
			{
				return child;
			}
		}
	}

	return nullptr;
}

QSize TreeWidgetEntity::sizeHint() const
{
	const auto hint = QTreeWidget::sizeHint();
	return {450, hint.width()};
}


text:
<?php

use yii\db\Migration;

class m160404_201204_users_to_partners extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%users_to_partners}}', [
            'id' => $this->primaryKey(),
            'user_id' =>  $this->Integer()->notNull(),
            'partner_id' => $this->integer()->notNull(),

        ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('{{%users_to_partners}}');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
package net.atos.dwAngularStartup.api;

import static com.google.common.base.Preconditions.checkNotNull;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Todo {

  public static TodoBuilder newBuilder() {
    return new TodoBuilder();
  }

  @JsonProperty
  private final String id;

  @JsonProperty
  private final String title;

  @JsonProperty
  private final Boolean completed;

  @JsonCreator
  public Todo(
      @JsonProperty("id") String id,
      @JsonProperty("title") String title,
      @JsonProperty("completed") Boolean completed
  ) {
    this.id = checkNotNull(id, "id is null");
    this.title = title;
    this.completed = completed;
  }

  public String getId() {
    return id;
  }

  public String getTitle() {
    return title;
  }

  public Boolean getCompleted() {
    return completed;
  }

  public TodoBuilder toBuilder() {
    return new TodoBuilder(this);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Todo)) return false;

    Todo todo = (Todo) o;

    if (completed != null ? !completed.equals(todo.completed) : todo.completed != null) return false;
    if (title != null ? !title.equals(todo.title) : todo.title != null) return false;
    if (id != null ? !id.equals(todo.id) : todo.id != null) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = id != null ? id.hashCode() : 0;
    result = 31 * result + (title != null ? title.hashCode() : 0);
    result = 31 * result + (completed != null ? completed.hashCode() : 0);
    return result;
  }

  @Override
  public String toString() {
    return "Todo{" +
        "id='" + id + '\'' +
        ", title='" + title + '\'' +
        ", completed=" + completed +
        '}';
  }
}


text:
<%= header %>
<%= boomerangScriptMin %>
<script src="28-send-plugin-disabled.js" type="text/javascript"></script>
<script>
function errorFunction() {
	BOOMR.plugins.Errors.send("ERROR!");
}
errorFunction();

BOOMR_test.init({
	testAfterOnBeacon: true,
	Errors: {
		enabled: false
	}
});
</script>
<%= footer %>


text:
package edu.cmu.cs.stage3.alice.core.response;

import edu.cmu.cs.stage3.alice.core.Direction;

public class RollAnimation extends RotateAnimation {
	private static Class[] s_supportedCoercionClasses = { TurnAnimation.class };
	public Class[] getSupportedCoercionClasses() {
		return s_supportedCoercionClasses;
	}
	protected boolean acceptsDirection( Direction direction ) {
		return direction.getRollAxis()!=null;
	}
	public class RuntimeRollAnimation extends RuntimeRotateAnimation {
		protected javax.vecmath.Vector3d getAxis( Direction direction ) {
			if( direction!=null ) {
				return direction.getRollAxis();
			} else {
				return null;
			}
		}
	}
}


text:
from bears.vimscript.VintBear import VintBear
from coalib.testing.LocalBearTestHelper import verify_local_bear

good_file = """
:let foo = 'bar'
:echo foo
"""

bad_file = """
:let foo = "bar"
:echo foo
"""

VintBearTest = verify_local_bear(VintBear,
                                 valid_files=(good_file,),
                                 invalid_files=(bad_file,))


text:
<?php

namespace Training\AnnonceBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * EstimerRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class EstimerRepository extends EntityRepository
{
}


text:
package org.apache.yoko.orb.CORBA;

final public class StubForObject extends org.omg.CORBA_2_4.portable.ObjectImpl
        implements org.omg.CORBA.portable.IDLEntity {
    // ------------------------------------------------------------------
    // Standard IDL to Java Mapping
    // ------------------------------------------------------------------

    public String[] _ids() {
        return new String[0];
    }
}


text:
package com.dotweblabs.friendscube.app.client.local.widgets;

import com.dotweblabs.friendscube.app.client.local.LoggedInUser;
import com.dotweblabs.friendscube.app.client.local.widgets.like.LikeButton;
import com.dotweblabs.friendscube.app.client.shared.entity.Profile;
import com.dotweblabs.friendscube.app.client.shared.entity.actions.Like;
import com.dotweblabs.friendscube.app.client.shared.entity.actions.Status;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import org.jboss.errai.ui.client.widget.HasModel;
import org.jboss.errai.ui.shared.ServerTemplateProvider;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.Templated;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;
/**
 * @author Kerby Martino
 * @version 1.0
 * @since 1.0
 */
@Dependent
@Templated
public class StatusWidget extends Composite implements HasModel<Status> {

    @Inject
    @DataField
    Label message;

    @Inject
    @DataField
    Label time;

    @Inject
    @DataField
    Label profileName;

    @Inject
    @DataField
    LikeButton like;

    @Inject
    LoggedInUser loggedInUser;

    Status status;

    Profile profile;

    @Override
    public Status getModel() {
        return status;
    }

    @Override
    public void setModel(Status status) {
        this.status = status;
        message.setText(status.getMessage());
        profileName.setText(profile.getFirstName()+" "+profile.getMiddleName()+" " +profile.getLastName());
        time.setText(DateTimeFormat.getFormat("dd/MM/yyyy h:mm a").format(status.getCreated()));
        like.setItemType(Like.LikeType.STATUS.toString());
        like.setItemId(status.getId());
        like.setUserId(loggedInUser.getUser().getId());

    }

    public void setProfile(Profile profile) {
        this.profile = profile;
    }
}


text:
class EleprojectPipeline(object):
    def process_item(self, item, spider):
        return item


text:
describe("Weather", function() {
    var weather;

    beforeEach(function() {
        weather = new Weather();
    });

    it("should report if it is stormy", function() {
        expect([true,false]).toContain(weather.stormy());
  });
});


text:
package suspend_test

import (
	"crypto/rand"
	"fmt"
	"hash"
	"hash/fnv"
	"sync/atomic"
	"testing"
	"time"

	"github.com/corestoreio/pkg/sync/bgwork"

	"github.com/corestoreio/errors"
	"github.com/corestoreio/pkg/store/scope"
	"github.com/corestoreio/pkg/sync/suspend"
)

const hashCount = 10

func generateHashes() (hashes [hashCount + 1]scope.TypeID) {
	const scopeCount = 2
	scopes := [scopeCount]scope.Type{
		scope.Website, scope.Store,
	}
	for i := 0; i < hashCount; i++ {
		s := scopes[i%2]
		hashes[i] = scope.MakeTypeID(s, uint32(i))
	}
	hashes[hashCount] = scope.DefaultTypeID
	return hashes
}

func TestHashState_Initialized(t *testing.T) {
	var hs suspend.State
	if hs.Initialized() {
		t.Error("Should not be initialized")
	}
	if err := hs.Done(scope.DefaultTypeID.ToUint64()); !errors.Fatal.Match(err) {
		t.Errorf("Expecting a Fatal error: %s", err)
	}
	if hs.ShouldWait(scope.DefaultTypeID.ToUint64()) {
		t.Error("Should not be running")
	}

	hs = suspend.NewState()
	if !hs.Initialized() {
		t.Error("Should be initialized")
	}
	if err := hs.Done(scope.DefaultTypeID.ToUint64()); !errors.Fatal.Match(err) {
		t.Errorf("Expecting a Fatal error: %s", err)
	}
}

func TestHashState_CanRun(t *testing.T) {
	var hs suspend.State

	if hs.ShouldStart(scope.DefaultTypeID.ToUint64()) {
		t.Fatal("Should not return true because not yet initialized")
	}
	hs = suspend.NewState()

	hashes := generateHashes()

	t.Run("Start", func(t *testing.T) {
		bgwork.Wait(len(hashes), func(i int) {
			h := hashes[i]
			if hs.ShouldWait(h.ToUint64()) {
				panic("Should not run")
			}
			if !hs.ShouldStart(h.ToUint64()) {
				panic("Should return true that it has been started")
			}
		})
	})

	t.Run("NoStart", func(t *testing.T) {
		bgwork.Wait(len(hashes), func(i int) {
			h := hashes[i]
			if hs.ShouldStart(h.ToUint64()) {
				panic("Multiple starts not allowed")
			}
		})
	})

	if have, want := hs.Len(), len(hashes); have != want {
		t.Errorf("Incorrect HashState Length: Have %d Want %d", have, want)
	}
}

func TestHashState_ShouldWait(t *testing.T) {
	var hs suspend.State
	if hs.ShouldStart(scope.DefaultTypeID.ToUint64()) {
		t.Fatal("Should not return true because not yet initialized")
	}

	hs = suspend.NewState()

	hashes := generateHashes()

	const iterations = 23 // just a random number picked, this would be the expect # of http.requests
	countWaiter := new(uint32)
	countRun := new(uint32)

	for i := 0; i < len(hashes); i++ {
		bgwork.Wait(iterations, func(j int) {
			h := hashes[i]
			switch {
			// You should stick to the sequence of the cases: 1. Start 2. Running
			case hs.ShouldStart(h.ToUint64()):
				atomic.AddUint32(countRun, 1)
				time.Sleep(2 * time.Millisecond) // simulate race detector ;-)
				if err := hs.Done(h.ToUint64()); err != nil {
					panic(fmt.Sprintf("%+v", err))
				}
			case hs.ShouldWait(h.ToUint64()): // this case is normally not needed
				atomic.AddUint32(countWaiter, 1)
			}

			if hs.ShouldWait(h.ToUint64()) {
				println(fmt.Sprintf("Should not be running, because it should have ran "+
					"already, so now we're waiting. Iteration %d Hash %s", j, h))
			}
		})
	}

	if have, want := atomic.LoadUint32(countRun), uint32(len(hashes)); have != want {
		t.Errorf("Runner: Have %d Want %d", have, want)
	}
	if have, want := atomic.LoadUint32(countWaiter), uint32(140); have < want {
		// we have around ~50-190 waiting goroutines. the number of waiting goroutines
		// is totally random and depends on how fast the case CanRun: can process the
		// work or if the race detector has been enabled. So we check here for at least
		// 100 sleeper.
		t.Errorf("Waiter: Have %d > Want %d", have, want)
	} else {
		t.Logf("INFO Waiter: %d", have)
	}

	hs.Reset()
	if have, want := hs.Len(), 0; have != want {
		t.Errorf("After calling Reset the internal map must be cleared. Have %d", have)
	}
}

func TestHashStateBytes_ShouldWait(t *testing.T) {
	hs := suspend.NewStateWithHash(fnv.New64a())

	const randBytesGenerate = 11

	const iterations = 5 // just a random number picked, this would be the expect # of http.requests
	countWaiter := new(uint32)
	countRun := new(uint32)

	for i := 0; i < randBytesGenerate; i++ {
		key := make([]byte, 32)
		if n, err := rand.Read(key); err != nil || n == 0 {
			t.Fatalf("Failed to random Bytes: %s Read Count: %d", err, n)
		}

		bgwork.Wait(iterations, func(j int) {
			switch {
			// You should stick to the sequence of the cases: 1. Start 2. Running
			case hs.ShouldStartBytes(key):
				atomic.AddUint32(countRun, 1)
				time.Sleep(time.Millisecond) // simulate race detector ;-)
				if err := hs.DoneBytes(key); err != nil {
					panic(fmt.Sprintf("%+v", err))
				}
			case hs.ShouldWaitBytes(key): // this case is normally not needed
				atomic.AddUint32(countWaiter, 1)
			}

			if hs.ShouldWaitBytes(key) {
				panic(fmt.Sprintf("Should not be running, because it should have ran "+
					"already, so now we're waiting. Iteration %d Hash %x", j, key))
			}
		})

	}

	if have, want := atomic.LoadUint32(countRun), uint32(randBytesGenerate); have != want {
		t.Errorf("Runner: Have %d Want %d", have, want)
	}
	if have, want := atomic.LoadUint32(countWaiter), uint32(iterations*4); have < want {
		t.Errorf("Waiter: Have %d > Want %d", have, want)
	} else {
		t.Logf("INFO Waiter: %d", have)
	}

	hs.Reset()
	if have, want := hs.Len(), 0; have != want {
		t.Errorf("After calling Reset the internal map must be cleared. Have %d", have)
	}
}

var _ hash.Hash64 = (*hashMock)(nil)

type hashMock struct {
	err error
	hash.Hash64
}

func (hm hashMock) Write(p []byte) (n int, err error) {
	return 0, hm.err
}
func (hm hashMock) Reset()        {}
func (hm hashMock) Sum64() uint64 { return 0 }

func TestHashStateBytes_Error(t *testing.T) {
	hs := suspend.NewStateWithHash(hashMock{
		err: errors.WriteFailed.Newf("Write failed"),
	})
	key := []byte(`I'm writing Go code`)
	if hs.ShouldWaitBytes(key) {
		t.Error("Should not wait")
	}
	if have, want := hs.Len(), 0; have != want {
		t.Errorf("Have: %v Want: %v", have, want)
	}
}


text:
module Capistrano
  module Cluster
    class Service
      attr :name, :cmd
      def initialize(name, &block)
        @name = name
        instance_eval(&block)
      end

      def start(*args)
        @start = args.first if args.length > 0
        @start || fail("no start command defined for #{@name}")
      end

      def working_dir(*args)
        @working_dir = args.first if args.length > 0
        @working_dir || "/tmp"
      end

      def pid_file(*args)
        @pid_file = args.first if args.length > 0
        @pid_file || "/var/run/#{@name}.pid"
      end

      def reload(*args)
        @reload = args.first if args.length > 0
        @reload || "stop;start"
      end

      def stop(*args)
        @stop = args.first if args.length > 0
        @stop || "kill -TERM $(< #{pid_file})"
      end

      def user(*args)
        @user = args.first if args.length > 0
        @user
      end

      def log_file(*args)
        @log_file = args.first if args.length > 0
        @log_file || "/var/log/service.#{@name}.log"
      end

      def script
        file("service", name: name, start_cmd: start, pid_file: pid_file, working_dir: working_dir, reload_cmd: reload, stop_cmd: stop, user: user)
      end

      module DSL

        def service(name, &block)
          service = Capistrano::Cluster::Service.new(name, &block)
          upload_as :root, service.script, "/etc/init.d/#{name}"
          sudo :chmod, "0777", "/etc/init.d/#{name}"
          sudo "update-rc.d", name, :defaults
        end

      end

    end

  end

end

include Capistrano::Cluster::Service::DSL


text:
@import UIKit;
@import QuartzCore.CAMetalLayer;

@interface MBEMetalView : UIView

@property (nonatomic, readonly) CAMetalLayer *metalLayer;

@end


text:
namespace dioptre {
namespace physics {
namespace bullet {

class Shape {
public:
  ~Shape() { delete collisionShape_; }
  btCollisionShape *getCollisionShape() { return collisionShape_; };

protected:
  btCollisionShape *collisionShape_;
}; // Shape

} // bullet
} // physics
} // dioptre

#endif // DIOPTRE_PHYSICS_BULLET_SHAPE_H_


text:
MathJax.Localization.addTranslation("es","HTML-CSS",{
        version: "2.7.2",
        isLoaded: true,
        strings: {
          LoadWebFont: "Cargando el tipo de letra web %1",
          CantLoadWebFont: "No se pudo cargar la fuente web %1",
          FirefoxCantLoadWebFont: "Firefox no puede cargar tipos de letra web desde un equipo remoto",
          CantFindFontUsing: "No se puede encontrar un tipo de letra v\u00E1lido mediante %1",
          WebFontsNotAvailable: "No hay fuentes web disponibles. Usando fuentes de imagen en su lugar"
        }
});

MathJax.Ajax.loadComplete("[MathJax]/localization/es/HTML-CSS.js");


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.databind.util.ClassUtil.Ctor (jackson-databind 2.7.0 API)</title>
<meta name="date" content="2016-01-15">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.fasterxml.jackson.databind.util.ClassUtil.Ctor

Packages that use ClassUtil.Ctor

Package
Description

com.fasterxml.jackson.databind.introspect

Functionality needed for Bean introspection, required for detecting
 accessors and mutators for Beans, as well as locating and handling
 method annotations.

com.fasterxml.jackson.databind.util

Utility classes for Mapper package.

Uses of ClassUtil.Ctor in com.fasterxml.jackson.databind.introspect

Methods in com.fasterxml.jackson.databind.introspect with parameters of type ClassUtil.Ctor

Modifier and Type
Method and Description

protected AnnotatedConstructor
AnnotatedClass._constructDefaultConstructor(ClassUtil.Ctor ctor,
                            TypeResolutionContext typeContext)

protected AnnotatedConstructor
AnnotatedClass._constructNonDefaultConstructor(ClassUtil.Ctor ctor,
                               TypeResolutionContext typeContext)

Uses of ClassUtil.Ctor in com.fasterxml.jackson.databind.util

Methods in com.fasterxml.jackson.databind.util that return ClassUtil.Ctor

Modifier and Type
Method and Description

static ClassUtil.Ctor[]
ClassUtil.getConstructors(Class<?> cls)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2008–2016 FasterXML. All rights reserved.


text:
using System.Diagnostics;

namespace System.Reflection.Metadata
{
    /// <summary>
    /// Lexical scope within which a group of imports are available. Stored in debug metadata.
    /// </summary>
    /// <remarks>
    /// See https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#importscope-table-0x35
    /// </remarks>
    public readonly struct ImportScope
    {
        private readonly MetadataReader _reader;

        // Workaround: JIT doesn't generate good code for nested structures, so use RowId.
        private readonly int _rowId;

        internal ImportScope(MetadataReader reader, ImportScopeHandle handle)
        {
            Debug.Assert(reader != null);
            Debug.Assert(!handle.IsNil);

            _reader = reader;
            _rowId = handle.RowId;
        }

        private ImportScopeHandle Handle => ImportScopeHandle.FromRowId(_rowId);

        public ImportScopeHandle Parent => _reader.ImportScopeTable.GetParent(Handle);
        public BlobHandle ImportsBlob => _reader.ImportScopeTable.GetImports(Handle);

        public ImportDefinitionCollection GetImports()
        {
            return new ImportDefinitionCollection(_reader.BlobHeap.GetMemoryBlock(ImportsBlob));
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE690_NULL_Deref_From_Return__fopen_67b.c
Label Definition File: CWE690_NULL_Deref_From_Return.fclose.label.xml
Template File: source-sinks-67b.tmpl.c
*/
/*
 * @description
 * CWE: 690 Unchecked Return Value To NULL Pointer
 * BadSource: fopen Open data with fopen()
 * Sinks: 0
 *    GoodSink: Check data for NULL
 *    BadSink : Do not check data for NULL
 * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
 *
 * */

#include "std_testcase.h"

typedef struct _CWE690_NULL_Deref_From_Return__fopen_67_structType
{
    FILE * structFirst;
} CWE690_NULL_Deref_From_Return__fopen_67_structType;

#ifndef OMITBAD

void CWE690_NULL_Deref_From_Return__fopen_67b_badSink(CWE690_NULL_Deref_From_Return__fopen_67_structType myStruct)
{
    FILE * data = myStruct.structFirst;
    /* FLAW: if the fopen failed, data will be NULL here */
    fclose(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G uses the BadSource with the GoodSink */
void CWE690_NULL_Deref_From_Return__fopen_67b_goodB2GSink(CWE690_NULL_Deref_From_Return__fopen_67_structType myStruct)
{
    FILE * data = myStruct.structFirst;
    /* FIX: check the return value */
    if (data != NULL)
    {
        fclose(data);
    }
}

#endif /* OMITGOOD */


text:
describe("Tags", () => {
  let testRunId: string;

  before(() => {
    cy.log("Créer un tir");
    cy.createFilledTestRun().then((testRun) => {
      testRunId = testRun.id;
    });
  });

  const existingTag = "tutu";
  const unexistingTag = "unexisting";

  beforeEach(() => {
    cy.visit(`/ui/test-runs/${testRunId}/tags`);

    cy.contains("h1", "Tous les tags").should("exist");
  });

  it("should display tags", () => {
    cy.findByTestId("tags").within(() => {
      cy.get("tbody tr").should("not.be.empty");
    });
  });

  it("should filter with unexisting tag", () => {
    cy.findByTestId("tag-filter-form").within(() => {
      cy.findByLabelText("Tag").type(unexistingTag);
    });

    cy.findByTestId("tags").within(() => {
      cy.get("tbody tr").should("not.exist");
    });
  });

  it("should filter with existing tag", () => {
    cy.findByTestId("tag-filter-form").within(() => {
      cy.findByLabelText("Tag").type(existingTag);
    });

    cy.findByTestId("tags").within(() => {
      cy.get("tbody tr").should("have.length", 1);
    });
  });

  it("should clear tag selection", () => {
    cy.findByTestId("tags")
      .get("tbody tr")
      .then((rows) => rows.length)
      .as("tagCount");

    // Select one tag

    cy.findByTestId("tag-filter-form").within(() => {
      cy.findByLabelText("Tag").type(existingTag);
    });

    cy.findByTestId("tags").within(() => {
      cy.get("tbody tr").should("have.length", 1);
    });

    // Clear selection, verify update

    cy.findByTestId("tag-filter-form").within(() => {
      cy.findByText("Effacer").parent("button").click();
    });

    cy.get("@tagCount").then((tagCount) => {
      cy.findByTestId("tags").within(() => {
        cy.get("tbody tr").should("have.length", tagCount);
      });
    });
  });

  it("should navigate to some tag", () => {
    cy.findByTestId("tags").contains("a", `@${existingTag}`).click();

    cy.url().should("have.string", `tag-details?tag=${existingTag}`);
  });
});


text:
using System;

namespace Shock.Test.Unit.FakesAndStubs
{
    public class FakeTaskClass
    {
        public void DoSomething()
        {
            Console.WriteLine("Hi");
        }

        public void DoSomethingWithAParameter(string abc)
        {
        }

        public string DoSomethingWithAReturnValue()
        {
            return "something";
        }

        public string Throw()
        {
            throw new NotImplementedException("Nope!");
        }

        public int ReturnsOneHundred()
        {
            return 100;
        }
    }
}


text:
#include "main.h"

void CharacterInstance::makeRawPoseDescriptor(const vector<UINT64> &segmentList, float *result) const
{
    size_t resultIndex = 0;
    for (UINT64 signature : segmentList)
    {
        auto it = segments.find(signature);
        if (it == segments.end())
        {
            for (int i = 0; i < 3; i++)
                result[resultIndex++] = 0.0f;
        }
        else
        {
            result[resultIndex++] = it->second.centeredCentroid.x;
            result[resultIndex++] = it->second.centeredCentroid.y;
            result[resultIndex++] = it->second.centeredCentroid.z;
        }
    }
}

void Character::init(const vector<UINT64> &segments, int _characterIndex)
{
    characterIndex = _characterIndex;

    allSegmentsVec = segments;
    for (UINT64 segment : segments)
        allSegmentsSet.insert(segment);
}

void Character::recordAllFrames(const ReplayDatabase &frames)
{
    for (const ReplayDatabaseEntry &entry : frames.entries)
    {
        cout << "Recording poses for character " << characterIndex << " in " << entry.replay->sourceFilename << endl;
        for (const auto &frame : entry.processedFrames)
        {
            recordFramePoses(frame);
        }
    }

    for (auto &instance : allInstances)
        allInstancesVec.push_back(&instance.second);

    computePosePCA();
    computePoseDescriptors();

    computePoseChainForwardPCA();
    computePoseChainForwardDescriptors();

    computePoseChainReversePCA();
    computePoseChainReverseDescriptors();

    saveAnimationCurve();

    makePoseLSHSearch();

    makePoseClusters();

    //computeAnimationSequences();
}

void Character::computePoseDescriptors()
{
    cout << "Computing pose descriptors..." << endl;

    const int poseFeatureCount = 3 * (int)allSegmentsVec.size();
    vector<float> rawPoseDescriptor(poseFeatureCount);

    for (auto &instance : allInstances)
    {
        instance.second.makeRawPoseDescriptor(allSegmentsVec, rawPoseDescriptor.data());
        posePCA.transform(rawPoseDescriptor, posePCADimension, instance.second.poseDescriptor);
    }
}

void Character::computePoseChainForwardDescriptors()
{
    cout << "Computing pose chain forward descriptors..." << endl;

    const int poseChainFeatureCount = min(Constants::poseChainForwardMaxDim, posePCADimension) * Constants::poseChainForwardLength;
    vector<float> rawPoseChainDescriptor(poseChainFeatureCount);

    for (auto &instance : allInstances)
    {
        computePoseChainForwardDescriptor(instance.first, rawPoseChainDescriptor.data());
        poseChainForwardPCA.transform(rawPoseChainDescriptor, poseChainForwardPCADimension, instance.second.poseChainForwardDescriptor);
    }
}

int Character::poseChainReverseFeatureCount() const
{
    return min(Constants::poseChainReverseMaxDim, posePCADimension) * Constants::poseChainReverseLength;;
}

void Character::computePoseChainReverseDescriptors()
{
    cout << "Computing pose chain reverse descriptors..." << endl;

    vector<float> rawPoseChainReverseDescriptor(poseChainReverseFeatureCount());

    for (auto &instance : allInstances)
    {
        computePoseChainReverseDescriptor(instance.first, rawPoseChainReverseDescriptor.data());
        poseChainReversePCA.transform(rawPoseChainReverseDescriptor, poseChainReversePCADimension, instance.second.poseChainReverseDescriptor);
    }
}

bool Character::computePoseChainForwardDescriptor(const FrameID &startFrame, float *result) const
{
    const int poseDims = min(Constants::poseChainForwardMaxDim, posePCADimension);

    bool valid = true;
    int animationFeatureIndex = 0;
    for (int windowOffset = 0; windowOffset < Constants::poseChainForwardLength; windowOffset++)
    {
        const FrameID curFrame = startFrame.delta(windowOffset);
        const CharacterInstance *instance = findInstanceAtFrame(curFrame);
        if (instance == nullptr)
        {
            valid = false;
            for (int poseFeatureIndex = 0; poseFeatureIndex < poseDims; poseFeatureIndex++)
                result[animationFeatureIndex++] = 0.0f;
        }
        else
        {
            for (int poseFeatureIndex = 0; poseFeatureIndex < poseDims; poseFeatureIndex++)
                result[animationFeatureIndex++] = instance->poseDescriptor[poseFeatureIndex];
        }
    }
    return valid;
}

void Character::computePoseChainReverseDescriptor(const deque<const PoseCluster *> &clusterHistory, float *result) const
{
    const int poseDims = min(Constants::poseChainReverseMaxDim, posePCADimension);

    int animationFeatureIndex = 0;
    for (int windowOffset = 0; windowOffset < Constants::poseChainReverseLength; windowOffset++)
    {
        const PoseCluster &pose = *clusterHistory[windowOffset];
        const CharacterInstance *instance = findInstanceAtFrame(pose.seedFrame);
        for (int poseFeatureIndex = 0; poseFeatureIndex < poseDims; poseFeatureIndex++)
            result[animationFeatureIndex++] = instance->poseDescriptor[poseFeatureIndex];
    }
}

bool Character::computePoseChainReverseDescriptor(const FrameID &startFrame, float *result) const
{
    const int poseDims = min(Constants::poseChainReverseMaxDim, posePCADimension);

    bool valid = true;
    int animationFeatureIndex = 0;
    for (int windowOffset = 0; windowOffset < Constants::poseChainReverseLength; windowOffset++)
    {
        const FrameID curFrame = startFrame.delta(-windowOffset);
        const CharacterInstance *instance = findInstanceAtFrame(curFrame);
        if (instance == nullptr)
        {
            valid = false;
            for (int poseFeatureIndex = 0; poseFeatureIndex < poseDims; poseFeatureIndex++)
                result[animationFeatureIndex++] = 0.0f;
        }
        else
        {
            for (int poseFeatureIndex = 0; poseFeatureIndex < poseDims; poseFeatureIndex++)
                result[animationFeatureIndex++] = instance->poseDescriptor[poseFeatureIndex];
        }
    }
    return valid;
}

void Character::computePoseChainForwardPCA()
{
    const string PCADir = learningParams().datasetDir + "poseChainForwardPCA/";
    const string PCAFile = PCADir + "character" + to_string(characterIndex) + ".dat";

    if (util::fileExists(PCAFile))
    {
        cout << "Loading animation PCA from " << PCAFile << endl;
        poseChainForwardPCA.load(PCAFile);
    }
    else
    {
        const int poseChainFeatureCount = min(Constants::poseChainForwardMaxDim, posePCADimension) * Constants::poseChainForwardLength;

        DenseMatrixf M(Constants::poseChainPCASamples, poseChainFeatureCount);

        for (int sampleIndex = 0; sampleIndex < Constants::poseChainPCASamples; sampleIndex++)
        {
            bool valid = false;
            while (!valid)
            {
                const CharacterInstance &randomInstance = *util::randomElement(allInstancesVec);
                valid = computePoseChainForwardDescriptor(randomInstance.frameID, &M(sampleIndex, 0));
            }
        }

        poseChainForwardPCA.init(M);

        util::makeDirectory(PCADir);
        poseChainForwardPCA.save(PCAFile);
    }

    poseChainForwardPCADimension = (int)poseChainForwardPCA.reducedDimension(learningParams().PCAEnergy);
    cout << "Pose chain forward PCA dimension: " << poseChainForwardPCADimension << endl;
}

void Character::computePoseChainReversePCA()
{
    const string PCADir = learningParams().datasetDir + "poseChainReversePCA/";
    const string PCAFile = PCADir + "character" + to_string(characterIndex) + ".dat";

    if (util::fileExists(PCAFile))
    {
        cout << "Loading animation PCA from " << PCAFile << endl;
        poseChainReversePCA.load(PCAFile);
    }
    else
    {
        const int poseChainFeatureCount = min(Constants::poseChainReverseMaxDim, posePCADimension) * Constants::poseChainReverseLength;

        DenseMatrixf M(Constants::poseChainPCASamples, poseChainFeatureCount);

        for (int sampleIndex = 0; sampleIndex < Constants::poseChainPCASamples; sampleIndex++)
        {
            bool valid = false;
            while (!valid)
            {
                const CharacterInstance &randomInstance = *util::randomElement(allInstancesVec);
                valid = computePoseChainReverseDescriptor(randomInstance.frameID, &M(sampleIndex, 0));
            }
        }

        poseChainReversePCA.init(M);

        util::makeDirectory(PCADir);
        poseChainReversePCA.save(PCAFile);
    }

    poseChainReversePCADimension = (int)poseChainReversePCA.reducedDimension(learningParams().PCAEnergy);
    cout << "Pose chain reverse PCA dimension: " << poseChainReversePCADimension << endl;
}

/*void Character::saveControllerCurve()
{
    const string curveDir = learningParams().datasetDir + "curves/";
    const string curveFile = curveDir + "controller" + to_string(characterIndex) + ".csv";

    if (util::fileExists(curveFile))
    {
        cout << "Controller curve already exported" << endl;
    }
    else
    {
        util::makeDirectory(curveDir);
        ofstream file(curveFile);

        file << "pose0,pose1,animation0,animation1" << endl;

        for (int sampleIndex = 0; sampleIndex < allInstancesVec.size(); sampleIndex++)
        {
            const CharacterInstance &instance = *allInstancesVec[sampleIndex];
            file << instance.poseDescriptor[0] << "," << instance.poseDescriptor[1] << ",";
            //file << instance.reducedPoseChainDescriptor[0] << "," << instance.reducedPoseChainDescriptor[1];
            file << endl;
        }
    }

    posePCADimension = (int)posePCA.reducedDimension(learningParams().PCAEnergy);
    cout << "Pose PCA dimension: " << posePCADimension << endl;
}*/

void Character::saveAnimationCurve()
{
    const string curveDir = learningParams().datasetDir + "curves/";
    const string curveFile = curveDir + "character" + to_string(characterIndex) + ".csv";

    if (util::fileExists(curveFile))
    {
        cout << "Animation curve already exported" << endl;
    }
    else
    {
        util::makeDirectory(curveDir);
        ofstream file(curveFile);

        file << "pose0,pose1,animation0,animation1" << endl;

        for (int sampleIndex = 0; sampleIndex < allInstancesVec.size(); sampleIndex++)
        {
            const CharacterInstance &instance = *allInstancesVec[sampleIndex];
            file << instance.poseDescriptor[0] << "," << instance.poseDescriptor[1] << ",";
            //file << instance.reducedPoseChainDescriptor[0] << "," << instance.reducedPoseChainDescriptor[1];
            file << endl;
        }
    }

    posePCADimension = (int)posePCA.reducedDimension(learningParams().PCAEnergy);
    cout << "Pose PCA dimension: " << posePCADimension << endl;
}

void Character::computePosePCA()
{
    const string PCADir = learningParams().datasetDir + "posePCA/";
    const string PCAFile = PCADir + "character" + to_string(characterIndex) + ".dat";

    if (util::fileExists(PCAFile))
    {
        cout << "Loading pose PCA from " << PCAFile << endl;
        posePCA.load(PCAFile);
    }
    else
    {
        const int poseFeatureCount = 3 * (int)allSegmentsVec.size();

        DenseMatrixf M(Constants::posePCASamples, poseFeatureCount);

        for (int sampleIndex = 0; sampleIndex < Constants::posePCASamples; sampleIndex++)
        {
            const CharacterInstance &instance = *util::randomElement(allInstancesVec);
            instance.makeRawPoseDescriptor(allSegmentsVec, &M(sampleIndex, 0));

            //vector<float> descriptor = instance.makeRawPoseDescriptor(allSegmentsVec);
            //for(int featureIndex = 0; featureIndex < poseFeatureCount; featureIndex++)
            //   M(sampleIndex, featureIndex) = descriptor[featureIndex];
        }

        posePCA.init(M);

        util::makeDirectory(PCADir);
        posePCA.save(PCAFile);
    }

    posePCADimension = (int)posePCA.reducedDimension(learningParams().PCAEnergy);
    cout << "Pose PCA dimension: " << posePCADimension << endl;
}

/*bool Character::makeInstance(const ProcessedFrame &frame, CharacterInstance &result) const
{
    vec3f sum = vec3f::origin;
    float sumCount = 0.0f;

    for (UINT64 signature : allSegmentsVec)
    {
        if (frame.signatureMap.count(signature) > 0)
        {
            CharacterSegmentInstance &segmentInstance = result.segments[signature];
            segmentInstance.signature = signature;
            segmentInstance.worldCentroid = frame.signatureMap.find(signature)->second.front()->centroid;
            sum += segmentInstance.worldCentroid;
            sumCount += 1.0f;
        }
    }

    if (sumCount <= 0.0f)
        return false;

    result.frameID = frame.frameID;
    sum /= sumCount;
    for (auto &segmentInstance : result.segments)
    {
        segmentInstance.second.centeredCentroid = segmentInstance.second.worldCentroid - sum;
    }

    const int poseFeatureCount = 3 * (int)allSegmentsVec.size();
    vector<float> rawPoseDescriptor(poseFeatureCount);

    result.makeRawPoseDescriptor(allSegmentsVec, rawPoseDescriptor.data());
    posePCA.transform(rawPoseDescriptor, posePCADimension, result.poseDescriptor);

    const int poseChainReverseFeatureCount = min(Constants::poseChainReverseMaxDim, posePCADimension) * Constants::poseChainReverseLength;
    vector<float> rawPoseChainReverseDescriptor(poseChainReverseFeatureCount);

    for (auto &instance : allInstances)
    {
        computePoseChainReverseDescriptor(instance.first, rawPoseChainDescriptor.data());
        poseChainReversePCA.transform(rawPoseChainDescriptor, poseChainReversePCADimension, instance.second.poseChainReverseDescriptor);
    }

    return true;
}*/

void Character::recordFramePoses(const ProcessedFrame &frame)
{
    CharacterInstance frameInstance;

    vec3f sum = vec3f::origin;
    float sumCount = 0.0f;

    for (UINT64 signature : allSegmentsVec)
    {
        if (frame.signatureMap.count(signature) > 0)
        {
            CharacterSegmentInstance &segmentInstance = frameInstance.segments[signature];
            segmentInstance.signature = signature;
            segmentInstance.worldCentroid = frame.signatureMap.find(signature)->second.front()->centroid;
            sum += segmentInstance.worldCentroid;
            sumCount += 1.0f;
        }
    }

    if (sumCount > 0.0f)
    {
        frameInstance.frameID = frame.frameID;
        sum /= sumCount;
        for (auto &segmentInstance : frameInstance.segments)
        {
            segmentInstance.second.centeredCentroid = segmentInstance.second.worldCentroid - sum;
        }
        frameInstance.worldCentroid = sum;
        allInstances[frame.frameID] = frameInstance;
    }
}

void Character::computeAnimationSequences()
{
    cout << "*** Computing animation sequences" << endl;

    // this is just so I can focus on Marth for now
    if (characterIndex == 0)
        return;

    cout << "Filling priority queue" << endl;

    priority_queue<CharacterInstance*, vector<CharacterInstance*>, CharacterInstanceCompare> seedQueue;
    for (CharacterInstance *instance : allInstancesVec)
    {
        vector< pair<CharacterInstance*, float> > candidates = findPoseChainsForwardRadius(*instance, (float)learningParams().poseChainDistSq);
        instance->similarPoseChainCount = (int)candidates.size();
        if (instance->similarPoseChainCount >= learningParams().minAnimationInstances)
        {
            seedQueue.push(instance);
        }
    }

    cout << "Emptying priority queue" << endl;
    while (!seedQueue.empty())
    {
        CharacterInstance &seedInstance = *seedQueue.top();
        seedQueue.pop();

        if (seedInstance.animation.sequence == nullptr)
        {
            addNewAnimation(seedInstance);
        }
    }

    cout << "Animation count: " << animations.size() << endl;

    for (CharacterInstance *instance : allInstancesVec)
    {
        if (instance->animation.sequence != nullptr)
            instance->animation.sequence->instances.push_back(instance->frameID);
    }
}

void Character::addNewAnimation(const CharacterInstance &seed)
{
    const int animationLength = Constants::poseChainForwardLength;
    for (int offset = 0; offset < animationLength; offset++)
    {
        FrameID animationFrame = seed.frameID.delta(offset);
        CharacterInstance *animationInstance = findInstanceAtFrame(animationFrame);
        if (animationInstance == nullptr || animationInstance->animation.sequence != nullptr)
        {
            cout << "Animation rejected" << endl;
            return;
        }
    }

    AnimationSequence *animation = new AnimationSequence(seed.frameID, animationLength, (int)animations.size());

    int frameCount = 0;

    vector< pair<CharacterInstance*, float> > candidates = findPoseChainsForwardRadius(seed, (float)learningParams().poseChainDistSq);
    for (auto &candidate : candidates)
    {
        for (int offset = 0; offset < animationLength; offset++)
        {
            FrameID candidateFrame = candidate.first->frameID.delta(offset);
            CharacterInstance *otherInstance = findInstanceAtFrame(candidateFrame);

            if (otherInstance != nullptr && otherInstance->animation.sequence == nullptr)
            {
                frameCount++;
                otherInstance->animation.sequence = animation;
                otherInstance->animation.offset = offset;
                otherInstance->animation.poseDistSq = 0.0f;
            }
        }
    }
    /*for (int offset = 0; offset < animationLength; offset++)
    {
        FrameID animationFrame = seed.frameID.delta(offset);
        CharacterInstance *animationInstance = findInstanceAtFrame(animationFrame);

        for (auto pose : findPosesRadius(*animationInstance, (float)learningParams().poseDistSqThreshold))
        {
            CharacterInstance *otherInstance = pose.first;
            const float poseDistSq = pose.second;
            if (otherInstance->animation.poseDistSq > poseDistSq)
            {
                if (otherInstance->animation.sequence != animation)
                    frameCount++;
                otherInstance->animation.sequence = animation;
                otherInstance->animation.offset = offset;
                otherInstance->animation.poseDistSq = poseDistSq;
            }
        }
    }*/

    cout << "New animation: length=" << animationLength << ", estFrameCount=" << frameCount << endl;

    animations.push_back(animation);
}

void Character::makePoseClusters()
{
    cout << "Making pose clusters" << endl;

    auto &params = learningParams();
    poseClusterSearch.init(posePCADimension, (float)params.LSHpNorm, params.LSHminiHashCount, params.LSHmacroTableCount);
    for (CharacterInstance *instance : allInstancesVec)
    {
        PoseCluster *cluster = findBestPoseCluster(*instance, (float)learningParams().poseDistSqThreshold);
        if (cluster == nullptr)
        {
            cluster = new PoseCluster();
            cluster->index = (int)poseClusters.size();
            cluster->seedFrame = instance->frameID;
            poseClusters.push_back(cluster);
            poseClusterSearch.insert(instance->poseDescriptor, cluster);
        }
        instance->poseCluster = cluster;
        //cout << "poseCluster=" << instance->poseClusterIndex << endl;
        cluster->allInstances.push_back(instance->frameID);
    }
    cout << "Pose cluster count: " << poseClusters.size() << endl;
}

void Character::testAnimationSearch(float pNorm, UINT miniHashFunctionCount, UINT macroTableCount)
{
    cout << "Testing LSH " << pNorm << ", " << miniHashFunctionCount << ", " << macroTableCount << endl;
    LSHEuclidean<CharacterInstance*> search;
    search.init(poseChainForwardPCADimension, pNorm, miniHashFunctionCount, macroTableCount);
    for (auto &instance : allInstances)
        search.insert(instance.second.poseChainForwardDescriptor, &instance.second);

    const UINT testInstanceCount = 500;
    const float targetDistSq = 10.0f;
    size_t missedSamples = 0;
    size_t wastedSamples = 0;

    size_t totalValidSamples = 0;

    ofstream fileDebug("debug.txt");
    for (int test = 0; test < testInstanceCount; test++)
    {
        const CharacterInstance &randomInstance = *util::randomElement(allInstancesVec);

        auto results = search.findSimilar(randomInstance.poseChainForwardDescriptor);
        for (CharacterInstance *candidate : results)
        {
            const float distSq = math::distSq(candidate->poseChainForwardDescriptor, randomInstance.poseChainForwardDescriptor);
            if (distSq > targetDistSq)
                wastedSamples++;
        }

        for (auto &instance : allInstancesVec)
        {
            const float distSq = math::distSq(instance->poseChainForwardDescriptor, randomInstance.poseChainForwardDescriptor);
            if (test == 0)
                fileDebug << distSq << endl;
            if (distSq < targetDistSq)
            {
                if (results.count(instance) == 0)
                    missedSamples++;
                totalValidSamples++;
            }
        }
    }

    const string filename = "logs/animationSearchTest.txt";
    bool emitHeader = !util::fileExists(filename);
    ofstream file(filename, ios::app);
    if (emitHeader)
    {
        file << "pNorm\tminiHashCount\tmacroTableCount\ttargetDistSq\tavg valid count\tavg missed samples\tavg wasted samples" << endl;
    }
    file << pNorm << '\t' << miniHashFunctionCount << '\t' << macroTableCount << '\t' << targetDistSq << '\t';
    file << (double)totalValidSamples / (double)testInstanceCount << '\t';
    file << (double)missedSamples / (double)testInstanceCount << '\t';
    file << (double)wastedSamples / (double)testInstanceCount << endl;
}

void Character::makePoseLSHSearch()
{
    const bool LSHParameterSearch = false;
    if (LSHParameterSearch)
    {
        // best values found for targetDistSq = 5.0:
        // pNorm=0.0135, k=30, L=20
        for (float dist = 0.004f; dist <= 0.3f; dist *= 1.5f)
            for (int k = 10; k <= 30; k += 5)
                for (int L = 5; L <= 20; L += 5)
                    testAnimationSearch(dist, k, L);
    }

    cout << "Building pose LSH tables" << endl;
    auto &params = learningParams();

    poseSearch.init(posePCADimension, (float)params.LSHpNorm, params.LSHminiHashCount, params.LSHmacroTableCount);
    for (auto &instance : allInstances)
    {
        poseSearch.insert(instance.second.poseDescriptor, &instance.second);
    }

    poseChainForwardSearch.init(poseChainForwardPCADimension, (float)params.LSHpNorm, params.LSHminiHashCount, params.LSHmacroTableCount);
    for (auto &instance : allInstances)
    {
        poseChainForwardSearch.insert(instance.second.poseChainForwardDescriptor, &instance.second);
    }

    poseChainReverseSearch.init(poseChainForwardPCADimension, (float)params.LSHpNorm, params.LSHminiHashCount, params.LSHmacroTableCount);
    for (auto &instance : allInstances)
    {
        poseChainReverseSearch.insert(instance.second.poseChainReverseDescriptor, &instance.second);
    }
}

PoseCluster* Character::findBestPoseCluster(const CharacterInstance &instance, float maxDistSq) const
{
    auto candidates = poseClusterSearch.findSimilar(instance.poseDescriptor);

    PoseCluster *bestCluster = nullptr;
    float bestClusterDistSq = maxDistSq;

    for (auto &candidateCluster : candidates)
    {
        const CharacterInstance *candidateInstance = findInstanceAtFrame(candidateCluster->seedFrame);
        const float distSq = math::distSq(instance.poseDescriptor, candidateInstance->poseDescriptor);
        if (distSq < bestClusterDistSq)
        {
            bestCluster = candidateCluster;
            bestClusterDistSq = distSq;
        }
    }

    return bestCluster;
}

vector< pair<PoseCluster*, float> > Character::findPoseClustersRadius(const CharacterInstance &instance, float maxDistSq) const
{
    auto candidates = poseClusterSearch.findSimilar(instance.poseDescriptor);
    vector< pair<PoseCluster*, float> > result;
    for (auto &candidateCluster : candidates)
    {
        const CharacterInstance *candidateInstance = findInstanceAtFrame(candidateCluster->seedFrame);
        const float distSq = math::distSq(instance.poseDescriptor, candidateInstance->poseDescriptor);
        if (distSq <= maxDistSq)
            result.push_back(make_pair(candidateCluster, distSq));
    }
    return result;
}

vector< pair<CharacterInstance*, float> > Character::findPosesRadius(const CharacterInstance &instance, float maxDistSq) const
{
    auto candidates = poseSearch.findSimilar(instance.poseDescriptor);
    vector< pair<CharacterInstance*, float> > result;
    for (auto &candidateInstance : candidates)
    {
        const float distSq = math::distSq(instance.poseDescriptor, candidateInstance->poseDescriptor);
        if (distSq <= maxDistSq)
            result.push_back(make_pair(candidateInstance, distSq));
    }
    return result;
}

vector< pair<CharacterInstance*, float> > Character::findPoseChainsForwardRadius(const CharacterInstance &instance, float maxDistSq) const
{
    auto candidates = poseChainForwardSearch.findSimilar(instance.poseChainForwardDescriptor);
    vector< pair<CharacterInstance*, float> > result;
    for (auto &candidateInstance : candidates)
    {
        const float distSq = math::distSq(instance.poseChainForwardDescriptor, candidateInstance->poseChainForwardDescriptor);
        if (distSq <= maxDistSq)
            result.push_back(make_pair(candidateInstance, distSq));
    }
    return result;
}

vector< pair<CharacterInstance*, float> > Character::findSimilarClusterHistoryInstances(const deque<const PoseCluster *> &clusterHistory, float maxDistSq) const
{
    vector<float> rawPoseChainReverseDescriptor(poseChainReverseFeatureCount());
    vector<float> reducedDescriptor;

    computePoseChainReverseDescriptor(clusterHistory, rawPoseChainReverseDescriptor.data());

    poseChainReversePCA.transform(rawPoseChainReverseDescriptor, poseChainReversePCADimension, reducedDescriptor);

    auto candidates = poseChainReverseSearch.findSimilar(reducedDescriptor);
    vector< pair<CharacterInstance*, float> > result;
    for (auto &candidateInstance : candidates)
    {
        const float distSq = math::distSq(reducedDescriptor, candidateInstance->poseChainReverseDescriptor);
        if (distSq <= maxDistSq)
            result.push_back(make_pair(candidateInstance, distSq));
    }
    return result;
}

void CharacterDatabase::init(SegmentAnalyzer &analyzer)
{
    characters.resize(analyzer.characterSegments.size());
    for (size_t characterIndex = 0; characterIndex < characters.size(); characterIndex++)
    {
        characters[characterIndex].init(analyzer.characterSegments[characterIndex], (int)characterIndex);
    }
}

void CharacterDatabase::recordAllFrames(const ReplayDatabase &frames)
{
    for (Character &c : characters)
    {
        c.recordAllFrames(frames);
    }
}


text:
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/spdy/spdy_buffer.h"

#include <cstddef>
#include <cstring>
#include <memory>
#include <string>

#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "net/base/io_buffer.h"
#include "net/spdy/spdy_protocol.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

const char kData[] = "hello!\0hi.";
const size_t kDataSize = arraysize(kData);

class SpdyBufferTest : public ::testing::Test {};

// Make a string from the data remaining in |buffer|.
std::string BufferToString(const SpdyBuffer& buffer) {
  return std::string(buffer.GetRemainingData(), buffer.GetRemainingSize());
}

// Construct a SpdyBuffer from a SpdySerializedFrame and make sure its data
// points to the frame's underlying data.
TEST_F(SpdyBufferTest, FrameConstructor) {
  SpdyBuffer buffer(
      std::unique_ptr<SpdySerializedFrame>(new SpdySerializedFrame(
          const_cast<char*>(kData), kDataSize, false /* owns_buffer */)));

  EXPECT_EQ(kData, buffer.GetRemainingData());
  EXPECT_EQ(kDataSize, buffer.GetRemainingSize());
}

// Construct a SpdyBuffer from a const char*/size_t pair and make sure
// it makes a copy of the data.
TEST_F(SpdyBufferTest, DataConstructor) {
  std::string data(kData, kDataSize);
  SpdyBuffer buffer(data.data(), data.size());
  // This mutation shouldn't affect |buffer|'s data.
  data[0] = 'H';

  EXPECT_NE(kData, buffer.GetRemainingData());
  EXPECT_EQ(kDataSize, buffer.GetRemainingSize());
  EXPECT_EQ(std::string(kData, kDataSize), BufferToString(buffer));
}

void IncrementBy(size_t* x,
                 SpdyBuffer::ConsumeSource expected_consume_source,
                 size_t delta,
                 SpdyBuffer::ConsumeSource consume_source) {
  EXPECT_EQ(expected_consume_source, consume_source);
  *x += delta;
}

// Construct a SpdyBuffer and call Consume() on it, which should
// update the remaining data pointer and size appropriately, as well
// as calling the consume callbacks.
TEST_F(SpdyBufferTest, Consume) {
  SpdyBuffer buffer(kData, kDataSize);

  size_t x1 = 0;
  size_t x2 = 0;
  buffer.AddConsumeCallback(
      base::Bind(&IncrementBy, &x1, SpdyBuffer::CONSUME));
  buffer.AddConsumeCallback(
      base::Bind(&IncrementBy, &x2, SpdyBuffer::CONSUME));

  EXPECT_EQ(std::string(kData, kDataSize), BufferToString(buffer));

  buffer.Consume(5);
  EXPECT_EQ(std::string(kData + 5, kDataSize - 5), BufferToString(buffer));
  EXPECT_EQ(5u, x1);
  EXPECT_EQ(5u, x2);

  buffer.Consume(kDataSize - 5);
  EXPECT_EQ(0u, buffer.GetRemainingSize());
  EXPECT_EQ(kDataSize, x1);
  EXPECT_EQ(kDataSize, x2);
}

// Construct a SpdyBuffer and attach a ConsumeCallback to it. The
// callback should be called when the SpdyBuffer is destroyed.
TEST_F(SpdyBufferTest, ConsumeOnDestruction) {
  size_t x = 0;

  {
    SpdyBuffer buffer(kData, kDataSize);
    buffer.AddConsumeCallback(
        base::Bind(&IncrementBy, &x, SpdyBuffer::DISCARD));
  }

  EXPECT_EQ(kDataSize, x);
}

// Make sure the IOBuffer returned by GetIOBufferForRemainingData()
// points to the buffer's remaining data and isn't updated by
// Consume().
TEST_F(SpdyBufferTest, GetIOBufferForRemainingData) {
  SpdyBuffer buffer(kData, kDataSize);

  buffer.Consume(5);
  scoped_refptr<IOBuffer> io_buffer = buffer.GetIOBufferForRemainingData();
  size_t io_buffer_size = buffer.GetRemainingSize();
  const std::string expectedData(kData + 5, kDataSize - 5);
  EXPECT_EQ(expectedData, std::string(io_buffer->data(), io_buffer_size));

  buffer.Consume(kDataSize - 5);
  EXPECT_EQ(expectedData, std::string(io_buffer->data(), io_buffer_size));
}

// Make sure the IOBuffer returned by GetIOBufferForRemainingData()
// outlives the buffer itself.
TEST_F(SpdyBufferTest, IOBufferForRemainingDataOutlivesBuffer) {
  std::unique_ptr<SpdyBuffer> buffer(new SpdyBuffer(kData, kDataSize));

  scoped_refptr<IOBuffer> io_buffer = buffer->GetIOBufferForRemainingData();
  buffer.reset();

  // This will cause a use-after-free error if |io_buffer| doesn't
  // outlive |buffer|.
  std::memcpy(io_buffer->data(), kData, kDataSize);
}

}  // namespace

}  // namespace net


text:
namespace YAF.Pages {

    public partial class pmessage {

        /// <summary>
        /// PageLinks control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.PageLinks PageLinks;

        /// <summary>
        /// LocalizedLabel1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.LocalizedLabel LocalizedLabel1;

        /// <summary>
        /// PreviewRow control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableRow PreviewRow;

        /// <summary>
        /// LocalizedLabel3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.LocalizedLabel LocalizedLabel3;

        /// <summary>
        /// PreviewCell control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableCell PreviewCell;

        /// <summary>
        /// PreviewMessagePost control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.MessagePost PreviewMessagePost;

        /// <summary>
        /// ToRow control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableRow ToRow;

        /// <summary>
        /// LocalizedLabel2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.LocalizedLabel LocalizedLabel2;

        /// <summary>
        /// To control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox To;

        /// <summary>
        /// ToList control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.DropDownList ToList;

        /// <summary>
        /// FindUsers control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button FindUsers;

        /// <summary>
        /// AllUsers control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button AllUsers;

        /// <summary>
        /// AllBuddies control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button AllBuddies;

        /// <summary>
        /// Clear control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button Clear;

        /// <summary>
        /// MultiReceiverInfo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label MultiReceiverInfo;

        /// <summary>
        /// LocalizedLabel4 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.LocalizedLabel LocalizedLabel4;

        /// <summary>
        /// PmSubjectTextBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox PmSubjectTextBox;

        /// <summary>
        /// LocalizedLabel5 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.LocalizedLabel LocalizedLabel5;

        /// <summary>
        /// SmileysBox control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.smileys SmileysBox;

        /// <summary>
        /// EditorLine control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlTableCell EditorLine;

        /// <summary>
        /// Preview control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.ThemeButton Preview;

        /// <summary>
        /// Save control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.ThemeButton Save;

        /// <summary>
        /// Cancel control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.ThemeButton Cancel;

        /// <summary>
        /// SmartScroller1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::YAF.Controls.SmartScroller SmartScroller1;
    }
}


text:
namespace {

std::wstring getLocation(TIStream &is) {
  return L"File: " + is.getFilePath().getWideString() + L":" +
         std::to_wstring(is.getLine());
}

std::wstring message(TIStream &is, std::wstring msg) {
  return getLocation(is) + L"\n" + msg;
}

std::wstring message(TIStream &is, std::string msg) {
  return message(is, ::to_wstring(msg));
}

}  // namespace

TIStreamException::TIStreamException(TIStream &is)
    : TException(message(is, L"unknown exception")) {}

TIStreamException::TIStreamException(TIStream &is, const TException &e)
    : TException(message(is, e.getMessage())) {}

TIStreamException::TIStreamException(TIStream &is, std::wstring msg)
    : TException(message(is, msg)) {}

TIStreamException::TIStreamException(TIStream &is, std::string msg)
    : TException(message(is, msg)) {}

TIStreamException::~TIStreamException() {}


text:
namespace base {

// A "blocking call" refers to any call that causes the calling thread to wait
// off-CPU. It includes but is not limited to calls that wait on synchronous
// file I/O operations: read or write a file from disk, interact with a pipe or
// a socket, rename or delete a file, enumerate files in a directory, etc.
// Acquiring a low contention lock is not considered a blocking call.

// BlockingType indicates the likelihood that a blocking call will actually
// block.
enum class BlockingType {
  // The call might block (e.g. file I/O that might hit in memory cache).
  MAY_BLOCK,
  // The call will definitely block (e.g. cache already checked and now pinging
  // server synchronously).
  WILL_BLOCK
};

namespace internal {

class BlockingObserver;

// Common implementation class for both ScopedBlockingCall and
// ScopedBlockingCallWithBaseSyncPrimitives without assertions.
class BASE_EXPORT UncheckedScopedBlockingCall {
 public:
  UncheckedScopedBlockingCall(BlockingType blocking_type);
  ~UncheckedScopedBlockingCall();

 private:
  internal::BlockingObserver* const blocking_observer_;

  // Previous ScopedBlockingCall instantiated on this thread.
  UncheckedScopedBlockingCall* const previous_scoped_blocking_call_;

  // Whether the BlockingType of the current thread was WILL_BLOCK after this
  // ScopedBlockingCall was instantiated.
  const bool is_will_block_;

  DISALLOW_COPY_AND_ASSIGN(UncheckedScopedBlockingCall);
};

}  // namespace internal

// This class must be instantiated in every scope where a blocking call is made
// and serves as a precise annotation of the scope that may/will block for the
// scheduler. When a ScopedBlockingCall is instantiated, it asserts that
// blocking calls are allowed in its scope with a call to
// base::AssertBlockingAllowed(). CPU usage should be minimal within that scope.
// //base APIs that block instantiate their own ScopedBlockingCall; it is not
// necessary to instantiate another ScopedBlockingCall in the scope where these
// APIs are used. Nested ScopedBlockingCalls are supported (mostly a no-op
// except for WILL_BLOCK nested within MAY_BLOCK which will result in immediate
// WILL_BLOCK semantics).
//
// Good:
//   Data data;
//   {
//     ScopedBlockingCall scoped_blocking_call(BlockingType::WILL_BLOCK);
//     data = GetDataFromNetwork();
//   }
//   CPUIntensiveProcessing(data);
//
// Bad:
//   ScopedBlockingCall scoped_blocking_call(BlockingType::WILL_BLOCK);
//   Data data = GetDataFromNetwork();
//   CPUIntensiveProcessing(data);  // CPU usage within a ScopedBlockingCall.
//
// Good:
//   Data a;
//   Data b;
//   {
//     ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
//     a = GetDataFromMemoryCacheOrNetwork();
//     b = GetDataFromMemoryCacheOrNetwork();
//   }
//   CPUIntensiveProcessing(a);
//   CPUIntensiveProcessing(b);
//
// Bad:
//   ScopedBlockingCall scoped_blocking_call(BlockingType::MAY_BLOCK);
//   Data a = GetDataFromMemoryCacheOrNetwork();
//   Data b = GetDataFromMemoryCacheOrNetwork();
//   CPUIntensiveProcessing(a);  // CPU usage within a ScopedBlockingCall.
//   CPUIntensiveProcessing(b);  // CPU usage within a ScopedBlockingCall.
//
// Good:
//   base::WaitableEvent waitable_event(...);
//   waitable_event.Wait();
//
// Bad:
//  base::WaitableEvent waitable_event(...);
//  ScopedBlockingCall scoped_blocking_call(BlockingType::WILL_BLOCK);
//  waitable_event.Wait();  // Wait() instantiates its own ScopedBlockingCall.
//
// When a ScopedBlockingCall is instantiated from a TaskScheduler parallel or
// sequenced task, the thread pool size is incremented to compensate for the
// blocked thread (more or less aggressively depending on BlockingType).
class BASE_EXPORT ScopedBlockingCall
    : public internal::UncheckedScopedBlockingCall {
 public:
  ScopedBlockingCall(BlockingType blocking_type);
  ~ScopedBlockingCall() = default;
};

namespace internal {

// This class must be instantiated in every scope where a sync primitive is
// used. When a ScopedBlockingCallWithBaseSyncPrimitives is instantiated, it
// asserts that sync primitives are allowed in its scope with a call to
// internal::AssertBaseSyncPrimitivesAllowed(). The same guidelines as for
// ScopedBlockingCall should be followed.
class BASE_EXPORT ScopedBlockingCallWithBaseSyncPrimitives
    : public UncheckedScopedBlockingCall {
 public:
  ScopedBlockingCallWithBaseSyncPrimitives(BlockingType blocking_type);
  ~ScopedBlockingCallWithBaseSyncPrimitives() = default;
};

// Interface for an observer to be informed when a thread enters or exits
// the scope of ScopedBlockingCall objects.
class BASE_EXPORT BlockingObserver {
 public:
  virtual ~BlockingObserver() = default;

  // Invoked when a ScopedBlockingCall is instantiated on the observed thread
  // where there wasn't an existing ScopedBlockingCall.
  virtual void BlockingStarted(BlockingType blocking_type) = 0;

  // Invoked when a WILL_BLOCK ScopedBlockingCall is instantiated on the
  // observed thread where there was a MAY_BLOCK ScopedBlockingCall but not a
  // WILL_BLOCK ScopedBlockingCall.
  virtual void BlockingTypeUpgraded() = 0;

  // Invoked when the last ScopedBlockingCall on the observed thread is
  // destroyed.
  virtual void BlockingEnded() = 0;
};

// Registers |blocking_observer| on the current thread. It is invalid to call
// this on a thread where there is an active ScopedBlockingCall.
BASE_EXPORT void SetBlockingObserverForCurrentThread(
    BlockingObserver* blocking_observer);

BASE_EXPORT void ClearBlockingObserverForTesting();

// Unregisters the |blocking_observer| on the current thread within its scope.
// Used in TaskScheduler tests to prevent calls to //base sync primitives from
// affecting the thread pool capacity.
class BASE_EXPORT ScopedClearBlockingObserverForTesting {
 public:
  ScopedClearBlockingObserverForTesting();
  ~ScopedClearBlockingObserverForTesting();

 private:
  BlockingObserver* const blocking_observer_;

  DISALLOW_COPY_AND_ASSIGN(ScopedClearBlockingObserverForTesting);
};

}  // namespace internal

}  // namespace base

#endif  // BASE_THREADING_SCOPED_BLOCKING_CALL_H


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Home Wack-A-Mole</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="shortcut icon" href="/favicon.ico">

    <link rel="stylesheet" href="styles/main.css">

    <link href='http://fonts.googleapis.com/css?family=Bangers' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">


text:
title: Binding to Array, ArrayList and Generic List
page_title: Binding to Array, ArrayList and Generic List | RadDropDownTree for ASP.NET AJAX Documentation
description: Binding to Array, ArrayList and Generic List
slug: dropdowntree/data-binding/binding-to-array,-arraylist-and-generic-list
tags: binding,to,array,,arraylist,and,generic,list
published: True
position: 1
---

# Binding to Array, ArrayList and Generic List

Binding RadDropDownTree to a data source that implements **IEnumerable**, such as Array or ArrayList, can create a flat data structure as well as a hierarchy if the proper **ID** -> **ParentID** relationship is set.

Here is a general outline of **IEnumerable** data binding:

1. Create the collection.

2. Add values to the collection and set the **DataSource** property of RadDropDownTree to the instance of the collection.

3. Call the **DataBind()** method.

The collection is automatically mapped to the **Text** property of the respective tree Node.

## Binding to an Array

The examples below takes an array of strings as a data source.

![Binding to an Array](images/dropdowntree_array.png)

````ASPNET
<telerik:RadDropDownTree ID="RadDropDownTree1" runat="server" Width="250px" DefaultMessage="Select a car from the list">
    <DropDownSettings Width="250px" />
</telerik:RadDropDownTree>
````

````C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string[] cars = new string[] { "Porsche Carrera", "Ferrari F430", "Aston Martin DB9" };
        RadDropDownTree1.DataSource = cars;
        RadDropDownTree1.DataBind();
    }
}
````
````VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim cars As String() = New String() {"Porsche Carrera", "Ferrari F430", "Aston Martin DB9"}
        RadDropDownTree1.DataSource = cars
        RadDropDownTree1.DataBind()
    End If
End Sub
````

## Binding to an ArrayList

If you have a collection (any collection implementing **ICollection** or **IEnumerable**) that contains objects (as opposed to simple values),you can take advantage of **DataTextField**, and **DataValueField** properties to map object properties from the object directly to the **Text** or **Value** fields. If the **DataFieldID** and **DataFieldParentID** properties are set, RadDropDownTree will create a hierarchy of Nodes, determining the Root ones using the following algorithm:

>tip *their **DataFieldParentID** property must be **null** if it is of nullable (e.g. **int?** ) or reference (e.g. **string** ) type. Example:
>

**ID**  **ParentID**

1  (null)

2  1

>tip *their **DataFieldParentID** property must return the **default value** if it is value type (e.g. **0** for **int** , **Guid.Empty** for **Guid** ). Example:
>

**ID**  **ParentID**

1  0

2  1

Below you can find an example of a hierarchical data binding:

![Binding to an ArrayList](images/dropdowntree_arraylist.png)

````ASPNET
<telerik:RadDropDownTree ID="RadDropDownTree1" runat="server" Width="350px" DefaultMessage="Select a car from the list">
    <DropDownSettings Width="350px" />
</telerik:RadDropDownTree>
````

````C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Car[] cars = new Car[] {
           new Car("Cars", 00000, 0, 4),
           new Car("Porsche Carrera", 79100, 4, 1),
           new Car("Ferrari F430", 229955, 4, 2),
           new Car("Aston Martin DB9", 168000, 4, 3),
       };

        RadDropDownTree1.DataSource = cars;
        RadDropDownTree1.DataTextField = "Name";
        RadDropDownTree1.DataValueField = "Price";
        //establishing Parent-Child hierarchy
        RadDropDownTree1.DataFieldParentID = "Parent";
        RadDropDownTree1.DataFieldID = "Id";

        RadDropDownTree1.DataBind();
    }
}

public class Car
{
    public Car(string name, double price, int parent, int id)
    {
        _name = name;
        _price = price;
        _parent = parent;
        _id = id;

    }
    private string _name;
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    private double _price;
    public double Price
    {
        get { return _price; }
        set { _price = value; }
    }
    private int _parent;
    public int Parent
    {
        get { return _parent; }
        set { _parent = value; }
    }
    private int _id;
    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }

}
````
````VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

    If Not IsPostBack Then

        Dim cars As Car() = New Car() {
            New Car("Cars", 0, 0, 4),
            New Car("Porsche Carrera", 79100, 4, 1),
            New Car("Ferrari F430", 229955, 4, 2),
            New Car("Aston Martin DB9", 168000, 4, 3)}

        RadDropDownTree1.DataSource = cars
        RadDropDownTree1.DataTextField = "Name"
        RadDropDownTree1.DataValueField = "Price"
        RadDropDownTree1.DataFieldParentID = "Parent"
        RadDropDownTree1.DataFieldID = "Id"
        RadDropDownTree1.DataBind()
    End If
End Sub

Public Class Car
    Public Sub New(ByVal name As String, ByVal price As Double, ByVal parent As Integer, ByVal id As Integer)
        _name = name
        _price = price
        _parent = parent
        _id = id
    End Sub
    Private _name As String
    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property
    Private _price As Double
    Public Property Price() As Double
        Get
            Return _price
        End Get
        Set(ByVal value As Double)
            _price = value
        End Set
    End Property
    Private _parent As Integer
    Public Property Parent() As Integer
        Get
            Return _parent
        End Get
        Set(ByVal value As Integer)
            _parent = value
        End Set
    End Property
    Private _id As Integer
    Public Property Id() As Integer
        Get
            Return _id
        End Get
        Set(ByVal value As Integer)
            _id = value
        End Set
    End Property
End Class
````

## Binding to a Generic List

![Binding to Generic List](images/dropdowntree_ienumerable.png)

````ASPNET
<telerik:RadDropDownTree ID="RadDropDownTree1" runat="server" Width="350px" DefaultMessage="Select a product from the list">
    <DropDownSettings Width="350px" />
</telerik:RadDropDownTree>
````

````C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindToIEnumerable(RadDropDownTree1);
    }
}

private static void BindToIEnumerable(RadDropDownTree dropdowntree)
{
    List<SiteDataItem> siteData = new List<SiteDataItem>();

    siteData.Add(new SiteDataItem(1, 0, "Products"));
    siteData.Add(new SiteDataItem(2, 1, "RadControls for ASP.NET Ajax"));
    siteData.Add(new SiteDataItem(3, 1, "RadControls for Silverlight"));
    siteData.Add(new SiteDataItem(4, 2, "RadGrid"));
    siteData.Add(new SiteDataItem(5, 2, "RadScheduler"));
    siteData.Add(new SiteDataItem(6, 2, "RadEditor"));
    siteData.Add(new SiteDataItem(7, 3, "RadGrid"));
    siteData.Add(new SiteDataItem(8, 3, "RadMenu"));
    siteData.Add(new SiteDataItem(9, 3, "RadEditor"));

    dropdowntree.DataTextField = "Text";
    dropdowntree.DataFieldID = "ID";
    dropdowntree.DataFieldParentID = "ParentID";
    dropdowntree.DataSource = siteData;
    dropdowntree.DataBind();
}

internal class SiteDataItem
{
    private string _text;
    private int _id;
    private int _parentId;

    public string Text
    {
        get { return _text; }
        set { _text = value; }
    }

    public int ID
    {
        get { return _id; }
        set { _id = value; }
    }

    public int ParentID
    {
        get { return _parentId; }
        set { _parentId = value; }
    }

    public SiteDataItem(int id, int parentId, string text)
    {
        _id = id;
        _parentId = parentId;
        _text = text;
    }
}
````
````VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    If Not Page.IsPostBack Then

        BindToIEnumerable(RadDropDownTree1)
    End If

End Sub

Private Shared Sub BindToIEnumerable(ByVal dropdowntree As RadDropDownTree)
    Dim siteData As New List(Of SiteDataItem)()

    siteData.Add(New SiteDataItem(1, 0, "Products"))
    siteData.Add(New SiteDataItem(2, 1, "RadControls for ASP.NET Ajax"))
    siteData.Add(New SiteDataItem(3, 1, "RadControls for Silverlight"))
    siteData.Add(New SiteDataItem(4, 2, "RadGrid"))
    siteData.Add(New SiteDataItem(5, 2, "RadScheduler"))
    siteData.Add(New SiteDataItem(6, 2, "RadEditor"))
    siteData.Add(New SiteDataItem(7, 3, "RadGrid"))
    siteData.Add(New SiteDataItem(8, 3, "RadMenu"))
    siteData.Add(New SiteDataItem(9, 3, "RadEditor"))

    dropdowntree.DataTextField = "Text"
    dropdowntree.DataFieldID = "ID"
    dropdowntree.DataFieldParentID = "ParentID"
    dropdowntree.DataSource = siteData
    dropdowntree.DataBind()
End Sub

Friend Class SiteDataItem
    Private _text As String
    Private _id As Integer
    Private _parentId As Integer

    Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property

    Public Property ID() As Integer
        Get
            Return _id
        End Get
        Set(ByVal value As Integer)
            _id = value
        End Set
    End Property

    Public Property ParentID() As Integer
        Get
            Return _parentId
        End Get
        Set(ByVal value As Integer)
            _parentId = value
        End Set
    End Property

    Public Sub New(ByVal id As Integer, ByVal parentId As Integer, ByVal text As String)
        _id = id
        _parentId = parentId
        _text = text
    End Sub
End Class
````