text:
source("dataS/scripts/vehicles/specializations/SetTurnedOnEvent.lua");
WaterCannon = {};

function WaterCannon.prerequisitesPresent(specializations)
	if not SpecializationUtil.hasSpecialization(Fillable, specializations) then
		print("Warning: Specialization WaterCannon needs the specialization Fillable.");
	end;
	if not SpecializationUtil.hasSpecialization(WaterTrailer, specializations) then
		print("Warning: Specialization WaterCannon needs the specialization WaterTrailer.");
	end;
	if not SpecializationUtil.hasSpecialization(Pump, specializations) then
		print("Warning: Specialization WaterCannon needs the specialization Pump.");
	end;

	return SpecializationUtil.hasSpecialization(Fillable, specializations) and SpecializationUtil.hasSpecialization(WaterTrailer, specializations) and SpecializationUtil.hasSpecialization(Pump, specializations);
end;

function WaterCannon:load(xmlFile)

	assert(self.setIsTurnedOn == nil, "WaterCannon needs to be the first specialization which implements setIsTurnedOn");
	self.setIsTurnedOn = WaterCannon.setIsTurnedOn;
	self.getIsTurnedOnAllowed = WaterCannon.getIsTurnedOnAllowed;

	self.CannonLitersPerSecond = {};
	local i=0;
	while true do
		local key = string.format("vehicle.CannonUsages.CannonUsage(%d)", i);
		if not hasXMLProperty(xmlFile, key) then
			break;
		end;
		local fillType = getXMLString(xmlFile, key.. "#fillType");
		local litersPerSecond = getXMLFloat(xmlFile, key.. "#litersPerSecond");
		if fillType ~= nil and litersPerSecond ~= nil then
			local fillTypeInt = Fillable.fillTypeNameToInt[fillType];
			if fillTypeInt ~= nil then
				self.CannonLitersPerSecond[fillTypeInt] = litersPerSecond;
				if self.defaultCannonLitersPerSecond == nil then
					self.defaultCannonLitersPerSecond = litersPerSecond;
				end;
			else
				print("Warning: Invalid Cannon usage fill type '"..fillType.."' in '" .. self.configFileName.. "'");
			end;
		end;
		i = i+1;
	end;
	if self.defaultCannonLitersPerSecond == nil then
		print("Warning: No Cannon usage specified for '" .. self.configFileName.. "'. This WaterCannon will not use any Cannon.");
		self.defaultCannonLitersPerSecond = 0;
	end;

	self.CannonValves = {};

	if self.isClient then
		local psFile = getXMLString(xmlFile, "vehicle.CannonParticleSystem#file");
		if psFile ~= nil then
			local i=0;
			while true do
				local baseName = string.format("vehicle.CannonValves.CannonValve(%d)", i);
				local node = getXMLString(xmlFile, baseName.. "#index");
				if node == nil then
					break;
				end;
				node = Utils.indexToObject(self.components, node);
				if node ~= nil then
					local CannonValve = {};
					CannonValve.particleSystems = {};
					Utils.loadParticleSystem(xmlFile, CannonValve.particleSystems, "vehicle.CannonParticleSystem", node, false, nil, self.baseDirectory);
					table.insert(self.CannonValves, CannonValve);
				end;
				i = i+1;
			end;
		end;

		local cannonSound = getXMLString(xmlFile, "vehicle.CannonSound#file");
		if cannonSound ~= nil and cannonSound ~= "" then
			cannonSound = Utils.getFilename(cannonSound, self.baseDirectory);
			self.cannonSound = createSample("cannonSound");
			loadSample(self.cannonSound, cannonSound, false);
			self.cannonSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.CannonSound#pitchOffset"), 1.0);
			self.cannonSoundPitchScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.CannonSound#pitchScale"), 0.05);
			self.cannonSoundPitchMax = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.CannonSound#pitchMax"), 2.0);
			self.cannonSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.CannonSound#volume"), 1.0);

			self.cannonSoundEnabled = false;

			self.cannonSound3DVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.CannonSound#volume3D"), self.cannonSoundVolume);
			self.cannonSound3DInnerRadius = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.CannonSound#innerRadius"), 10);
			self.cannonSound3DRadius = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.CannonSound#radius"), 50);

			self.cannonSound3D = createAudioSource("cannonSound3D", cannonSound, self.cannonSound3DRadius, self.cannonSound3DInnerRadius, self.cannonSound3DVolume, 0);
			link(self.components[1].node, self.cannonSound3D);
			setVisibility(self.cannonSound3D, false);

		end;
	end;

	self.isPumpandRoll = Utils.getNoNil(getXMLBool(xmlFile, "vehicle.CannonUsages#isPumpandRoll"),false);

	self.isTurnedOn = false;
	self.speedViolationMaxTime = 1000;
	self.speedViolationTimer = self.speedViolationMaxTime;
end;

function WaterCannon:delete()

      for k,CannonValve in pairs(self.CannonValves) do
          Utils.deleteParticleSystem(CannonValve.particleSystems);
      end;

      if self.cannonSound ~= nil then
          delete(self.cannonSound);
      end;
end;

function WaterCannon:readStream(streamId, connection)
	local turnedOn = streamReadBool(streamId);

	self:setIsTurnedOn(turnedOn, true);

end;

function WaterCannon:writeStream(streamId, connection)
	streamWriteBool(streamId, self.isTurnedOn);

end;

function WaterCannon:readUpdateStream(streamId, timestamp, connection)
end;

function WaterCannon:writeUpdateStream(streamId, connection, dirtyMask)
end;

function WaterCannon:mouseEvent(posX, posY, isDown, isUp, button)
end;

function WaterCannon:keyEvent(unicode, sym, modifier, isDown)
end;

function WaterCannon:update(dt)

	if self.isClient then
		if self:getIsActiveForInput() then
			if InputBinding.hasEvent(InputBinding.WATERCANNON_SWITCH) then
				if Pump.isTurnedOn then
					self:setIsTurnedOn(not self.isTurnedOn);
				end;
			end;
			if not Pump.isTurnedOn then
				self:setIsTurnedOn(false);
			end;
		end;
	end;

end;

function WaterCannon:updateTick(dt)
	if self.isTurnedOn then

		if self:doCheckSpeedLimit() and self.lastSpeed*3600 > 90 then
			self.speedViolationTimer = self.speedViolationTimer - dt;

        else
            self.speedViolationTimer = self.speedViolationMaxTime;
        end;

		if self.isServer then
			if self.speedViolationTimer > 0 then
				local litersPerSecond = self.CannonLitersPerSecond[self.currentFillType];
				if litersPerSecond == nil then
					litersPerSecond = self.defaultCannonLitersPerSecond;
				end;
				local usage = litersPerSecond * dt*0.001;

				if not self.capacity == 0 or not self:getIsHired() then
					if self.fillLevel > 0 then
						self:setFillLevel(self.fillLevel - usage, self.currentFillType);
						if not self.isPumpandRoll then
							for k,wheel in pairs(self.wheels) do
								setWheelShapeProps(wheel.node, wheel.wheelShape, 0, 999, 0);
							end;
						end;
					end;
				end;
			end;
		end;
	end;

--	if self:getIsActive() then
		if self.isTurnedOn then
			if self.isClient then
				if not self.CannonSoundEnabled and self:getIsActiveForSound() then
					local alpha = 0.9;
					local roundPerMinute = self.lastRoundPerMinute*alpha + (1-alpha)*(self.motor.lastMotorRpm-self.motor.minRpm);
					self.lastRoundPerMinute = roundPerMinute;
					local roundPerSecond = roundPerMinute / 60;

--					playSample(self.cannonSound, 0, self.cannonSoundVolume, 0);
					if self.cannonSound3D ~= nil then
						setVisibility(self.cannonSound3D, true);
					end;
					local cannonSoundPitch = math.min(self.cannonSoundPitchOffset + self.cannonSoundPitchScale*math.abs(roundPerSecond), self.cannonSoundPitchMax)
					setSamplePitch(self.cannonSound, self.cannonSoundPitch);
					if self.cannonSound3D ~= nil then
						setSamplePitch(getAudioSourceSample(self.cannonSound3D), cannonSoundPitch);
					end;
					self.CannonSoundEnabled = true;
				end;
			end;

			if self.fillLevel <= 0 and self.capacity ~= 0 then
				self:setIsTurnedOn(false, true);
			end;
		else
			self.speedViolationTimer = self.speedViolationMaxTime;
			if self.cannonSound3D ~= nil then
				setVisibility(self.cannonSound3D, false);
			end;
		end;
--	end;

end;

function WaterCannon:draw()

	if self.isClient then
		if self.fillLevel <= 0 and self.capacity ~= 0 then
			g_currentMission:addExtraPrintText(g_i18n:getText("FirstFillTheTool"));
		end;

		if self.isTurnedOn then

			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_off_WaterCannon"), self.typeDesc), InputBinding.WATERCANNON_SWITCH);
		else
			g_currentMission:addHelpButtonText(string.format(g_i18n:getText("turn_on_WaterCannon"), self.typeDesc), InputBinding.WATERCANNON_SWITCH);
		end;

		--TODO Make that the Warning is showing longer then half second
		if InputBinding.hasEvent(InputBinding.WATERCANNON_SWITCH) and not Pump.isTurnedOn then
			g_currentMission:addWarning(g_i18n:getText("First_turn_on_Pump") .. "/n" .. string.format(InputBinding.getKeyNamesOfDigitalAction(InputBinding.Pump_SWITCH)), 0.07+0.022, 0.019+0.029);
		end;
	end;

end;

function WaterCannon:onDetach()
      if self.deactivateOnDetach then
          WaterCannon.onDeactivate(self);
      else
          WaterCannon.onDeactivateSounds(self);
      end;
end;

function WaterCannon:onLeave()
	if self.CannonSoundEnabled then
		stopSample(self.cannonSound);
	end;
--[[      if self.deactivateOnLeave then
          WaterCannon.onDeactivate(self);
      else
          WaterCannon.onDeactivateSounds(self);
      end;]]
end;
function WaterCannon:onDeactivate()
	self.speedViolationTimer = self.speedViolationMaxTime;
	self:setIsTurnedOn(false, true)
	WaterCannon.onDeactivateSounds(self);
end;

function WaterCannon:onDeactivateSounds()
	if self.CannonSoundEnabled then
		stopSample(self.cannonSound);

		self.CannonSoundEnabled = false;
	end;
	if self.cannonSound3D ~= nil then
		setVisibility(self.cannonSound3D, false);
	end;
end;

function WaterCannon:getIsTurnedOnAllowed(isTurnedOn)
	if not isTurnedOn or self.fillLevel > 0 or self.capacity == 0 then
		return true;
	end;
end;

function WaterCannon:setIsTurnedOn(isTurnedOn, noEventSend)
	if isTurnedOn ~= self.isTurnedOn then
		if self:getIsTurnedOnAllowed(isTurnedOn) then
			SetTurnedOnEvent.sendEvent(self, isTurnedOn, noEventSend)
			self.isTurnedOn = isTurnedOn;
			if self.isClient then
				for k,CannonValve in pairs(self.CannonValves) do
					Utils.setEmittingState(CannonValve.particleSystems, self.isTurnedOn);
				end;

				if not self.isTurnedOn and self.CannonSoundEnabled then
					stopSample(self.cannonSound);
					self.CannonSoundEnabled = false;
				end;
			end;
			self.speedViolationTimer = self.speedViolationMaxTime;
		end;
	end;
end;


text:
#include "PipeWin.h"

namespace Titanium {

PipeWin::PipeWin(bool isReader)
    : NativePipe(isReader)
    , readHandle(INVALID_HANDLE_VALUE)
    , writeHandle(INVALID_HANDLE_VALUE)
    , logger(Logger::Get("Process.PipeWin"))
{
}

void PipeWin::CreateHandles()
{
    SECURITY_ATTRIBUTES attr;
    attr.nLength              = sizeof(attr);
    attr.lpSecurityDescriptor = NULL;
    attr.bInheritHandle       = FALSE;

    ::CreatePipe(&readHandle, &writeHandle, &attr, 0);
}

void PipeWin::Close()
{
    NativePipe::Close();
}

int PipeWin::RawRead(char *buffer, int size)
{
    if (readHandle != INVALID_HANDLE_VALUE)
    {
        DWORD bytesRead;
        BOOL ok = ReadFile(readHandle, buffer, size, &bytesRead, NULL);
        int error = GetLastError();
        if (ok)
        {
            return bytesRead;
        }
        else if (error == ERROR_BROKEN_PIPE)
        {
            return -1;
        }
        else
        {
            throw ValueException::FromString("Error writing anonymous pipe");
        }
    }
    return -1;
}

int PipeWin::RawWrite(const char *data, int size)
{
    if (writeHandle != INVALID_HANDLE_VALUE)
    {
        DWORD bytesWritten;
        BOOL ok = WriteFile(writeHandle, (LPCVOID)data, size, &bytesWritten, NULL);
        if (ok || GetLastError() == ERROR_BROKEN_PIPE) {
            return bytesWritten;
        }
        else {
            throw ValueException::FromString("Error writing anonymous pipe");
        }
    }
    return 0;
}

void PipeWin::DuplicateRead(HANDLE process, LPHANDLE handle)
{
    DuplicateHandle(process, readHandle, process, handle, 0, TRUE, DUPLICATE_SAME_ACCESS);
    this->CloseNativeRead();
}

void PipeWin::DuplicateWrite(HANDLE process, LPHANDLE handle)
{
    DuplicateHandle(process, writeHandle, process, handle, 0, TRUE, DUPLICATE_SAME_ACCESS);
    this->CloseNativeWrite();
}

void PipeWin::CloseNativeRead()
{
    if (readHandle != INVALID_HANDLE_VALUE)
    {
        CloseHandle(readHandle);
        readHandle = INVALID_HANDLE_VALUE;
    }
}

void PipeWin::CloseNativeWrite()
{
    if (writeHandle != INVALID_HANDLE_VALUE)
    {
        CloseHandle(writeHandle);
        writeHandle = INVALID_HANDLE_VALUE;
    }
}

} // namespace Titanium

redpajama_set_name: RedPajamaGithub


text:
Overview

Our search engine helps you find publicly available datasets. These datasets are made available by diverse public agencies all the way from city government to the White House. Your task is to help us improve our search engine by determining how relevant certain datasets are to a corresponding query that a user entered on a particular domain in our system.

We Provide

A Search Query and Domain

The search query is an actual search query that a user has entered into a search box.

The query may either be a keyword search ("Seattle high school test scores") or a category search ("category=Education").

A Result, which contains:

Dataset Name

Dataset Description

Link to data on the site that provides it

Data sample (when available)

Options to select the level of relevance

Process

Read and Understand the search query

Review the result of each query

Select the level of relevance for each result.

Sometimes it will be hard to determine whether a dataset is relevant to the search query given just the description and the title. In those cases, click on the link to view the dataset itself (this should automatically open in a new tab in your browser, which you can then close). This may help you determine how relevant it is.

Rules and Tips

You should be assessing the results based on the intent of the query.

Intent is the purpose of the search

If a person is searching for 'political contributions', the intent of that search is to find datasets with information about contributions to political campaigns. If the result is a dataset containing healthcare data, we could say that the result is Irrelevant.

If a person searches for 'crimes by neighborhood', and the result is a dataset with crime data that includes details about the location of the crime, we could say that the result is Excellent.

If a person searches for category=Education, they are hoping to find general datasets relevant to the category of Education.

Review the information we've provided before making your decision.

Relevance Definitions

You should choose Irrelevant if:

The intent of the query was not matched.

The results are irrelevant to the search query

"Why is this item even being returned?"

Choose Loosely relevant if:

The intent of the query is poorly matched.

The result is somewhat related to the query, but it not a good match.

"I see why this is returned but it's definitely not what I wanted – I probably would not click on this result."

Choose Relevant if:

Matches most of the query intent - or the most important part of the query.

Technically, all parts of the intent are satisfied but result doesn't provide a full, clear and complete answer to the search.

"This broadly matches what I searched for, but it's not a perfect match"

Choose Excellent if:

The query intent is clearly satisfied.

Specifics of the Query appear in the Result

"This is exactly what I was looking for"

Choose Something went wrong / not enough information if:

the result title and/or description are missing and the link is broken

the result title and/or description text are in a foreign language

"I don't understand the result"

Thank you!

Thank you for your hard work in this task! Your efforts are greatly appreciated.


text:
namespace {

gfx::ColorSpace GetColorSpace(const avifImage* image) {
  if (image->icc.size) {
    auto iccp = gfx::ICCProfile::FromData(image->icc.data, image->icc.size);
    if (iccp.IsValid())
      return iccp.GetColorSpace();

    // TODO(dalecurtis): Do we need to reparse this per frame when dealing
    // with animated AVIF files? Or is it only for still picture?

    // TODO(wtc): We need to set the color profile using
    // SetEmbeddedColorProfile() rather than handling all the color space
    // conversion during decode.
  }
  media::VideoColorSpace color_space(
      image->colorPrimaries, image->transferCharacteristics,
      image->matrixCoefficients,
      image->yuvRange == AVIF_RANGE_FULL ? gfx::ColorSpace::RangeID::FULL
                                         : gfx::ColorSpace::RangeID::LIMITED);
  if (color_space.IsSpecified())
    return color_space.ToGfxColorSpace();
  if (image->yuvRange == AVIF_RANGE_FULL)
    return gfx::ColorSpace::CreateJpeg();
  return gfx::ColorSpace::CreateREC709();
}

media::VideoPixelFormat AvifToVideoPixelFormat(avifPixelFormat fmt, int depth) {
  if (depth != 8 && depth != 10 && depth != 12) {
    // Unsupported bit depth.
    NOTREACHED();
    return media::PIXEL_FORMAT_UNKNOWN;
  }
  int index = (depth - 8) / 2;
  static constexpr media::VideoPixelFormat kYUV420Formats[] = {
      media::PIXEL_FORMAT_I420, media::PIXEL_FORMAT_YUV420P10,
      media::PIXEL_FORMAT_YUV420P12};
  static constexpr media::VideoPixelFormat kYUV422Formats[] = {
      media::PIXEL_FORMAT_I422, media::PIXEL_FORMAT_YUV422P10,
      media::PIXEL_FORMAT_YUV422P12};
  static constexpr media::VideoPixelFormat kYUV444Formats[] = {
      media::PIXEL_FORMAT_I444, media::PIXEL_FORMAT_YUV444P10,
      media::PIXEL_FORMAT_YUV444P12};
  switch (fmt) {
    case AVIF_PIXEL_FORMAT_YUV420:
      return kYUV420Formats[index];
    case AVIF_PIXEL_FORMAT_YUV422:
      return kYUV422Formats[index];
    case AVIF_PIXEL_FORMAT_YUV444:
      return kYUV444Formats[index];
    case AVIF_PIXEL_FORMAT_YV12:
      NOTIMPLEMENTED();
      return media::PIXEL_FORMAT_UNKNOWN;
    case AVIF_PIXEL_FORMAT_NONE:
      NOTREACHED();
      return media::PIXEL_FORMAT_UNKNOWN;
  }
}

inline void WritePixel(float max_channel,
                       const gfx::Point3F& pixel,
                       int alpha,
                       uint32_t* rgba_dest) {
  *rgba_dest = SkPackARGB32NoCheck(
      alpha,
      gfx::ToRoundedInt(base::ClampToRange(pixel.x(), 0.0f, 1.0f) * 255.0f),
      gfx::ToRoundedInt(base::ClampToRange(pixel.y(), 0.0f, 1.0f) * 255.0f),
      gfx::ToRoundedInt(base::ClampToRange(pixel.z(), 0.0f, 1.0f) * 255.0f));
}

inline void WritePixel(float max_channel,
                       const gfx::Point3F& pixel,
                       int alpha,
                       uint64_t* rgba_dest) {
  float rgba_pixels[4];
  rgba_pixels[0] = pixel.x();
  rgba_pixels[1] = pixel.y();
  rgba_pixels[2] = pixel.z();
  rgba_pixels[3] = alpha / max_channel;

  gfx::FloatToHalfFloat(rgba_pixels, reinterpret_cast<uint16_t*>(rgba_dest),
                        base::size(rgba_pixels));
}

enum class ColorType { kMono, kColor };

template <ColorType color_type, typename InputType, typename OutputType>
void YUVAToRGBA(const avifImage* image,
                const gfx::ColorTransform* transform,
                OutputType* rgba_dest) {
  avifPixelFormatInfo format_info;
  avifGetPixelFormatInfo(image->yuvFormat, &format_info);
  gfx::Point3F pixel;
  const int max_channel_i = (1 << image->depth) - 1;
  const float max_channel = float{max_channel_i};
  for (uint32_t j = 0; j < image->height; ++j) {
    const int uv_j = j >> format_info.chromaShiftY;

    const InputType* y_ptr = reinterpret_cast<InputType*>(
        &image->yuvPlanes[AVIF_CHAN_Y][j * image->yuvRowBytes[AVIF_CHAN_Y]]);
    const InputType* u_ptr = reinterpret_cast<InputType*>(
        &image->yuvPlanes[AVIF_CHAN_U][uv_j * image->yuvRowBytes[AVIF_CHAN_U]]);
    const InputType* v_ptr = reinterpret_cast<InputType*>(
        &image->yuvPlanes[AVIF_CHAN_V][uv_j * image->yuvRowBytes[AVIF_CHAN_V]]);
    const InputType* a_ptr = nullptr;
    if (image->alphaPlane) {
      a_ptr = reinterpret_cast<InputType*>(
          &image->alphaPlane[j * image->alphaRowBytes]);
    }

    for (uint32_t i = 0; i < image->width; ++i) {
      const int uv_i = i >> format_info.chromaShiftX;
      // TODO(wtc): Use templates or other ways to avoid doing this comparison
      // and checking whether the image supports alpha in the inner loop.
      if (image->yuvRange == AVIF_RANGE_LIMITED) {
        pixel.set_x(avifLimitedToFullY(image->depth, y_ptr[i]) / max_channel);
        if (color_type == ColorType::kColor) {
          pixel.set_y(avifLimitedToFullUV(image->depth, u_ptr[uv_i]) /
                      max_channel);
          pixel.set_z(avifLimitedToFullUV(image->depth, v_ptr[uv_i]) /
                      max_channel);
        }
      } else {
        pixel.set_x(y_ptr[i] / max_channel);
        if (color_type == ColorType::kColor) {
          pixel.set_y(u_ptr[uv_i] / max_channel);
          pixel.set_z(v_ptr[uv_i] / max_channel);
        }
      }
      if (color_type == ColorType::kMono) {
        pixel.set_y(0.5f);
        pixel.set_z(0.5f);
      }

      transform->Transform(&pixel, 1);

      int alpha = max_channel_i;
      if (a_ptr) {
        alpha = a_ptr[i];
        if (image->alphaRange == AVIF_RANGE_LIMITED)
          alpha = avifLimitedToFullY(image->depth, alpha);
      }

      WritePixel(max_channel, pixel, alpha, rgba_dest);
      rgba_dest++;
    }
  }
}

}  // namespace

namespace blink {

AVIFImageDecoder::AVIFImageDecoder(AlphaOption alpha_option,
                                   HighBitDepthDecodingOption hbd_option,
                                   const ColorBehavior& color_behavior,
                                   size_t max_decoded_bytes)
    : ImageDecoder(alpha_option,
                   hbd_option,
                   color_behavior,
                   max_decoded_bytes) {}

AVIFImageDecoder::~AVIFImageDecoder() = default;

bool AVIFImageDecoder::ImageIsHighBitDepth() {
  return is_high_bit_depth_;
}

void AVIFImageDecoder::OnSetData(SegmentReader* data) {
  // avifDecoder requires all the data be available before reading and cannot
  // read incrementally as data comes in. See
  // https://github.com/AOMediaCodec/libavif/issues/11.
  if (IsAllDataReceived() && !MaybeCreateDemuxer())
    SetFailed();
}

int AVIFImageDecoder::RepetitionCount() const {
  return decoded_frame_count_ > 1 ? kAnimationLoopInfinite : kAnimationNone;
}

base::TimeDelta AVIFImageDecoder::FrameDurationAtIndex(size_t index) const {
  return index < frame_buffer_cache_.size()
             ? frame_buffer_cache_[index].Duration()
             : base::TimeDelta();
}

// static
bool AVIFImageDecoder::MatchesAVIFSignature(
    const FastSharedBufferReader& fast_reader) {
  // avifPeekCompatibleFileType() clamps compatible brands at 32 when reading in
  // the ftyp box in ISOBMFF for the 'av01' brand. So the maximum number of
  // bytes read is 144 bytes (type 4 bytes, size 4 bytes, major brand 4 bytes,
  // version 4 bytes, and 4 bytes * 32 compatible brands).
  char buffer[144];
  avifROData input;
  input.size = std::min(sizeof(buffer), fast_reader.size());
  input.data = reinterpret_cast<const uint8_t*>(
      fast_reader.GetConsecutiveData(0, input.size, buffer));
  return avifPeekCompatibleFileType(&input);
}

void AVIFImageDecoder::DecodeSize() {
  // Because avifDecoder cannot read incrementally as data comes in, we cannot
  // decode the size until all data is received. When all data is received,
  // OnSetData() decodes the size right away. So DecodeSize() doesn't need to do
  // anything.
}

size_t AVIFImageDecoder::DecodeFrameCount() {
  return decoded_frame_count_;
}

void AVIFImageDecoder::InitializeNewFrame(size_t index) {
  auto& buffer = frame_buffer_cache_[index];

  buffer.SetOriginalFrameRect(IntRect(IntPoint(), Size()));

  avifImageTiming timing;
  auto ret = avifDecoderNthImageTiming(decoder_.get(), index, &timing);
  DCHECK_EQ(ret, AVIF_RESULT_OK);
  buffer.SetDuration(base::TimeDelta::FromSecondsD(timing.duration));

  // The AVIF file format does not contain information equivalent to the
  // disposal method or alpha blend source. Since the AVIF decoder handles frame
  // dependence internally, set options that best correspond to "each frame is
  // independent".
  buffer.SetDisposalMethod(ImageFrame::kDisposeNotSpecified);
  buffer.SetAlphaBlendSource(ImageFrame::kBlendAtopBgcolor);

  if (decode_to_half_float_)
    buffer.SetPixelFormat(ImageFrame::PixelFormat::kRGBA_F16);

  // Leave all frames as being independent (the default) because we require all
  // frames be the same size.
  DCHECK_EQ(buffer.RequiredPreviousFrameIndex(), kNotFound);
}

void AVIFImageDecoder::Decode(size_t index) {
  // TODO(dalecurtis): For fragmented avif-sequence files we probably want to
  // allow partial decoding. Depends on if we see frequent use of multi-track
  // images where there's lots to ignore.
  if (Failed() || !IsAllDataReceived())
    return;

  if (!DecodeImage(index)) {
    SetFailed();
    return;
  }

  const auto* image = decoder_->image;
  // All frames must be the same size.
  if (Size() != IntSize(image->width, image->height)) {
    SetFailed();
    return;
  }

  ImageFrame& buffer = frame_buffer_cache_[index];
  DCHECK_NE(buffer.GetStatus(), ImageFrame::kFrameComplete);
  if (decode_to_half_float_)
    buffer.SetPixelFormat(ImageFrame::PixelFormat::kRGBA_F16);

  // Set color space information on the frame if appropriate.
  gfx::ColorSpace frame_cs;
  if (!IgnoresColorSpace())
    frame_cs = GetColorSpace(image);
  if (CanSetColorSpace()) {
    last_color_space_ = frame_cs.GetAsFullRangeRGB();
  } else {
    // Just use whatever color space Skia wants us to use.
  }

  // TODO(wtc): This should use the value of |last_color_space_|. Implement it.
  if (!InitFrameBuffer(index)) {
    DVLOG(1) << "Failed to create frame buffer...";
    SetFailed();
    return;
  }

  if (!RenderImage(image, frame_cs, &buffer)) {
    SetFailed();
    return;
  }

  buffer.SetPixelsChanged(true);
  buffer.SetHasAlpha(!!image->alphaPlane);
  buffer.SetStatus(ImageFrame::kFrameComplete);
}

bool AVIFImageDecoder::CanReusePreviousFrameBuffer(size_t index) const {
  // (a) Technically we can reuse the bitmap of the previous frame because the
  // AVIF decoder handles frame dependence internally and we never need to
  // preserve previous frames to decode later ones, and (b) since this function
  // will not currently be called, this is really more for the reader than any
  // functional purpose.
  return true;
}

bool AVIFImageDecoder::MaybeCreateDemuxer() {
  if (decoder_)
    return true;

  decoder_ = std::unique_ptr<avifDecoder, void (*)(avifDecoder*)>(
      avifDecoderCreate(), avifDecoderDestroy);
  if (!decoder_)
    return false;

  // TODO(dalecurtis): This may create a second copy of the media data in
  // memory, which is not great. Upstream should provide a read() based API:
  // https://github.com/AOMediaCodec/libavif/issues/11
  image_data_ = data_->GetAsSkData();
  if (!image_data_)
    return false;

  avifROData raw_data = {image_data_->bytes(), image_data_->size()};
  auto ret = avifDecoderParse(decoder_.get(), &raw_data);
  if (ret != AVIF_RESULT_OK) {
    DVLOG(1) << "avifDecoderParse failed: " << avifResultToString(ret);
    return false;
  }

  DCHECK_GT(decoder_->imageCount, 0);
  decoded_frame_count_ = decoder_->imageCount;
  is_high_bit_depth_ = decoder_->containerDepth > 8;
  decode_to_half_float_ =
      is_high_bit_depth_ &&
      high_bit_depth_decoding_option_ == kHighBitDepthToHalfFloat;

  // Try to get the size from the container if possible instead of decoding.
  if (decoder_->containerWidth && decoder_->containerHeight)
    return SetSize(decoder_->containerWidth, decoder_->containerHeight);

  // We need to SetSize() to proceed, so decode the first frame.
  return DecodeImage(0) &&
         SetSize(decoder_->image->width, decoder_->image->height);
}

bool AVIFImageDecoder::DecodeImage(size_t index) {
  auto ret = avifDecoderNthImage(decoder_.get(), index);
  if (ret != AVIF_RESULT_OK) {
    // We shouldn't be called more times than specified in
    // DecodeFrameCount(); possibly this should truncate if the initial
    // count is wrong?
    DCHECK_NE(ret, AVIF_RESULT_NO_IMAGES_REMAINING);
    return false;
  }

  const auto* image = decoder_->image;
  is_high_bit_depth_ = image->depth > 8;
  decode_to_half_float_ =
      is_high_bit_depth_ &&
      high_bit_depth_decoding_option_ == kHighBitDepthToHalfFloat;
  return true;
}

bool AVIFImageDecoder::UpdateColorTransform(const gfx::ColorSpace& src_cs,
                                            const gfx::ColorSpace& dest_cs) {
  if (color_transform_ && color_transform_->GetSrcColorSpace() == src_cs)
    return true;
  color_transform_ = gfx::ColorTransform::NewColorTransform(
      src_cs, dest_cs, gfx::ColorTransform::Intent::INTENT_PERCEPTUAL);
  return !!color_transform_;
}

// TODO(wtc): We must be able to set the color space accurately. Find a solution
// that lets us set the color space for all images and not just the half float
// and animated cases.
bool AVIFImageDecoder::CanSetColorSpace() const {
  return decode_to_half_float_ || decoded_frame_count_ > 1;
}

bool AVIFImageDecoder::RenderImage(const avifImage* image,
                                   const gfx::ColorSpace& frame_cs,
                                   ImageFrame* buffer) {
  const gfx::ColorSpace dest_rgb_cs(*buffer->Bitmap().colorSpace());

  const bool is_mono = !image->yuvPlanes[AVIF_CHAN_U];

  // TODO(dalecurtis): We should decode to YUV when possible. Currently the
  // YUV path seems to only support still-image YUV8.
  if (decode_to_half_float_) {
    if (!UpdateColorTransform(frame_cs, dest_rgb_cs)) {
      DVLOG(1) << "Failed to update color transform...";
      return false;
    }

    uint64_t* rgba_hhhh = buffer->GetAddrF16(0, 0);

    // Color and format convert from YUV HBD -> RGBA half float.
    if (is_mono) {
      YUVAToRGBA<ColorType::kMono, uint16_t>(image, color_transform_.get(),
                                             rgba_hhhh);
    } else {
      // TODO: Add fast path for 10bit 4:2:0 using libyuv.
      YUVAToRGBA<ColorType::kColor, uint16_t>(image, color_transform_.get(),
                                              rgba_hhhh);
    }
    return true;
  }

  uint32_t* rgba_8888 = buffer->GetAddr(0, 0);
  // TODO(wtc): Figure out a way to check frame_cs == ~BT.2020 too since
  // ConvertVideoFrameToRGBPixels() can handle that too.
  if (frame_cs == gfx::ColorSpace::CreateREC709() ||
      frame_cs == gfx::ColorSpace::CreateREC601() ||
      frame_cs == gfx::ColorSpace::CreateJpeg()) {
    // Create temporary frame wrapping the YUVA planes.
    scoped_refptr<media::VideoFrame> frame;
    auto pixel_format = AvifToVideoPixelFormat(image->yuvFormat, image->depth);
    if (pixel_format == media::PIXEL_FORMAT_UNKNOWN)
      return false;
    auto size = gfx::Size(image->width, image->height);
    if (image->alphaPlane) {
      if (pixel_format == media::PIXEL_FORMAT_I420 && image->yuvPlanes[1] &&
          image->yuvPlanes[2]) {
        // Genuine YUV 4:2:0, not monochrome 4:0:0.
        pixel_format = media::PIXEL_FORMAT_I420A;
      } else {
        NOTIMPLEMENTED();
        return false;
      }
      frame = media::VideoFrame::WrapExternalYuvaData(
          pixel_format, size, gfx::Rect(size), size, image->yuvRowBytes[0],
          image->yuvRowBytes[1], image->yuvRowBytes[2], image->alphaRowBytes,
          image->yuvPlanes[0], image->yuvPlanes[1], image->yuvPlanes[2],
          image->alphaPlane, base::TimeDelta());
    } else {
      frame = media::VideoFrame::WrapExternalYuvData(
          pixel_format, size, gfx::Rect(size), size, image->yuvRowBytes[0],
          image->yuvRowBytes[1], image->yuvRowBytes[2], image->yuvPlanes[0],
          image->yuvPlanes[1], image->yuvPlanes[2], base::TimeDelta());
    }
    frame->set_color_space(frame_cs);

    // Really only handles 709, 601, 2020, JPEG 8-bit conversions and uses
    // libyuv under the hood, so is much faster than our manual path.
    //
    // Technically has support for 10-bit 4:2:0 and 4:2:2, but not to
    // half-float and only has support for 4:4:4 and 12-bit by down-shifted
    // copies.
    //
    // https://bugs.chromium.org/p/libyuv/issues/detail?id=845
    media::PaintCanvasVideoRenderer::ConvertVideoFrameToRGBPixels(
        frame.get(), rgba_8888, frame->visible_rect().width() * 4);
    return true;
  }

  if (!UpdateColorTransform(frame_cs, dest_rgb_cs)) {
    DVLOG(1) << "Failed to update color transform...";
    return false;
  }
  if (ImageIsHighBitDepth()) {
    if (is_mono) {
      YUVAToRGBA<ColorType::kMono, uint16_t>(image, color_transform_.get(),
                                             rgba_8888);
    } else {
      YUVAToRGBA<ColorType::kColor, uint16_t>(image, color_transform_.get(),
                                              rgba_8888);
    }
  } else {
    if (is_mono) {
      YUVAToRGBA<ColorType::kMono, uint8_t>(image, color_transform_.get(),
                                            rgba_8888);
    } else {
      YUVAToRGBA<ColorType::kColor, uint8_t>(image, color_transform_.get(),
                                             rgba_8888);
    }
  }
  return true;
}

}  // namespace blink


text:
import datetime
import hashlib
import importlib
import sys

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured

DEFAULTS = {
    # Generating URLs
    "TOKEN_NAME": "sesame",
    # Tokens lifecycle
    "MAX_AGE": None,
    "ONE_TIME": False,
    "INVALIDATE_ON_PASSWORD_CHANGE": True,
    # Custom primary keys
    "PACKER": None,
    "PRIMARY_KEY_FIELD": "pk",
    # Tokens
    "TOKENS": ["sesame.tokens_v2", "sesame.tokens_v1"],
    # Tokens v2
    "KEY": "",
    # We want a short signature in order to keep tokens short. A 10-bytes
    # signature has about 1.2e24 possible values, which is sufficient here.
    "SIGNATURE_SIZE": 10,
    # Tokens v1
    "SALT": "sesame",
    # These parameters aren't updated anymore. Tokens v2 are recommended.
    "DIGEST": hashlib.md5,
    "ITERATIONS": 10000,
}

__all__ = list(DEFAULTS)

def derive_key(secret_key, key):
    """
    Make a 64-bytes key from Django's ``secret_key`` and django-sesame's ``key``.

    Include settings in the key to invalidate tokens when these settings change.
    This ensures that tokens generated with one packer cannot be misinterpreted
    by another packer, for example.

    """
    global MAX_AGE, PACKER, PRIMARY_KEY_FIELD
    return hashlib.blake2b(
        "|".join(
            [
                # Usually a str but Django also supports bytes.
                str(secret_key),
                # Treat key like secret_key for consistency.
                str(key),
                # Changing MAX_AGE is allowed as long as it is not None.
                "max_age" if MAX_AGE is not None else "",
                PACKER if PACKER is not None else "",
                PRIMARY_KEY_FIELD,
            ]
        ).encode(),
        person=b"sesame.settings",
    ).digest()

# load() also works for reloading settings, which is useful for testing.

def load():
    module = sys.modules[__name__]
    for name, default in DEFAULTS.items():
        setattr(module, name, getattr(settings, "SESAME_" + name, default))

    global KEY, MAX_AGE, SIGNING_KEY, TOKENS, VERIFICATION_KEYS

    # Support defining MAX_AGE as a timedelta rather than a number of seconds.
    if isinstance(MAX_AGE, datetime.timedelta):
        MAX_AGE = MAX_AGE.total_seconds()

    # Import token creation and parsing modules.
    TOKENS = [importlib.import_module(tokens) for tokens in TOKENS]

    # Derive signing and verification keys.
    SIGNING_KEY = derive_key(settings.SECRET_KEY, KEY)
    VERIFICATION_KEYS = [SIGNING_KEY] + [
        derive_key(secret_key, KEY)
        for secret_key in getattr(settings, "SECRET_KEY_FALLBACKS", [])
    ]

load()

# Django's checks framework was designed to run such checks. Unfortunately,
# there's no way to guarantee that a check would be discovered, because
# django-sesame never required adding the "sesame" app to INSTALLED_APPS.

# The benefits of writing this check with the checks framework don't justify
# adding another step to the installation instructions. Raising an exception
# is good enough.

def check():
    global MAX_AGE, INVALIDATE_ON_PASSWORD_CHANGE
    if MAX_AGE is None and not INVALIDATE_ON_PASSWORD_CHANGE:
        raise ImproperlyConfigured(
            "insecure configuration: set SESAME_MAX_AGE to a low value "
            "or set SESAME_INVALIDATE_ON_PASSWORD_CHANGE to True"
        )

check()


text:
using System.Text;

namespace Papper.Internal
{
    internal class PlcMetaDataTree : ITree
    {
        public ITreeNode Root { get; private set; }

        public PlcMetaDataTree() => Root = new PlcMetaDataTreeRootNode(this, PlcMetaDataTreePath.Separator);

        public ITreeNode? Get(ITreePath path) => Root.Get(path);

        public ITreeNode? Get(ITreePath path, ref int offset, ref StringBuilder symbolicPath, bool getRef = false) => Root.Get(path, ref offset, ref symbolicPath, getRef);

        public bool TryGet(ITreePath path, out ITreeNode node)
        {
            node = Root.Get(path)!;
            return node != null;
        }

        public bool TryGet(ITreePath path, ref int offset, ref StringBuilder symbolicPath, out ITreeNode node, bool getRef = false)
        {
            node = Root.Get(path, ref offset, ref symbolicPath, getRef)!;
            return node != null;
        }
    }
}


text:
title := BaseballGame
all: $(title).class

$(title).class: *.java
	javac *.java

again:
	javac *.java

edit:
	emacs $(title).java

run: $(title).class
	java $(title)


text:
using System;
using UnityEngine;

/// <summary>
/// Permet de s'abonner à des delegate ayant pour prototype : delegate void function().
/// </summary>
/// <typeparam name="EnumerationType"></typeparam>
public class EventManagerParamsVector3<EnumerationType> where EnumerationType : struct, IConvertible
{
    public delegate void Delegate(Vector3 paramA);

    #region Fields
    protected Delegate[] events;
    #endregion

    #region Constructor
    public EventManagerParamsVector3()
    {
        if (!typeof(EnumerationType).IsEnum)
            throw new ArgumentException("EnumerationType must be an enumerated type");

        this.events = new Delegate[EnumHelper.Count<EnumerationType>()];
    }
    #endregion

    #region Behaviour Methods
    /// <summary>
    /// Permet de récupérer l'event lié à l'énumération EnumerationType.
    /// </summary>
    /// <param name="enumeration"></param>
    /// <returns></returns>
    protected Delegate GetEvent(EnumerationType enumeration)
    {
        return this.events[EnumHelper.GetIndex<EnumerationType>(enumeration)];
    }

    /// <summary>
    /// S'abonne à l'action ayant pour identifiant un EnumerationType.
    /// </summary>
    /// <param name="enumeration"></param>
    /// <param name="action"></param>
    public void SubcribeToEvent(EnumerationType enumeration, Delegate action)
    {
        this.events[EnumHelper.GetIndex<EnumerationType>(enumeration)] += action;
    }

    /// <summary>
    /// Se désabonne d'une action ayant pour identifiant un EnumerationType
    /// </summary>
    /// <param name="enumeration"></param>
    /// <param name="action"></param>
    public void UnsubcribeToEvent(EnumerationType enumeration, Delegate action)
    {
        this.events[EnumHelper.GetIndex<EnumerationType>(enumeration)] -= action;
    }

    /// <summary>
    /// Appele les actions lié à l'identifiant EnumerationType.
    /// </summary>
    /// <param name="enumeration"></param>
    public void CallEvent(EnumerationType enumeration, Vector3 paramA)
    {
        Delegate action = this.GetEvent(enumeration);

        if (null != action)
            action(paramA);
    }
    #endregion
}


text:
package org.jivesoftware.smackx.bytestreams.socks5;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.util.CloseableUtil;

/**
 * The Socks5Proxy class represents a local SOCKS5 proxy server. It can be enabled/disabled by
 * invoking {@link #setLocalSocks5ProxyEnabled(boolean)}. The proxy is enabled by default.
 *

 * The port of the local SOCKS5 proxy can be configured by invoking
 * {@link #setLocalSocks5ProxyPort(int)}. Default port is 7777. If you set the port to a negative
 * value Smack tries to the absolute value and all following until it finds an open port.
 *

 * If your application is running on a machine with multiple network interfaces or if you want to
 * provide your public address in case you are behind a NAT router, invoke
 * {@link #addLocalAddress(InetAddress)} or {@link #replaceLocalAddresses(Collection)} to modify the list of
 * local network addresses used for outgoing SOCKS5 Bytestream requests.
 *

 * The local SOCKS5 proxy server refuses all connections except the ones that are explicitly allowed
 * in the process of establishing a SOCKS5 Bytestream (
 * {@link Socks5BytestreamManager#establishSession(org.jxmpp.jid.Jid)}).
 *

 * This Implementation has the following limitations:
 *

 *
only supports the no-authentication authentication method

 *
only supports the connect command and will not answer correctly to other
 * commands

 *
only supports requests with the domain address type and will not correctly answer to requests
 * with other address types

 *

 * (see RFC 1928)
 *
 * @author Henning Staib
 */
public class Socks5Proxy {
    private static final Logger LOGGER = Logger.getLogger(Socks5Proxy.class.getName());

    private static final List<Socks5Proxy> RUNNING_PROXIES = new CopyOnWriteArrayList<>();

    /* SOCKS5 proxy singleton */
    private static Socks5Proxy socks5Server;

    private static boolean localSocks5ProxyEnabled = true;

    /**
     * The default port of the local Socks5 Proxy. If this value is negative, the next ports will be tried
     * until a unused is found.
     */
    private static int DEFAULT_LOCAL_SOCKS5_PROXY_PORT = -7777;

    /**
     * The port of the local Socks5 Proxy. If this value is negative, the next ports will be tried
     * until a unused is found.
     */
    private int localSocks5ProxyPort = -7777;

    /* reusable implementation of a SOCKS5 proxy server process */
    private final Socks5ServerProcess serverProcess;

    /* thread running the SOCKS5 server process */
    private Thread serverThread;

    /* server socket to accept SOCKS5 connections */
    private ServerSocket serverSocket;

    /* assigns a connection to a digest */
    private final Map<String, Socket> connectionMap = new ConcurrentHashMap<>();

    /* list of digests connections should be stored */
    private final List<String> allowedConnections = Collections.synchronizedList(new LinkedList<String>());

    private final Set<InetAddress> localAddresses = new LinkedHashSet<>(4);

    /**
     * If set to true, then all connections are allowed and the digest is not verified. Should be set to
     * false for production usage and true for (unit) testing purposes.
     */
    private final boolean allowAllConnections;

    /**
     * Private constructor.
     */
    Socks5Proxy() {
        this.serverProcess = new Socks5ServerProcess();

        allowAllConnections = false;

        Enumeration<NetworkInterface> networkInterfaces;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            throw new IllegalStateException(e);
        }
        Set<InetAddress> localAddresses = new HashSet<>();
        for (NetworkInterface networkInterface : Collections.list(networkInterfaces)) {
            List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                localAddresses.add(interfaceAddress.getAddress());
            }
        }
        if (localAddresses.isEmpty()) {
            throw new IllegalStateException("Could not determine any local internet address");
        }
        replaceLocalAddresses(localAddresses);
    }

    /**
     * Constructor a Socks5Proxy with the given socket. Used for unit test purposes.
     *
     * @param serverSocket the server socket to use
     */
    protected Socks5Proxy(ServerSocket serverSocket) {
        this.serverProcess = new Socks5ServerProcess();
        this.serverSocket = serverSocket;

        allowAllConnections = true;

        startServerThread();
    }

   /**
    * Returns true if the local Socks5 proxy should be started. Default is true.
    *
    * @return if the local Socks5 proxy should be started
    */
   public static boolean isLocalSocks5ProxyEnabled() {
       return localSocks5ProxyEnabled;
   }

   /**
    * Sets if the local Socks5 proxy should be started. Default is true.
    *
    * @param localSocks5ProxyEnabled if the local Socks5 proxy should be started
    */
   public static void setLocalSocks5ProxyEnabled(boolean localSocks5ProxyEnabled) {
       Socks5Proxy.localSocks5ProxyEnabled = localSocks5ProxyEnabled;
   }

   private static void checkLocalSocks5ProxyPortArgument(int port) {
       if (Math.abs(port) > 65535) {
           throw new IllegalArgumentException("Local SOCKS5 proxy port must be within (-65535,65535)");
       }
   }

   public static int getDefaultLocalSocks5ProxyPort() {
       return DEFAULT_LOCAL_SOCKS5_PROXY_PORT;
   }

   public static void setDefaultLocalSocsk5ProxyPort(int defaultLocalSocks5ProxyPort) {
       checkLocalSocks5ProxyPortArgument(defaultLocalSocks5ProxyPort);
       DEFAULT_LOCAL_SOCKS5_PROXY_PORT = defaultLocalSocks5ProxyPort;
   }

   /**
    * Return the port of the local Socks5 proxy. Default is 7777.
    *
    * @return the port of the local Socks5 proxy
    */
   public int getLocalSocks5ProxyPort() {
       return localSocks5ProxyPort;
   }

   /**
    * Sets the port of the local Socks5 proxy. Default is 7777. If you set the port to a negative
    * value Smack tries the absolute value and all following until it finds an open port.
    *
    * @param localSocks5ProxyPort the port of the local Socks5 proxy to set
    */
   public void setLocalSocks5ProxyPort(int localSocks5ProxyPort) {
       checkLocalSocks5ProxyPortArgument(localSocks5ProxyPort);
       this.localSocks5ProxyPort = localSocks5ProxyPort;
   }

    /**
     * Returns the local SOCKS5 proxy server.
     *
     * @return the local SOCKS5 proxy server
     */
    public static synchronized Socks5Proxy getSocks5Proxy() {
        if (socks5Server == null) {
            socks5Server = new Socks5Proxy();
        }
        if (isLocalSocks5ProxyEnabled()) {
            socks5Server.start();
        }
        return socks5Server;
    }

    /**
     * Starts the local SOCKS5 proxy server. If it is already running, this method does nothing.
     *
     * @return the server socket.
     */
    public synchronized ServerSocket start() {
        if (isRunning()) {
            return this.serverSocket;
        }
        try {
            if (getLocalSocks5ProxyPort() < 0) {
                int port = Math.abs(getLocalSocks5ProxyPort());
                for (int i = 0; i < 65535 - port; i++) {
                    try {
                        this.serverSocket = new ServerSocket(port + i);
                        break;
                    }
                    catch (IOException e) {
                        // port is used, try next one
                    }
                }
            }
            else {
                this.serverSocket = new ServerSocket(getLocalSocks5ProxyPort());
            }

            if (this.serverSocket != null) {
                startServerThread();
            }
        }
        catch (IOException e) {
            // couldn't setup server
            LOGGER.log(Level.SEVERE, "couldn't setup local SOCKS5 proxy on port " + getLocalSocks5ProxyPort(), e);
        }

        return this.serverSocket;
    }

    private synchronized void startServerThread() {
        this.serverThread = new Thread(this.serverProcess);
        this.serverThread.setName("Smack Local SOCKS5 Proxy [" + this.serverSocket + ']');
        this.serverThread.setDaemon(true);

        RUNNING_PROXIES.add(this);
        this.serverThread.start();
    }

    /**
     * Stops the local SOCKS5 proxy server. If it is not running this method does nothing.
     */
    public synchronized void stop() {
        if (!isRunning()) {
            return;
        }

        RUNNING_PROXIES.remove(this);

        CloseableUtil.maybeClose(this.serverSocket, LOGGER);

        if (this.serverThread != null && this.serverThread.isAlive()) {
            try {
                this.serverThread.interrupt();
                this.serverThread.join();
            }
            catch (InterruptedException e) {
                LOGGER.log(Level.WARNING, "SOCKS5 server thread termination was interrupted", e);
            }
        }
        this.serverThread = null;
        this.serverSocket = null;
    }

    /**
     * Adds the given address to the list of local network addresses.
     *

     * Use this method if you want to provide multiple addresses in a SOCKS5 Bytestream request.
     * This may be necessary if your application is running on a machine with multiple network
     * interfaces or if you want to provide your public address in case you are behind a NAT router.
     *

     * The order of the addresses used is determined by the order you add addresses.
     *

     * Note that the list of addresses initially contains the address returned by
     * InetAddress.getLocalHost().getHostAddress(). You can replace the list of
     * addresses by invoking {@link #replaceLocalAddresses(Collection)}.
     *
     * @param address the local network address to add
     */
    public void addLocalAddress(InetAddress address) {
        if (address == null) {
            return;
        }
        synchronized (localAddresses) {
            this.localAddresses.add(address);
        }
    }

    /**
     * Removes the given address from the list of local network addresses. This address will then no
     * longer be used of outgoing SOCKS5 Bytestream requests.
     *
     * @param address the local network address to remove
     * @return true if the address was removed.
     */
    public boolean removeLocalAddress(InetAddress address) {
        synchronized (localAddresses) {
            return localAddresses.remove(address);
        }
    }

    /**
     * Returns an set of the local network addresses that will be used for streamhost
     * candidates of outgoing SOCKS5 Bytestream requests.
     *
     * @return set of the local network addresses
     */
    public List<InetAddress> getLocalAddresses() {
        synchronized (localAddresses) {
            return new LinkedList<>(localAddresses);
        }
    }

    /**
     * Replaces the list of local network addresses.
     *

     * Use this method if you want to provide multiple addresses in a SOCKS5 Bytestream request and
     * want to define their order. This may be necessary if your application is running on a machine
     * with multiple network interfaces or if you want to provide your public address in case you
     * are behind a NAT router.
     *
     * @param addresses the new list of local network addresses
     */
    public void replaceLocalAddresses(Collection<? extends InetAddress> addresses) {
        if (addresses == null) {
            throw new IllegalArgumentException("list must not be null");
        }
        synchronized (localAddresses) {
            localAddresses.clear();
            localAddresses.addAll(addresses);
        }
    }

    /**
     * Returns the port of the local SOCKS5 proxy server. If it is not running -1 will be returned.
     *
     * @return the port of the local SOCKS5 proxy server or -1 if proxy is not running
     */
    public int getPort() {
        if (!isRunning()) {
            return -1;
        }
        return this.serverSocket.getLocalPort();
    }

    /**
     * Returns the socket for the given digest. A socket will be returned if the given digest has
     * been in the list of allowed transfers (see {@link #addTransfer(String)}) while the peer
     * connected to the SOCKS5 proxy.
     *
     * @param digest identifying the connection
     * @return socket or null if there is no socket for the given digest
     */
    protected Socket getSocket(String digest) {
        return this.connectionMap.get(digest);
    }

    /**
     * Add the given digest to the list of allowed transfers. Only connections for allowed transfers
     * are stored and can be retrieved by invoking {@link #getSocket(String)}. All connections to
     * the local SOCKS5 proxy that don't contain an allowed digest are discarded.
     *
     * @param digest to be added to the list of allowed transfers
     */
    public void addTransfer(String digest) {
        this.allowedConnections.add(digest);
    }

    /**
     * Removes the given digest from the list of allowed transfers. After invoking this method
     * already stored connections with the given digest will be removed.
     *

     * The digest should be removed after establishing the SOCKS5 Bytestream is finished, an error
     * occurred while establishing the connection or if the connection is not allowed anymore.
     *
     * @param digest to be removed from the list of allowed transfers
     */
    protected void removeTransfer(String digest) {
        this.allowedConnections.remove(digest);
        this.connectionMap.remove(digest);
    }

    /**
     * Returns true if the local SOCKS5 proxy server is running, otherwise
     * false.
     *
     * @return true if the local SOCKS5 proxy server is running, otherwise
     *         false
     */
    public boolean isRunning() {
        return this.serverSocket != null;
    }

    /**
     * Implementation of a simplified SOCKS5 proxy server.
     */
    private class Socks5ServerProcess implements Runnable {

        @Override
        public void run() {
            while (true) {
                ServerSocket serverSocket = Socks5Proxy.this.serverSocket;
                if (serverSocket == null || serverSocket.isClosed() || Thread.currentThread().isInterrupted()) {
                    return;
                }

                // accept connection
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                    // initialize connection
                    establishConnection(socket);
                } catch (SmackException | IOException e) {
                    // Do nothing, if caused by closing the server socket, thread will terminate in next loop.
                    LOGGER.log(Level.FINE, "Exception while " + Socks5Proxy.this + " was handling connection", e);
                    CloseableUtil.maybeClose(socket, LOGGER);
                }
            }
        }

        /**
         * Negotiates a SOCKS5 connection and stores it on success.
         *
         * @param socket connection to the client
         * @throws SmackException if client requests a connection in an unsupported way
         * @throws IOException if a network error occurred
         */
        private void establishConnection(Socket socket) throws SmackException, IOException {
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            DataInputStream in = new DataInputStream(socket.getInputStream());

            // first byte is version should be 5
            int b = in.read();
            if (b != 5) {
                throw new SmackException.SmackMessageException("Only SOCKS5 supported: Peer send " + b + " but we expect 5");
            }

            // second byte number of authentication methods supported
            b = in.read();

            // read list of supported authentication methods
            byte[] auth = new byte[b];
            in.readFully(auth);

            byte[] authMethodSelectionResponse = new byte[2];
            authMethodSelectionResponse[0] = (byte) 0x05; // protocol version

            // only authentication method 0, no authentication, supported
            boolean noAuthMethodFound = false;
            for (int i = 0; i < auth.length; i++) {
                if (auth[i] == (byte) 0x00) {
                    noAuthMethodFound = true;
                    break;
                }
            }

            if (!noAuthMethodFound) {
                authMethodSelectionResponse[1] = (byte) 0xFF; // no acceptable methods
                out.write(authMethodSelectionResponse);
                out.flush();
                throw new SmackException.SmackMessageException("Authentication method not supported");
            }

            authMethodSelectionResponse[1] = (byte) 0x00; // no-authentication method
            out.write(authMethodSelectionResponse);
            out.flush();

            // receive connection request
            byte[] connectionRequest = Socks5Utils.receiveSocks5Message(in);

            // extract digest
            String responseDigest = new String(connectionRequest, 5, connectionRequest[4], StandardCharsets.UTF_8);

            // return error if digest is not allowed
            if (!allowAllConnections && !Socks5Proxy.this.allowedConnections.contains(responseDigest)) {
                connectionRequest[1] = (byte) 0x05; // set return status to 5 (connection refused)
                out.write(connectionRequest);
                out.flush();

                throw new SmackException.SmackMessageException(
                                "Connection with digest '" + responseDigest + "' is not allowed");
            }

            // Store the connection before we send the return status.
            Socks5Proxy.this.connectionMap.put(responseDigest, socket);

            connectionRequest[1] = (byte) 0x00; // set return status to 0 (success)
            out.write(connectionRequest);
            out.flush();
        }

    }

    public static Socket getSocketForDigest(String digest) {
        for (Socks5Proxy socks5Proxy : RUNNING_PROXIES) {
            Socket socket = socks5Proxy.getSocket(digest);
            if (socket != null) {
                return socket;
            }
        }
        return null;
    }

    static List<Socks5Proxy> getRunningProxies() {
        return RUNNING_PROXIES;
    }
}


text:
package com.example.oauth;

import java.io.IOException;

import com.example.oauth.fragment.SelectAccountDialogFragment;
import com.example.oauth.fragment.SelectAccountDialogFragment.SelectAccountDialogProtocol;
import com.loopj.android.http.*;

import android.os.Bundle;
import android.accounts.*;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class GoogleLoginActivity extends Activity implements SelectAccountDialogProtocol {
	private AccountManager mAccountManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_google_login);

		findViewById(R.id.google_login_button).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View view) {
						selectAccount();
					}
				});
	}

	private void selectAccount() {
		mAccountManager = AccountManager.get(GoogleLoginActivity.this);
		Account[] accounts = mAccountManager.getAccountsByType("com.google");

		if (accounts.length == 0) {
			Toast.makeText(getApplicationContext(), R.string.no_account_found_message, Toast.LENGTH_SHORT).show();
		} else if (accounts.length == 1) {
			getTokenForAccount(accounts[0]);
		} else {
			String[] accountNames = new String[accounts.length];

			for (int i = 0; i < accounts.length; i++) {
				accountNames[i] = accounts[i].name;
			}

			DialogFragment newFragment = SelectAccountDialogFragment.newInstance(R.string.select_account_dialog_title, accountNames);
			newFragment.show(getFragmentManager(), "dialog");
		}
	}

	public void gotAccount(int index) {
		Account[] accounts = mAccountManager.getAccountsByType("com.google");
		getTokenForAccount(accounts[index]);
	}

	@Override
	public void onBackPressed() {
		// Exit gracefully by starting OS Home Activity
		Intent setIntent = new Intent(Intent.ACTION_MAIN);
		setIntent.addCategory(Intent.CATEGORY_HOME);
		setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(setIntent);
	}

	private void getTokenForAccount(Account account) {
		Bundle options = new Bundle();

		mAccountManager.getAuthToken(
				account,
				"oauth2:https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
				options,
				this,
				new OnTokenAcquired(),
				null
				);
	}

	private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
		@Override
		public void run(AccountManagerFuture<Bundle> result) {

			Bundle bundle = null;
			try {
				bundle = result.getResult();

				String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
				Intent launch = (Intent) result.getResult().get(AccountManager.KEY_INTENT);

				if (launch != null) {
					startActivityForResult(launch, 0);
					return;
				}

				requestAPIKeyFromOAuthToken(token);
			} catch (OperationCanceledException e) {
				e.printStackTrace();
			} catch (AuthenticatorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	private void requestAPIKeyFromOAuthToken(String token) {
		AsyncHttpClient client = new AsyncHttpClient();
		RequestParams params = new RequestParams("token", token);

		client.post("https://myrailsapp.com/api/v1/auth/verify", params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String response) {
				Log.w("OAUTH", "Got API key from server: " + response);
				finish();
			}

			@Override
			public void onFailure(Throwable e) {
				Log.w("OAUTH", "Error getting API key");
				Toast.makeText(getApplicationContext(), R.string.connection_error_message, Toast.LENGTH_LONG).show();

				e.printStackTrace();
			}
		});
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//package verteiltesysteme.p2;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 *
 * @author Katharina
 */
public class KuehlschrankServer extends Thread {

    DatagramSocket dS;
    String s;
    String product = "";
    String rotwein = "";
    String butter = "";
    String milch = "";
    String milchreis = "";

    KuehlschrankServer(DatagramSocket datagramSocket) {
        this.dS = datagramSocket;
    }

    public void run() {
        try {
            Webserver webserver = new Webserver();
            webserver.start();

            /*
                Paket zum Empfang vorbereiten
            */
            // Speicherplatz anlegen
            byte[] data = new byte[65536];
            DatagramPacket dP = new DatagramPacket(data, data.length);

            while (true) {
                // Warten bis ein Paket eintrifft. Receive() legt die empfangen
                // Daten in datagramPacket ab

                dS.receive(dP);
                s = new String(data, 0, dP.getLength());
                // Timeout
                dS.setSoTimeout(5000);

                // Paketinhalt ausgeben
                echo(s);

                product = s.substring(0, s.indexOf(":"));

                switch (product){
                    case "Rotwein (Merlot)":
                        rotwein += s.substring(s.indexOf(":") + 1, s.indexOf("%") + 1);
                        webserver.sendMessage(product + rotwein);
                        break;
                    case "Butter":
                        butter += s.substring(s.indexOf(":") + 1, s.indexOf("%") + 1);
                        webserver.sendMessage(product + butter);
                        break;
                    case "H-Milch 3.5":
                        milch += s.substring(s.indexOf(":") + 1, s.indexOf("%") + 1);
                        webserver.sendMessage(product + milch);
                        break;
                    case "Muellers Milchreis":
                        milchreis += s.substring(s.indexOf(":") + 1, s.indexOf("%") + 1);
                        webserver.sendMessage(product + milchreis);
                        break;
                }

            }

        }
        catch (Exception e) {
            System.out.println("Timeout abgelaufen");
            dS.close();
        }
    }

    public static void echo(String message) {
        System.out.println(message);
    }

}


text:
"""This module contains the GSoC Comment Model."""

from google.appengine.ext import db

from django.utils.translation import ugettext

import soc.models.role

class GSoCComment(db.Model):
  """Model of a comment on a work.

  A comment is usually associated with a Work or a Proposal,
  for example a Document or a Student Proposal, and with a user, the author.
  There are two types of comment, public (i.e. visible to the student),
  or private (i.e. visible to programme/club staff). Neither type are
  visible to people who are not connected to the work being commented on.

  Parent:
    soc.modules.gsoc.models.proposal.Proposal
  """

  #: A required many:1 relationship with a comment entity indicating
  #: the user who provided that comment.
  author = db.ReferenceProperty(reference_class=soc.models.role.Profile,
      required=True, collection_name="commented")

  #: The rich textual content of this comment
  content = db.TextProperty(verbose_name='')

  #: Indicated if the comment should be visible to the appropriate student
  is_private = db.BooleanProperty(default=True,
      verbose_name=ugettext('Private'))
  is_private.help_text = ugettext(
      'Whether this comment will only be seen by admins and mentors')

  #: Date when the comment was added
  created = db.DateTimeProperty(auto_now_add=True)


text:
#pragma once
#include <map>
#include <vector>
#include "Transponder.h"
#include "Service.h"

class ChannelList:public std::map<Transponder*,std::vector<Service*>> {
public:
	/**
	 * Reads a channel list from a file
	 */
	ChannelList(std::string const &filename);
	Transponder *transponder(std::string const &name, std::string const &providerName="") const;
	Service *service(std::string const &name, std::string const &providerName="") const;
	std::pair<Transponder const *,Service const *> find(std::string const &name, std::string const &providerName="") const;
};


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { TaskStatusDetailsComponent } from './task-status-details.component';

xdescribe('TaskStatusDetailsComponent', () => {
  let component: TaskStatusDetailsComponent;
  let fixture: ComponentFixture<TaskStatusDetailsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [TaskStatusDetailsComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TaskStatusDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create component', () => {
    expect(component).toBeTruthy();
  });
});


text:
package distributed.systems.launchers;

import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;

import distributed.systems.network.Address;
import distributed.systems.network.ConnectionException;
import distributed.systems.network.LocalSocket;
import distributed.systems.network.NodeAddress;
import distributed.systems.network.NodeType;
import distributed.systems.network.PlayerNode;
import distributed.systems.network.ServerNode;

public class Server {

	/**
	 * arg[0] = ip of server
	 * arg[1] = port of server
	 */
	public static void main(String[] args) throws RemoteException, ConnectionException {
		securitySetup();
		if(args.length < 1) {
			throw new RuntimeException("Invalid format requires the arguments: <myport> <ip> <port> (connect to cluster) or <myport> (create cluster)");
		}
		ServerNode server1;
		if(args.length == 1) {
			System.out.println("Creating cluster on port " + args[0]);
			server1 = new ServerNode(Integer.valueOf(args[0]));
			server1.startCluster();
		} else if(args.length == 2) {
			System.out.println("Creating cluster on port " + args[1] + " with ip " + args[0]);
			server1 = new ServerNode(Integer.valueOf(args[1]));
			server1.startCluster();
			server1.getAddress().setPhysicalAddress(new Address(args[0], Integer.valueOf(args[1])));
		} else {
			System.out.println("Connecting to cluster on " + args[1] + ":" + args[2]);
			server1 = new ServerNode(Integer.valueOf(args[0]));
			server1.connect(discoverServer(args[1], Integer.valueOf(args[2])));
		}

		for(String arg : args) {
			if(arg.equalsIgnoreCase("viewer")) {
				System.out.println("Launching viewer");
				server1.launchViewer();
			}
		}
	}

	public static NodeAddress discoverServer(String ip, int port) throws RemoteException, ConnectionException {
		LocalSocket socket = LocalSocket.connectTo(ip, port);
		String[] bindings = socket.getRegistry().list();
		for(String binding : bindings) {
			NodeAddress nodeAddress = NodeAddress.fromAddress(binding);
			if(nodeAddress.getType().equals(NodeType.SERVER)) {
				nodeAddress.setPhysicalAddress(new Address(ip, port));
				return nodeAddress;
			}
		}
		throw new RuntimeException("No server found on the provided location: " + ip + ":" + port);
	}

	public static void securitySetup() {
		System.setProperty("java.security.policy","file:./my.policy");
		// Create and install a security manager
		if (System.getSecurityManager() == null) {
			System.setSecurityManager(new RMISecurityManager());
		}
	}
}


text:
import { take } from 'redux-saga/effects'

function* logActions() {
  while (true) {
    const action = yield take()
    console.log(action)
  }
}

export default logActions


text:
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>

    <style type="text/css">

    </style>
</head>
<body>
<input id="man-news" name="man-news">
<input name="milkman">
<input id="letterman" name="new-letterman">
<input name="newmilk">

<script>
    $( "input[id][name$='man']" ).val( "only this one" );
</script>

</body>
</html>


text:
package org.sakaiproject.gradebookng.tool.actions;

import com.fasterxml.jackson.databind.JsonNode;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.model.Model;
import org.sakaiproject.gradebookng.tool.model.GbModalWindow;
import org.sakaiproject.gradebookng.tool.pages.GradebookPage;
import org.sakaiproject.gradebookng.tool.panels.CourseGradeOverrideLogPanel;

import java.io.Serializable;

public class ViewCourseGradeLogAction extends InjectableAction implements Serializable {

	private static final long serialVersionUID = 1L;

	public ViewCourseGradeLogAction() {
	}

	@Override
	public ActionResponse handleEvent(final JsonNode params, final AjaxRequestTarget target) {
		final String studentUuid = params.get("studentId").asText();

		final GradebookPage page = (GradebookPage) target.getPage();
		final GbModalWindow window = page.getUpdateCourseGradeDisplayWindow();

		window.setStudentToReturnFocusTo(studentUuid);
		window.setReturnFocusToCourseGrade();
		window.setContent(new CourseGradeOverrideLogPanel(window.getContentId(), Model.of(studentUuid), window));
		window.showUnloadConfirmation(false);
		window.show(target);

		return new EmptyOkResponse();
	}
}


text:
title: iOS手势识别的几个问题
date: 2014-07-01 17:07
categories: iOS
---
![shoushi](http://pic.kyfxbl.com/shoushi.jpg)
iOS手势识别的几个问题
<!--more-->

# 只让部分subview响应手势

比如一个view hierarchical下面,挂着3个subview,只想让其中的一个subview响应tap手势,有2种做法:

第一种方法,把UIGestureRecognizer挂到目标subview上

第二种方法,把UIGestureRecognizer挂到父view上,然后让另外2个subview不响应:

```
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer;
```

在这个delegate方法中return NO就可以了

# 让UILabel也能响应手势

默认情况下,UILabel和UIImage这些UIView无法响应手势,需要设置:

```
imageView.userInteractionEnabled = YES;
```

# 让手势和UITableViewCell点击共存

我在UITableView里挂了一个UIGestureRecognizer,结果发现手势识别覆盖了TableCell的触摸响应事件,需要设置"事件冒泡"

```
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:controller action:@selector(hideSubViews:)];
[singleTap setNumberOfTapsRequired:1];
[singleTap setNumberOfTouchesRequired:1];
singleTap.cancelsTouchesInView = NO;
```


text:
@class SDLChoiceCell;
@class SDLChoiceSet;
@class SDLFileManager;
@class SDLKeyboardProperties;
@class SDLWindowCapability;

@protocol SDLConnectionManagerType;

NS_ASSUME_NONNULL_BEGIN

typedef void(^SDLUploadChoicesCompletionHandler)(NSSet<SDLChoiceCell *> *updatedLoadedCells, NSError *_Nullable error);

@interface SDLPreloadPresentChoicesOperation : SDLAsynchronousOperation

/// The cells that are loaded on the head unit
@property (strong, nonatomic) NSSet<SDLChoiceCell *> *loadedCells;

// Preload only init
- (instancetype)initWithConnectionManager:(id<SDLConnectionManagerType>)connectionManager fileManager:(SDLFileManager *)fileManager displayName:(NSString *)displayName windowCapability:(SDLWindowCapability *)defaultMainWindowCapability isVROptional:(BOOL)isVROptional cellsToPreload:(NSArray<SDLChoiceCell *> *)cellsToPreload loadedCells:(NSSet<SDLChoiceCell *> *)loadedCells preloadCompletionHandler:(SDLUploadChoicesCompletionHandler)preloadCompletionHandler;

/// Preload and Present Init
- (instancetype)initWithConnectionManager:(id<SDLConnectionManagerType>)connectionManager fileManager:(SDLFileManager *)fileManager choiceSet:(SDLChoiceSet *)choiceSet mode:(SDLInteractionMode)mode  keyboardProperties:(nullable SDLKeyboardProperties *)originalKeyboardProperties keyboardDelegate:(nullable id<SDLKeyboardDelegate>)keyboardDelegate cancelID:(UInt16)cancelID displayName:(NSString *)displayName windowCapability:(SDLWindowCapability *)windowCapability isVROptional:(BOOL)isVROptional loadedCells:(NSSet<SDLChoiceCell *> *)loadedCells preloadCompletionHandler:(SDLUploadChoicesCompletionHandler)preloadCompletionHandler;

@end

NS_ASSUME_NONNULL_END


text:
package main

import (
	"fmt"
	"strings"
)

func main() {
	fmt.Println(strings.Title("her royal highness"))
}