text:
# Overview

This library allows you to run a [WebSharper](http://websharper.com)
Sitelet application through an [OWIN](http://owin.org/) interface,
version 1.0. In the terminology of [the OWIN
specification](http://owin.org/spec/spec/owin-1.0.0.html), WebSharper
is a Web Framework and WebSharper.Owin is an adapter layer for it.

After adding the reference to the project all the classes can be found
under the `WebSharper.Owin` module.

# Usage

WebSharper.Owin provides its functionality through several extension
methods on the `IAppBuilder` type. They are the following:

```fsharp
UseDiscoveredSitelet : webRoot: string -> IAppBuilder
```

Inspects the `webRoot` folder, looking for an assembly in the `bin`
subfolder that contains a WebSharper Sitelet, and runs this Sitelet
with `webRoot` as the root folder.

```fsharp
UseSitelet : webRoot: string * Sitelet<'T> -> IAppBuilder
```

Runs the provided Sitelet with `webRoot` as the root folder, using
WebSharper metadata loaded from assemblies located in the `bin`
subfolder of `webRoot`.

```fsharp
UseCustomSitelet : Options * Sitelet<'T> -> IAppBuilder
```

Runs the provided Sitelet. Allows a more customized setup than the
previous methods, for example running a Sitelet whose code isn't
located in the `bin` subfolder of the root folder, or running the
Sitelet with a URL prefix.

```fsharp
UseWebSharperRemoting : webRoot: string -> IAppBuilder
```

Runs the WebSharper Remoting service, allowing WebSharper-compiled
client-side code to invoke `[<Rpc>]`-annotated server-side functions.
Note that the Remoting service is automatically run by the above
methods `UseDiscoveredSitelet` and `UseSitelet`, as well as
`UseCustomSitelet` if `options.RunRemoting` is set to `true`.

# Notes

This library does not take care of serving the files extracted from
WebSharper assemblies, such as the generated JavaScript files, from
the file system. You need to use a static files middleware. The
example self-hosted Sitelet application uses a middleware available
from NuGet as `Microsoft.Owin.StaticFiles`, as follows:

```fsharp
open global.Owin
open Microsoft.Owin.StaticFiles
open Microsoft.Owin.FileSystems
open WebSharper.Owin

let RunSitelet (appB: IAppBuilder) mySitelet rootFolder =
    appB.UseStaticFiles(
        StaticFileOptions(
            FileSystem = PhysicalFileSystem(rootFolder)))
        .UseSitelet(rootFolder, mySitelet)
```


text:
<?php

/**
 * Handle a PUT request
 * @param {ReadStorable,WriteStorable} $storage
 * @param SimpleRequest $request
 * @throws BadFunctionCallException
 * @return SimpleResponse
 */
function put($storage, $user,  $request) {
	$response = new SimpleResponse();

	// Cache the request's body
	$bodyArray = $request->getData();

	if ($request->getId() != NULL &&  $bodyArray != NULL)
	{ // Receiving an existing object
		// TODO Use getTypeByUUID to find out if the entity exists thus saving an SQL query
		if ($storage->entityExists($request->getId()))
		{
			// If the entity exists, load it and update it.
			if ($storage->getTypeFromUUID($request->getId()) == $bodyArray['type'])
			{
			    // Lock the Entity, throws exception if it is already locked
			    $storage->setLock($request->getId());

				$element = existingElementFactory($storage, $user,  $request->getId());
				$element->setAssociativeArray($bodyArray);
				$response->setRawData($element->getAssociativeArray());
				$response->setHeader(201);

				$storage->releaseLock($request->getId());
			}
			else
			{
				// The new element's type different from what was stored.
				// TODO Send correct HTTP status code
				throw new BadFunctionCallException("Requested type did not match stored type.");
			}
		}
		else
		{
			// An ID was requested, but it was not found in the database.
			// TODO Send correct HTTP status code
			throw new BadFunctionCallException("No such ID.");
		}
	}
	else if ($request->getId() == NULL && $bodyArray)
	{ // Receiving new object
		$type = $bodyArray['type'];

		// TODO Call database for these
		$validTypesArray = array (
				'Process',
				'Multiprocess',
				'ExternalInteractor',
				'DataStore',
				'DataFlowDiagram',
				'DataFlow'
		);

		// Check that the received type was valid
		if (in_array($type, $validTypesArray))
		{
			$element = new $type($storage, $user,  $bodyArray);
			$response->setRawData($element->getAssociativeArray());
			$response->setHeader(201);
		}
		else
		{
			// TODO Send correct HTTP status code
			throw new BadFunctionCallException("Type was not valid");
		}
	}
	else
	{ // Error state
		// TODO Send correct HTTP status code
		throw new BadFunctionCallException("Request was not formed correctly.");
	}

	// Return the response
	return $response;
}

redpajama_set_name: RedPajamaGithub


text:
package com.savy3.hadoop.hive.serde2.cobol;

import com.savy3.hadoop.hive.serde3.cobol.CobolSerdeUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.serde2.AbstractSerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.SerDeStats;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;

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

/**
 * CobolSerde is under construction currently implemented are
 *
 * @author Ram Manohar <ram.manohar2708@gmail.com>
 */
public final class CobolSerDe extends AbstractSerDe {

	private ObjectInspector inspector;
	private int numCols;
	private List<TypeInfo> columnTypes;
	private List<Map<String, Integer>> columnProperties;

	private CobolDeserializer cobolDeserializer = null;
	private CobolCopybook ccb;

	@Override
	public void initialize(final Configuration conf, final Properties tbl)
			throws SerDeException {

		// final int fixedRecordlLength =
		// Integer.parseInt(tbl.getProperty("fb.length"));
		// conf.setInt(FixedLengthInputFormat.FIXED_RECORD_LENGTH,
		// fixedRecordlLength);
		try {
			this.ccb = new CobolCopybook(
					CobolSerdeUtils.determineLayoutOrThrowException(conf, tbl));
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		numCols = ccb.getFieldNames().size();
		this.inspector = ObjectInspectorFactory
				.getStandardStructObjectInspector(ccb.getFieldNames(),
						ccb.getFieldOIs());
		this.columnTypes = ccb.getFieldTypeInfos();
		this.columnProperties = ccb.getFieldProperties();

	}

	@Override
	public Writable serialize(Object obj, ObjectInspector objInspector)
			throws SerDeException {
		// Serializing to cobol layout format is out-of-scope
		throw new SerDeException("Serializer not built");
		// return new Text("Out-of-scope");
	}

	@Override
	public Object deserialize(final Writable blob) throws SerDeException {
		return getDeserializer().deserialize(ccb.getFieldNames(),
				this.columnTypes, this.columnProperties, this.numCols, blob);
	}

	@Override
	public ObjectInspector getObjectInspector() throws SerDeException {
		return inspector;
	}

	@Override
	public Class<? extends Writable> getSerializedClass() {
		return Text.class;
	}

	public SerDeStats getSerDeStats() {
		return null;
	}

	private CobolDeserializer getDeserializer() {
		if (cobolDeserializer == null) {
			cobolDeserializer = new CobolDeserializer();
		}

		return cobolDeserializer;
	}

}


text:
package com.browser_example;

import android.app.Application;

import com.facebook.react.ReactApplication;

import io.branch.referral.Branch;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.PackageList;
import com.facebook.soloader.SoLoader;

import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return new PackageList(this).getPackages();
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
    Branch.getAutoInstance(this);
  }
}


text:
package com.evolveum.midpoint.schema.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.xml.bind.JAXBElement;

import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.EntryType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ParamsType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;

public class ParamsTypeUtil {

    public static ParamsType toParamsType(Map<String, Collection<String>> paramsMap){
        Set<Entry<String, Collection<String>>> params = paramsMap.entrySet();
        if (!params.isEmpty()) {
            ParamsType paramsType = new ParamsType();

            for (Entry<String, Collection<String>> entry : params) {
                if (entry.getValue() == null) {
                    paramsType.getEntry().add(createEntryElement(entry.getKey(), null));
                } else {
                    for (String value: entry.getValue()) {
                        paramsType.getEntry().add(createEntryElement(entry.getKey(), value));
                    }
                }
            }
            return paramsType;
        }
        return null;
    }

    private static EntryType createEntryElement(String key, String value) {
        EntryType entryType = new EntryType();
        entryType.setKey(key);
        if (value != null) {
            entryType.setEntryValue(new JAXBElement<>(SchemaConstants.C_PARAM_VALUE, Serializable.class, value));
        }
        return entryType;
    }

    public static Map<String, Serializable> fromParamsType(ParamsType paramsType, PrismContext prismContext) throws SchemaException {
        if (paramsType != null) {
            Map<String, Serializable> params = new HashMap<>();
            for (EntryType entry : paramsType.getEntry()) {
                Serializable realValue;
                if (entry.getEntryValue() != null) {
                    Serializable value = (Serializable) entry.getEntryValue().getValue();
                    if (value instanceof RawType) {
                        RawType raw = (RawType) value;
                        if (raw.isParsed()) {
                            realValue = raw.getAlreadyParsedValue().getRealValue();
                        } else {
                            realValue = raw.guessFormattedValue();
                        }
                    } else {
                        realValue = value;
                    }
                } else {
                    realValue = null;
                }
                params.put(entry.getKey(), realValue);
            }
            return params;
        }
        return null;
    }

    public static Map<String, Collection<String>> fromParamsType(ParamsType paramsType) {
        if (paramsType != null) {
            Map<String, Collection<String>> params = new HashMap<>();
            for (EntryType entry : paramsType.getEntry()) {
                if (entry.getEntryValue() != null) {
                    String newValue = extractString(entry.getEntryValue());
                    Collection<String> values = params.computeIfAbsent(entry.getKey(), k -> new ArrayList<>());
                    values.add(newValue);
                }
            }
            return params;
        }
        return null;
    }

    private static String extractString(JAXBElement<?> jaxbElement) {
        Object value = jaxbElement.getValue();
        if (value instanceof RawType) {
            return ((RawType) value).extractString();
        } else {
            return value.toString();
        }
    }

}


text: ALTER TABLE posts ADD COLUMN published_at TIMESTAMP;


text:
<?php

/**
 * MIT License
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Spryker\Sniffs\WhiteSpace;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;

/**
 * No whitespace should be between implicit cast and variable, the same as with other casts.
 * This includes incrementor and decrementor.
 */
class ImplicitCastSpacingSniff implements Sniff
{
    /**
     * @inheritDoc
     */
    public function register(): array
    {
        return [T_BOOLEAN_NOT, T_NONE, T_ASPERAND, T_INC, T_DEC];
    }

    /**
     * @inheritDoc
     */
    public function process(File $phpcsFile, $stackPtr): void
    {
        $tokens = $phpcsFile->getTokens();

        if ($tokens[$stackPtr]['code'] === T_INC || $tokens[$stackPtr]['code'] === T_DEC) {
            $this->processIncDec($phpcsFile, $stackPtr);

            return;
        }

        $nextIndex = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);

        if ($nextIndex - $stackPtr === 1) {
            return;
        }

        $fix = $phpcsFile->addFixableError('No whitespace should be between ' . $tokens[$stackPtr]['content'] . ' and variable.', $stackPtr, 'WhitespaceBetweenContentVariable');
        if ($fix && $phpcsFile->fixer->enabled) {
            $phpcsFile->fixer->beginChangeset();
            $phpcsFile->fixer->replaceToken($stackPtr + 1, '');
            $phpcsFile->fixer->endChangeset();
        }
    }

    /**
     * @param \PHP_CodeSniffer\Files\File $phpcsFile
     * @param int $stackPtr
     *
     * @return void
     */
    protected function processIncDec(File $phpcsFile, int $stackPtr): void
    {
        $tokens = $phpcsFile->getTokens();

        $nextIndex = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
        if ($tokens[$nextIndex]['code'] === T_VARIABLE) {
            if ($nextIndex - $stackPtr === 1) {
                return;
            }

            $fix = $phpcsFile->addFixableError('No whitespace should be between incrementor and variable.', $stackPtr, 'WhitespaceBeforeVariable');
            if ($fix) {
                $phpcsFile->fixer->beginChangeset();
                $phpcsFile->fixer->replaceToken($stackPtr + 1, '');
                $phpcsFile->fixer->endChangeset();
            }

            return;
        }

        $prevIndex = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
        if ($tokens[$prevIndex]['code'] === T_VARIABLE) {
            if ($stackPtr - $prevIndex === 1) {
                return;
            }

            $fix = $phpcsFile->addFixableError('No whitespace should be between variable and incrementor.', $stackPtr, 'WhitespaceAfterVariable');
            if ($fix) {
                $phpcsFile->fixer->beginChangeset();
                $phpcsFile->fixer->replaceToken($stackPtr - 1, '');
                $phpcsFile->fixer->endChangeset();
            }

            return;
        }
    }
}


text:
@interface UAASMetricGranularityType : UAASModel

@property (nonatomic, copy) NSString *granularity;

@end


text:
<?php

namespace spec\BenGorUser\User\Application\Command\PurgeOutdatedTokens;

use BenGorUser\User\Application\Command\PurgeOutdatedTokens\PurgeOutdatedInvitationTokensUserCommand;
use PhpSpec\ObjectBehavior;

/**
 * Spec file of PurgeOutdatedInvitationTokensCommand class.
 *
 * @author Beñat Espiña <benatespina@gmail.com>
 */
class PurgeOutdatedInvitationTokensUserCommandSpec extends ObjectBehavior
{
    function it_creates_request()
    {
        $this->beConstructedWith();
        $this->shouldHaveType(PurgeOutdatedInvitationTokensUserCommand::class);
    }
}


text:
@interface KTOneFingerRotationGestureRecognizer()
@end

@implementation KTOneFingerRotationGestureRecognizer

//@synthesize rotation = rotation_;
//@synthesize rotation = rotation_;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   // Fail when more than 1 finger detected.
   if ([[event touchesForGestureRecognizer:self] count] > 1) {
      [self setState:UIGestureRecognizerStateFailed];
   }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
   if ([self state] == UIGestureRecognizerStatePossible) {
      [self setState:UIGestureRecognizerStateBegan];
   } else {
      [self setState:UIGestureRecognizerStateChanged];
   }

   // We can look at any touch object since we know we
   // have only 1. If there were more than 1 then
   // touchesBegan:withEvent: would have failed the recognizer.
   UITouch *touch = [touches anyObject];

   // To rotate with one finger, we simulate a second finger.
   // The second figure is on the opposite side of the virtual
   // circle that represents the rotation gesture.

   UIView *view = [self view];
   CGPoint center = CGPointMake(CGRectGetMidX([view bounds]), CGRectGetMidY([view bounds]));
   CGPoint currentTouchPoint = [touch locationInView:view];
   CGPoint previousTouchPoint = [touch previousLocationInView:view];

   CGFloat angleInRadians = atan2f(currentTouchPoint.y - center.y, currentTouchPoint.x - center.x) - atan2f(previousTouchPoint.y - center.y, previousTouchPoint.x - center.x);

    self.rotation = angleInRadians;
   //[self setRotation:angleInRadians];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
   // Perform final check to make sure a tap was not misinterpreted.
   if ([self state] == UIGestureRecognizerStateChanged) {
      [self setState:UIGestureRecognizerStateEnded];
   } else {
      [self setState:UIGestureRecognizerStateFailed];
   }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
   [self setState:UIGestureRecognizerStateFailed];
}

@end


text:
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'raf/polyfill';

Enzyme.configure({ adapter: new Adapter() });


text:
Data Pemilih Tetap Pemilihan Ketua OSIS 2016-2017

    <button class="btn btn-success" onclick="add_person()"> Tambah Data</button>
    <button class="btn btn-primary" onclick="reload_table()"> Refresh</button>
    <button class="btn btn-info" onclick="import_excel()"> Import Excel</button>
    <a href= "<?php echo base_url('admin/export_excel') ?>" class="btn btn-warning"> Export Excel

                NIS
                Nama
                Kelas
                Action

          NIS
          Nama
          Kelas
          Action

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Form Data Pemilih

            <form action="#" id="form" class="form-horizontal">
                <input type="hidden" value="" name="id"/>

                        NIS

                            <input name="nis" placeholder="nis Pemilih" class="form-control" type="text">

                        Nama

                            <input name="nama" placeholder="Nama Pemilih" class="form-control" type="text">

                        Kelas

                            <select name="kelas" class="form-control">
                                <option value="">--Pilih Kelas--</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                            </select>

            </form>

            <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Import Data Pemilih

            <form method="post" action="<?php echo site_url('admin/upload'); ?>" id="excel" name="file" class="form-horizontal" enctype="multipart/form-data">
              <input type="file" name="userfile" id="userfile"/>
              <input type="submit" value="submit" name="submit" id="submit"/>

            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter, Alert } from 'reactstrap';
import { gettext } from '../../utils/constants';
import { seafileAPI } from '../../utils/seafile-api';
import FileChooser from '../file-chooser/file-chooser';
import { Utils } from '../../utils/utils';

const propTypes = {
  sharedToken: PropTypes.string.isRequired,
  filePath: PropTypes.string,
  toggleCancel: PropTypes.func.isRequired,
  handleSaveSharedFile: PropTypes.func.isRequired,
};

class SaveSharedFileDialog extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      repo: null,
      selectedPath: '',
      errMessage: '',
    };
  }

  onSaveSharedFile = () => {
    const { sharedToken, filePath } = this.props;
    seafileAPI.saveSharedFile(this.state.repo.repo_id, this.state.selectedPath, sharedToken, filePath).then((res) => {
      this.props.toggleCancel();
      this.props.handleSaveSharedFile();
    }).catch((error) => {
      let errMessage = Utils.getErrorMsg(error);
      this.setState({errMessage: errMessage});
    });
  }

  onDirentItemClick = (repo, selectedPath, dirent) => {
    if (dirent.type === 'dir') {
      this.setState({
        repo: repo,
        selectedPath: selectedPath,
      });
    }
    else {
      this.setState({
        repo: null,
        selectedPath: '',
      });
    }
  }

  onRepoItemClick = (repo) => {
    this.setState({
      repo: repo,
      selectedPath: '/',
    });
  }

  render() {
    return (
      <Modal isOpen={true} className="sf-save-file">
        <ModalHeader toggle={this.props.toggleCancel}>{gettext('Save to:')}</ModalHeader>
        <ModalBody>
          <FileChooser
            isShowFile={false}
            onDirentItemClick={this.onDirentItemClick}
            onRepoItemClick={this.onRepoItemClick}
            mode="only_all_repos"
          />
          {this.state.errMessage && <Alert color="danger">{this.state.errMessage}</Alert>}
        </ModalBody>
        <ModalFooter>
          <Button color="secondary" onClick={this.props.toggleCancel}>{gettext('Cancel')}</Button>
          { this.state.selectedPath ?
            <Button color="primary" onClick={this.onSaveSharedFile}>{gettext('Submit')}</Button>
            :
            <Button color="primary" disabled>{gettext('Submit')}</Button>
          }
        </ModalFooter>
      </Modal>
    );
  }
}

SaveSharedFileDialog.propTypes = propTypes;

export default SaveSharedFileDialog;


text:
from gametree import *
import environ

class Teleporter(Component):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.item = None
        self.forbid_item = False
        self.destination = None

    def on_player_interaction(self):
        locked = False
        if self.item is not None:
            player_has_item = self.item.id in [i.entity.id for i in environ.game.player.inventory]
            if self.forbid_item and player_has_item:
                locked = True
            elif not self.forbid_item and not player_has_item:
                locked = True

        if locked:
            return

        if self.destination is None:
            return

        environ.game.player.transform.position.x = self.destination.transform.position.x
        environ.game.player.transform.position.y = self.destination.transform.position.y


text:
package org.apache.pulsar.proxy.server;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import io.netty.handler.ssl.SslHandler;
import io.netty.resolver.dns.DnsAddressResolverGroup;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ClosedChannelException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import javax.naming.AuthenticationException;
import javax.net.ssl.SSLSession;
import lombok.Getter;
import org.apache.pulsar.PulsarVersion;
import org.apache.pulsar.broker.PulsarServerException;
import org.apache.pulsar.broker.authentication.AuthenticationDataSource;
import org.apache.pulsar.broker.authentication.AuthenticationProvider;
import org.apache.pulsar.broker.authentication.AuthenticationState;
import org.apache.pulsar.broker.limiter.ConnectionController;
import org.apache.pulsar.client.api.Authentication;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.impl.ClientCnx;
import org.apache.pulsar.client.impl.ConnectionPool;
import org.apache.pulsar.client.impl.PulsarChannelInitializer;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.client.impl.conf.ConfigurationDataUtils;
import org.apache.pulsar.client.internal.PropertiesUtils;
import org.apache.pulsar.common.api.AuthData;
import org.apache.pulsar.common.api.proto.CommandAuthResponse;
import org.apache.pulsar.common.api.proto.CommandConnect;
import org.apache.pulsar.common.api.proto.CommandConnected;
import org.apache.pulsar.common.api.proto.CommandGetSchema;
import org.apache.pulsar.common.api.proto.CommandGetTopicsOfNamespace;
import org.apache.pulsar.common.api.proto.CommandLookupTopic;
import org.apache.pulsar.common.api.proto.CommandPartitionedTopicMetadata;
import org.apache.pulsar.common.api.proto.ProtocolVersion;
import org.apache.pulsar.common.api.proto.ServerError;
import org.apache.pulsar.common.protocol.Commands;
import org.apache.pulsar.common.protocol.PulsarHandler;
import org.apache.pulsar.policies.data.loadbalancer.ServiceLookupData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles incoming discovery request from client and sends appropriate response back to client.
 *
 */
public class ProxyConnection extends PulsarHandler {
    private static final Logger LOG = LoggerFactory.getLogger(ProxyConnection.class);
    // ConnectionPool is used by the proxy to issue lookup requests
    private ConnectionPool connectionPool;
    private final AtomicLong requestIdGenerator =
            new AtomicLong(ThreadLocalRandom.current().nextLong(0, Long.MAX_VALUE / 2));
    private final ProxyService service;
    private final DnsAddressResolverGroup dnsAddressResolverGroup;
    AuthenticationDataSource authenticationData;
    private State state;

    private LookupProxyHandler lookupProxyHandler = null;
    @Getter
    private DirectProxyHandler directProxyHandler = null;
    private final BrokerProxyValidator brokerProxyValidator;
    private final ConnectionController connectionController;
    String clientAuthRole;
    AuthData clientAuthData;
    String clientAuthMethod;

    private String authMethod = "none";
    AuthenticationProvider authenticationProvider;
    AuthenticationState authState;
    private ClientConfigurationData clientConf;
    private boolean hasProxyToBrokerUrl;
    private int protocolVersionToAdvertise;
    private String proxyToBrokerUrl;
    private HAProxyMessage haProxyMessage;

    protected static final Integer SPLICE_BYTES = 1024 * 1024 * 1024;
    private static final byte[] EMPTY_CREDENTIALS = new byte[0];

    boolean isTlsInboundChannel = false;

    enum State {
        Init,

        // Connecting between user client and proxy server.
        // Mutual authn needs verify between client and proxy server several times.
        Connecting,

        // Proxy the lookup requests to a random broker
        // Follow redirects
        ProxyLookupRequests,

        // Connecting to the broker
        ProxyConnectingToBroker,

        // If we are proxying a connection to a specific broker, we
        // are just forwarding data between the 2 connections, without
        // looking into it
        ProxyConnectionToBroker,

        Closing,

        Closed,
    }

    ConnectionPool getConnectionPool() {
        return connectionPool;
    }

    public ProxyConnection(ProxyService proxyService, DnsAddressResolverGroup dnsAddressResolverGroup) {
        super(30, TimeUnit.SECONDS);
        this.service = proxyService;
        this.dnsAddressResolverGroup = dnsAddressResolverGroup;
        this.state = State.Init;
        this.brokerProxyValidator = service.getBrokerProxyValidator();
        this.connectionController = proxyService.getConnectionController();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        ProxyService.ACTIVE_CONNECTIONS.inc();
        SocketAddress rmAddress = ctx.channel().remoteAddress();
        ConnectionController.State state = connectionController.increaseConnection(rmAddress);
        if (!state.equals(ConnectionController.State.OK)) {
            ctx.writeAndFlush(Commands.newError(-1, ServerError.NotAllowedError,
                    state.equals(ConnectionController.State.REACH_MAX_CONNECTION)
                            ? "Reached the maximum number of connections"
                            : "Reached the maximum number of connections on address" + rmAddress))
                            .addListener(result -> ctx.close());
            ProxyService.REJECTED_CONNECTIONS.inc();
        }
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        connectionController.decreaseConnection(ctx.channel().remoteAddress());
        ProxyService.ACTIVE_CONNECTIONS.dec();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        ProxyService.NEW_CONNECTIONS.inc();
        service.getClientCnxs().add(this);
        isTlsInboundChannel = ProxyConnection.isTlsChannel(ctx.channel());
        LOG.info("[{}] New connection opened", remoteAddress);
    }

    @Override
    public synchronized void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        if (directProxyHandler != null) {
            directProxyHandler.close();
            directProxyHandler = null;
        }

        service.getClientCnxs().remove(this);
        LOG.info("[{}] Connection closed", remoteAddress);

        if (connectionPool != null) {
            try {
                connectionPool.close();
                connectionPool = null;
            } catch (Exception e) {
                LOG.error("Failed to close connection pool {}", e.getMessage(), e);
            }
        }

        state = State.Closed;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        LOG.warn("[{}] Got exception {} : Message: {} State: {}", remoteAddress, cause.getClass().getSimpleName(),
                cause.getMessage(), state,
                ClientCnx.isKnownException(cause) ? null : cause);
        if (state != State.Closed) {
            state = State.Closing;
        }
        if (ctx.channel().isOpen()) {
            ctx.close();
        } else {
            // close connection to broker if that is present
            if (directProxyHandler != null) {
                directProxyHandler.close();
                directProxyHandler = null;
            }
        }
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        if (directProxyHandler != null && directProxyHandler.outboundChannel != null) {
            // handle backpressure
            // stop/resume reading input from connection between the proxy and the broker
            // when the writability of the connection between the client and the proxy changes
            directProxyHandler.outboundChannel.config().setAutoRead(ctx.channel().isWritable());
        }
        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HAProxyMessage) {
            haProxyMessage = (HAProxyMessage) msg;
            return;
        }
        switch (state) {
        case Init:
        case Connecting:
        case ProxyLookupRequests:
            // Do the regular decoding for the Connected message
            super.channelRead(ctx, msg);
            break;

        case ProxyConnectionToBroker:
            if (directProxyHandler != null) {
                ProxyService.OPS_COUNTER.inc();
                if (msg instanceof ByteBuf) {
                    int bytes = ((ByteBuf) msg).readableBytes();
                    directProxyHandler.getInboundChannelRequestsRate().recordEvent(bytes);
                    ProxyService.BYTES_COUNTER.inc(bytes);
                }
                directProxyHandler.outboundChannel.writeAndFlush(msg)
                        .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);

                if (service.proxyZeroCopyModeEnabled && service.proxyLogLevel == 0) {
                    if (!directProxyHandler.isTlsOutboundChannel && !isTlsInboundChannel) {
                        spliceNIC2NIC((EpollSocketChannel) ctx.channel(),
                                (EpollSocketChannel) directProxyHandler.outboundChannel, SPLICE_BYTES)
                                .addListener(future -> {
                                    ProxyService.OPS_COUNTER.inc();
                                    ProxyService.BYTES_COUNTER.inc(SPLICE_BYTES);
                                    directProxyHandler.getInboundChannelRequestsRate().recordEvent(SPLICE_BYTES);
                                });
                    }
                }
            } else {
                LOG.warn("Received message of type {} while connection to broker is missing in state {}. "
                                + "Dropping the input message (readable bytes={}).", msg.getClass(), state,
                        msg instanceof ByteBuf ? ((ByteBuf) msg).readableBytes() : -1);
            }
            break;
        case ProxyConnectingToBroker:
            LOG.warn("Received message of type {} while connecting to broker. "
                            + "Dropping the input message (readable bytes={}).", msg.getClass(),
                    msg instanceof ByteBuf ? ((ByteBuf) msg).readableBytes() : -1);
            break;
        default:
            break;
        }
    }

    /**
     * Use splice to zero-copy of NIC to NIC.
     * @param inboundChannel input channel
     * @param outboundChannel output channel
     */
    protected static ChannelPromise spliceNIC2NIC(EpollSocketChannel inboundChannel,
                                                  EpollSocketChannel outboundChannel, int spliceLength) {
        ChannelPromise promise = inboundChannel.newPromise();
        inboundChannel.spliceTo(outboundChannel, spliceLength, promise);
        promise.addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess() && !(future.cause() instanceof ClosedChannelException)) {
                future.channel().pipeline().fireExceptionCaught(future.cause());
            }
        });
        return promise;
    }

    protected static boolean isTlsChannel(Channel channel) {
        return channel.pipeline().get(ServiceChannelInitializer.TLS_HANDLER) != null;
    }

    private synchronized void completeConnect(AuthData clientData) throws PulsarClientException {
        Supplier<ClientCnx> clientCnxSupplier;
        if (service.getConfiguration().isAuthenticationEnabled()) {
            if (service.getConfiguration().isForwardAuthorizationCredentials()) {
                this.clientAuthData = clientData;
                this.clientAuthMethod = authMethod;
            }
            clientCnxSupplier = () -> new ProxyClientCnx(clientConf, service.getWorkerGroup(), clientAuthRole,
                    clientAuthData, clientAuthMethod, protocolVersionToAdvertise,
                    service.getConfiguration().isForwardAuthorizationCredentials(), this);
        } else {
            clientCnxSupplier = () -> new ClientCnx(clientConf, service.getWorkerGroup(), protocolVersionToAdvertise);
        }

        if (this.connectionPool == null) {
            this.connectionPool = new ConnectionPool(clientConf, service.getWorkerGroup(),
                    clientCnxSupplier,
                    Optional.of(dnsAddressResolverGroup.getResolver(service.getWorkerGroup().next())));
        } else {
            LOG.error("BUG! Connection Pool has already been created for proxy connection to {} state {} role {}",
                    remoteAddress, state, clientAuthRole);
        }

        LOG.info("[{}] complete connection, init proxy handler. authenticated with {} role {}, hasProxyToBrokerUrl: {}",
                remoteAddress, authMethod, clientAuthRole, hasProxyToBrokerUrl);
        if (hasProxyToBrokerUrl) {
            // Optimize proxy connection to fail-fast if the target broker isn't active
            // Pulsar client will retry connecting after a back off timeout
            if (service.getConfiguration().isCheckActiveBrokers()
                    && !isBrokerActive(proxyToBrokerUrl)) {
                state = State.Closing;
                LOG.warn("[{}] Target broker '{}' isn't available. authenticated with {} role {}.",
                        remoteAddress, proxyToBrokerUrl, authMethod, clientAuthRole);
                ctx()
                        .writeAndFlush(
                                Commands.newError(-1, ServerError.ServiceNotReady, "Target broker isn't available."))
                        .addListener(ChannelFutureListener.CLOSE);
                return;
            }

            state = State.ProxyConnectingToBroker;
            brokerProxyValidator.resolveAndCheckTargetAddress(proxyToBrokerUrl)
                    .thenAcceptAsync(this::connectToBroker, ctx.executor())
                    .exceptionally(throwable -> {
                        if (throwable instanceof TargetAddressDeniedException
                                || throwable.getCause() instanceof TargetAddressDeniedException) {
                            TargetAddressDeniedException targetAddressDeniedException =
                                    (TargetAddressDeniedException) (throwable instanceof TargetAddressDeniedException
                                            ? throwable : throwable.getCause());

                            LOG.warn("[{}] Target broker '{}' cannot be validated. {}. authenticated with {} role {}.",
                                    remoteAddress, proxyToBrokerUrl, targetAddressDeniedException.getMessage(),
                                    authMethod, clientAuthRole);
                        } else {
                            LOG.error("[{}] Error validating target broker '{}'. authenticated with {} role {}.",
                                    remoteAddress, proxyToBrokerUrl, authMethod, clientAuthRole, throwable);
                        }
                        ctx()
                                .writeAndFlush(
                                        Commands.newError(-1, ServerError.ServiceNotReady,
                                                "Target broker cannot be validated."))
                                .addListener(ChannelFutureListener.CLOSE);
                        return null;
                    });
        } else {
            // Client is doing a lookup, we can consider the handshake complete
            // and we'll take care of just topics and
            // partitions metadata lookups
            state = State.ProxyLookupRequests;
            lookupProxyHandler = new LookupProxyHandler(service, this);
            ctx.writeAndFlush(Commands.newConnected(protocolVersionToAdvertise, false))
                    .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
        }
    }

    private void handleBrokerConnected(DirectProxyHandler directProxyHandler, CommandConnected connected) {
        checkState(ctx.executor().inEventLoop(), "This method should be called in the event loop");
        if (state == State.ProxyConnectingToBroker && ctx.channel().isOpen() && this.directProxyHandler == null) {
            this.directProxyHandler = directProxyHandler;
            state = State.ProxyConnectionToBroker;
            int maxMessageSize =
                    connected.hasMaxMessageSize() ? connected.getMaxMessageSize() : Commands.INVALID_MAX_MESSAGE_SIZE;
            ctx.writeAndFlush(Commands.newConnected(connected.getProtocolVersion(), maxMessageSize,
                            connected.hasFeatureFlags() && connected.getFeatureFlags().isSupportsTopicWatchers()))
                    .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
        } else {
            LOG.warn("[{}] Channel is {}. ProxyConnection is in {}. "
                            + "Closing connection to broker '{}'.",
                    remoteAddress, ctx.channel().isOpen() ? "open" : "already closed",
                    state != State.ProxyConnectingToBroker ? "invalid state " + state : "state " + state,
                    proxyToBrokerUrl);
            directProxyHandler.close();
            ctx.close();
        }
    }

    private void connectToBroker(InetSocketAddress brokerAddress) {
        checkState(ctx.executor().inEventLoop(), "This method should be called in the event loop");
        DirectProxyHandler directProxyHandler = new DirectProxyHandler(service, this);
        directProxyHandler.connect(proxyToBrokerUrl, brokerAddress, protocolVersionToAdvertise);
    }

    public void brokerConnected(DirectProxyHandler directProxyHandler, CommandConnected connected) {
        try {
            final CommandConnected finalConnected = new CommandConnected().copyFrom(connected);
            ctx.executor().execute(() -> handleBrokerConnected(directProxyHandler, finalConnected));
        } catch (RejectedExecutionException e) {
            LOG.error("Event loop was already closed. Closing broker connection.", e);
            directProxyHandler.close();
        }
    }

    // According to auth result, send newConnected or newAuthChallenge command.
    private void doAuthentication(AuthData clientData)
            throws Exception {
        AuthData brokerData = authState.authenticate(clientData);
        // authentication has completed, will send newConnected command.
        if (authState.isComplete()) {
            clientAuthRole = authState.getAuthRole();
            if (LOG.isDebugEnabled()) {
                LOG.debug("[{}] Client successfully authenticated with {} role {}",
                        remoteAddress, authMethod, clientAuthRole);
            }

            // First connection
            if (this.connectionPool == null || state == State.Connecting) {
                // authentication has completed, will send newConnected command.
                completeConnect(clientData);
            }
            return;
        }

        // auth not complete, continue auth with client side.
        ctx.writeAndFlush(Commands.newAuthChallenge(authMethod, brokerData, protocolVersionToAdvertise))
                .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
        if (LOG.isDebugEnabled()) {
            LOG.debug("[{}] Authentication in progress client by method {}.",
                    remoteAddress, authMethod);
        }
        state = State.Connecting;
    }

    @Override
    protected void handleConnect(CommandConnect connect) {
        checkArgument(state == State.Init);
        this.setRemoteEndpointProtocolVersion(connect.getProtocolVersion());
        this.hasProxyToBrokerUrl = connect.hasProxyToBrokerUrl();
        this.protocolVersionToAdvertise = getProtocolVersionToAdvertise(connect);
        this.proxyToBrokerUrl = connect.hasProxyToBrokerUrl() ? connect.getProxyToBrokerUrl() : "null";

        if (LOG.isDebugEnabled()) {
            LOG.debug("Received CONNECT from {} proxyToBroker={}", remoteAddress, proxyToBrokerUrl);
            LOG.debug(
                "[{}] Protocol version to advertise to broker is {}, clientProtocolVersion={}, proxyProtocolVersion={}",
                remoteAddress, protocolVersionToAdvertise, getRemoteEndpointProtocolVersion(),
                Commands.getCurrentProtocolVersion());
        }

        if (getRemoteEndpointProtocolVersion() < ProtocolVersion.v10.getValue()) {
            LOG.warn("[{}] Client doesn't support connecting through proxy", remoteAddress);
            state = State.Closing;
            ctx.close();
            return;
        }

        try {
            // init authn
            this.clientConf = createClientConfiguration();

            // authn not enabled, complete
            if (!service.getConfiguration().isAuthenticationEnabled()) {
                completeConnect(null);
                return;
            }

            AuthData clientData = AuthData.of(connect.hasAuthData() ? connect.getAuthData() : EMPTY_CREDENTIALS);
            if (connect.hasAuthMethodName()) {
                authMethod = connect.getAuthMethodName();
            } else if (connect.hasAuthMethod()) {
                // Legacy client is passing enum
                authMethod = connect.getAuthMethod().name().substring(10).toLowerCase();
            } else {
                authMethod = "none";
            }

            authenticationProvider = service
                .getAuthenticationService()
                .getAuthenticationProvider(authMethod);

            // Not find provider named authMethod. Most used for tests.
            // In AuthenticationDisabled, it will set authMethod "none".
            if (authenticationProvider == null) {
                clientAuthRole = service.getAuthenticationService().getAnonymousUserRole()
                    .orElseThrow(() ->
                        new AuthenticationException("No anonymous role, and no authentication provider configured"));

                completeConnect(clientData);
                return;
            }

            // init authState and other var
            ChannelHandler sslHandler = ctx.channel().pipeline().get(PulsarChannelInitializer.TLS_HANDLER);
            SSLSession sslSession = null;
            if (sslHandler != null) {
                sslSession = ((SslHandler) sslHandler).engine().getSession();
            }

            authState = authenticationProvider.newAuthState(clientData, remoteAddress, sslSession);
            authenticationData = authState.getAuthDataSource();
            doAuthentication(clientData);
        } catch (Exception e) {
            LOG.warn("[{}] Unable to authenticate: ", remoteAddress, e);
            ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, "Failed to authenticate"))
                    .addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    protected void handleAuthResponse(CommandAuthResponse authResponse) {
        checkArgument(authResponse.hasResponse());
        checkArgument(authResponse.getResponse().hasAuthData() && authResponse.getResponse().hasAuthMethodName());

        if (LOG.isDebugEnabled()) {
            LOG.debug("Received AuthResponse from {}, auth method: {}",
                    remoteAddress, authResponse.getResponse().getAuthMethodName());
        }

        try {
            AuthData clientData = AuthData.of(authResponse.getResponse().getAuthData());
            doAuthentication(clientData);
            if (service.getConfiguration().isForwardAuthorizationCredentials()
                    && connectionPool != null && state == State.ProxyLookupRequests) {
                connectionPool.getConnections().forEach(toBrokerCnxFuture -> {
                    String clientVersion;
                    if (authResponse.hasClientVersion()) {
                        clientVersion = authResponse.getClientVersion();
                    } else {
                        clientVersion = PulsarVersion.getVersion();
                    }
                    int protocolVersion;
                    if (authResponse.hasProtocolVersion()) {
                        protocolVersion = authResponse.getProtocolVersion();
                    } else {
                        protocolVersion = Commands.getCurrentProtocolVersion();
                    }

                    ByteBuf cmd =
                            Commands.newAuthResponse(clientAuthMethod, clientData, protocolVersion, clientVersion);
                    toBrokerCnxFuture.thenAccept(toBrokerCnx -> toBrokerCnx.ctx().writeAndFlush(cmd)
                                    .addListener(writeFuture -> {
                                        if (writeFuture.isSuccess()) {
                                            if (LOG.isDebugEnabled()) {
                                                LOG.debug("{} authentication is refreshed successfully by {}, "
                                                                + "auth method: {} ",
                                                        toBrokerCnx.ctx().channel(), ctx.channel(), clientAuthMethod);
                                            }
                                        } else {
                                            LOG.error("Failed to forward the auth response "
                                                            + "from the proxy to the broker through the proxy client, "
                                                            + "proxy: {}, proxy client: {}",
                                                    ctx.channel(),
                                                    toBrokerCnx.ctx().channel(),
                                                    writeFuture.cause());
                                            toBrokerCnx.ctx().channel().pipeline()
                                                    .fireExceptionCaught(writeFuture.cause());
                                        }
                                    }))
                            .whenComplete((__, ex) -> {
                                if (ex != null) {
                                    LOG.error("Failed to forward the auth response from the proxy to "
                                                    + "the broker through the proxy client, proxy: {}",
                                            ctx().channel(), ex);
                                }
                            });
                });
            }
        } catch (Exception e) {
            String msg = "Unable to handleAuthResponse";
            LOG.warn("[{}] {} ", remoteAddress, msg, e);
            ctx.writeAndFlush(Commands.newError(-1, ServerError.AuthenticationError, msg))
                    .addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    protected void handlePartitionMetadataRequest(CommandPartitionedTopicMetadata partitionMetadata) {
        checkArgument(state == State.ProxyLookupRequests);

        lookupProxyHandler.handlePartitionMetadataResponse(partitionMetadata);
    }

    @Override
    protected void handleGetTopicsOfNamespace(CommandGetTopicsOfNamespace commandGetTopicsOfNamespace) {
        checkArgument(state == State.ProxyLookupRequests);

        lookupProxyHandler.handleGetTopicsOfNamespace(commandGetTopicsOfNamespace);
    }
    @Override
    protected void handleGetSchema(CommandGetSchema commandGetSchema) {
        checkArgument(state == State.ProxyLookupRequests);

        lookupProxyHandler.handleGetSchema(commandGetSchema);
    }

    /**
     * handles discovery request from client ands sends next active broker address.
     */
    @Override
    protected void handleLookup(CommandLookupTopic lookup) {
        checkArgument(state == State.ProxyLookupRequests);
        lookupProxyHandler.handleLookup(lookup);
    }

    ClientConfigurationData createClientConfiguration() {
        ClientConfigurationData initialConf = new ClientConfigurationData();
        ProxyConfiguration proxyConfig = service.getConfiguration();
        initialConf.setServiceUrl(
                proxyConfig.isTlsEnabledWithBroker() ? service.getServiceUrlTls() : service.getServiceUrl());

        // Apply all arbitrary configuration. This must be called before setting any fields annotated as
        // @Secret on the ClientConfigurationData object because of the way they are serialized.
        // See https://github.com/apache/pulsar/issues/8509 for more information.
        Map<String, Object> overrides = PropertiesUtils
                .filterAndMapProperties(proxyConfig.getProperties(), "brokerClient_");
        ClientConfigurationData clientConf = ConfigurationDataUtils
                .loadData(overrides, initialConf, ClientConfigurationData.class);
        /** The proxy service does not need to automatically clean up invalid connections, so set false. **/
        initialConf.setConnectionMaxIdleSeconds(-1);
        clientConf.setAuthentication(this.getClientAuthentication());
        if (proxyConfig.isTlsEnabledWithBroker()) {
            clientConf.setUseTls(true);
            clientConf.setTlsHostnameVerificationEnable(proxyConfig.isTlsHostnameVerificationEnabled());
            if (proxyConfig.isBrokerClientTlsEnabledWithKeyStore()) {
                clientConf.setUseKeyStoreTls(true);
                clientConf.setTlsTrustStoreType(proxyConfig.getBrokerClientTlsTrustStoreType());
                clientConf.setTlsTrustStorePath(proxyConfig.getBrokerClientTlsTrustStore());
                clientConf.setTlsTrustStorePassword(proxyConfig.getBrokerClientTlsTrustStorePassword());
                clientConf.setTlsKeyStoreType(proxyConfig.getBrokerClientTlsKeyStoreType());
                clientConf.setTlsKeyStorePath(proxyConfig.getBrokerClientTlsKeyStore());
                clientConf.setTlsKeyStorePassword(proxyConfig.getBrokerClientTlsKeyStorePassword());
            } else {
                clientConf.setTlsTrustCertsFilePath(proxyConfig.getBrokerClientTrustCertsFilePath());
                clientConf.setTlsKeyFilePath(proxyConfig.getBrokerClientKeyFilePath());
                clientConf.setTlsCertificateFilePath(proxyConfig.getBrokerClientCertificateFilePath());
            }
            clientConf.setTlsAllowInsecureConnection(proxyConfig.isTlsAllowInsecureConnection());
        }
        return clientConf;
    }

    private static int getProtocolVersionToAdvertise(CommandConnect connect) {
        return Math.min(connect.getProtocolVersion(), Commands.getCurrentProtocolVersion());
    }

    long newRequestId() {
        return requestIdGenerator.getAndIncrement();
    }

    public Authentication getClientAuthentication() {
        return service.getProxyClientAuthenticationPlugin();
    }

    @Override
    protected boolean isHandshakeCompleted() {
        return state != State.Init;
    }

    SocketAddress clientAddress() {
        return remoteAddress;
    }

    ChannelHandlerContext ctx() {
        return ctx;
    }

    public boolean hasHAProxyMessage() {
        return haProxyMessage != null;
    }

    public HAProxyMessage getHAProxyMessage() {
        return haProxyMessage;
    }

    private boolean isBrokerActive(String targetBrokerHostPort) {
        for (ServiceLookupData serviceLookupData : getAvailableBrokers()) {
            if (matchesHostAndPort("pulsar://", serviceLookupData.getPulsarServiceUrl(), targetBrokerHostPort)
                    || matchesHostAndPort("pulsar+ssl://", serviceLookupData.getPulsarServiceUrlTls(),
                    targetBrokerHostPort)) {
                return true;
            }
        }
        return false;
    }

    private List<? extends ServiceLookupData> getAvailableBrokers() {
        if (service.getDiscoveryProvider() == null) {
            LOG.warn("Unable to retrieve active brokers. service.getDiscoveryProvider() is null."
                    + "zookeeperServers and configurationStoreServers must be configured in proxy configuration "
                    + "when checkActiveBrokers is enabled.");
            return Collections.emptyList();
        }
        try {
            return service.getDiscoveryProvider().getAvailableBrokers();
        } catch (PulsarServerException e) {
            LOG.error("Unable to get available brokers", e);
            return Collections.emptyList();
        }
    }

    static boolean matchesHostAndPort(String expectedPrefix, String pulsarServiceUrl, String brokerHostPort) {
        return pulsarServiceUrl != null
                && pulsarServiceUrl.length() == expectedPrefix.length() + brokerHostPort.length()
                && pulsarServiceUrl.startsWith(expectedPrefix)
                && pulsarServiceUrl.startsWith(brokerHostPort, expectedPrefix.length());
    }
}


text:
namespace WorkflowAuthoring
{
    using System;
    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Workflow.ComponentModel.Design;
    using System.Workflow.ComponentModel;
    using System.Workflow.ComponentModel.Serialization;
    using System.Workflow.ComponentModel.Compiler;
    using System.Drawing;
    using System.Collections;
    using System.Workflow.Activities;
    using System.Workflow.Runtime;

    public partial class ITSMSoftwareScheduleSync : System.Workflow.Activities.SequentialWorkflowActivity
    {
    }
}


text:
package no.kino.command;

import no.kino.projections.ForestillingProjeksjon;
import no.kino.spring.SpringTestContext;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CommandHandlerIntegrasjonsTest extends SpringTestContext {
    private final String FORESTILLING = "Naboer";
    private ForestillingProjeksjon projeksjon = null;
    KinoCommandHandler commandHandler = null;

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        commandHandler = ctx.getBean(KinoCommandHandler.class);
        projeksjon = ctx.getBean(ForestillingProjeksjon.class);
    }

    @Test
    public void testAtOpprettForestillingGirRiktigAntallSeter() throws Exception {
        commandHandler.handle(new OpprettNyForestilling(FORESTILLING,100));
        Assert.assertEquals(100, projeksjon.antallLedigeSeter(FORESTILLING).intValue());
    }

    @Test
    public void testAtReserverSeterGirRiktigAntallSeter() throws Exception {
        commandHandler.handle(new OpprettNyForestilling(FORESTILLING,100));
        commandHandler.handle(new ReserverSeter(FORESTILLING,2));
        Assert.assertEquals(98, projeksjon.antallLedigeSeter(FORESTILLING).intValue());
    }
}


text:
@interface ZonesTableViewController : UITableViewController

@property (nonatomic) NSInteger activityId;

@end


text:
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.Contents;
using OrchardCore.Mvc.Utilities;

namespace OrchardCore.Content.Controllers
{
    [Route("api/content")]
    [ApiController]
    [Authorize(AuthenticationSchemes = "Api"), IgnoreAntiforgeryToken, AllowAnonymous]
    public class ApiController : Controller
    {
        private static readonly JsonMergeSettings UpdateJsonMergeSettings = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace };

        private readonly IContentManager _contentManager;
        private readonly IAuthorizationService _authorizationService;
        private readonly IStringLocalizer S;

        public ApiController(
            IContentManager contentManager,
            IAuthorizationService authorizationService,
            IStringLocalizer<ApiController> stringLocalizer)
        {
            _authorizationService = authorizationService;
            _contentManager = contentManager;
            S = stringLocalizer;
        }

        [Route("{contentItemId}"), HttpGet]
        public async Task<IActionResult> Get(string contentItemId)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.AccessContentApi))
            {
                return this.ChallengeOrForbid();
            }

            var contentItem = await _contentManager.GetAsync(contentItemId);

            if (contentItem == null)
            {
                return NotFound();
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContent, contentItem))
            {
                return this.ChallengeOrForbid();
            }

            return Ok(contentItem);
        }

        [HttpDelete]
        [Route("{contentItemId}")]
        public async Task<IActionResult> Delete(string contentItemId)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.AccessContentApi))
            {
                return this.ChallengeOrForbid();
            }

            var contentItem = await _contentManager.GetAsync(contentItemId);

            if (contentItem == null)
            {
                return StatusCode(204);
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.DeleteContent, contentItem))
            {
                return this.ChallengeOrForbid();
            }

            await _contentManager.RemoveAsync(contentItem);

            return Ok(contentItem);
        }

        [HttpPost]
        public async Task<IActionResult> Post(ContentItem model, bool draft = false)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.AccessContentApi))
            {
                return this.ChallengeOrForbid();
            }

            // It is really important to keep the proper method calls order with the ContentManager
            // so that all event handlers gets triggered in the right sequence.

            var contentItem = await _contentManager.GetAsync(model.ContentItemId, VersionOptions.DraftRequired);

            if (contentItem == null)
            {
                if (!await _authorizationService.AuthorizeAsync(User, Permissions.PublishContent))
                {
                    return this.ChallengeOrForbid();
                }

                var newContentItem = await _contentManager.NewAsync(model.ContentType);
                newContentItem.Merge(model);

                var result = await _contentManager.UpdateValidateAndCreateAsync(newContentItem, draft ? VersionOptions.DraftRequired : VersionOptions.Published);
                if (result.Succeeded)
                {
                    contentItem = newContentItem;
                }
                else
                {
                    return Problem(
                        title: S["One or more validation errors occurred."],
                        detail: string.Join(',', result.Errors),
                        statusCode: (int)HttpStatusCode.BadRequest);
                }
            }
            else
            {
                if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, contentItem))
                {
                    return this.ChallengeOrForbid();
                }

                contentItem.Merge(model, UpdateJsonMergeSettings);

                await _contentManager.UpdateAsync(contentItem);
                var result = await _contentManager.ValidateAsync(contentItem);

                if (result.Succeeded)
                {
                    if (!draft)
                    {
                        await _contentManager.PublishAsync(contentItem);
                    }
                }
                else
                {
                    return Problem(
                        title: S["One or more validation errors occurred."],
                        detail: string.Join(',', result.Errors),
                        statusCode: (int)HttpStatusCode.BadRequest);
                }
            }

            return Ok(contentItem);
        }
    }
}


text:
declare module 'lookup-dns-cache' {
	import { LookupOneOptions, LookupAllOptions, LookupOptions, LookupAddress } from 'dns';

	function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
	function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
	function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void;
	function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void;
	function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void;
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/tinderbox/XR-Trunk/WINNT_5.2_Depend/mozilla/layout/xul/base/src/tree/public/nsITreeSelection.idl
 */

#ifndef __gen_nsITreeSelection_h__
#define __gen_nsITreeSelection_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsITreeBoxObject; /* forward declaration */

class nsITreeColumn; /* forward declaration */

/* starting interface:    nsITreeSelection */
#define NS_ITREESELECTION_IID_STR "ab6fe746-300b-4ab4-abb9-1c0e3977874c"

#define NS_ITREESELECTION_IID \
  {0xab6fe746, 0x300b, 0x4ab4, \
    { 0xab, 0xb9, 0x1c, 0x0e, 0x39, 0x77, 0x87, 0x4c }}

class NS_NO_VTABLE NS_SCRIPTABLE nsITreeSelection : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_ITREESELECTION_IID)

  /**
   * The tree widget for this selection.
   */
  /* attribute nsITreeBoxObject tree; */
  NS_SCRIPTABLE NS_IMETHOD GetTree(nsITreeBoxObject * *aTree) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetTree(nsITreeBoxObject * aTree) = 0;

  /**
   * This attribute is a boolean indicating single selection.
   */
  /* readonly attribute boolean single; */
  NS_SCRIPTABLE NS_IMETHOD GetSingle(PRBool *aSingle) = 0;

  /**
   * The number of rows currently selected in this tree.
   */
  /* readonly attribute long count; */
  NS_SCRIPTABLE NS_IMETHOD GetCount(PRInt32 *aCount) = 0;

  /**
   * Indicates whether or not the row at the specified index is
   * part of the selection.
   */
  /* boolean isSelected (in long index); */
  NS_SCRIPTABLE NS_IMETHOD IsSelected(PRInt32 index, PRBool *_retval) = 0;

  /**
   * Deselect all rows and select the row at the specified index.
   */
  /* void select (in long index); */
  NS_SCRIPTABLE NS_IMETHOD Select(PRInt32 index) = 0;

  /**
   * Perform a timed select.
   */
  /* void timedSelect (in long index, in long delay); */
  NS_SCRIPTABLE NS_IMETHOD TimedSelect(PRInt32 index, PRInt32 delay) = 0;

  /**
   * Toggle the selection state of the row at the specified index.
   */
  /* void toggleSelect (in long index); */
  NS_SCRIPTABLE NS_IMETHOD ToggleSelect(PRInt32 index) = 0;

  /**
   * Select the range specified by the indices.  If augment is true,
   * then we add the range to the selection without clearing out anything
   * else.  If augment is false, everything is cleared except for the specified range.
   */
  /* void rangedSelect (in long startIndex, in long endIndex, in boolean augment); */
  NS_SCRIPTABLE NS_IMETHOD RangedSelect(PRInt32 startIndex, PRInt32 endIndex, PRBool augment) = 0;

  /**
   * Clears the range.
   */
  /* void clearRange (in long startIndex, in long endIndex); */
  NS_SCRIPTABLE NS_IMETHOD ClearRange(PRInt32 startIndex, PRInt32 endIndex) = 0;

  /**
   * Clears the selection.
   */
  /* void clearSelection (); */
  NS_SCRIPTABLE NS_IMETHOD ClearSelection(void) = 0;

  /**
   * Inverts the selection.
   */
  /* void invertSelection (); */
  NS_SCRIPTABLE NS_IMETHOD InvertSelection(void) = 0;

  /**
   * Selects all rows.
   */
  /* void selectAll (); */
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void) = 0;

  /**
   * Iterate the selection using these methods.
   */
  /* long getRangeCount (); */
  NS_SCRIPTABLE NS_IMETHOD GetRangeCount(PRInt32 *_retval) = 0;

  /* void getRangeAt (in long i, out long min, out long max); */
  NS_SCRIPTABLE NS_IMETHOD GetRangeAt(PRInt32 i, PRInt32 *min, PRInt32 *max) = 0;

  /**
   * Can be used to invalidate the selection.
   */
  /* void invalidateSelection (); */
  NS_SCRIPTABLE NS_IMETHOD InvalidateSelection(void) = 0;

  /**
   * Called when the row count changes to adjust selection indices.
   */
  /* void adjustSelection (in long index, in long count); */
  NS_SCRIPTABLE NS_IMETHOD AdjustSelection(PRInt32 index, PRInt32 count) = 0;

  /**
   * This attribute is a boolean indicating whether or not the
   * "select" event should fire when the selection is changed using
   * one of our methods.  A view can use this to temporarily suppress
   * the selection while manipulating all of the indices, e.g., on
   * a sort.
   */
  /* attribute boolean selectEventsSuppressed; */
  NS_SCRIPTABLE NS_IMETHOD GetSelectEventsSuppressed(PRBool *aSelectEventsSuppressed) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetSelectEventsSuppressed(PRBool aSelectEventsSuppressed) = 0;

  /**
   * The current item (the one that gets a focus rect in addition to being
   * selected).
   */
  /* attribute long currentIndex; */
  NS_SCRIPTABLE NS_IMETHOD GetCurrentIndex(PRInt32 *aCurrentIndex) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetCurrentIndex(PRInt32 aCurrentIndex) = 0;

  /**
   * The current column.
   */
  /* attribute nsITreeColumn currentColumn; */
  NS_SCRIPTABLE NS_IMETHOD GetCurrentColumn(nsITreeColumn * *aCurrentColumn) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetCurrentColumn(nsITreeColumn * aCurrentColumn) = 0;

  /**
   * The selection "pivot".  This is the first item the user selected as
   * part of a ranged select.
   */
  /* readonly attribute long shiftSelectPivot; */
  NS_SCRIPTABLE NS_IMETHOD GetShiftSelectPivot(PRInt32 *aShiftSelectPivot) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsITreeSelection, NS_ITREESELECTION_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSITREESELECTION \
  NS_SCRIPTABLE NS_IMETHOD GetTree(nsITreeBoxObject * *aTree); \
  NS_SCRIPTABLE NS_IMETHOD SetTree(nsITreeBoxObject * aTree); \
  NS_SCRIPTABLE NS_IMETHOD GetSingle(PRBool *aSingle); \
  NS_SCRIPTABLE NS_IMETHOD GetCount(PRInt32 *aCount); \
  NS_SCRIPTABLE NS_IMETHOD IsSelected(PRInt32 index, PRBool *_retval); \
  NS_SCRIPTABLE NS_IMETHOD Select(PRInt32 index); \
  NS_SCRIPTABLE NS_IMETHOD TimedSelect(PRInt32 index, PRInt32 delay); \
  NS_SCRIPTABLE NS_IMETHOD ToggleSelect(PRInt32 index); \
  NS_SCRIPTABLE NS_IMETHOD RangedSelect(PRInt32 startIndex, PRInt32 endIndex, PRBool augment); \
  NS_SCRIPTABLE NS_IMETHOD ClearRange(PRInt32 startIndex, PRInt32 endIndex); \
  NS_SCRIPTABLE NS_IMETHOD ClearSelection(void); \
  NS_SCRIPTABLE NS_IMETHOD InvertSelection(void); \
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void); \
  NS_SCRIPTABLE NS_IMETHOD GetRangeCount(PRInt32 *_retval); \
  NS_SCRIPTABLE NS_IMETHOD GetRangeAt(PRInt32 i, PRInt32 *min, PRInt32 *max); \
  NS_SCRIPTABLE NS_IMETHOD InvalidateSelection(void); \
  NS_SCRIPTABLE NS_IMETHOD AdjustSelection(PRInt32 index, PRInt32 count); \
  NS_SCRIPTABLE NS_IMETHOD GetSelectEventsSuppressed(PRBool *aSelectEventsSuppressed); \
  NS_SCRIPTABLE NS_IMETHOD SetSelectEventsSuppressed(PRBool aSelectEventsSuppressed); \
  NS_SCRIPTABLE NS_IMETHOD GetCurrentIndex(PRInt32 *aCurrentIndex); \
  NS_SCRIPTABLE NS_IMETHOD SetCurrentIndex(PRInt32 aCurrentIndex); \
  NS_SCRIPTABLE NS_IMETHOD GetCurrentColumn(nsITreeColumn * *aCurrentColumn); \
  NS_SCRIPTABLE NS_IMETHOD SetCurrentColumn(nsITreeColumn * aCurrentColumn); \
  NS_SCRIPTABLE NS_IMETHOD GetShiftSelectPivot(PRInt32 *aShiftSelectPivot);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSITREESELECTION(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetTree(nsITreeBoxObject * *aTree) { return _to GetTree(aTree); } \
  NS_SCRIPTABLE NS_IMETHOD SetTree(nsITreeBoxObject * aTree) { return _to SetTree(aTree); } \
  NS_SCRIPTABLE NS_IMETHOD GetSingle(PRBool *aSingle) { return _to GetSingle(aSingle); } \
  NS_SCRIPTABLE NS_IMETHOD GetCount(PRInt32 *aCount) { return _to GetCount(aCount); } \
  NS_SCRIPTABLE NS_IMETHOD IsSelected(PRInt32 index, PRBool *_retval) { return _to IsSelected(index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD Select(PRInt32 index) { return _to Select(index); } \
  NS_SCRIPTABLE NS_IMETHOD TimedSelect(PRInt32 index, PRInt32 delay) { return _to TimedSelect(index, delay); } \
  NS_SCRIPTABLE NS_IMETHOD ToggleSelect(PRInt32 index) { return _to ToggleSelect(index); } \
  NS_SCRIPTABLE NS_IMETHOD RangedSelect(PRInt32 startIndex, PRInt32 endIndex, PRBool augment) { return _to RangedSelect(startIndex, endIndex, augment); } \
  NS_SCRIPTABLE NS_IMETHOD ClearRange(PRInt32 startIndex, PRInt32 endIndex) { return _to ClearRange(startIndex, endIndex); } \
  NS_SCRIPTABLE NS_IMETHOD ClearSelection(void) { return _to ClearSelection(); } \
  NS_SCRIPTABLE NS_IMETHOD InvertSelection(void) { return _to InvertSelection(); } \
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void) { return _to SelectAll(); } \
  NS_SCRIPTABLE NS_IMETHOD GetRangeCount(PRInt32 *_retval) { return _to GetRangeCount(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetRangeAt(PRInt32 i, PRInt32 *min, PRInt32 *max) { return _to GetRangeAt(i, min, max); } \
  NS_SCRIPTABLE NS_IMETHOD InvalidateSelection(void) { return _to InvalidateSelection(); } \
  NS_SCRIPTABLE NS_IMETHOD AdjustSelection(PRInt32 index, PRInt32 count) { return _to AdjustSelection(index, count); } \
  NS_SCRIPTABLE NS_IMETHOD GetSelectEventsSuppressed(PRBool *aSelectEventsSuppressed) { return _to GetSelectEventsSuppressed(aSelectEventsSuppressed); } \
  NS_SCRIPTABLE NS_IMETHOD SetSelectEventsSuppressed(PRBool aSelectEventsSuppressed) { return _to SetSelectEventsSuppressed(aSelectEventsSuppressed); } \
  NS_SCRIPTABLE NS_IMETHOD GetCurrentIndex(PRInt32 *aCurrentIndex) { return _to GetCurrentIndex(aCurrentIndex); } \
  NS_SCRIPTABLE NS_IMETHOD SetCurrentIndex(PRInt32 aCurrentIndex) { return _to SetCurrentIndex(aCurrentIndex); } \
  NS_SCRIPTABLE NS_IMETHOD GetCurrentColumn(nsITreeColumn * *aCurrentColumn) { return _to GetCurrentColumn(aCurrentColumn); } \
  NS_SCRIPTABLE NS_IMETHOD SetCurrentColumn(nsITreeColumn * aCurrentColumn) { return _to SetCurrentColumn(aCurrentColumn); } \
  NS_SCRIPTABLE NS_IMETHOD GetShiftSelectPivot(PRInt32 *aShiftSelectPivot) { return _to GetShiftSelectPivot(aShiftSelectPivot); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSITREESELECTION(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetTree(nsITreeBoxObject * *aTree) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTree(aTree); } \
  NS_SCRIPTABLE NS_IMETHOD SetTree(nsITreeBoxObject * aTree) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetTree(aTree); } \
  NS_SCRIPTABLE NS_IMETHOD GetSingle(PRBool *aSingle) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSingle(aSingle); } \
  NS_SCRIPTABLE NS_IMETHOD GetCount(PRInt32 *aCount) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCount(aCount); } \
  NS_SCRIPTABLE NS_IMETHOD IsSelected(PRInt32 index, PRBool *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->IsSelected(index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD Select(PRInt32 index) { return !_to ? NS_ERROR_NULL_POINTER : _to->Select(index); } \
  NS_SCRIPTABLE NS_IMETHOD TimedSelect(PRInt32 index, PRInt32 delay) { return !_to ? NS_ERROR_NULL_POINTER : _to->TimedSelect(index, delay); } \
  NS_SCRIPTABLE NS_IMETHOD ToggleSelect(PRInt32 index) { return !_to ? NS_ERROR_NULL_POINTER : _to->ToggleSelect(index); } \
  NS_SCRIPTABLE NS_IMETHOD RangedSelect(PRInt32 startIndex, PRInt32 endIndex, PRBool augment) { return !_to ? NS_ERROR_NULL_POINTER : _to->RangedSelect(startIndex, endIndex, augment); } \
  NS_SCRIPTABLE NS_IMETHOD ClearRange(PRInt32 startIndex, PRInt32 endIndex) { return !_to ? NS_ERROR_NULL_POINTER : _to->ClearRange(startIndex, endIndex); } \
  NS_SCRIPTABLE NS_IMETHOD ClearSelection(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->ClearSelection(); } \
  NS_SCRIPTABLE NS_IMETHOD InvertSelection(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->InvertSelection(); } \
  NS_SCRIPTABLE NS_IMETHOD SelectAll(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->SelectAll(); } \
  NS_SCRIPTABLE NS_IMETHOD GetRangeCount(PRInt32 *_retval) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRangeCount(_retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetRangeAt(PRInt32 i, PRInt32 *min, PRInt32 *max) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetRangeAt(i, min, max); } \
  NS_SCRIPTABLE NS_IMETHOD InvalidateSelection(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->InvalidateSelection(); } \
  NS_SCRIPTABLE NS_IMETHOD AdjustSelection(PRInt32 index, PRInt32 count) { return !_to ? NS_ERROR_NULL_POINTER : _to->AdjustSelection(index, count); } \
  NS_SCRIPTABLE NS_IMETHOD GetSelectEventsSuppressed(PRBool *aSelectEventsSuppressed) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSelectEventsSuppressed(aSelectEventsSuppressed); } \
  NS_SCRIPTABLE NS_IMETHOD SetSelectEventsSuppressed(PRBool aSelectEventsSuppressed) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetSelectEventsSuppressed(aSelectEventsSuppressed); } \
  NS_SCRIPTABLE NS_IMETHOD GetCurrentIndex(PRInt32 *aCurrentIndex) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCurrentIndex(aCurrentIndex); } \
  NS_SCRIPTABLE NS_IMETHOD SetCurrentIndex(PRInt32 aCurrentIndex) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCurrentIndex(aCurrentIndex); } \
  NS_SCRIPTABLE NS_IMETHOD GetCurrentColumn(nsITreeColumn * *aCurrentColumn) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCurrentColumn(aCurrentColumn); } \
  NS_SCRIPTABLE NS_IMETHOD SetCurrentColumn(nsITreeColumn * aCurrentColumn) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetCurrentColumn(aCurrentColumn); } \
  NS_SCRIPTABLE NS_IMETHOD GetShiftSelectPivot(PRInt32 *aShiftSelectPivot) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetShiftSelectPivot(aShiftSelectPivot); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsTreeSelection : public nsITreeSelection
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSITREESELECTION

  nsTreeSelection();

private:
  ~nsTreeSelection();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsTreeSelection, nsITreeSelection)

nsTreeSelection::nsTreeSelection()
{
  /* member initializers and constructor code */
}

nsTreeSelection::~nsTreeSelection()
{
  /* destructor code */
}

/* attribute nsITreeBoxObject tree; */
NS_IMETHODIMP nsTreeSelection::GetTree(nsITreeBoxObject * *aTree)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTreeSelection::SetTree(nsITreeBoxObject * aTree)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute boolean single; */
NS_IMETHODIMP nsTreeSelection::GetSingle(PRBool *aSingle)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute long count; */
NS_IMETHODIMP nsTreeSelection::GetCount(PRInt32 *aCount)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* boolean isSelected (in long index); */
NS_IMETHODIMP nsTreeSelection::IsSelected(PRInt32 index, PRBool *_retval)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void select (in long index); */
NS_IMETHODIMP nsTreeSelection::Select(PRInt32 index)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void timedSelect (in long index, in long delay); */
NS_IMETHODIMP nsTreeSelection::TimedSelect(PRInt32 index, PRInt32 delay)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void toggleSelect (in long index); */
NS_IMETHODIMP nsTreeSelection::ToggleSelect(PRInt32 index)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void rangedSelect (in long startIndex, in long endIndex, in boolean augment); */
NS_IMETHODIMP nsTreeSelection::RangedSelect(PRInt32 startIndex, PRInt32 endIndex, PRBool augment)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void clearRange (in long startIndex, in long endIndex); */
NS_IMETHODIMP nsTreeSelection::ClearRange(PRInt32 startIndex, PRInt32 endIndex)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void clearSelection (); */
NS_IMETHODIMP nsTreeSelection::ClearSelection()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void invertSelection (); */
NS_IMETHODIMP nsTreeSelection::InvertSelection()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void selectAll (); */
NS_IMETHODIMP nsTreeSelection::SelectAll()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* long getRangeCount (); */
NS_IMETHODIMP nsTreeSelection::GetRangeCount(PRInt32 *_retval)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void getRangeAt (in long i, out long min, out long max); */
NS_IMETHODIMP nsTreeSelection::GetRangeAt(PRInt32 i, PRInt32 *min, PRInt32 *max)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void invalidateSelection (); */
NS_IMETHODIMP nsTreeSelection::InvalidateSelection()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void adjustSelection (in long index, in long count); */
NS_IMETHODIMP nsTreeSelection::AdjustSelection(PRInt32 index, PRInt32 count)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute boolean selectEventsSuppressed; */
NS_IMETHODIMP nsTreeSelection::GetSelectEventsSuppressed(PRBool *aSelectEventsSuppressed)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTreeSelection::SetSelectEventsSuppressed(PRBool aSelectEventsSuppressed)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute long currentIndex; */
NS_IMETHODIMP nsTreeSelection::GetCurrentIndex(PRInt32 *aCurrentIndex)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTreeSelection::SetCurrentIndex(PRInt32 aCurrentIndex)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* attribute nsITreeColumn currentColumn; */
NS_IMETHODIMP nsTreeSelection::GetCurrentColumn(nsITreeColumn * *aCurrentColumn)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsTreeSelection::SetCurrentColumn(nsITreeColumn * aCurrentColumn)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* readonly attribute long shiftSelectPivot; */
NS_IMETHODIMP nsTreeSelection::GetShiftSelectPivot(PRInt32 *aShiftSelectPivot)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsITreeSelection_h__ */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mikity;
using mikity.LinearAlgebra;
using Grasshopper.Kernel.Data;
using Grasshopper.Kernel.Types;
using mikity.NumericalMethodHelper;
using mikity.NumericalMethodHelper.elements;
using mikity.NumericalMethodHelper.objects;
using mikity.NumericalMethodHelper.materials;
namespace mikity.ghComponents
{
    /// <summary>
    /// Construct a point array using isoparametric shape functions.
    /// </summary>
    public class node_pairs_bar : Grasshopper.Kernel.GH_Component
    {
        protected override System.Drawing.Bitmap Icon
        {
            get
            {
                //現在のコードを実行しているAssemblyを取得
                System.Reflection.Assembly myAssembly =
                    System.Reflection.Assembly.GetExecutingAssembly();

                System.IO.Stream st = myAssembly.GetManifestResourceStream("mikity.ghComponents.icons.node-pairs-rigid-bars.bmp");
                //指定されたマニフェストリソースを読み込む
                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(st);
                return bmp;
            }
        }

        public node_pairs_bar()
            : base("nodePairs->rigidBars [Constraint Condition]", "nodePairs->rigidBars", "nodePairs->rigidBars (Constraint conditions)", "Ricecooker", "Convenience store")
        {
        }
        protected override void RegisterInputParams(Grasshopper.Kernel.GH_Component.GH_InputParamManager pManager)
        {
            pManager.AddPointParameter("PointList1", "listP1", "First point list", Grasshopper.Kernel.GH_ParamAccess.list);
            pManager.AddPointParameter("PointList2", "listP2", "Second point list", Grasshopper.Kernel.GH_ParamAccess.list);
            pManager.AddNumberParameter("Length", "L", "Prescribed value for the length", Grasshopper.Kernel.GH_ParamAccess.item);
        }

        protected override void RegisterOutputParams(Grasshopper.Kernel.GH_Component.GH_OutputParamManager pManager)
        {
            pManager.AddGenericParameter("Particle System", "pS", "Particle System", Grasshopper.Kernel.GH_ParamAccess.item);
        }
        public override void BakeGeometry(Rhino.RhinoDoc doc, Rhino.DocObjects.ObjectAttributes att, List<Guid> obj_ids)
        {
            if (this.BKGT != null)
            {
                this.BKGT(doc, att, obj_ids);
            }
            base.BakeGeometry(doc, att, obj_ids);
        }

        public override void DrawViewportWires(Grasshopper.Kernel.IGH_PreviewArgs args)
        {
            if (this.DVPW != null)
            {
                this.DVPW(args);
            }
            base.DrawViewportWires(args);
        }
        private const int _dim = 1;
        int nNewNodes = 0;
        int nElements = 0;
        GH_particleSystem pS;
        DrawViewPortWire DVPW = null;
        BakeGeometry BKGT = null;
        List<mikity.NumericalMethodHelper.objects.constrainVolumeObject> lCV=new List<constrainVolumeObject>();
        List<Rhino.Geometry.Line> lGeometry = new List<Rhino.Geometry.Line>();
        List<Rhino.Geometry.Line> lGeometry2 = new List<Rhino.Geometry.Line>();
        protected override void SolveInstance(Grasshopper.Kernel.IGH_DataAccess DA)
        {
            double v = -1.0;
            DA.GetData(2, ref v);
            if (!FriedChiken.isInitialized)
            {

                List<GH_Point> pointList1 = new List<GH_Point>();
                List<GH_Point> pointList2 = new List<GH_Point>();
                List<GH_Point> tmpPointList = new List<GH_Point>();
                if (!DA.GetDataList(0, pointList1)) return;
                if (!DA.GetDataList(1, pointList2)) return;
                if (pointList1.Count != pointList2.Count)
                {
                    AddRuntimeMessage(Grasshopper.Kernel.GH_RuntimeMessageLevel.Error, "The first and second lists must have the same elements");
                    return;
                }
                tmpPointList.AddRange(pointList1);
                tmpPointList.AddRange(pointList2);
                nNewNodes = tmpPointList.Count();
                nElements = pointList1.Count();
                lCV.Clear();
                mikity.NumericalMethodHelper.particle[] particles = new mikity.NumericalMethodHelper.particle[nNewNodes];
                for (int i = 0; i < nNewNodes; i++)
                {
                    particles[i] = new particle(tmpPointList[i].Value.X, tmpPointList[i].Value.Y, tmpPointList[i].Value.Z);
                }
                pS = new GH_particleSystem(particles);
                for (int i = 0; i < nElements; i++)
                {
                    lCV.Add(new constrainVolumeObject(v));
                    lCV[i].addElement(new isoparametricElement(i,i+nElements));
                }
                pS.Value.addObjects(lCV.ToArray());
                lGeometry.Clear();
                for (int i = 0; i < nElements; i++)
                {
                    lGeometry.Add(new Rhino.Geometry.Line(pS.Value.particles[i, 0], pS.Value.particles[i, 1], pS.Value.particles[i, 2], pS.Value.particles[i+nElements, 0], pS.Value.particles[i+nElements, 1], pS.Value.particles[i+nElements, 2]));
                }
             }
            else
            {
                if (lCV != null)
                {
                    if (v > 0)
                    {
                        for (int i = 0; i < nElements; i++)
                        {
                            lCV[i].refVolume = v;
                        }
                    }
                }
            }
            this.DVPW = GetDVPW(lGeometry);
            this.BKGT = GetBKGT(lGeometry);
            pS.DVPW = GetDVPW(lGeometry2);
            pS.UPGR = GetUPGR(lGeometry2);
            pS.BKGT = GetBKGT(lGeometry2);
            DA.SetData(0, pS);
        }
        public BakeGeometry GetBKGT(List<Rhino.Geometry.Line> m)
        {
            return new BakeGeometry((d, a, o) =>
            {
                Rhino.DocObjects.ObjectAttributes a2 = a.Duplicate();
                a2.LayerIndex = 4;
                foreach (Rhino.Geometry.Line l in m)
                {
                    o.Add(d.Objects.AddLine(l, a2));
                }
            });
        }

        public UpdateGeometry GetUPGR(List<Rhino.Geometry.Line> m)
        {
            return new UpdateGeometry((x, y, z) =>
            {
                m.Clear();
                for (int i = 0; i < nElements; i++)
                {
                    m.Add(new Rhino.Geometry.Line(pS.Value.particles[i, 0] + x, pS.Value.particles[i, 1] + y, pS.Value.particles[i, 2] + z, pS.Value.particles[i + nElements, 0] + x, pS.Value.particles[i + nElements, 1] + y, pS.Value.particles[i + nElements, 2] + z));
                }
            });
        }
        public DrawViewPortWire GetDVPW(List<Rhino.Geometry.Line> m)
        {
            return new DrawViewPortWire((args) =>
            {
                if (Hidden)
                {
                    return;
                }
                if (this.Attributes.Selected)
                {
                    args.Display.DrawLines(m, System.Drawing.Color.Red, 3);
                }
                else
                {
                    args.Display.DrawLines(m, System.Drawing.Color.Blue, 3);
                }

            });
        }
        public override Guid ComponentGuid
        {
            get { return new Guid("609cf721-4669-4cb6-9c77-5d333cbe1a80"); }
        }

    }
}


text:
package org.apache.maven.api.services;

import org.apache.maven.api.annotations.Experimental;

/**
 * The Exception class throw by the {@link ToolchainsBuilder}.
 *
 * @since 4.0
 */
@Experimental
public class ToolchainsBuilderException extends MavenException {
    /**
     * @param message the message to give
     * @param e the {@link Exception}
     */
    public ToolchainsBuilderException(String message, Exception e) {
        super(message, e);
    }

    // TODO: add ToolchainsBuilderResult
}


text:
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.collide.client.code;

import com.google.collide.client.AppContext;
import com.google.collide.client.code.FileSelectedPlace.NavigationEvent;
import com.google.collide.client.history.PlaceNavigationHandler;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;

/**
 * {@link PlaceNavigationHandler} responsible for handling the selection of files.
 */
public class FileSelectedPlaceNavigationHandler
    extends PlaceNavigationHandler<FileSelectedPlace.NavigationEvent> {

  private final AppContext appContext;
  private final FileSelectionController fileSelectionController;
  private final EditableContentArea contentArea;

  public FileSelectedPlaceNavigationHandler(AppContext appContext,
      CodePerspective codePerspective,
      FileSelectionController fileSelectionController,
      EditableContentArea contentArea) {
    this.appContext = appContext;
    this.fileSelectionController = fileSelectionController;
    this.contentArea = contentArea;
  }

  @Override
  public void cleanup() {
    contentArea.getEditorToolBar().hide();
  }

  @Override
  protected void enterPlace(final NavigationEvent navigationEvent) {
    contentArea.getEditorToolBar().show();
    selectFile(navigationEvent);
  }

  @Override
  protected void reEnterPlace(final NavigationEvent navigationEvent, boolean hasNewState) {
    if (!hasNewState && !navigationEvent.shouldForceReload()) {

      // Nothing to do.
      return;
    }

    selectFile(navigationEvent);
  }

  private void selectFile(final NavigationEvent navigationEvent) {
    /*
     * The navigation event will not be active until all handlers have been called, so wait until
     * the end of the event loop for the navigation event to become active.
     */
    Scheduler.get().scheduleFinally(new ScheduledCommand() {
      @Override
      public void execute() {
        if (navigationEvent.isActiveLeaf()) {
          fileSelectionController.selectFile(navigationEvent);
          contentArea.getEditorToolBar().setCurrentPath(navigationEvent.getPath(),
              fileSelectionController.getFileTreeModel().getLastAppliedTreeMutationRevision());
        }
      }
    });
  }
}