text:
Great!! We are always on the lookout for more OpenEBS hackers. You can get started by reading this [overview](./contribute/design/README.md)

Firstly, if you are unsure or afraid of anything, just ask or submit the issue or pull request anyways. You won't be yelled at for giving your best effort. The worst that can happen is that you'll be politely asked to change something. We appreciate any sort of contributions and don't want a wall of rules to get in the way of that.

However, for those individuals who want a bit more guidance on the best way to contribute to the project, read on. This document will cover all the points we're looking for in your contributions, raising your chances of quickly merging or addressing your contributions.

That said, OpenEBS is an innovation in Open Source. You are welcome to contribute in any way you can and all the help provided is very much appreciated.

- [Raise issues to request new functionality, fix documentation or for reporting bugs.](#raising-issues)
- [Submit changes to improve documentation.](#submit-change-to-improve-documentation)
- [Submit proposals for new features/enhancements.](#submit-proposals-for-new-features)
- [Solve existing issues related to documentation or code.](#contributing-to-source-code-and-bug-fixes)

There are a few simple guidelines that you need to follow before providing your hacks.

## Raising Issues

When raising issues, please specify the following:
- Setup details needs to be filled as specified in the issue template clearly for the reviewer to check.
- A scenario where the issue occurred (with details on how to reproduce it).
- Errors and log messages that are displayed by the software.
- Any other details that might be useful.

## Submit Change to Improve Documentation

Getting documentation right is hard! Refer to this [page](./contribute/CONTRIBUTING-TO-DEVELOPER-DOC.md) for more information on how you could improve the developer documentation by submitting pull requests with appropriate tags. Here's a [list of tags](./contribute/labels-of-issues.md) that could be used for the same. Help us keep our documentation clean, easy to understand, and accessible.

## Submit Proposals for New Features

There is always something more that is required, to make it easier to suit your use-cases. Feel free to join the discussion on new features or raise a PR with your proposed change.

- Join us at [Slack](https://openebsslacksignup.herokuapp.com/)
 	 - Already signed up? Head to our discussions at [#openebs-users](https://openebs-community.slack.com/messages/openebs-users/)

## Contributing to Source Code and Bug Fixes

Provide PRs with appropriate tags for bug fixes or enhancements to the source code. For a list of tags that could be used, see [this](./contribute/labels-of-issues.md).

* For contributing to K8s demo, please refer to this [document](./contribute/CONTRIBUTING-TO-K8S-DEMO.md).
	- For checking out how OpenEBS works with K8s, refer to this [document](./k8s/README.md)
- For contributing to Kubernetes OpenEBS Provisioner, please refer to this [document](./contribute/CONTRIBUTING-TO-KUBERNETES-OPENEBS-PROVISIONER.md).
* For contributing to CI and e2e, refer to this [document](./contribute/CONTRIBUTING-TO-CI-AND-E2E.md)
	- Refer to this [overview](./e2e/README.md) of e2e.

Refer to this [document](./contribute/design/code-structuring.md) for more information on code structuring and guidelines to follow on the same.

## Solve Existing Issues
Head over to [issues](https://github.com/openebs/openebs/issues) to find issues where help is needed from contributors. See our [list of labels guide](./contribute/labels-of-issues.md) to help you find issues that you can solve faster.

A person looking to contribute can take up an issue by claiming it as a comment/assign their Github ID to it. In case there is no PR or update in progress for a week on the said issue, then the issue reopens for anyone to take up again. We need to consider high priority issues/regressions where response time must be a day or so.

---
### Sign your work

We use the Developer Certificate of Origin (DCO) as an additional safeguard for the OpenEBS project. This is a well established and widely used mechanism to assure contributors have confirmed their right to license their contribution under the project's license. Please read [developer-certificate-of-origin](./contribute/developer-certificate-of-origin).

If you can certify it, then just add a line to every git commit message:

````
  Signed-off-by: Random J Developer <random@developer.example.org>
````
or use the command `git commit -s -m "commit message comes here"` to sign-off on your commits.

Use your real name (sorry, no pseudonyms or anonymous contributions). If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. You can also use git [aliases](https://git-scm.com/book/tr/v2/Git-Basics-Git-Aliases) like `git config --global alias.ci 'commit -s'`. Now you can commit with `git ci` and the commit will be signed.

---

## Join our community

Want to actively develop and contribute in the OpenEBS community, refer to this [document](./community/README.md).


text:
import pytest

pytest.importorskip("asyncssh")

import dask
from dask.distributed import Client
from distributed.deploy.ssh import SSHCluster
from distributed.utils_test import loop  # noqa: F401

@pytest.mark.asyncio
async def test_basic():
    async with SSHCluster(
        ["127.0.0.1"] * 3,
        connect_options=dict(known_hosts=None),
        asynchronous=True,
        scheduler_options={"port": 0, "idle_timeout": "5s"},
        worker_options={"death_timeout": "5s"},
    ) as cluster:
        assert len(cluster.workers) == 2
        async with Client(cluster, asynchronous=True) as client:
            result = await client.submit(lambda x: x + 1, 10)
            assert result == 11
        assert not cluster._supports_scaling

        assert "SSH" in repr(cluster)

@pytest.mark.asyncio
async def test_keywords():
    async with SSHCluster(
        ["127.0.0.1"] * 3,
        connect_options=dict(known_hosts=None),
        asynchronous=True,
        worker_options={
            "nprocs": 2,  # nprocs checks custom arguments with cli_keywords
            "nthreads": 2,
            "memory_limit": "2 GiB",
            "death_timeout": "5s",
        },
        scheduler_options={"idle_timeout": "10s", "port": 0},
    ) as cluster:
        async with Client(cluster, asynchronous=True) as client:
            assert (
                await client.run_on_scheduler(
                    lambda dask_scheduler: dask_scheduler.idle_timeout
                )
            ) == 10
            d = client.scheduler_info()["workers"]
            assert all(v["nthreads"] == 2 for v in d.values())

@pytest.mark.avoid_travis
def test_defer_to_old(loop):
    with pytest.warns(Warning):
        with SSHCluster(
            scheduler_addr="127.0.0.1",
            scheduler_port=7437,
            worker_addrs=["127.0.0.1", "127.0.0.1"],
        ) as c:
            from distributed.deploy.old_ssh import SSHCluster as OldSSHCluster

            assert isinstance(c, OldSSHCluster)

@pytest.mark.avoid_travis
def test_old_ssh_wih_local_dir(loop):
    with pytest.warns(Warning):
        from distributed.deploy.old_ssh import SSHCluster as OldSSHCluster

        with OldSSHCluster(
            scheduler_addr="127.0.0.1",
            scheduler_port=7437,
            worker_addrs=["127.0.0.1", "127.0.0.1"],
            local_directory="/tmp",
        ) as c:
            assert len(c.workers) == 2
            with Client(c) as client:
                result = client.submit(lambda x: x + 1, 10)
                result = result.result()
                assert result == 11

@pytest.mark.asyncio
async def test_config_inherited_by_subprocess(loop):
    def f(x):
        return dask.config.get("foo") + 1

    with dask.config.set(foo=100):
        async with SSHCluster(
            ["127.0.0.1"] * 2,
            connect_options=dict(known_hosts=None),
            asynchronous=True,
            scheduler_options={"port": 0, "idle_timeout": "5s"},
            worker_options={"death_timeout": "5s"},
        ) as cluster:
            async with Client(cluster, asynchronous=True) as client:
                result = await client.submit(f, 1)
                assert result == 101

@pytest.mark.asyncio
async def test_unimplemented_options():
    with pytest.raises(Exception):
        async with SSHCluster(
            ["127.0.0.1"] * 3,
            connect_kwargs=dict(known_hosts=None),
            asynchronous=True,
            worker_kwargs={
                "nthreads": 2,
                "memory_limit": "2 GiB",
                "death_timeout": "5s",
                "unimplemented_option": 2,
            },
            scheduler_kwargs={"idle_timeout": "5s", "port": 0},
        ) as cluster:
            assert cluster

redpajama_set_name: RedPajamaGithub


text:
package sqlbuilder_test

import (
	"testing"

	"github.com/issue9/assert/v3"

	"github.com/issue9/orm/v5/core"
	"github.com/issue9/orm/v5/internal/test"
	"github.com/issue9/orm/v5/sqlbuilder"
)

var (
	_ sqlbuilder.DDLStmt = &sqlbuilder.CreateIndexStmt{}
	_ sqlbuilder.DDLStmt = &sqlbuilder.DropIndexStmt{}
)

func TestIndex(t *testing.T) {
	a := assert.New(t, false)
	suite := test.NewSuite(a)

	suite.Run(func(t *test.Driver) {
		initDB(t)
		defer clearDB(t)

		createStmt := sqlbuilder.CreateIndex(t.DB).
			Table("users").
			Name("index_key").
			Columns("id", "name")
		err := createStmt.Exec()
		t.NotError(err)

		// 同名约束名,应该会出错
		createStmt.Reset()
		err = createStmt.Table("users").
			Name("index_key").
			Columns("id", "name").
			Exec()
		t.Error(err)

		// 唯一约束
		createStmt.Reset()
		err = createStmt.Table("users").
			Name("index_unique_key").
			Type(core.IndexUnique).
			Columns("id", "name").
			Exec()
		t.NotError(err)

		dropStmt := sqlbuilder.DropIndex(t.DB).
			Table("users").
			Name("index_key")
		err = dropStmt.Exec()
		t.NotError(err)

		// 不存在的索引
		dropStmt.Reset()
		err = dropStmt.Table("users").
			Name("index_key").
			Exec()
		a.Error(err)

		dropStmt.Reset()
		err = dropStmt.Table("users").
			Name("index_unique_key").
			Exec()
		t.NotError(err, "cc")

		createStmt.Reset()
		a.ErrorIs(createStmt.Exec(), sqlbuilder.ErrTableIsEmpty)

		createStmt.Reset()
		createStmt.Table("test")
		a.ErrorIs(createStmt.Exec(), sqlbuilder.ErrColumnsIsEmpty)

		dropStmt.Reset()
		dropStmt.Table("test")
		a.ErrorIs(dropStmt.Exec(), sqlbuilder.ErrColumnsIsEmpty)
	})
}


text:
import sys
import os

sys.path.insert(0, '/opt/external_reporting')
sys.path.insert(1, '/opt/external_reporting/app')
from app import app
application = app


text:
package com.basilio.hiit.entity;

import javax.annotation.Generated;
import javax.persistence.metamodel.SetAttribute;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

@Generated(value="Dali", date="2015-02-13T22:32:57.524-0500")
@StaticMetamodel(IterationEntity.class)
public class IterationEntity_ extends BaseEntity_ {
	public static volatile SingularAttribute<IterationEntity, Integer> cycles;
	public static volatile SingularAttribute<IterationEntity, ProgramEntity> programEntity;
	public static volatile SetAttribute<IterationEntity, StepEntity> stepEntity;
}


text:
@interface BBBOverlayView ()

@property (strong, nonatomic) UIActivityIndicatorView *indicator;
@property (strong, nonatomic) UILabel *labelTop;
@property (strong, nonatomic) BBBSearchEmptyCellsView *emptyCellView;

@end

@implementation BBBOverlayView

#pragma mark - UIView

- (id) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void) layoutSubviews{
    [self.emptyCellView setNeedsDisplay];
}
#pragma mark - Setters

- (void) setViewMode:(BBBOverlayViewMode)viewMode{
    if (_viewMode != viewMode) {
        _viewMode = viewMode;
        [self configureForCurrentViewMode];
    }
}

#pragma mark - Private

- (void) setup{
    _viewMode = BBBOverlayViewModeEmpty;
    self.userInteractionEnabled = NO;
}

- (void) addLabelWithAttributedString:(NSAttributedString *)string{

    CGFloat verticalPadding = [UIDevice bbb_isiPad] ? 80.0f : 40.0f;

    self.labelTop = [[UILabel alloc] initWithFrame:CGRectZero];
    self.labelTop.attributedText = string;
    CGRect frame = CGRectMake(0,
                              verticalPadding,
                              self.bounds.size.width,
                              self.bounds.size.height);
    CGSize sizeThatFits;
    NSDictionary *attributes = [self regularTextAttributes];
    sizeThatFits = [self.labelTop.text sizeWithAttributes:attributes];
    sizeThatFits.width = self.bounds.size.width;
    sizeThatFits.height = ceil(sizeThatFits.height);
    frame.size = sizeThatFits;

    self.labelTop.frame = frame;
    self.labelTop.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    self.labelTop.numberOfLines = 0;
    [self addSubview:self.labelTop];
}

- (void) configureForCurrentViewMode{

    [self.indicator removeFromSuperview];
    self.indicator = nil;
    [self.labelTop removeFromSuperview];
    self.labelTop = nil;
    [self.emptyCellView removeFromSuperview];
    self.emptyCellView = nil;

    if (self.viewMode == BBBOverlayViewModeLoading) {
        self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhiteLarge)];
        self.indicator.color = [BBBAssetsHelper colorForKey:BBBBrandPurple];
        self.indicator.frame = self.bounds;
        [self.indicator startAnimating];
        self.indicator.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self addSubview:self.indicator];
    }
    else if (self.viewMode == BBBOverlayViewModeNoResults) {

        [self.indicator removeFromSuperview];
        self.indicator = nil;
        [self addLabelWithAttributedString:[self topAttributedStringNoResults]];
    }
    else if (self.viewMode == BBBOverlayViewModeError) {
        [self addLabelWithAttributedString:[self topAttributedStringError]];
    }
    else if (self.viewMode == BBBOverlayViewModeInitial ) {
        [self addLabelWithAttributedString:[self topAttributedStringInitialContent]];

        self.emptyCellView = [[BBBSearchEmptyCellsView alloc] initWithFrame:self.frame];
        [self.emptyCellView setBackgroundColor:[UIColor clearColor]];
        self.emptyCellView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        [self addSubview:self.emptyCellView];
        [self addSubview:self.labelTop];

    }
}

#pragma mark - NSAttributesString creation and manipulation
- (NSDictionary *) boldTextAttributes{
    return [BBBAssetsHelper attributesForStyle:[self boldTextStyle]];
}

- (NSDictionary *) regularTextAttributes{
    return [BBBAssetsHelper attributesForStyle:[self regularTextStyle]];
}

- (NSAttributedString *) topAttributedStringWithMessage:(NSString *)message{

    NSDictionary *boldAttributes = [self boldTextAttributes];
    NSDictionary *normalAttributes = [self regularTextAttributes];

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:message
                                                                               attributes:normalAttributes];
    [string bbb_replaceBreaksWithNewLines];
    [string bbb_applyStrongAttributes:boldAttributes];
    [string bbb_makeTextCentered];
    return string;
}

- (NSAttributedString *) topAttributedStringInitialContent{

    NSString *message = NSLocalizedString(@"search.overlay.initial-content", nil);
    return [self topAttributedStringWithMessage:message];
}

- (NSAttributedString *) topAttributedStringError{

    NSString *message = NSLocalizedString(@"search.overlay.error-title", nil);
    return [self topAttributedStringWithMessage:message];
}

- (NSAttributedString *) topAttributedStringNoResults{

    NSString *message = NSLocalizedString(@"search.overlay.no-results", nil);
    return [self topAttributedStringWithMessage:message];
}

- (BBBTextStyle) boldTextStyle{
    return BBBTextStyleSearchOverlayBold;
}

- (BBBTextStyle) regularTextStyle{
    return BBBTextStyleSearchOverlayRegular;

}

@end


text:
module Google
  module Apis
    module RecommendationengineV1beta1
      # Version of the google-apis-recommendationengine_v1beta1 gem
      GEM_VERSION = "0.21.0"

      # Version of the code generator used to generate this client
      GENERATOR_VERSION = "0.11.0"

      # Revision of the discovery document this client was generated from
      REVISION = "20220615"
    end
  end
end


text:
package org.jkiss.dbeaver.runtime.qm;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.app.DBPProject;
import org.jkiss.dbeaver.model.app.DBPWorkspace;
import org.jkiss.dbeaver.model.auth.SMAuthSpace;
import org.jkiss.dbeaver.model.auth.SMSession;
import org.jkiss.dbeaver.model.auth.SMSessionContext;
import org.jkiss.dbeaver.model.auth.SMSessionPersistent;
import org.jkiss.dbeaver.model.exec.DBCExecutionContext;
import org.jkiss.dbeaver.model.exec.DBCResultSet;
import org.jkiss.dbeaver.model.exec.DBCSavepoint;
import org.jkiss.dbeaver.model.exec.DBCStatement;
import org.jkiss.dbeaver.model.qm.*;
import org.jkiss.dbeaver.model.qm.meta.*;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.LoggingProgressMonitor;
import org.jkiss.utils.LongKeyMap;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Query manager execution handler implementation
 */
public class QMMCollectorImpl extends DefaultExecutionHandler implements QMMCollector {

    private static final Log log = Log.getLog(QMMCollectorImpl.class);

    private static final long EVENT_DISPATCH_PERIOD = 250;
    private static final int MAX_HISTORY_EVENTS = 10000;

    // Session map
    private LongKeyMap<QMMConnectionInfo> connectionMap = new LongKeyMap<>();
    private List<Long> closedConnections = new ArrayList<>();

    // External listeners
    private final List<QMMetaListener> listeners = new ArrayList<>();

    // Temporary event pool
    private List<QMMetaEvent> eventPool = new ArrayList<>();
    // Sync object
    private final Object historySync = new Object();
    // History (may be purged when limit reached)
    private List<QMMetaEvent> pastEvents = new ArrayList<>();
    private boolean running = true;

    public QMMCollectorImpl() {
        new EventDispatcher().schedule(EVENT_DISPATCH_PERIOD);
    }

    public synchronized void dispose() {
        if (!connectionMap.isEmpty()) {
            List<QMMConnectionInfo> openSessions = new ArrayList<>();
            for (QMMConnectionInfo connection : connectionMap.values()) {
                if (!connection.isClosed()) {
                    openSessions.add(connection);
                }
            }
            if (!openSessions.isEmpty()) {
                log.warn("Some sessions are still open: " + openSessions);
            }
        }
        synchronized (listeners) {
            if (!listeners.isEmpty()) {
                log.warn("Some QM meta collector listeners are still open: " + listeners);
                listeners.clear();
            }
        }
        running = false;
    }

    boolean isRunning() {
        return running;
    }

    @NotNull
    @Override
    public String getHandlerName() {
        return "Meta info collector";
    }

    public void addListener(QMMetaListener listener) {
        synchronized (listeners) {
            listeners.add(listener);
        }
    }

    public void removeListener(QMMetaListener listener) {
        synchronized (listeners) {
            if (!listeners.remove(listener)) {
                log.warn("Listener '" + listener + "' is not registered in QM meta collector");
            }
        }
    }

    private List<QMMetaListener> getListeners() {
        synchronized (listeners) {
            if (listeners.isEmpty()) {
                return Collections.emptyList();
            }
            if (listeners.size() == 1) {
                return Collections.singletonList(listeners.get(0));
            }
            return new ArrayList<>(listeners);
        }
    }

    private synchronized void tryFireMetaEvent(final QMMObject object, final QMEventAction action, DBCExecutionContext context) {
        try {
            DBRProgressMonitor monitor = new LoggingProgressMonitor();
            DBPProject project = context.getDataSource().getContainer().getProject();
            SMSessionContext projectAuthContext = project.getSessionContext();
            SMAuthSpace projectPrimaryAuthSpace = projectAuthContext.getPrimaryAuthSpace();

            SMSession session = null;
            if (projectPrimaryAuthSpace != null) {
                session = project.getSessionContext().getSpaceSession(monitor, projectPrimaryAuthSpace, false);
            }
            if (session == null) {
                DBPWorkspace workspace = project.getWorkspace();
                session = workspace.getAuthContext().getSpaceSession(monitor, workspace, false);
            }

            SMSessionPersistent sessionPersistent = DBUtils.getAdapter(SMSessionPersistent.class, session);
            if (sessionPersistent == null) {
                log.warn("Session persistent not found");
                return;
            }

            eventPool.add(new QMMetaEvent(object, action, sessionPersistent.getAttribute(QMConstants.QM_SESSION_ID_ATTR)));
        } catch (DBException e) {
            log.error("Failed to fire qm meta event", e);
        }
    }

    private synchronized List<QMMetaEvent> obtainEvents() {
        if (eventPool.isEmpty()) {
            return Collections.emptyList();
        }
        List<QMMetaEvent> events = eventPool;
        eventPool = new ArrayList<>();
        return events;
    }

    public QMMConnectionInfo getConnectionInfo(DBCExecutionContext context) {
        QMMConnectionInfo connectionInfo = connectionMap.get(context.getContextId());
        if (connectionInfo == null) {
            log.debug("Can't find connectionInfo meta information: " + context.getContextId() + " (" + context.getContextName() + ")");
        }
        return connectionInfo;
    }

    public List<QMMetaEvent> getPastEvents() {
        synchronized (historySync) {
            return new ArrayList<>(pastEvents);
        }
    }

    @Override
    public synchronized void handleContextOpen(@NotNull DBCExecutionContext context, boolean transactional) {
        final long contextId = context.getContextId();
        QMMConnectionInfo connection = connectionMap.get(contextId);
        if (connection == null) {
            connection = new QMMConnectionInfo(
                context,
                transactional);
            connectionMap.put(contextId, connection);
        } else {
            // This session may already be in cache in case of reconnect/invalidate
            // (when context closed and reopened without new context object creation)
            connection.reopen(context);
        }

        // Remove from closed sessions (in case of re-opened connection)
        closedConnections.remove(contextId);
        tryFireMetaEvent(connection, QMEventAction.BEGIN, context);
        // Notify
    }

    @Override
    public synchronized void handleContextClose(@NotNull DBCExecutionContext context) {
        QMMConnectionInfo session = getConnectionInfo(context);
        if (session != null) {
            session.close();
            tryFireMetaEvent(session, QMEventAction.END, context);
        }
        closedConnections.add(context.getContextId());
    }

    @Override
    public synchronized void handleTransactionAutocommit(@NotNull DBCExecutionContext context, boolean autoCommit) {
        QMMConnectionInfo sessionInfo = getConnectionInfo(context);
        if (sessionInfo != null) {
            QMMTransactionInfo oldTxn = sessionInfo.changeTransactional(!autoCommit);
            if (oldTxn != null) {
                tryFireMetaEvent(oldTxn, QMEventAction.END, context);
            }
            tryFireMetaEvent(sessionInfo, QMEventAction.UPDATE, context);
        }
    }

    @Override
    public synchronized void handleTransactionCommit(@NotNull DBCExecutionContext context) {
        QMMConnectionInfo sessionInfo = getConnectionInfo(context);
        if (sessionInfo != null) {
            QMMTransactionInfo oldTxn = sessionInfo.commit();
            if (oldTxn != null) {
                tryFireMetaEvent(oldTxn, QMEventAction.END, context);
            }
        }
    }

    @Override
    public synchronized void handleTransactionRollback(@NotNull DBCExecutionContext context, DBCSavepoint savepoint) {
        QMMConnectionInfo sessionInfo = getConnectionInfo(context);
        if (sessionInfo != null) {
            QMMObject oldTxn = sessionInfo.rollback(savepoint);
            if (oldTxn != null) {
                tryFireMetaEvent(oldTxn, QMEventAction.END, context);
            }
        }
    }

    @Override
    public synchronized void handleStatementOpen(@NotNull DBCStatement statement) {
        QMMConnectionInfo session = getConnectionInfo(statement.getSession().getExecutionContext());
        if (session != null) {
            QMMStatementInfo stat = session.openStatement(statement);
            tryFireMetaEvent(stat, QMEventAction.BEGIN, statement.getSession().getExecutionContext());
        }
    }

    @Override
    public synchronized void handleStatementClose(@NotNull DBCStatement statement, long rows) {
        QMMConnectionInfo session = getConnectionInfo(statement.getSession().getExecutionContext());
        if (session != null) {
            QMMStatementInfo stat = session.closeStatement(statement, rows);
            if (stat == null) {
                log.warn("Can't properly handle statement close");
            } else {
                tryFireMetaEvent(stat, QMEventAction.END, statement.getSession().getExecutionContext());
            }
        }
    }

    @Override
    public synchronized void handleStatementExecuteBegin(@NotNull DBCStatement statement) {
        QMMConnectionInfo session = getConnectionInfo(statement.getSession().getExecutionContext());
        if (session != null) {
            QMMStatementExecuteInfo exec = session.beginExecution(statement);
            if (exec != null) {
                tryFireMetaEvent(exec, QMEventAction.BEGIN, statement.getSession().getExecutionContext());
            }
        }
    }

    @Override
    public synchronized void handleStatementExecuteEnd(@NotNull DBCStatement statement, long rows, Throwable error) {
        QMMConnectionInfo session = getConnectionInfo(statement.getSession().getExecutionContext());
        if (session != null) {
            QMMStatementExecuteInfo exec = session.endExecution(statement, rows, error);
            if (exec != null) {
                tryFireMetaEvent(exec, QMEventAction.END, statement.getSession().getExecutionContext());
            }
        }
    }

    @Override
    public synchronized void handleResultSetOpen(@NotNull DBCResultSet resultSet) {
        QMMConnectionInfo session = getConnectionInfo(resultSet.getSession().getExecutionContext());
        if (session != null) {
            QMMStatementExecuteInfo exec = session.beginFetch(resultSet);
            if (exec != null) {
                tryFireMetaEvent(exec, QMEventAction.UPDATE, resultSet.getSession().getExecutionContext());
            }
        }
    }

    @Override
    public synchronized void handleResultSetClose(@NotNull DBCResultSet resultSet, long rowCount) {
        QMMConnectionInfo session = getConnectionInfo(resultSet.getSession().getExecutionContext());
        if (session != null) {
            QMMStatementExecuteInfo exec = session.endFetch(resultSet, rowCount);
            if (exec != null) {
                tryFireMetaEvent(exec, QMEventAction.UPDATE, resultSet.getSession().getExecutionContext());
            }
        }
    }

    private class EventDispatcher extends AbstractJob {

        protected EventDispatcher() {
            super("QM meta events dispatcher");
            setUser(false);
            setSystem(true);
        }

        @Override
        protected IStatus run(DBRProgressMonitor monitor) {
            final List<QMMetaEvent> events;
            List<Long> sessionsToClose;
            synchronized (QMMCollectorImpl.this) {
                events = obtainEvents();
                sessionsToClose = closedConnections;
                closedConnections.clear();
            }
            if (!events.isEmpty()) {
                final List<QMMetaListener> listeners = getListeners();
                if (!listeners.isEmpty() && !events.isEmpty()) {
                    // Reverse collection. Fresh events must come first.
                    Collections.reverse(events);
                    // Dispatch all events
                    for (QMMetaListener listener : listeners) {
                        try {
                            listener.metaInfoChanged(monitor, events);
                        } catch (Throwable e) {
                            log.error("Error notifying event listener", e);
                        }
                    }
                }
                synchronized (historySync) {
                    pastEvents.addAll(events);
                    int size = pastEvents.size();
                    if (size > MAX_HISTORY_EVENTS) {
                        pastEvents = new ArrayList<>(pastEvents.subList(
                            size - MAX_HISTORY_EVENTS,
                            size));
                    }
                }
            }
            // Cleanup closed sessions
            synchronized (QMMCollectorImpl.this) {
                for (Long sessionId : sessionsToClose) {
                    final QMMConnectionInfo session = connectionMap.get(sessionId);
                    if (session != null && !session.isClosed()) {
                        // It is possible (rarely) that session was reopened before event dispatcher run
                        // In that case just ignore it
                        connectionMap.remove(sessionId);
                    }
                }
            }
            if (isRunning()) {
                this.schedule(EVENT_DISPATCH_PERIOD);
            }
            return Status.OK_STATUS;
        }
    }

}


text:
namespace NArrange.Tests.Gui.Configuration
{
    using System;
    using System.ComponentModel;
    using System.Drawing.Design;

    using NArrange.Core.Configuration;
    using NArrange.Gui.Configuration;

    using NUnit.Framework;

    /// <summary>
    /// Test fixture for the ConfigurationElementTypeDescriptionProvider
    /// class.
    /// </summary>
    [TestFixture]
    public class ConfigurationElementTypeDescriptionProviderTests
    {
        #region Methods

        /// <summary>
        /// Tests the GetTypeDescriptor method.
        /// </summary>
        [Test]
        public void GetTypeDescriptorTest()
        {
            Type configType = typeof(ElementConfiguration);

            ConfigurationElementTypeDescriptionProvider typeDescriptionProvider =
                new ConfigurationElementTypeDescriptionProvider(configType);

            ICustomTypeDescriptor typeDescriptor =
                typeDescriptionProvider.GetTypeDescriptor(configType);

            Assert.IsNotNull(
                typeDescriptor,
                "Expected a valid type descriptor instance to be returned from GetTypeDescriptor().");

            PropertyDescriptorCollection properties = typeDescriptor.GetProperties();

            PropertyDescriptor elementsProperty = properties["Elements"];
            Assert.IsNotNull(elementsProperty, "Expected property 'Elements' to be present.");

            object editor = elementsProperty.GetEditor(typeof(UITypeEditor));
            Assert.IsNotNull(editor, "Expected an editor instance.");
            Assert.AreEqual(
                typeof(ConfigurationElementCollectionEditor),
                editor.GetType(),
                "Unexpected editor type for the Elements property.");
        }

        #endregion Methods
    }
}


text:
<?php
/**
 * Placeholder for bbPress plugin bridge.
 *
 * @package BuddyPress
 * @subpackage ForumsbbPress
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;


text:
CLI tool for outputting random codes with some basic options

After global installation this can be run using the 'gencodes' command with the following options

 Options:

    -h, --help                     output usage information
    -c, --count <count>            The amount of codes to create
    -p, --prefix <prefix>          The prefix for codes
    -l, --codelength <codelength>  The length of each code
    -m, --mask <mask>              The types of letters to include A: uppercase, a: lowercase, #: numbers, !:special chars e.g. A#  (will be a combination of uppercase and numbers)
    -e, --exclusions <exclusions>  Specific types of letters to exclude

Example usage:
``` gencodes  --prefix pp --codelength 40 --mask A --exclusions ABCDEFGHIJK --count 500  ./test.csv ```

Output:
``` PPVNZOTUWSWVSTYOLLPYQLTNLTSYXPVQTSQWQUTQYP ```


text:
//---------------------------------------------------------------------
// <copyright file="SyndicationDeserializer.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
//      Provides a deserializer for atom content structured as
//      syndication items or feeds.
//
//
// @owner [....]
//---------------------------------------------------------------------

namespace System.Data.Services.Serializers
{
    #region Namespaces.

    using System;
    using System.Collections.Generic;
    using System.Data.Services.Common;
    using System.Data.Services.Providers;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.ServiceModel.Syndication;
    using System.Text;
    using System.Xml;

    #endregion Namespaces.

    /// Provides a deserializer for structured content.
    internal class SyndicationDeserializer : Deserializer
    {
        /// Factory for syndication formatting objects.
        private readonly SyndicationFormatterFactory factory;

        /// reader to read xml from the request stream
        private readonly XmlReader xmlReader;

        /// Initializes a new <see cref="SyndicationDeserializer"/> for the specified stream.
        /// <param name="stream">Input stream reader from which ATOM content must be read.</param>
        /// <param name="encoding">Encoding to use for the stream (null to auto-discover).</param>
        /// <param name="dataService">Data service for which the deserializer will act.</param>
        /// <param name="update">indicates whether this is a update operation or not</param>
        /// <param name="factory">Factory for formatter objects.</param>
        /// <param name="tracker">Tracker to use for modifications.</param>
        internal SyndicationDeserializer(Stream stream, Encoding encoding, IDataService dataService, bool update, SyndicationFormatterFactory factory, UpdateTracker tracker)
            : base(update, dataService, tracker)
        {
            Debug.Assert(stream != null, "stream != null");
            Debug.Assert(factory != null, "factory != null");

            this.factory = factory;
            this.xmlReader = factory.CreateReader(stream, encoding);
        }

        ///
        /// Indicates the various form of data in the inline xml element
        ///
        private enum LinkContent
        {
            /// If the link element didn't not contain an inline element at all.
            NoInlineElementSpecified,

            /// If the link element contained an empty inline element.
            EmptyInlineElementSpecified,

            /// If the inline element under the link element contained some data.
            InlineElementContainsData
        }

        /// returns the content format for the deserializer
        protected override ContentFormat ContentFormat
        {
            get
            {
                return ContentFormat.Atom;
            }
        }

        ///
        /// Assumes the payload to represent a single object and processes accordingly
        ///
        /// <param name="segmentInfo">info about the object being created</param>
        /// <returns>the newly formed object that the payload represents</returns>
        protected override object CreateSingleObject(SegmentInfo segmentInfo)
        {
            SyndicationItem item = ReadSyndicationItem(this.factory.CreateSyndicationItemFormatter(), this.xmlReader);
            return this.CreateObject(segmentInfo, true /*topLevel*/, item);
        }

        /// Provides an opportunity to clean-up resources.
        /// <param name="disposing">
        /// Whether the call is being made from an explicit call to
        /// IDisposable.Dispose() rather than through the finalizer.
        /// </param>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (disposing)
            {
                this.xmlReader.Close();
            }
        }

        ///
        /// Get the resource referred by the uri in the payload
        ///
        /// <returns>resource referred by the uri in the payload.</returns>
        protected override string GetLinkUriFromPayload()
        {
            throw Error.NotImplemented();
        }

        /// Checks whether the specified item has a payload.
        /// <param name='item'>Item to check.</param>
        /// <returns>true if the item has content or links specified; false otherwise.</returns>
        private static bool HasContent(SyndicationItem item)
        {
            return item.Content != null || item.Links.Count > 0;
        }

        /// Gets the text for the type annotated on the specified <paramref name='item' />.
        /// <param name='item'>Item to read type from.</param>
        /// <returns>The text for the type annotated on the specified item; null if none is set.</returns>
        private static string SyndicationItemGetType(SyndicationItem item)
        {
            Debug.Assert(item != null, "item != null");
            SyndicationCategory category = item.Categories.Where(c => c.Scheme == XmlConstants.DataWebSchemeNamespace).FirstOrDefault();
            return (category == null) ? null : category.Name;
        }

        /// Reads a SyndicationFeed object from the specified XmlReader.
        /// <param name='formatter'>Formatter to use when reading content.</param>
        /// <param name='reader'>Read to read feed from.</param>
        /// <returns>A new SyndicationFeed instance.</returns>
        private static SyndicationFeed ReadSyndicationFeed(SyndicationFeedFormatter formatter, XmlReader reader)
        {
            Debug.Assert(formatter != null, "formatter != null");
            Debug.Assert(reader != null, "reader != null");

            try
            {
                formatter.ReadFrom(reader);
            }
            catch (XmlException exception)
            {
                throw DataServiceException.CreateBadRequestError(Strings.Syndication_ErrorReadingFeed(exception.Message), exception);
            }

            Debug.Assert(formatter.Feed != null, "formatter.Feed != null");
            return formatter.Feed;
        }

        /// Reads a SyndicationItem object from the specified XmlReader.
        /// <param name='formatter'>Formatter to use when reading content.</param>
        /// <param name='reader'>Read to read feed from.</param>
        /// <returns>A new SyndicationItem instance.</returns>
        private static SyndicationItem ReadSyndicationItem(SyndicationItemFormatter formatter, XmlReader reader)
        {
            Debug.Assert(formatter != null, "formatter != null");
            Debug.Assert(reader != null, "reader != null");

            try
            {
                formatter.ReadFrom(reader);
            }
            catch (XmlException exception)
            {
                throw DataServiceException.CreateBadRequestError(Strings.Syndication_ErrorReadingEntry(exception.Message), exception);
            }

            Debug.Assert(formatter.Item != null, "formatter.Item != null");
            return formatter.Item;
        }

        ///
        /// Read the link media type and validate for non open property types
        ///
        /// <param name="mediaType">media type as specified on the link element.</param>
        /// <param name="property">property which the link represents.</param>
        /// <returns>returns the type parameters specified in the media link.</returns>
        private static string ValidateTypeParameterForNonOpenTypeProperties(string mediaType, ResourceProperty property)
        {
            string typeParameterValue = null;
            if (!String.IsNullOrEmpty(mediaType))
            {
                string mime;
                Encoding encoding;
                KeyValuePair<string, string>[] contentTypeParameters = HttpProcessUtility.ReadContentType(mediaType, out mime, out encoding);
                if (mime != XmlConstants.MimeApplicationAtom)
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_MimeTypeMustBeApplicationAtom(mime, XmlConstants.MimeApplicationAtom));
                }

                // If the type parameter is specified, make sure its correct. We do the validation for known properties here
                // and for open-properties, the validation is done if the link is expanded. Otherwise, there is no good way of
                // doing the validation.
                typeParameterValue = HttpProcessUtility.GetParameterValue(contentTypeParameters, XmlConstants.AtomTypeAttributeName);
                if (!String.IsNullOrEmpty(typeParameterValue) && property != null)
                {
                    if (property.Kind == ResourcePropertyKind.ResourceReference)
                    {
                        if (typeParameterValue != XmlConstants.AtomEntryElementName)
                        {
                            throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidTypeParameterSpecifiedInMimeType(typeParameterValue, XmlConstants.AtomEntryElementName));
                        }
                    }
                    else if (typeParameterValue != XmlConstants.AtomFeedElementName)
                    {
                        throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidTypeParameterSpecifiedInMimeType(typeParameterValue, XmlConstants.AtomFeedElementName));
                    }
                }
            }

            return typeParameterValue;
        }

        ///
        /// Gets the XmlReader for the m:properties element under the atom:entry element
        ///
        /// <param name="item">item to read from</param>
        /// <returns>XmlReader for the m:properties element if found, null otherwise.</returns>
        private static XmlReader GetPropertiesReaderFromEntry(SyndicationItem item)
        {
            SyndicationElementExtension properties = item.ElementExtensions.Where(p => p.OuterName == XmlConstants.AtomPropertiesElementName && p.OuterNamespace == XmlConstants.DataWebMetadataNamespace).FirstOrDefault();
            if (properties != null)
            {
                return properties.GetReader();
            }

            return null;
        }

        ///
        /// Gets the XmlReader for the m:properties element under the atom:content element
        ///
        /// <param name="item">item to read from</param>
        /// <returns>XmlReader for the m:properties element if found, null otherwise.</returns>
        private static XmlReader GetPropertiesReaderFromContent(SyndicationItem item)
        {
            XmlSyndicationContent itemContent = item.Content as XmlSyndicationContent;
            XmlReader reader = null;
            if (itemContent != null)
            {
                string contentType = itemContent.Type;
                if (!WebUtil.CompareMimeType(contentType, XmlConstants.MimeApplicationXml))
                {
                    throw DataServiceException.CreateBadRequestError(
                        Strings.Syndication_EntryContentTypeUnsupported(contentType));
                }

                bool shouldDispose = false;
                try
                {
                    reader = itemContent.GetReaderAtContent();
                    WebUtil.XmlReaderEnsureElement(reader);
                    Debug.Assert(
                        reader.NodeType == XmlNodeType.Element,
                        reader.NodeType.ToString() + " == XmlNodeType.Element -- otherwise XmlSyndicationContent didn't see a 'content' tag");

                    reader.ReadStartElement(XmlConstants.AtomContentElementName, XmlConstants.AtomNamespace);
                    if (!reader.IsStartElement(XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace))
                    {
                        shouldDispose = true;
                    }
                }
                catch
                {
                    shouldDispose = true;
                    throw;
                }
                finally
                {
                    if (shouldDispose)
                    {
                        WebUtil.Dispose(reader);
                        reader = null;
                    }
                }
            }

            return reader;
        }

        /// Applies the properties in the plain XML content to the specified resource.
        /// <param name="item">item to read from.</param>
        /// <param name='resourceType'>Type of resource whose values are being set.</param>
        /// <param name="propertiesApplied">Properties that have been applied to the <paramref name="resource"/></param>
        /// <param name='resource'>Target resource.</param>
        private void ApplyProperties(SyndicationItem item, ResourceType resourceType, EpmContentDeSerializer.EpmAppliedPropertyInfo propertiesApplied, object resource)
        {
            Debug.Assert(item != null, "item != null");
            Debug.Assert(resourceType != null, "resourceType != null");
            Debug.Assert(propertiesApplied != null, "propertiesApplied != null");
            Debug.Assert(resource != null, "resource != null");

            using (XmlReader propertiesFromEntry = GetPropertiesReaderFromEntry(item))
            using (XmlReader propertiesFromContent = GetPropertiesReaderFromContent(item))
            {
                XmlReader reader = null;

                if (resourceType.IsMediaLinkEntry)
                {
                    if (propertiesFromContent != null)
                    {
                        // The server is expecting a MLE payload, however we found a <m:properties> element under the <atom:content> element.
                        // The client must assumed the resource type is a non-MLE type and serialized as such.
                        //
                        // We must throw here otherwise the client would falsely assume all the properties are correctly deserialized on
                        // the server where as in fact the properties element is under the wrong node.
                        throw DataServiceException.CreateBadRequestError(Strings.DataServiceException_GeneralError);
                    }

                    reader = propertiesFromEntry;
                }
                else
                {
                    if (propertiesFromEntry != null)
                    {
                        // The server is expecting a non-MLE payload, however we found a <m:properties> element under the <entry> element.
                        // The client must assumed the resource type is a MLE type and serialized as such.
                        //
                        // We must throw here otherwise the client would falsely assume all the properties are correctly deserialized on
                        // the server where as in fact the properties element is under the wrong node.
                        throw DataServiceException.CreateBadRequestError(Strings.DataServiceException_GeneralError);
                    }

                    reader = propertiesFromContent;
                }

                if (reader != null)
                {
                    reader.ReadStartElement(XmlConstants.AtomPropertiesElementName, XmlConstants.DataWebMetadataNamespace);
                    PlainXmlDeserializer.ApplyContent(this, reader, resourceType, resource, propertiesApplied, this.MaxObjectCount);
                }
            }
        }

        /// Reads the current object from the <paramref name="item"/>.
        /// <param name="segmentInfo">segmentinfo containing information about the current element that is getting processes</param>
        /// <param name="topLevel">true if the element currently pointed by the xml reader refers to a top level element</param>
        /// <param name="item">Item to read from.</param>
        /// <returns>returns the clr object with the data populated</returns>
        private object CreateObject(SegmentInfo segmentInfo, bool topLevel, SyndicationItem item)
        {
            Debug.Assert(item != null, "item != null");
            Debug.Assert(topLevel || !this.Update, "deep updates not supported");

            this.RecurseEnter();
            object result;

            // update the object count everytime you encounter a new resource
            this.CheckAndIncrementObjectCount();

            // Process the type annotation.
            ResourceType currentResourceType = this.GetResourceType(item, segmentInfo.TargetResourceType);
            if (currentResourceType.ResourceTypeKind != ResourceTypeKind.EntityType)
            {
                throw DataServiceException.CreateBadRequestError(Strings.BadRequest_OnlyEntityTypesMustBeSpecifiedInEntryElement(currentResourceType.FullName));
            }

            // We have the actual type info from the payload. Update the request/response DSV if any property is FF mapped with KeepInContent=false.
            this.UpdateAndCheckEpmRequestResponseDSV(currentResourceType, topLevel);

            // Get a resource cookie from the provider.
            ResourceSetWrapper container;
            if (segmentInfo.TargetKind == RequestTargetKind.OpenProperty)
            {
                // Open navigation properties are not supported on OpenTypes.
                throw DataServiceException.CreateBadRequestError(Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(segmentInfo.Identifier));
            }
            else
            {
                Debug.Assert(segmentInfo.TargetKind == RequestTargetKind.Resource, "segmentInfo.TargetKind == RequestTargetKind.Resource");
                container = segmentInfo.TargetContainer;
            }

            DataServiceHostWrapper host = this.Service.OperationContext.Host;
            if (this.Update)
            {
                Debug.Assert(currentResourceType.ResourceTypeKind == ResourceTypeKind.EntityType, "only expecting entity types");

                // Only verify ETag if there is going to be some update applied (that's the idea)
                // In reality:
                //   - for normal entities (V1 compatible) - don't check ETags if there is no content element. (Same as in V1)
                //   - for V2 stuff - check ETags always as we can't tell if there's going to be something modified or not
                //       with EPM properties can be anywhere in the payload and thus even without content there still can be updates
                //       with MLE the properties are not in the content element but in their own element
                // It's hard to recognize if there's going to be update up front and so this below is an approximation
                //   which seems to be good enough. Note that if we add new ways of handling properties in the content
                //   the condition below might need to change.
                bool verifyETag =
                    topLevel &&
                    (HasContent(item) || currentResourceType.HasEntityPropertyMappings || currentResourceType.IsMediaLinkEntry);
                bool replaceResource = topLevel && host.AstoriaHttpVerb == AstoriaVerbs.PUT;

                // if its a top level resource, then it cannot be null
                result = this.GetObjectFromSegmentInfo(currentResourceType, segmentInfo, verifyETag, topLevel /*checkForNull*/, replaceResource);
                if (this.Tracker != null)
                {
                    this.Tracker.TrackAction(result, container, UpdateOperations.Change);
                }
            }
            else
            {
                if (segmentInfo.TargetKind == RequestTargetKind.Resource)
                {
                    DataServiceConfiguration.CheckResourceRights(segmentInfo.TargetContainer, EntitySetRights.WriteAppend);
                }

                result = this.Updatable.CreateResource(container.Name, currentResourceType.FullName);
                if (this.Tracker != null)
                {
                    this.Tracker.TrackAction(result, container, UpdateOperations.Add);
                }
            }

            // Process the content in the entry.
            EpmContentDeSerializer.EpmAppliedPropertyInfo propertiesApplied = new EpmContentDeSerializer.EpmAppliedPropertyInfo();
            this.ApplyProperties(item, currentResourceType, propertiesApplied, result);

            // Perform application of epm properties here
            if (currentResourceType.HasEntityPropertyMappings)
            {
                new EpmContentDeSerializer(currentResourceType, result).DeSerialize(
                        item,
                        new EpmContentDeSerializer.EpmContentDeserializerState { IsUpdateOperation = this.Update, Updatable = this.Updatable, Service = this.Service, PropertiesApplied = propertiesApplied });
            }

            // Process the links in the entry.
            foreach (SyndicationLink link in item.Links)
            {
                string navigationPropertyName = UriUtil.GetNameFromAtomLinkRelationAttribute(link.RelationshipType);

                if (null == navigationPropertyName)
                {
                    continue;
                }

                Deserializer.CheckForBindingInPutOperations(host.AstoriaHttpVerb);
                Debug.Assert(segmentInfo.TargetContainer != null, "segmentInfo.TargetContainer != null");
                this.ApplyLink(link, segmentInfo.TargetContainer, currentResourceType, result, navigationPropertyName);
            }

            this.RecurseLeave();
            return result;
        }

        /// Applies the information from a link to the specified resource.
        /// <param name='link'>LinkDescriptor with information to apply.</param>
        /// <param name="resourceSet">Set for the target resource.</param>
        /// <param name='resourceType'>Type for the target resource.</param>
        /// <param name='resource'>Target resource to which information will be applied.</param>
        /// <param name="propertyName">Name of the property that this link represents.</param>
        private void ApplyLink(SyndicationLink link, ResourceSetWrapper resourceSet, ResourceType resourceType, object resource, string propertyName)
        {
            Debug.Assert(link != null, "link != null");
            Debug.Assert(resourceType != null, "resourceType != null");
            Debug.Assert(resource != null, "resource != null");

            ResourceProperty property = resourceType.TryResolvePropertyName(propertyName);
            if (property == null)
            {
                // Open navigation properties are not supported on OpenTypes
                throw DataServiceException.CreateBadRequestError(Strings.OpenNavigationPropertiesNotSupportedOnOpenTypes(propertyName));
            }

            if (property.TypeKind != ResourceTypeKind.EntityType)
            {
                throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidNavigationPropertyName(propertyName, resourceType.FullName));
            }

            string typeParameterValue = ValidateTypeParameterForNonOpenTypeProperties(link.MediaType, property);
            LinkContent linkContent = this.HandleLinkContent(link, resource, resourceSet, resourceType, property, typeParameterValue, propertyName);

            #region Handle bind/unbind operation
            // If the href was specified empty or an empty inline element was specified, then we will set the
            // reference to null - this helps in overrriding if there was a default non-value for this property
            // else if only link element was specified, and then href points to a single result, then we will
            // perform a bind operation
            if ((linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && String.IsNullOrEmpty(link.Uri.OriginalString)) ||
                linkContent == LinkContent.EmptyInlineElementSpecified)
            {
                // update the object count when you are performing a bind operation
                this.CheckAndIncrementObjectCount();
                if (property != null && property.Kind == ResourcePropertyKind.ResourceSetReference)
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_CannotSetCollectionsToNull(propertyName));
                }

                // For open properties, we will assume that this is a reference property and set it to null
                this.Updatable.SetReference(resource, propertyName, null);
            }
            else if (linkContent == LinkContent.NoInlineElementSpecified && link.Uri != null && !String.IsNullOrEmpty(link.Uri.OriginalString))
            {
                // update the object count when you are performing a bind operation
                this.CheckAndIncrementObjectCount();

                // If the link points to a reference navigation property, then update the link
                Uri referencedUri = RequestUriProcessor.GetAbsoluteUriFromReference(link.Uri.OriginalString, this.Service.OperationContext);
                RequestDescription description = RequestUriProcessor.ProcessRequestUri(referencedUri, this.Service);
                if (!description.IsSingleResult)
                {
                    if (property != null && property.Kind == ResourcePropertyKind.ResourceReference)
                    {
                        throw DataServiceException.CreateBadRequestError(Strings.BadRequest_LinkHrefMustReferToSingleResource(propertyName));
                    }

                    return;
                }

                // no need to check for null. For collection properties, they can never be null and that
                // check has been added below. For reference properties, if they are null, it means unbind
                // and hence no need to check for null.
                // Get the resource
                object targetResource = this.Service.GetResource(description, description.SegmentInfos.Length - 1, null);
                if (property.Kind == ResourcePropertyKind.ResourceReference)
                {
                    this.Updatable.SetReference(resource, propertyName, targetResource);
                }
                else
                {
                    WebUtil.CheckResourceExists(targetResource != null, description.LastSegmentInfo.Identifier);
                    this.Updatable.AddReferenceToCollection(resource, propertyName, targetResource);
                }
            }
            #endregion Handle bind/unbind operation
        }

        /// Gets the type attribute and resolves the type.
        /// <param name="item">Item from which type attribute needs to be read</param>
        /// <param name="expectedType">Expected base type for the item.</param>
        /// <returns>Resolved type.</returns>
        private ResourceType GetResourceType(SyndicationItem item, ResourceType expectedType)
        {
            Debug.Assert(item != null, "item != null");
            string typeName = SyndicationItemGetType(item);
            ResourceType resourceType;

            // If the type is not specified in the payload, we assume the type to be the expected type
            if (String.IsNullOrEmpty(typeName))
            {
                // check if the expected type takes part in inheritance
                resourceType = expectedType;
                if (this.Service.Provider.HasDerivedTypes(resourceType))
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_TypeInformationMustBeSpecifiedForInhertiance);
                }
            }
            else
            {
                // Otherwise, try and resolve the name specified in the payload
                resourceType = this.Service.Provider.TryResolveResourceType(typeName);
                if (resourceType == null)
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidTypeName(typeName));
                }
            }

            return resourceType;
        }

        ///
        /// Handle the contents under the link element
        ///
        /// <param name="link">syndication link element</param>
        /// <param name="parentResource">parent resource which contains the link.</param>
        /// <param name="parentResourceSet">resource set of the parent resource</param>
        /// <param name="parentResourceType">resource type of the parent resource</param>
        /// <param name="property">property representing the link.</param>
        /// <param name="typeParameterValue">type parameter value as specified in the type attribute.</param>
        /// <param name="propertyName">name of the property that this link represents.</param>
        /// <returns>returns whether there are child elements under link element.</returns>
        private LinkContent HandleLinkContent(
            SyndicationLink link,
            object parentResource,
            ResourceSetWrapper parentResourceSet,
            ResourceType parentResourceType,
            ResourceProperty property,
            string typeParameterValue,
            string propertyName)
        {
            Debug.Assert(parentResource != null, "parent resource cannot be null");
            Debug.Assert(property != null, "property != null");
            Debug.Assert(link != null, "link != null");

            LinkContent linkContent = LinkContent.NoInlineElementSpecified;
            foreach (var e in link.ElementExtensions)
            {
                // link can contain other elements apart from the inline elements.
                if (e.OuterNamespace != XmlConstants.DataWebMetadataNamespace ||
                    e.OuterName != XmlConstants.AtomInlineElementName)
                {
                    continue;
                }

                // Deep payload cannot be specified for update
                if (this.Update)
                {
                    throw DataServiceException.CreateBadRequestError(Strings.BadRequest_DeepUpdateNotSupported);
                }

                linkContent = LinkContent.EmptyInlineElementSpecified;
                using (XmlReader linkReader = e.GetReader())
                {
                    while (linkReader.Read())
                    {
                        if (linkReader.NodeType == XmlNodeType.Element)
                        {
                            string elementName = linkReader.LocalName;
                            string namespaceUri = linkReader.NamespaceURI;
                            if (namespaceUri != XmlConstants.AtomNamespace)
                            {
                                throw DataServiceException.CreateBadRequestError(
                                    Strings.BadRequest_InlineElementMustContainValidElement(
                                        elementName,
                                        XmlConstants.AtomInlineElementName,
                                        XmlConstants.AtomFeedElementName,
                                        XmlConstants.AtomEntryElementName));
                            }

                            ResourceSetWrapper targetSet = this.Service.Provider.GetContainer(parentResourceSet, parentResourceType, property);
                            if (targetSet == null)
                            {
                                throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidPropertyNameSpecified(propertyName, parentResourceType.FullName));
                            }

                            // FeatureVersion needs to be 2.0 if any of the property in the types contained in the resource set has KeepInContent false
                            this.RequestDescription.UpdateAndCheckEpmFeatureVersion(targetSet, this.Service);

                            linkContent = LinkContent.InlineElementContainsData;
                            if (elementName == XmlConstants.AtomEntryElementName)
                            {
                                if (property.Kind != ResourcePropertyKind.ResourceReference)
                                {
                                    throw DataServiceException.CreateBadRequestError(Strings.Syndication_EntryElementForReferenceProperties(e.OuterName, propertyName));
                                }

                                // Make sure if the media type is specified. If its specified, it should better be link
                                SyndicationItem propertyItem;
                                propertyItem = ReadSyndicationItem(this.factory.CreateSyndicationItemFormatter(), linkReader);

                                SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, true /* singleResult */);
                                Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes.");

                                object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, propertyItem);
                                this.Updatable.SetReference(parentResource, propertyName, propertyValue);
                            }
                            else if (elementName == XmlConstants.AtomFeedElementName)
                            {
                                    if (property.Kind != ResourcePropertyKind.ResourceSetReference)
                                    {
                                        throw DataServiceException.CreateBadRequestError(Strings.Syndication_FeedElementForCollections(e.OuterName, propertyName));
                                    }

                                SyndicationFeed propertyFeed;
                                propertyFeed = ReadSyndicationFeed(this.factory.CreateSyndicationFeedFormatter(), linkReader);

                                SegmentInfo propertySegment = CreateSegment(property, propertyName, targetSet, false /* singleResult */);
                                Debug.Assert(propertySegment.TargetKind != RequestTargetKind.OpenProperty, "Open navigation properties are not supported on OpenTypes.");

                                foreach (SyndicationItem item in propertyFeed.Items)
                                {
                                    object propertyValue = this.CreateObject(propertySegment, false /* topLevel */, item);
                                    if (propertyValue == null)
                                    {
                                        if (propertySegment.ProjectedProperty != null &&
                                            propertySegment.ProjectedProperty.Kind == ResourcePropertyKind.ResourceSetReference)
                                        {
                                            throw DataServiceException.CreateBadRequestError(
                                                Strings.BadRequest_CannotSetCollectionsToNull(propertyName));
                                        }
                                    }

                                    Debug.Assert(
                                            propertySegment.TargetSource == RequestTargetSource.Property &&
                                            propertySegment.TargetKind == RequestTargetKind.Resource &&
                                            propertySegment.SingleResult == false,
                                            "Must be navigation set property.");

                                    this.Updatable.AddReferenceToCollection(parentResource, propertyName, propertyValue);
                                }
                            }
                            else
                            {
                                throw DataServiceException.CreateBadRequestError(
                                    Strings.BadRequest_InlineElementMustContainValidElement(
                                        elementName,
                                        XmlConstants.AtomInlineElementName,
                                        XmlConstants.AtomFeedElementName,
                                        XmlConstants.AtomEntryElementName));
                            }
                        }
                    }
                }
            }

            return linkContent;
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using Microsoft.CodeAnalysis.Features.RQName.SimpleTree;

namespace Microsoft.CodeAnalysis.Features.RQName.Nodes
{
    internal class RQTypeVariableType : RQType
    {
        public readonly string Name;

        public RQTypeVariableType(string name)
            => Name = name;

        public override SimpleTreeNode ToSimpleTree()
            => new SimpleGroupNode(RQNameStrings.TyVar, Name);
    }
}


text:
package org.apache.pulsar.functions.api.examples;

import java.util.Collection;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;

/**
 * Example Function that acts on a window of tuples at a time rather than per tuple basis.
 */
@Slf4j
public class AddWindowFunction implements Function<Collection<Integer>, Integer> {
    @Override
    public Integer apply(Collection<Integer> integers) {
        return integers.stream().reduce(0, (x, y) -> x + y);
    }
}


text:
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/)
[![standard-readme compliant](https://img.shields.io/badge/standard--readme-OK-green.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme)
[![npm version](https://img.shields.io/npm/v/brittanica-t.svg?style=flat-square)](https://badge.fury.io/js/brittanica-t)

> All words starting with t

## Install
```
npm install brittanica-t
```

## Contribute

PRs accepted

## License

MIT (c) brittanica


text:
namespace rocon_std_msgs
{

  class KeyValue : public ros::Msg
  {
    public:
      typedef const char* _key_type;
      _key_type key;
      typedef const char* _value_type;
      _value_type value;

    KeyValue():
      key(""),
      value("")
    {
    }

    virtual int serialize(unsigned char *outbuffer) const
    {
      int offset = 0;
      uint32_t length_key = strlen(this->key);
      varToArr(outbuffer + offset, length_key);
      offset += 4;
      memcpy(outbuffer + offset, this->key, length_key);
      offset += length_key;
      uint32_t length_value = strlen(this->value);
      varToArr(outbuffer + offset, length_value);
      offset += 4;
      memcpy(outbuffer + offset, this->value, length_value);
      offset += length_value;
      return offset;
    }

    virtual int deserialize(unsigned char *inbuffer)
    {
      int offset = 0;
      uint32_t length_key;
      arrToVar(length_key, (inbuffer + offset));
      offset += 4;
      for(unsigned int k= offset; k< offset+length_key; ++k){
          inbuffer[k-1]=inbuffer[k];
      }
      inbuffer[offset+length_key-1]=0;
      this->key = (char *)(inbuffer + offset-1);
      offset += length_key;
      uint32_t length_value;
      arrToVar(length_value, (inbuffer + offset));
      offset += 4;
      for(unsigned int k= offset; k< offset+length_value; ++k){
          inbuffer[k-1]=inbuffer[k];
      }
      inbuffer[offset+length_value-1]=0;
      this->value = (char *)(inbuffer + offset-1);
      offset += length_value;
     return offset;
    }

    const char * getType(){ return "rocon_std_msgs/KeyValue"; };
    const char * getMD5(){ return "cf57fdc6617a881a88c16e768132149c"; };

  };

}
#endif


text:
package org.spongepowered.despector.decompiler.ir;

import org.spongepowered.despector.util.DebugUtil;

public class TypeIntInsn extends Insn {

    private String type;
    private int val;

    public TypeIntInsn(int op, String type, int val) {
        super(op);
        this.type = type;
        this.val = val;
    }

    public String getType() {
        return this.type;
    }

    public int getValue() {
        return this.val;
    }

    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        str.append(DebugUtil.opcodeToString(this.opcode));
        str.append(" ").append(this.type);
        str.append(" ").append(this.val);
        return str.toString();
    }

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <Button
            android:id="@+id/ButtonBluetooth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="24dp"
            android:layout_marginLeft="24dp"
            android:onClick="cancel"
            android:text="@string/expertconfig_cancel"/>

    <Button
            android:id="@+id/buttonSettings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_marginBottom="24dp"
            android:layout_marginRight="24dp"
            android:onClick="save"
            android:text="@string/expertconfig_save"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/ButtonBluetooth"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/TextView03"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/prefs_menu_initialmenuitemid_title" />

            <EditText
                android:id="@+id/editinitialmenuitemid"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="number" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/TextView02"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/prefs_menu_menuvibrationtime_title" />

            <EditText
                android:id="@+id/editvibrationtime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="number"
                />

        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" >

            <TextView
                android:id="@+id/TextView03"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/prefs_menu_notificationfilter_title" />

            <EditText
                android:id="@+id/editnotificationfilter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ems="10"
                android:inputType="text" />

        </LinearLayout>
    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="@string/expertconfig_information" />

</RelativeLayout>


text:
using System.Collections.Generic;

namespace TimeTortoise.Model
{
	public class Activity
	{
		public Activity()
		{
			TimeSegments = new List<TimeSegment>();
		}

		public int Id { get; set; }
		public string Name { get; set; }
		public List<TimeSegment> TimeSegments { get; }
	}
}


text:
package org.eclipse.ceylon.compiler.java.codegen;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.ceylon.compiler.java.codegen.AbstractTransformer.BoxingStrategy;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree;
import org.eclipse.ceylon.compiler.typechecker.tree.Tree.AssignmentOp;
import org.eclipse.ceylon.langtools.tools.javac.tree.JCTree;
import org.eclipse.ceylon.model.typechecker.model.Type;

/**
 * Aggregation of mappings from Ceylon operator to Java operator and optimisation strategy.
 *
 * @author Stéphane Épardaud <stef@epardaud.fr>
 */
public class Operators {

    private enum PrimitiveType {
        BOOLEAN("ceylon.language.Boolean"),
        BYTE("ceylon.language.Byte"),
        CHARACTER("ceylon.language.Character"),
        INTEGER("ceylon.language.Integer"),
        FLOAT("ceylon.language.Float"),
        STRING("ceylon.language.String");

        public final String fqn;

        PrimitiveType(String fqn) {
            this.fqn = fqn;
        }
    }

    private static final PrimitiveType[] IntegerByte = new PrimitiveType[]{PrimitiveType.INTEGER, PrimitiveType.BYTE};
    private static final PrimitiveType[] IntegerFloat = new PrimitiveType[]{PrimitiveType.INTEGER, PrimitiveType.FLOAT};
    private static final PrimitiveType[] IntegerFloatByte = new PrimitiveType[]{PrimitiveType.INTEGER, PrimitiveType.FLOAT, PrimitiveType.BYTE};
    private static final PrimitiveType[] IntegerCharacterByte = new PrimitiveType[]{PrimitiveType.INTEGER, PrimitiveType.CHARACTER, PrimitiveType.BYTE};
    private static final PrimitiveType[] IntegerFloatCharacter = new PrimitiveType[]{PrimitiveType.INTEGER, PrimitiveType.FLOAT, PrimitiveType.CHARACTER};
    private static final PrimitiveType[] IntegerFloatStringByte = new PrimitiveType[]{PrimitiveType.INTEGER, PrimitiveType.FLOAT, PrimitiveType.STRING, PrimitiveType.BYTE};
    private static final PrimitiveType[] All = PrimitiveType.values();

    public enum OptimisationStrategy {
        /** Optimize using the equivalent javac operator */
        OPTIMISE(true, false, BoxingStrategy.UNBOXED),
        /** Optimize using the static method (for a value type) */
        OPTIMISE_VALUE_TYPE(false, true, BoxingStrategy.UNBOXED),
        /** A special case used for String == */
        OPTIMISE_BOXING(false, false, BoxingStrategy.INDIFFERENT),
        /** No optimization possible: Call the (virtual) method corresponding to the ceylon operator */
        NONE(false, false, BoxingStrategy.BOXED);

        private BoxingStrategy boxingStrategy;
        private boolean useJavaOperator;
        private boolean useValueTypeMethod;

        OptimisationStrategy(boolean useJavaOperator, boolean useValueTypeMethod, BoxingStrategy boxingStrategy){
            this.useJavaOperator = useJavaOperator;
            this.useValueTypeMethod = useValueTypeMethod;
            this.boxingStrategy = boxingStrategy;
        }

        public BoxingStrategy getBoxingStrategy(){
            return boxingStrategy;
        }

        public boolean useJavaOperator(){
            return useJavaOperator;
        }

        public boolean useValueTypeMethod(){
            return useValueTypeMethod;
        }
    }

    //
    // Unary and binary operators

    public enum OperatorTranslation {

        // Unary operators
        UNARY_POSITIVE(Tree.PositiveOp.class, 1, "<noop>", JCTree.Tag.POS, IntegerFloatByte),
        UNARY_NEGATIVE(Tree.NegativeOp.class, 1, "negated", JCTree.Tag.NEG, IntegerFloatByte),

        UNARY_BITWISE_NOT(1, "not", JCTree.Tag.COMPL, IntegerByte),
        UNARY_BITWISE_NOT_OP(Tree.FlipOp.class, 1, "not", JCTree.Tag.COMPL, IntegerByte),

        UNARY_POSTFIX_INCREMENT(Tree.PostfixIncrementOp.class, 1, "getSuccessor", JCTree.Tag.POSTINC, IntegerCharacterByte),
        UNARY_POSTFIX_DECREMENT(Tree.PostfixDecrementOp.class, 1, "getPredecessor", JCTree.Tag.POSTDEC, IntegerCharacterByte),
        UNARY_PREFIX_INCREMENT(Tree.IncrementOp.class, 1, "getSuccessor", JCTree.Tag.PREINC, IntegerCharacterByte),
        UNARY_PREFIX_DECREMENT(Tree.DecrementOp.class, 1, "getPredecessor", JCTree.Tag.PREDEC, IntegerCharacterByte),

        // Binary operators
        BINARY_SUM(Tree.SumOp.class, 2, "plus", JCTree.Tag.PLUS, IntegerFloatStringByte),
        BINARY_DIFFERENCE(Tree.DifferenceOp.class, 2, "minus", JCTree.Tag.MINUS, IntegerFloatByte),
        BINARY_PRODUCT(Tree.ProductOp.class, 2, "times", JCTree.Tag.MUL, IntegerFloat),
        BINARY_QUOTIENT(Tree.QuotientOp.class, 2, "divided", JCTree.Tag.DIV, IntegerFloat),
        BINARY_POWER(Tree.PowerOp.class, 2, "power", null) {
            public String getCeylonValueTypeMethodName() {
                return "$power$";
            }
        },
        BINARY_REMAINDER(Tree.RemainderOp.class, 2, "remainder", JCTree.Tag.MOD, PrimitiveType.INTEGER),

        BINARY_SCALE(Tree.ScaleOp.class, 2, "scale"),

        BINARY_BITWISE_AND(2, "and", JCTree.Tag.BITAND, IntegerByte),
        BINARY_BITWISE_OR(2, "or", JCTree.Tag.BITOR, IntegerByte),
        BINARY_BITWISE_XOR(2, "xor", JCTree.Tag.BITXOR, IntegerByte),
        BINARY_BITWISE_LOG_LEFT_SHIFT_INT(2, "leftLogicalShift", JCTree.Tag.SL, PrimitiveType.INTEGER),
        BINARY_BITWISE_LOG_LEFT_SHIFT_BYTE(2, "leftLogicalShift", 0, 0b111, JCTree.Tag.SL, PrimitiveType.BYTE),
        BINARY_BITWISE_LOG_RIGHT_SHIFT_INT(2, "rightLogicalShift", JCTree.Tag.USR, PrimitiveType.INTEGER),
        BINARY_BITWISE_LOG_RIGHT_SHIFT_BYTE(2, "rightLogicalShift", 0xff, 0b111, JCTree.Tag.USR, PrimitiveType.BYTE),
        BINARY_BITWISE_ARI_RIGHT_SHIFT_INT(2, "rightArithmeticShift", JCTree.Tag.SR, PrimitiveType.INTEGER),
        BINARY_BITWISE_ARI_RIGHT_SHIFT_BYTE(2, "rightArithmeticShift", 0, 0b111, JCTree.Tag.SR, PrimitiveType.BYTE),

        BINARY_AND(Tree.AndOp.class, 2, "<not-used>", JCTree.Tag.AND, PrimitiveType.BOOLEAN),
        BINARY_OR(Tree.OrOp.class, 2, "<not-used>", JCTree.Tag.OR, PrimitiveType.BOOLEAN),

        BINARY_BITWISE_AND_OP(Tree.IntersectionOp.class, 2, "and", JCTree.Tag.BITAND, IntegerByte),
        BINARY_BITWISE_OR_OP(Tree.UnionOp.class, 2, "or", JCTree.Tag.BITOR, IntegerByte),

        BINARY_UNION(Tree.UnionOp.class, 2, "union"),
        BINARY_INTERSECTION(Tree.IntersectionOp.class, 2, "intersection"),
        BINARY_COMPLEMENT(Tree.ComplementOp.class, 2, "complement"),

        BINARY_EQUAL(Tree.EqualOp.class, 2, "equals", JCTree.Tag.EQ, All){
            @Override
            public OptimisationStrategy getBinOpOptimisationStrategy(Tree.Term t,
                    Tree.Term leftTerm, Type leftType,
                    Tree.Term rightTerm, Type rightType, AbstractTransformer gen) {
                // no optimised operator returns a boxed type
                if(!t.getUnboxed())
                    return OptimisationStrategy.NONE;
                OptimisationStrategy left = isTermOptimisable(leftTerm, gen);
                OptimisationStrategy right = isTermOptimisable(rightTerm, gen);
                if(left == OptimisationStrategy.OPTIMISE
                        && right == OptimisationStrategy.OPTIMISE){
                    // make sure both types are the same, can't optimise otherwise
                    if(!leftType.isExactly(rightType))
                        return OptimisationStrategy.NONE;

                    // special case for String where we can't use == but don't need to box
                    if(gen.isCeylonString(leftType)
                        && gen.isCeylonString(rightType)){
                        return OptimisationStrategy.OPTIMISE_BOXING;
                    }
                }
                return lessPermissive(left, right);
            }
        },
        BINARY_COMPARE(Tree.CompareOp.class, 2, "compare"),

        // Binary operators that act on intermediary Comparison objects
        BINARY_LARGER(Tree.LargerOp.class, 2, "largerThan", JCTree.Tag.GT, IntegerFloatCharacter),
        BINARY_SMALLER(Tree.SmallerOp.class, 2, "smallerThan", JCTree.Tag.LT, IntegerFloatCharacter),
        BINARY_LARGE_AS(Tree.LargeAsOp.class, 2, "notSmallerThan",  JCTree.Tag.GE, IntegerFloatCharacter),
        BINARY_SMALL_AS(Tree.SmallAsOp.class, 2, "notLargerThan", JCTree.Tag.LE, IntegerFloatCharacter);

        // we can have either a mapping from Tree operator class
        Class<? extends Tree.OperatorExpression> operatorClass;

        int arity;
        /** The name of the method which the boxed transformation invokes */
        private String ceylonMethod;
        JCTree.Tag javacOperator;
        PrimitiveType[] optimisableTypes;
        /** The name of a top level value from the language module */
        String ceylonValue;
        /** The operator with which to compare against {@link #ceylonValue} */
        JCTree.Tag javacValueOperator;
        /** A mask to apply to the LHS before applying the operator */
        int leftValueMask;
        /** A mask to apply to the RHS before applying the operator */
        int rightValueMask;

        OperatorTranslation(int arity, String ceylonMethod,
                JCTree.Tag javacOperator, PrimitiveType... optimisableTypes) {
            this.ceylonMethod = ceylonMethod;
            this.javacOperator = javacOperator;
            this.optimisableTypes = optimisableTypes;
            this.arity = arity;
        }
        OperatorTranslation(int arity, String ceylonMethod, int leftValueMask, int rightValueMask,
                JCTree.Tag javacOperator, PrimitiveType... optimisableTypes) {
            this(arity, ceylonMethod, javacOperator, optimisableTypes);
            this.leftValueMask = leftValueMask;
            this.rightValueMask = rightValueMask;
        }
        OperatorTranslation(Class<? extends Tree.OperatorExpression> operatorClass,
                int arity, String ceylonMethod,
                JCTree.Tag javacOperator, PrimitiveType... optimisableTypes) {
            this(arity, ceylonMethod, javacOperator, optimisableTypes);
            this.operatorClass = operatorClass;
        }
        OperatorTranslation(Class<? extends Tree.BinaryOperatorExpression> operatorClass,
                int arity, String ceylonMethod) {
            this(operatorClass, arity, ceylonMethod, null);
        }

        public final OptimisationStrategy getUnOpOptimisationStrategy(Tree.Term expression, Tree.Term term, AbstractTransformer gen){
            // no optimised operator returns a boxed type
            if(!expression.getUnboxed())
                return OptimisationStrategy.NONE;
            return isTermOptimisable(term, gen);
        }

        public OptimisationStrategy getBinOpOptimisationStrategy(Tree.Term expression,
                Tree.Term leftTerm,
                Tree.Term rightTerm, AbstractTransformer gen){
            return getBinOpOptimisationStrategy(expression, leftTerm, leftTerm.getTypeModel(),
                    rightTerm, rightTerm.getTypeModel(), gen);
        }

        public OptimisationStrategy getBinOpOptimisationStrategy(Tree.Term expression,
                Tree.Term leftTerm, Type leftType,
                Tree.Term rightTerm, Type rightType, AbstractTransformer gen){
            // no optimised operator returns a boxed type
            if(!expression.getUnboxed()) {
                return OptimisationStrategy.NONE;
            }
            // for Comparable<Integer>, we can no longer always optimize
            if (leftType.isComparable() && !Decl.isValueTypeDecl(leftType)) {
                return OptimisationStrategy.NONE;
            }
            // Can we do an operator optimization?
            OptimisationStrategy optimisationStrategy;
            OptimisationStrategy left = isTermOptimisable(leftTerm, leftType, gen);
            OptimisationStrategy right = isTermOptimisable(rightTerm, rightType, gen);
            optimisationStrategy = mostAggressive(left, right);
            if (optimisationStrategy != OptimisationStrategy.OPTIMISE) {
                // we can't use operator optimization, but maybe was can
                // use static value type method to avoid boxing
                if (Decl.isValueTypeDecl(leftType)) {
                    optimisationStrategy = OptimisationStrategy.OPTIMISE_VALUE_TYPE;
                } else {
                    Type selfType = ExpressionTransformer.getSelfType(leftType);
                    if (selfType != null) {
                        if (Decl.isValueTypeDecl(selfType)) {
                            // a self type of a value type (e.g. Summable<Integer>)
                            optimisationStrategy = OptimisationStrategy.OPTIMISE_VALUE_TYPE;
                        }
                    }
                }
            }
            return optimisationStrategy;
        }

        /** Returns the least aggressive optimization of the two given optimizations */
        protected static OptimisationStrategy lessPermissive(OptimisationStrategy left, OptimisationStrategy right) {
            // it's from most permissive to less permissive, so return the one with the higher ordinal (less permissive)
            if(left.ordinal() > right.ordinal())
                return left;
            return right;
        }
        /** Returns the more aggressive optimization of the two given optimizations */
        protected static OptimisationStrategy mostAggressive(OptimisationStrategy left, OptimisationStrategy right) {
            // it's from most permissive to less permissive, so return the one with the higher ordinal (less permissive)
            if(left.ordinal() < right.ordinal())
                return left;
            return right;
        }
        final OptimisationStrategy isTermOptimisable(Tree.Term t, AbstractTransformer gen){
            return isTermOptimisable(t, t.getTypeModel(), gen);
        }
        final OptimisationStrategy isTermOptimisable(Tree.Term t, Type pt, AbstractTransformer gen){
            if(javacOperator == null || !t.getUnboxed())
                return OptimisationStrategy.NONE;
            if(pt == null) // typechecker error?
                return OptimisationStrategy.NONE;
            if(optimisableTypes == null)
                return OptimisationStrategy.NONE;
            // see if it's a supported type
            for(PrimitiveType type : optimisableTypes){
                switch(type){
                case BOOLEAN:
                    if(gen.isCeylonBoolean(pt))
                        return OptimisationStrategy.OPTIMISE;
                    break;
                case BYTE:
                    if(gen.isCeylonByte(pt))
                        return OptimisationStrategy.OPTIMISE;
                    break;
                case CHARACTER:
                    if(gen.isCeylonCharacter(pt))
                        return OptimisationStrategy.OPTIMISE;
                    break;
                case FLOAT:
                    if(gen.isCeylonFloat(pt))
                        return OptimisationStrategy.OPTIMISE;
                    break;
                case INTEGER:
                    if(gen.isCeylonInteger(pt))
                        return OptimisationStrategy.OPTIMISE;
                    break;
                case STRING:
                    if(gen.isCeylonString(pt))
                        return OptimisationStrategy.OPTIMISE;
                    break;
                }
            }
            return OptimisationStrategy.NONE;
        }

        public int getArity(){
            return arity;
        }

        public String getCeylonMethodName() {
            return ceylonMethod;
        }

        public String getCeylonValueTypeMethodName() {
            return ceylonMethod;
        }
    }

    //
    // Assignment operators

    public enum AssignmentOperatorTranslation {
        // Assignment operators
        ADD(Tree.AddAssignOp.class, OperatorTranslation.BINARY_SUM, JCTree.Tag.PLUS_ASG),
        SUBSTRACT(Tree.SubtractAssignOp.class, OperatorTranslation.BINARY_DIFFERENCE, JCTree.Tag.MINUS_ASG),
        MULTIPLY(Tree.MultiplyAssignOp.class, OperatorTranslation.BINARY_PRODUCT, JCTree.Tag.MUL_ASG),
        DIVIDE(Tree.DivideAssignOp.class, OperatorTranslation.BINARY_QUOTIENT, JCTree.Tag.DIV_ASG),
        REMAINDER(Tree.RemainderAssignOp.class, OperatorTranslation.BINARY_REMAINDER, JCTree.Tag.MOD_ASG),
        AND(Tree.AndAssignOp.class, OperatorTranslation.BINARY_AND, JCTree.Tag.BITAND_ASG),
        OR(Tree.OrAssignOp.class, OperatorTranslation.BINARY_OR, JCTree.Tag.BITOR_ASG),

        BINARY_BITWISE_OR(Tree.UnionAssignOp.class, OperatorTranslation.BINARY_BITWISE_OR_OP, JCTree.Tag.BITOR_ASG),
        BINARY_BITWISE_AND(Tree.IntersectAssignOp.class, OperatorTranslation.BINARY_BITWISE_AND_OP, JCTree.Tag.BITAND_ASG),

        // Set assignment
        BINARY_UNION(Tree.UnionAssignOp.class, OperatorTranslation.BINARY_UNION),
        BINARY_INTERSECTION(Tree.IntersectAssignOp.class, OperatorTranslation.BINARY_INTERSECTION),
        BINARY_COMPLEMENT(Tree.ComplementAssignOp.class, OperatorTranslation.BINARY_COMPLEMENT),
        ;

        JCTree.Tag javacOperator;
        OperatorTranslation binaryOperator;
        Class<? extends AssignmentOp> operatorClass;

        AssignmentOperatorTranslation(Class<? extends Tree.AssignmentOp> operatorClass, OperatorTranslation binaryOperator) {
            this.operatorClass = operatorClass;
            this.binaryOperator = binaryOperator;
        }

        AssignmentOperatorTranslation(Class<? extends Tree.AssignmentOp> operatorClass,
                OperatorTranslation binaryOperator,
                JCTree.Tag javacOperator) {
            this.operatorClass = operatorClass;
            this.javacOperator = javacOperator;
            this.binaryOperator = binaryOperator;
        }
    }

    //
    // Public API

    private static final Map<Class<? extends Tree.OperatorExpression>, OperatorTranslation> operators;
    private static final Map<String, OperatorTranslation> methodsAsOperators;
    private static final Map<Class<? extends Tree.AssignmentOp>, AssignmentOperatorTranslation> assignmentOperators;

    static {
        operators = new HashMap<Class<? extends Tree.OperatorExpression>, OperatorTranslation>();
        methodsAsOperators = new HashMap<String, OperatorTranslation>();
        assignmentOperators = new HashMap<Class<? extends Tree.AssignmentOp>, AssignmentOperatorTranslation>();

        for(OperatorTranslation operator : OperatorTranslation.values()){
            // some operators are virtual translations from method calls to java operators and so don't have
            // a Tree class
            if(operator.operatorClass != null) {
                operators.put(operator.operatorClass, operator);
            } else {
                for (PrimitiveType t : operator.optimisableTypes) {
                    String optimisedMethod = t.fqn + "." + operator.ceylonMethod;
                    methodsAsOperators.put(optimisedMethod, operator);
                }
            }
        }

        for(AssignmentOperatorTranslation operator : AssignmentOperatorTranslation.values())
            assignmentOperators.put(operator.operatorClass, operator);
    }

    public static OperatorTranslation getOperator(Tree.OperatorExpression operator) {
        if (operator instanceof Tree.BitwiseOp) {
            Tree.BitwiseOp bo = (Tree.BitwiseOp) operator;
            if (operator instanceof Tree.UnionOp) {
                return bo.getBinary() ?
                        OperatorTranslation.BINARY_BITWISE_OR_OP :
                        OperatorTranslation.BINARY_UNION;
            }
            if (operator instanceof Tree.IntersectionOp) {
                return bo.getBinary() ?
                        OperatorTranslation.BINARY_BITWISE_AND_OP :
                        OperatorTranslation.BINARY_INTERSECTION;
            }
        }
        return operators.get(operator.getClass());
    }

    public static OperatorTranslation getOperator(String signature) {
        return methodsAsOperators.get(signature);
    }

    public static AssignmentOperatorTranslation getAssignmentOperator(Tree.AssignmentOp operator) {
        if (operator instanceof Tree.BitwiseAssignmentOp) {
            Tree.BitwiseAssignmentOp bo = (Tree.BitwiseAssignmentOp) operator;
            if (operator instanceof Tree.UnionAssignOp) {
                return bo.getBinary() ?
                        AssignmentOperatorTranslation.BINARY_BITWISE_OR :
                        AssignmentOperatorTranslation.BINARY_UNION;
            }
            if (operator instanceof Tree.IntersectAssignOp) {
                return bo.getBinary() ?
                        AssignmentOperatorTranslation.BINARY_BITWISE_AND :
                        AssignmentOperatorTranslation.BINARY_INTERSECTION;
            }
        }
        return assignmentOperators.get(operator.getClass());
    }

    // only there to make sure this class is initialised before the enums defined in it, otherwise we
    // get an initialisation error
    public static void init(){}
}