text:
//===- CodegenNameGenerator.cpp - Codegen name generation -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Determines the name that the symbol will get for code generation.
//
//===----------------------------------------------------------------------===//

#include "clang/Index/CodegenNameGenerator.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Mangle.h"
#include "clang/AST/VTableBuilder.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Mangler.h"
#include "llvm/Support/raw_ostream.h"

using namespace clang;
using namespace clang::index;

struct CodegenNameGenerator::Implementation {
  std::unique_ptr<MangleContext> MC;
  llvm::DataLayout DL;

  Implementation(ASTContext &Ctx)
    : MC(Ctx.createMangleContext()),
      DL(Ctx.getTargetInfo().getDataLayout()) {}

  bool writeName(const Decl *D, raw_ostream &OS) {
    // First apply frontend mangling.
    SmallString<128> FrontendBuf;
    llvm::raw_svector_ostream FrontendBufOS(FrontendBuf);
    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
      if (FD->isDependentContext())
        return true;
      if (writeFuncOrVarName(FD, FrontendBufOS))
        return true;
    } else if (auto *VD = dyn_cast<VarDecl>(D)) {
      if (writeFuncOrVarName(VD, FrontendBufOS))
        return true;
    } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
      MC->mangleObjCMethodNameWithoutSize(MD, OS);
      return false;
    } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
      writeObjCClassName(ID, FrontendBufOS);
    } else {
      return true;
    }

    // Now apply backend mangling.
    llvm::Mangler::getNameWithPrefix(OS, FrontendBufOS.str(), DL);
    return false;
  }

  std::string getName(const Decl *D) {
    std::string Name;
    {
      llvm::raw_string_ostream OS(Name);
      writeName(D, OS);
    }
    return Name;
  }

  enum ObjCKind {
    ObjCClass,
    ObjCMetaclass,
  };

  std::vector<std::string> getAllManglings(const ObjCContainerDecl *OCD) {
    StringRef ClassName;
    if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
      ClassName = OID->getObjCRuntimeNameAsString();
    else if (const auto *OID = dyn_cast<ObjCImplementationDecl>(OCD))
      ClassName = OID->getObjCRuntimeNameAsString();

    if (ClassName.empty())
      return {};

    auto Mangle = [&](ObjCKind Kind, StringRef ClassName) -> std::string {
      SmallString<40> Mangled;
      auto Prefix = getClassSymbolPrefix(Kind, OCD->getASTContext());
      llvm::Mangler::getNameWithPrefix(Mangled, Prefix + ClassName, DL);
      return Mangled.str();
    };

    return {
      Mangle(ObjCClass, ClassName),
      Mangle(ObjCMetaclass, ClassName),
    };
  }

  std::vector<std::string> getAllManglings(const Decl *D) {
    if (const auto *OCD = dyn_cast<ObjCContainerDecl>(D))
      return getAllManglings(OCD);

    if (!(isa<CXXRecordDecl>(D) || isa<CXXMethodDecl>(D)))
      return {};

    const NamedDecl *ND = cast<NamedDecl>(D);

    ASTContext &Ctx = ND->getASTContext();
    std::unique_ptr<MangleContext> M(Ctx.createMangleContext());

    std::vector<std::string> Manglings;

    auto hasDefaultCXXMethodCC = [](ASTContext &C, const CXXMethodDecl *MD) {
      auto DefaultCC = C.getDefaultCallingConvention(/*IsVariadic=*/false,
                                                     /*IsCSSMethod=*/true);
      auto CC = MD->getType()->getAs<FunctionProtoType>()->getCallConv();
      return CC == DefaultCC;
    };

    if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND)) {
      Manglings.emplace_back(getMangledStructor(CD, Ctor_Base));

      if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily())
        if (!CD->getParent()->isAbstract())
          Manglings.emplace_back(getMangledStructor(CD, Ctor_Complete));

      if (Ctx.getTargetInfo().getCXXABI().isMicrosoft())
        if (CD->hasAttr<DLLExportAttr>() && CD->isDefaultConstructor())
          if (!(hasDefaultCXXMethodCC(Ctx, CD) && CD->getNumParams() == 0))
            Manglings.emplace_back(getMangledStructor(CD, Ctor_DefaultClosure));
    } else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND)) {
      Manglings.emplace_back(getMangledStructor(DD, Dtor_Base));
      if (Ctx.getTargetInfo().getCXXABI().isItaniumFamily()) {
        Manglings.emplace_back(getMangledStructor(DD, Dtor_Complete));
        if (DD->isVirtual())
          Manglings.emplace_back(getMangledStructor(DD, Dtor_Deleting));
      }
    } else if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(ND)) {
      Manglings.emplace_back(getName(ND));
      if (MD->isVirtual())
        if (const auto *TIV = Ctx.getVTableContext()->getThunkInfo(MD))
          for (const auto &T : *TIV)
            Manglings.emplace_back(getMangledThunk(MD, T));
    }

    return Manglings;
  }

private:
  bool writeFuncOrVarName(const NamedDecl *D, raw_ostream &OS) {
    if (MC->shouldMangleDeclName(D)) {
      if (const auto *CtorD = dyn_cast<CXXConstructorDecl>(D))
        MC->mangleCXXCtor(CtorD, Ctor_Complete, OS);
      else if (const auto *DtorD = dyn_cast<CXXDestructorDecl>(D))
        MC->mangleCXXDtor(DtorD, Dtor_Complete, OS);
      else
        MC->mangleName(D, OS);
      return false;
    } else {
      IdentifierInfo *II = D->getIdentifier();
      if (!II)
        return true;
      OS << II->getName();
      return false;
    }
  }

  void writeObjCClassName(const ObjCInterfaceDecl *D, raw_ostream &OS) {
    OS << getClassSymbolPrefix(ObjCClass, D->getASTContext());
    OS << D->getObjCRuntimeNameAsString();
  }

  static StringRef getClassSymbolPrefix(ObjCKind Kind, const ASTContext &Context) {
    if (Context.getLangOpts().ObjCRuntime.isGNUFamily())
      return Kind == ObjCMetaclass ? "_OBJC_METACLASS_" : "_OBJC_CLASS_";
    return Kind == ObjCMetaclass ? "OBJC_METACLASS_$_" : "OBJC_CLASS_$_";
  }

  std::string getMangledStructor(const NamedDecl *ND, unsigned StructorType) {
    std::string FrontendBuf;
    llvm::raw_string_ostream FOS(FrontendBuf);

    if (const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(ND))
      MC->mangleCXXCtor(CD, static_cast<CXXCtorType>(StructorType), FOS);
    else if (const auto *DD = dyn_cast_or_null<CXXDestructorDecl>(ND))
      MC->mangleCXXDtor(DD, static_cast<CXXDtorType>(StructorType), FOS);

    std::string BackendBuf;
    llvm::raw_string_ostream BOS(BackendBuf);

    llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL);

    return BOS.str();
  }

  std::string getMangledThunk(const CXXMethodDecl *MD, const ThunkInfo &T) {
    std::string FrontendBuf;
    llvm::raw_string_ostream FOS(FrontendBuf);

    MC->mangleThunk(MD, T, FOS);

    std::string BackendBuf;
    llvm::raw_string_ostream BOS(BackendBuf);

    llvm::Mangler::getNameWithPrefix(BOS, FOS.str(), DL);

    return BOS.str();
  }
};

CodegenNameGenerator::CodegenNameGenerator(ASTContext &Ctx)
  : Impl(new Implementation(Ctx)) {
}

CodegenNameGenerator::~CodegenNameGenerator() {
}

bool CodegenNameGenerator::writeName(const Decl *D, raw_ostream &OS) {
  return Impl->writeName(D, OS);
}

std::string CodegenNameGenerator::getName(const Decl *D) {
  return Impl->getName(D);
}

std::vector<std::string> CodegenNameGenerator::getAllManglings(const Decl *D) {
  return Impl->getAllManglings(D);
}


text:
<?php

namespace LibBundle\Grid\SearchOperator;

use Doctrine\Common\Collections\Criteria;

class GreaterType implements OperatorTypeInterface
{
    public static function getLabel()
    {
        return 'greater';
    }

    public static function getNumberOfInput()
    {
        return 1;
    }

    public static function search(Criteria $criteria, $name, array $values)
    {
        $expr = Criteria::expr();
        $criteria->andWhere($expr->gt($name, $values[0]));
    }
}

redpajama_set_name: RedPajamaGithub


text:
NAMESPACE_UPP

#define LLOG(x) // LOG(x)
#define LTIMING(x) // RTIMING(x)

#ifdef PLATFORM_WIN32

static COLORREF sLightGray;

void StaticExitDraw_()
{
	Draw::FreeFonts();
}

EXITBLOCK
{
	StaticExitDraw_();
}

#ifndef PLATFORM_WINCE
void Add(LOGPALETTE *pal, int r, int g, int b)
{
	pal->palPalEntry[pal->palNumEntries].peRed   = min(r, 255);
	pal->palPalEntry[pal->palNumEntries].peGreen = min(g, 255);
	pal->palPalEntry[pal->palNumEntries].peBlue  = min(b, 255);
	pal->palPalEntry[pal->palNumEntries++].peFlags = PC_NOCOLLAPSE;
}

HPALETTE GetQlibPalette()
{
	static HPALETTE hQlibPalette;
	if(hQlibPalette) return hQlibPalette;
	Draw::InitColors();
	LOGPALETTE *pal = (LOGPALETTE *) new byte[sizeof(LOGPALETTE) + 256 * sizeof(PALETTEENTRY)];
	pal->palNumEntries = 0;
	pal->palVersion    = 0x300;
	for(int r = 0; r < 6; r++)
		for(int g = 0; g < 6; g++)
			for(int b = 0; b < 6; b++)
				Add(pal, 255 * r / 5, 255 * g / 5, 255 * b / 5);
	for(int q = 0; q <= 16; q++)
		Add(pal, 16 * q, 16 * q, 16 * q);
	Add(pal, GetRValue(sLightGray), GetGValue(sLightGray), GetBValue(sLightGray));
	hQlibPalette = CreatePalette(pal);
	delete[] pal;
	return hQlibPalette;
}
#endif

Draw& GLOBAL_VP(ScreenDraw, ScreenInfo, (true))

HDC ScreenHDC()
{
	return ScreenInfo();
}

static bool _AutoPalette = true;
bool Draw::AutoPalette() { return _AutoPalette; }
void Draw::SetAutoPalette(bool ap) { _AutoPalette = ap; }

COLORREF Draw::GetColor(Color c) const {
	COLORREF color = c;
#ifdef PLATFORM_WINCE
	return color;
#else
	if(!palette)
		return color;
	static Index<dword> *SColor;
	ONCELOCK {
		static Index<dword> StaticColor;
		StaticColor << RGB(0x00, 0x00, 0x00) << RGB(0x80, 0x00, 0x00) << RGB(0x00, 0x80, 0x00)
					<< RGB(0x80, 0x80, 0x00) << RGB(0x00, 0x00, 0x80) << RGB(0x80, 0x00, 0x80)
					<< RGB(0x00, 0x80, 0x80) << RGB(0xC0, 0xC0, 0xC0) << RGB(0xC0, 0xDC, 0xC0)
					<< RGB(0xA6, 0xCA, 0xF0) << RGB(0xFF, 0xFB, 0xF0) << RGB(0xA0, 0xA0, 0xA4)
					<< RGB(0x80, 0x80, 0x80) << RGB(0xFF, 0x00, 0x00) << RGB(0x00, 0xFF, 0x00)
					<< RGB(0xFF, 0xFF, 0x00) << RGB(0x00, 0x00, 0xFF) << RGB(0xFF, 0x00, 0xFF)
					<< RGB(0x00, 0xFF, 0xFF) << RGB(0xFF, 0xFF, 0xFF);
		SColor = &StaticColor;
	}
	if(color16 || !AutoPalette())
		return GetNearestColor(handle, color);
	if(SColor->Find(color) >= 0)
		return color;
	if(color == sLightGray)
		return PALETTEINDEX(216 + 17);
	int r = GetRValue(color);
	int g = GetGValue(color);
	int b = GetBValue(color);
	return PALETTEINDEX(r == g && g == b ? (r + 8) / 16 + 216
		                                 : (r + 25) / 51 * 36 +
		                                   (g + 25) / 51 * 6 +
		                                   (b + 25) / 51);
#endif
}

void Draw::InitColors()
{
}

void Draw::SetColor(Color color)
{
	DrawLock __;
	LLOG("SetColor " << color);
	if(color != lastColor) {
		LLOG("Setting, lastColor:" << FormatIntHex(lastColor.GetRaw())
			<< " color:" << FormatIntHex(color.GetRaw()) <<
		     " GetColor:" << FormatIntHex(GetColor(color)) << " palette:" << palette);
		HBRUSH oldBrush = actBrush;
		HBRUSH h;
		if(!IsNull(color))
			h = (HBRUSH) SelectObject(handle, actBrush = CreateSolidBrush(GetColor(color)));
		else {
			HGDIOBJ empty = GetStockObject(HOLLOW_BRUSH);
			h = (HBRUSH) SelectObject(handle, empty);
			actBrush = NULL;
		}
		ASSERT(h);
		if(!orgBrush) orgBrush = h;
		if(oldBrush) DeleteObject(oldBrush);
		lastColor = color;
	}
}

void Draw::SetDrawPen(int width, Color color) {
	DrawLock __;
	if(IsNull(width))
		width = PEN_NULL;
	if(width != lastPen || color != lastPenColor) {
		static int penstyle[] = {
			PS_NULL, PS_SOLID, PS_DASH,
		#ifndef PLATFORM_WINCE
			PS_DOT, PS_DASHDOT, PS_DASHDOTDOT
		#endif
		};
		HPEN oldPen = actPen;
		actPen = CreatePen(width < 0 ? penstyle[-width - 1] : PS_SOLID,
			               width < 0 ? 0 : width, GetColor(color));
		HPEN h = (HPEN) SelectObject(handle, actPen);
		if(!orgPen) orgPen = h;
		if(oldPen) DeleteObject(oldPen);
		lastPen = width;
		lastPenColor = color;
	}
}

void Draw::SetOrg() {
	DrawLock __;
#ifdef PLATFORM_WINCE
	::SetViewportOrgEx(handle, actual_offset.x, actual_offset.y, 0);
#else
	LLOG("Draw::SetOrg: clip = " << GetClip() << ", offset = " << actual_offset);
	::SetWindowOrgEx(handle, -actual_offset.x, -actual_offset.y, 0);
	LLOG("//Draw::SetOrg: clip = " << GetClip());
#endif
}

#ifndef PLATFORM_WINCE
Point Draw::LPtoDP(Point p) const {
	DrawLock __;
	::LPtoDP(handle, p, 1);
	return p;
}

Point Draw::DPtoLP(Point p) const {
	DrawLock __;
	::DPtoLP(handle, p, 1);
	return p;
}

Rect  Draw::LPtoDP(const Rect& r) const {
	DrawLock __;
	Rect w = r;
	::LPtoDP(handle, reinterpret_cast<POINT *>(&w), 2);
	return w;
}

Rect  Draw::DPtoLP(const Rect& r) const {
	DrawLock __;
	Rect w = r;
	::LPtoDP(handle, reinterpret_cast<POINT *>(&w), 2);
	return w;
}
#endif

Size Draw::GetSizeCaps(int i, int j) const {
	DrawLock __;
	return Size(GetDeviceCaps(handle, i), GetDeviceCaps(handle, j));
}

void Draw::DotsMode()
{
	::SetMapMode(handle, MM_ANISOTROPIC);
	::SetViewportExtEx(handle, nativeDpi.cx, nativeDpi.cy, NULL);
	::SetViewportOrgEx(handle, 0, 0, NULL);
	::SetWindowExtEx(handle, 600, 600, NULL);
	::SetWindowOrgEx(handle, 0, 0, NULL);
}

void Draw::BeginNative()
{
	if(inchPixels != nativeDpi && ++native == 1) {
		::SetMapMode(handle, MM_TEXT);
		actual_offset_bak = actual_offset;
		Native(actual_offset);
		SetOrg();
	}
}

void Draw::EndNative()
{
	if(inchPixels != nativeDpi && --native == 0) {
		DotsMode();
		actual_offset = actual_offset_bak;
		SetOrg();
	}
}

void Draw::LoadCaps() {
	DrawLock __;
	color16 = false;
	palette = (GetDeviceCaps(handle, RASTERCAPS) & RC_PALETTE);
	if(palette)
		color16 = GetDeviceCaps(handle, SIZEPALETTE) != 256;
	pageDots = pagePixels = GetSizeCaps(HORZRES, VERTRES);
	pageMMs = GetSizeCaps(HORZSIZE, VERTSIZE);
	nativeDpi = inchPixels = GetSizeCaps(LOGPIXELSX, LOGPIXELSY);
	sheetPixels = GetSizeCaps(PHYSICALWIDTH, PHYSICALHEIGHT);
	pageOffset = GetSizeCaps(PHYSICALOFFSETX, PHYSICALOFFSETY);
	is_mono = GetDeviceCaps(handle, BITSPIXEL) == 1 && GetDeviceCaps(handle, PLANES) == 1;
}

void Draw::SetDevice(const char *s) {
	DrawLock __;
	static Index<String> map;
	device = map.FindAdd(s) + 1;
	LoadCaps();
}

void Draw::Cinit() {
	DrawLock __;
	lastColor = Color::FromCR(COLORREF(-5));
	lastPenColor = Color::FromCR(COLORREF(-5));
	lastTextColor = COLORREF(-1);
	lastPen = Null;
	actBrush = orgBrush = NULL;
	actPen = orgPen = NULL;
	orgFont = NULL;
	lastFont.Clear();
}

void Draw::Init() {
	DrawLock __;
	Cinit();
	SetBkMode(handle, TRANSPARENT);
	::SetTextAlign(handle, TA_BASELINE);
#ifdef PLATFORM_WINCE
	actual_offset = Point(0, 0);
#else
	::GetViewportOrgEx(handle, actual_offset);
#endif
	LoadCaps();
}

void Draw::Reset() {
	DrawLock __;
	device = 0;
	pixels = true;
	printer = aborted = backdraw = is_mono = false;
}

Draw::Draw() {
	DrawLock __;
	native = 0;
	InitColors();
	InitFonts();
	actual_offset = Point(0, 0);
	Reset();
	handle = NULL;
}

Draw::Draw(HDC hdc) {
	DrawLock __;
	native = 0;
	InitColors();
	InitFonts();
	Reset();
	Attach(hdc);
}

void Draw::Unselect0() {
	DrawLock __;
	if(orgPen) SelectObject(handle, orgPen);
	if(orgBrush) SelectObject(handle, orgBrush);
	if(orgFont) SelectObject(handle, orgFont);
	if(actPen) DeleteObject(actPen);
	if(actBrush) DeleteObject(actBrush);
	Cinit();
}

void Draw::Unselect() {
	DrawLock __;
	while(cloff.GetCount())
		End();
	Unselect0();
}

Draw::~Draw() {
	DrawLock __;
	if(handle)
		Unselect();
}

HDC Draw::BeginGdi() {
	DrawLock __;
	Begin();
	return handle;
}

void Draw::EndGdi() {
	DrawLock __;
	Unselect0();
	End();
}

NilDraw::NilDraw() {
	DrawLock __;
	Attach(ScreenInfo().GetHandle());
	pixels = false;
	cloff.Clear();
}

NilDraw::~NilDraw() {
	DrawLock __;
	Detach();
}

void BackDraw::Create(Draw& w, int cx, int cy) {
	ASSERT(w.GetHandle());
	DrawLock __;
	Destroy();
	size.cx = cx;
	size.cy = cy;
	hbmp = ::CreateCompatibleBitmap(w.GetHandle(), cx, cy);
	handle = ::CreateCompatibleDC(w.GetHandle());
	ASSERT(hbmp);
	ASSERT(handle);
#ifndef PLATFORM_WINCE
	if(w.PaletteMode() && AutoPalette()) {
		::SelectPalette(handle, GetQlibPalette(), FALSE);
		::RealizePalette(handle);
	}
#endif
	hbmpold = (HBITMAP) ::SelectObject(handle, hbmp);
	Init();
	backdraw = true;
}

void BackDraw::Put(Draw& w, int x, int y) {
	DrawLock __;
	ASSERT(handle);
	LTIMING("BackDraw::Put");
#ifdef PLATFORM_WINCE
	::SetViewportOrgEx(handle, 0, 0, 0);
#else
	::SetWindowOrgEx(handle, 0, 0, NULL);
#endif
	::BitBlt(w, x, y, size.cx, size.cy, *this, 0, 0, SRCCOPY);
}

void BackDraw::Destroy() {
	DrawLock __;
	if(handle) {
		Unselect();
		::SelectObject(handle, hbmpold);
		::DeleteDC(handle);
		::DeleteObject(hbmp);
		handle = NULL;
	}
}

ScreenDraw::ScreenDraw(bool ic) {
	DrawLock __;
#ifdef PLATFORM_WINCE
	Attach(CreateDC(NULL, NULL, NULL, NULL));
#else
	Attach((ic ? CreateIC : CreateDC)("DISPLAY", NULL, NULL, NULL));
	if(PaletteMode() && AutoPalette()) {
		SelectPalette(handle, GetQlibPalette(), TRUE);
		RealizePalette(handle);
	}
#endif
}

ScreenDraw::~ScreenDraw() {
	DrawLock __;
	Unselect();
	DeleteDC(handle);
}

#ifndef PLATFORM_WINCE

void PrintDraw::InitPrinter()
{
	DrawLock __;
	Init();
	printer = true;
	pixels = false;
	nativeDpi = inchPixels;
	DotsMode();
	native = 0;
	actual_offset = Point(0, 0);
	pageDots.cx = 600 * pagePixels.cx / inchPixels.cx;
	pageDots.cy = 600 * pagePixels.cy / inchPixels.cy;
	inchPixels.cx = 600;
	inchPixels.cy = 600;
}

void PrintDraw::StartPage()
{
	DrawLock __;
	if(IsAborted()) return;
	Unselect();
	if(::StartPage(handle) <= 0)
		Abort();
	else
		InitPrinter();
}

void PrintDraw::EndPage()
{
	DrawLock __;
	if(IsAborted()) return;
	Unselect();
	ASSERT(printer);
	if(::EndPage(handle) <= 0)
		Abort();
}

PrintDraw::PrintDraw(HDC hdc, const char *docname)
   : Draw(hdc)
{
	DrawLock __;
	DOCINFO di;
	memset(&di, 0, sizeof(di));
	di.cbSize = sizeof(di);
	String sys_docname = ToSystemCharset(docname);
	di.lpszDocName = ~sys_docname;
	if(::StartDoc(hdc, &di) <= 0) {
		Abort();
		return;
	}
	InitPrinter();
}

PrintDraw::~PrintDraw() {
	DrawLock __;
	if(IsAborted())
		::AbortDoc(handle);
	else
		::EndDoc(handle);
	DeleteDC(handle);
	handle = NULL;
}
#endif

#endif

END_UPP_NAMESPACE


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Pap. Proc. R. Soc. Tasm. (1921)

#### Original name
Gymnomyces solidus Rodway

### Remarks
null


text:
#include <rte_cryptodev.h>
#include <rte_malloc.h>

#include "rte_cryptodev_scheduler_operations.h"
#include "scheduler_pmd_private.h"

#define DEF_PKT_SIZE_THRESHOLD			(0xffffff80)
#define SLAVE_IDX_SWITCH_MASK			(0x01)
#define PRIMARY_SLAVE_IDX			0
#define SECONDARY_SLAVE_IDX			1
#define NB_PKT_SIZE_SLAVES			2

/** pkt size based scheduler context */
struct psd_scheduler_ctx {
	uint32_t threshold;
};

/** pkt size based scheduler queue pair context */
struct psd_scheduler_qp_ctx {
	struct scheduler_slave primary_slave;
	struct scheduler_slave secondary_slave;
	uint32_t threshold;
	uint8_t deq_idx;
} __rte_cache_aligned;

/** scheduling operation variables' wrapping */
struct psd_schedule_op {
	uint8_t slave_idx;
	uint16_t pos;
};

static uint16_t
schedule_enqueue(void *qp, struct rte_crypto_op **ops, uint16_t nb_ops)
{
	struct scheduler_qp_ctx *qp_ctx = qp;
	struct psd_scheduler_qp_ctx *psd_qp_ctx = qp_ctx->private_qp_ctx;
	struct rte_crypto_op *sched_ops[NB_PKT_SIZE_SLAVES][nb_ops];
	uint32_t in_flight_ops[NB_PKT_SIZE_SLAVES] = {
			psd_qp_ctx->primary_slave.nb_inflight_cops,
			psd_qp_ctx->secondary_slave.nb_inflight_cops
	};
	struct psd_schedule_op enq_ops[NB_PKT_SIZE_SLAVES] = {
		{PRIMARY_SLAVE_IDX, 0}, {SECONDARY_SLAVE_IDX, 0}
	};
	struct psd_schedule_op *p_enq_op;
	uint16_t i, processed_ops_pri = 0, processed_ops_sec = 0;
	uint32_t job_len;

	if (unlikely(nb_ops == 0))
		return 0;

	for (i = 0; i < nb_ops && i < 4; i++) {
		rte_prefetch0(ops[i]->sym);
		rte_prefetch0(ops[i]->sym->session);
	}

	for (i = 0; (i < (nb_ops - 8)) && (nb_ops > 8); i += 4) {
		rte_prefetch0(ops[i + 4]->sym);
		rte_prefetch0(ops[i + 4]->sym->session);
		rte_prefetch0(ops[i + 5]->sym);
		rte_prefetch0(ops[i + 5]->sym->session);
		rte_prefetch0(ops[i + 6]->sym);
		rte_prefetch0(ops[i + 6]->sym->session);
		rte_prefetch0(ops[i + 7]->sym);
		rte_prefetch0(ops[i + 7]->sym->session);

		/* job_len is initialized as cipher data length, once
		 * it is 0, equals to auth data length
		 */
		job_len = ops[i]->sym->cipher.data.length;
		job_len += (ops[i]->sym->cipher.data.length == 0) *
				ops[i]->sym->auth.data.length;
		/* decide the target op based on the job length */
		p_enq_op = &enq_ops[!(job_len & psd_qp_ctx->threshold)];

		/* stop schedule cops before the queue is full, this shall
		 * prevent the failed enqueue
		 */
		if (p_enq_op->pos + in_flight_ops[p_enq_op->slave_idx] ==
				qp_ctx->max_nb_objs) {
			i = nb_ops;
			break;
		}

		sched_ops[p_enq_op->slave_idx][p_enq_op->pos] = ops[i];
		p_enq_op->pos++;

		job_len = ops[i+1]->sym->cipher.data.length;
		job_len += (ops[i+1]->sym->cipher.data.length == 0) *
				ops[i+1]->sym->auth.data.length;
		p_enq_op = &enq_ops[!(job_len & psd_qp_ctx->threshold)];

		if (p_enq_op->pos + in_flight_ops[p_enq_op->slave_idx] ==
				qp_ctx->max_nb_objs) {
			i = nb_ops;
			break;
		}

		sched_ops[p_enq_op->slave_idx][p_enq_op->pos] = ops[i+1];
		p_enq_op->pos++;

		job_len = ops[i+2]->sym->cipher.data.length;
		job_len += (ops[i+2]->sym->cipher.data.length == 0) *
				ops[i+2]->sym->auth.data.length;
		p_enq_op = &enq_ops[!(job_len & psd_qp_ctx->threshold)];

		if (p_enq_op->pos + in_flight_ops[p_enq_op->slave_idx] ==
				qp_ctx->max_nb_objs) {
			i = nb_ops;
			break;
		}

		sched_ops[p_enq_op->slave_idx][p_enq_op->pos] = ops[i+2];
		p_enq_op->pos++;

		job_len = ops[i+3]->sym->cipher.data.length;
		job_len += (ops[i+3]->sym->cipher.data.length == 0) *
				ops[i+3]->sym->auth.data.length;
		p_enq_op = &enq_ops[!(job_len & psd_qp_ctx->threshold)];

		if (p_enq_op->pos + in_flight_ops[p_enq_op->slave_idx] ==
				qp_ctx->max_nb_objs) {
			i = nb_ops;
			break;
		}

		sched_ops[p_enq_op->slave_idx][p_enq_op->pos] = ops[i+3];
		p_enq_op->pos++;
	}

	for (; i < nb_ops; i++) {
		job_len = ops[i]->sym->cipher.data.length;
		job_len += (ops[i]->sym->cipher.data.length == 0) *
				ops[i]->sym->auth.data.length;
		p_enq_op = &enq_ops[!(job_len & psd_qp_ctx->threshold)];

		if (p_enq_op->pos + in_flight_ops[p_enq_op->slave_idx] ==
				qp_ctx->max_nb_objs) {
			i = nb_ops;
			break;
		}

		sched_ops[p_enq_op->slave_idx][p_enq_op->pos] = ops[i];
		p_enq_op->pos++;
	}

	processed_ops_pri = rte_cryptodev_enqueue_burst(
			psd_qp_ctx->primary_slave.dev_id,
			psd_qp_ctx->primary_slave.qp_id,
			sched_ops[PRIMARY_SLAVE_IDX],
			enq_ops[PRIMARY_SLAVE_IDX].pos);
	/* enqueue shall not fail as the slave queue is monitored */
	RTE_ASSERT(processed_ops_pri == enq_ops[PRIMARY_SLAVE_IDX].pos);

	psd_qp_ctx->primary_slave.nb_inflight_cops += processed_ops_pri;

	processed_ops_sec = rte_cryptodev_enqueue_burst(
			psd_qp_ctx->secondary_slave.dev_id,
			psd_qp_ctx->secondary_slave.qp_id,
			sched_ops[SECONDARY_SLAVE_IDX],
			enq_ops[SECONDARY_SLAVE_IDX].pos);
	RTE_ASSERT(processed_ops_sec == enq_ops[SECONDARY_SLAVE_IDX].pos);

	psd_qp_ctx->secondary_slave.nb_inflight_cops += processed_ops_sec;

	return processed_ops_pri + processed_ops_sec;
}

static uint16_t
schedule_enqueue_ordering(void *qp, struct rte_crypto_op **ops,
		uint16_t nb_ops)
{
	struct rte_ring *order_ring =
			((struct scheduler_qp_ctx *)qp)->order_ring;
	uint16_t nb_ops_to_enq = get_max_enqueue_order_count(order_ring,
			nb_ops);
	uint16_t nb_ops_enqd = schedule_enqueue(qp, ops,
			nb_ops_to_enq);

	scheduler_order_insert(order_ring, ops, nb_ops_enqd);

	return nb_ops_enqd;
}

static uint16_t
schedule_dequeue(void *qp, struct rte_crypto_op **ops, uint16_t nb_ops)
{
	struct psd_scheduler_qp_ctx *qp_ctx =
			((struct scheduler_qp_ctx *)qp)->private_qp_ctx;
	struct scheduler_slave *slaves[NB_PKT_SIZE_SLAVES] = {
			&qp_ctx->primary_slave, &qp_ctx->secondary_slave};
	struct scheduler_slave *slave = slaves[qp_ctx->deq_idx];
	uint16_t nb_deq_ops_pri = 0, nb_deq_ops_sec = 0;

	if (slave->nb_inflight_cops) {
		nb_deq_ops_pri = rte_cryptodev_dequeue_burst(slave->dev_id,
			slave->qp_id, ops, nb_ops);
		slave->nb_inflight_cops -= nb_deq_ops_pri;
	}

	qp_ctx->deq_idx = (~qp_ctx->deq_idx) & SLAVE_IDX_SWITCH_MASK;

	if (nb_deq_ops_pri == nb_ops)
		return nb_deq_ops_pri;

	slave = slaves[qp_ctx->deq_idx];

	if (slave->nb_inflight_cops) {
		nb_deq_ops_sec = rte_cryptodev_dequeue_burst(slave->dev_id,
				slave->qp_id, &ops[nb_deq_ops_pri],
				nb_ops - nb_deq_ops_pri);
		slave->nb_inflight_cops -= nb_deq_ops_sec;

		if (!slave->nb_inflight_cops)
			qp_ctx->deq_idx = (~qp_ctx->deq_idx) &
					SLAVE_IDX_SWITCH_MASK;
	}

	return nb_deq_ops_pri + nb_deq_ops_sec;
}

static uint16_t
schedule_dequeue_ordering(void *qp, struct rte_crypto_op **ops,
		uint16_t nb_ops)
{
	struct rte_ring *order_ring =
			((struct scheduler_qp_ctx *)qp)->order_ring;

	schedule_dequeue(qp, ops, nb_ops);

	return scheduler_order_drain(order_ring, ops, nb_ops);
}

static int
slave_attach(__rte_unused struct rte_cryptodev *dev,
		__rte_unused uint8_t slave_id)
{
	return 0;
}

static int
slave_detach(__rte_unused struct rte_cryptodev *dev,
		__rte_unused uint8_t slave_id)
{
	return 0;
}

static int
scheduler_start(struct rte_cryptodev *dev)
{
	struct scheduler_ctx *sched_ctx = dev->data->dev_private;
	struct psd_scheduler_ctx *psd_ctx = sched_ctx->private_ctx;
	uint16_t i;

	/* for packet size based scheduler, nb_slaves have to >= 2 */
	if (sched_ctx->nb_slaves < NB_PKT_SIZE_SLAVES) {
		CS_LOG_ERR("not enough slaves to start");
		return -1;
	}

	for (i = 0; i < dev->data->nb_queue_pairs; i++) {
		struct scheduler_qp_ctx *qp_ctx = dev->data->queue_pairs[i];
		struct psd_scheduler_qp_ctx *ps_qp_ctx =
				qp_ctx->private_qp_ctx;

		ps_qp_ctx->primary_slave.dev_id =
				sched_ctx->slaves[PRIMARY_SLAVE_IDX].dev_id;
		ps_qp_ctx->primary_slave.qp_id = i;
		ps_qp_ctx->primary_slave.nb_inflight_cops = 0;

		ps_qp_ctx->secondary_slave.dev_id =
				sched_ctx->slaves[SECONDARY_SLAVE_IDX].dev_id;
		ps_qp_ctx->secondary_slave.qp_id = i;
		ps_qp_ctx->secondary_slave.nb_inflight_cops = 0;

		ps_qp_ctx->threshold = psd_ctx->threshold;
	}

	if (sched_ctx->reordering_enabled) {
		dev->enqueue_burst = &schedule_enqueue_ordering;
		dev->dequeue_burst = &schedule_dequeue_ordering;
	} else {
		dev->enqueue_burst = &schedule_enqueue;
		dev->dequeue_burst = &schedule_dequeue;
	}

	return 0;
}

static int
scheduler_stop(struct rte_cryptodev *dev)
{
	uint16_t i;

	for (i = 0; i < dev->data->nb_queue_pairs; i++) {
		struct scheduler_qp_ctx *qp_ctx = dev->data->queue_pairs[i];
		struct psd_scheduler_qp_ctx *ps_qp_ctx = qp_ctx->private_qp_ctx;

		if (ps_qp_ctx->primary_slave.nb_inflight_cops +
				ps_qp_ctx->secondary_slave.nb_inflight_cops) {
			CS_LOG_ERR("Some crypto ops left in slave queue");
			return -1;
		}
	}

	return 0;
}

static int
scheduler_config_qp(struct rte_cryptodev *dev, uint16_t qp_id)
{
	struct scheduler_qp_ctx *qp_ctx = dev->data->queue_pairs[qp_id];
	struct psd_scheduler_qp_ctx *ps_qp_ctx;

	ps_qp_ctx = rte_zmalloc_socket(NULL, sizeof(*ps_qp_ctx), 0,
			rte_socket_id());
	if (!ps_qp_ctx) {
		CS_LOG_ERR("failed allocate memory for private queue pair");
		return -ENOMEM;
	}

	qp_ctx->private_qp_ctx = (void *)ps_qp_ctx;

	return 0;
}

static int
scheduler_create_private_ctx(struct rte_cryptodev *dev)
{
	struct scheduler_ctx *sched_ctx = dev->data->dev_private;
	struct psd_scheduler_ctx *psd_ctx;

	if (sched_ctx->private_ctx)
		rte_free(sched_ctx->private_ctx);

	psd_ctx = rte_zmalloc_socket(NULL, sizeof(struct psd_scheduler_ctx), 0,
			rte_socket_id());
	if (!psd_ctx) {
		CS_LOG_ERR("failed allocate memory");
		return -ENOMEM;
	}

	psd_ctx->threshold = DEF_PKT_SIZE_THRESHOLD;

	sched_ctx->private_ctx = (void *)psd_ctx;

	return 0;
}
static int
scheduler_option_set(struct rte_cryptodev *dev, uint32_t option_type,
		void *option)
{
	struct psd_scheduler_ctx *psd_ctx = ((struct scheduler_ctx *)
			dev->data->dev_private)->private_ctx;
	uint32_t threshold;

	if ((enum rte_cryptodev_schedule_option_type)option_type !=
			CDEV_SCHED_OPTION_THRESHOLD) {
		CS_LOG_ERR("Option not supported");
		return -EINVAL;
	}

	threshold = ((struct rte_cryptodev_scheduler_threshold_option *)
			option)->threshold;
	if (!rte_is_power_of_2(threshold)) {
		CS_LOG_ERR("Threshold is not power of 2");
		return -EINVAL;
	}

	psd_ctx->threshold = ~(threshold - 1);

	return 0;
}

static int
scheduler_option_get(struct rte_cryptodev *dev, uint32_t option_type,
		void *option)
{
	struct psd_scheduler_ctx *psd_ctx = ((struct scheduler_ctx *)
			dev->data->dev_private)->private_ctx;
	struct rte_cryptodev_scheduler_threshold_option *threshold_option;

	if ((enum rte_cryptodev_schedule_option_type)option_type !=
			CDEV_SCHED_OPTION_THRESHOLD) {
		CS_LOG_ERR("Option not supported");
		return -EINVAL;
	}

	threshold_option = option;
	threshold_option->threshold = (~psd_ctx->threshold) + 1;

	return 0;
}

struct rte_cryptodev_scheduler_ops scheduler_ps_ops = {
	slave_attach,
	slave_detach,
	scheduler_start,
	scheduler_stop,
	scheduler_config_qp,
	scheduler_create_private_ctx,
	scheduler_option_set,
	scheduler_option_get
};

struct rte_cryptodev_scheduler psd_scheduler = {
		.name = "packet-size-based-scheduler",
		.description = "scheduler which will distribute crypto op "
				"burst based on the packet size",
		.mode = CDEV_SCHED_MODE_PKT_SIZE_DISTR,
		.ops = &scheduler_ps_ops
};

struct rte_cryptodev_scheduler *pkt_size_based_distr_scheduler = &psd_scheduler;


text:
@interface SutroTileSource: RMAbstractMercatorWebSource <RMAbstractMercatorWebSource>{
}

@end


text:
cask "webtorrent" do
  version "0.24.0"
  sha256 "9cf28d0f0ef74d793cca5a0fee0d7195a11c055b4a6c118cea295c308a3bfd9d"

  url "https://github.com/webtorrent/webtorrent-desktop/releases/download/v#{version}/WebTorrent-v#{version}.dmg",
      verified: "github.com/webtorrent/webtorrent-desktop/"
  name "WebTorrent Desktop"
  desc "Torrent streaming application"
  homepage "https://webtorrent.io/desktop/"

  app "WebTorrent.app"

  zap trash: [
    "~/Library/Application Support/io.webtorrent.webtorrent.ShipIt",
    "~/Library/Application Support/WebTorrent",
    "~/Library/Caches/io.webtorrent.webtorrent",
    "~/Library/Caches/io.webtorrent.webtorrent.ShipIt",
    "~/Library/Caches/WebTorrent",
    "~/Library/Cookies/io.webtorrent.webtorrent.binarycookies",
    "~/Library/Preferences/ByHost/io.webtorrent.webtorrent.ShipIt.*.plist",
    "~/Library/Preferences/io.webtorrent.webtorrent-helper.plist",
    "~/Library/Preferences/io.webtorrent.webtorrent.plist",
    "~/Library/Saved Application State/io.webtorrent.webtorrent.savedState",
    "~/Library/WebKit/io.webtorrent.webtorrent",
  ]
end


text:
#include "window_size.h"

#include "disparity_toolkit/genericfunctions.h"
#include "debugmatstore.h"
#include "disparity_region.h"

void showWindowSizes(cv::Mat& sizes)
{
	int conf[] = {0,0, 1,1};

	cv::Mat y_sizes(sizes.size[0], sizes.size[1], CV_8UC1);
	cv::Mat x_sizes(sizes.size[0], sizes.size[1], CV_8UC1);
	cv::Mat out[] = {y_sizes, x_sizes};

	cv::mixChannels(&sizes, 1, out, 2, conf, 2);

	matstore.add_mat(value_scaled_image<unsigned char, unsigned char>(y_sizes), "sizesY");
	matstore.add_mat(value_scaled_image<unsigned char, unsigned char>(x_sizes), "sizesX");
}

inline int countLabels(cv::Mat window, int clabel)
{
	assert(window.isContinuous());
	int* csubwindow_ptr = window.ptr<int>(0);
	return static_cast<int>(std::count(csubwindow_ptr, csubwindow_ptr + window.cols*window.rows + 1, clabel));
}

inline float countLabelsDisp(cv::Mat window, int clabel, const std::vector<disparity_region>& regions)
{
	assert(window.isContinuous());
	int cdisparity = regions[clabel].disparity;
	int* csubwindow_ptr = window.ptr<int>(0);

	int disp_error = 0;
	int trunc = 3;
	for(int i = 0; i < window.cols*window.rows; ++i)
	{
		int current_label = *csubwindow_ptr++;
		disp_error += std::min(std::abs(regions[current_label].disparity - cdisparity), trunc);
	}
	int total = window.cols*window.rows*trunc;
	return std::max(1.0f-disp_error/(float)total, 0.0f);
}

inline float compare_disparity(const cv::Mat& plabel_window, int clabel, const std::vector<short>& disparities)
{
	cv::Mat label_window = plabel_window.clone();
	assert(label_window.isContinuous());
	short cdisparity = disparities[clabel];
	const int* csubwindow_ptr = label_window.ptr<int>(0);
	const unsigned short totalpixel = label_window.cols*label_window.rows;
	//const int* end_ptr = csubwindow_ptr + totalpixel;

	const int trunc = 3;
	std::array<int, trunc+1> label_counter;
	std::fill(label_counter.begin(), label_counter.end(), 0);

	for(unsigned short i = 0; i < totalpixel; ++i)
	//while(csubwindow_ptr != end_ptr)
	{
		//int current_label = *csubwindow_ptr++;
		//unsigned char disp_dev = std::min(std::abs(disparities[current_label] - cdisparity), trunc);
		//auto disp_dev = std::min(std::abs(disparities[current_label] - cdisparity), trunc);
		//auto disp_dev = std::min(std::abs(disparities[*csubwindow_ptr++] - cdisparity), trunc);
		auto disp_dev = std::min(std::abs(disparities[csubwindow_ptr[i]] - cdisparity), trunc);

		assert(disp_dev <= trunc); //disp_dev >= 0
		++(label_counter[disp_dev]);
	}
	int pos_labels = 3*label_counter[0]+2*label_counter[1]+label_counter[2];
	int total = pos_labels+3*label_counter[3];
	return pos_labels/(float)total;
}

template<typename lambda_type>
cv::Mat_<cv::Vec2b> adaptive_window_size(const cv::Mat& image, const cv::Mat_<int>& labels, float threshold, int minsize, int maxsize, const std::vector<disparity_region>& regions, lambda_type func)
{
	assert(minsize > 0);
	assert(maxsize > 0);

	std::vector<short> disparities(regions.size());
	for(std::size_t i = 0; i < regions.size(); ++i)
		disparities[i] = regions[i].disparity;

	cv::Mat_<cv::Vec2b> result = cv::Mat::zeros(labels.size(), CV_8UC2);
	const int onesidesizeMin = (minsize-1)/2;
	const int onesidesizeMax = (maxsize-1)/2;
	#pragma omp parallel for default(none) shared(labels, image, result, disparities, threshold, func, minsize, maxsize)
	for(int y = onesidesizeMin; y < labels.rows - onesidesizeMin; ++y)
	{
		int lastWindowSize = onesidesizeMin*2+1;

		for(int x = onesidesizeMin; x < labels.cols - onesidesizeMin; ++x)
		{
			int clabel = labels(y,x);
			int maxposs = std::min( std::min(labels.cols - x-1, labels.rows - y-1), onesidesizeMax );
			maxposs = std::min( maxposs, std::min( std::min(y-1, x-1), onesidesizeMax ) );

			maxposs = maxposs*2+1;

			int windowsizeX = std::min(lastWindowSize, maxposs);
			int windowsizeY = std::min(lastWindowSize, maxposs);

			bool grow = (lastWindowSize == minsize) ? true : false;

			while(true)
			{
				float measured = func(subwindow(labels, x,y, windowsizeX, windowsizeY), clabel, disparities);
				if(grow)
				{
					if(measured < threshold)
					{
						//shrink each direction seperatly
						float measured_altY = func(subwindow(labels, x,y, windowsizeX, windowsizeY-2), clabel, disparities);
						float measured_altX = func(subwindow(labels, x,y, windowsizeX-2, windowsizeY), clabel, disparities);

						if(measured_altY > threshold)
							windowsizeY -= 2;
						else if(measured_altX > threshold)
							windowsizeX -= 2;
						else {
							windowsizeX -= 2;
							windowsizeY -= 2;
							break;
						}
					}
					if(windowsizeX < maxposs && windowsizeY < maxposs)
					{
						windowsizeX += 2;
						windowsizeY += 2;
					} else
						break;
				} else {
					if(measured >= threshold)
					{
						grow = true;
						continue;
					}
					if( windowsizeX > minsize && windowsizeY > minsize) {
						windowsizeX -= 2;
						windowsizeY -= 2;
					} else
						break;
				}
			}
			lastWindowSize = std::min(windowsizeX, windowsizeY);
			result(y,x) = cv::Vec2b(std::max(windowsizeY, minsize), std::max(windowsizeX, minsize));
		}
	}

	return result;
}

cv::Mat_<cv::Vec2b> adaptive_window_size(const cv::Mat& image, const cv::Mat_<int>& labels, float threshold, int minsize, int maxsize, const std::vector<disparity_region>& regions)
{
	return adaptive_window_size(image, labels, threshold, minsize, maxsize, regions, compare_disparity);
}


text:
package edu.isi.wubble.physics.entity.controller;

import com.jme.math.Vector3f;

import edu.isi.wubble.physics.entity.DynamicEntity;

public class MovementController extends BinaryController {

	private static final long serialVersionUID = 1L;
	protected int _count;

    public MovementController(DynamicEntity entity) {
    	this(entity, 4.0f);
    }

    public MovementController(DynamicEntity entity, float speed) {
    	super(entity, "forward", "backward", speed);
		_count = 0;
    }

	public void update(float tpf) {
		if (!canUpdate())
			return;

		float value = _positive.getValue() - _negative.getValue();

		if (value != 0.0f) {
			if (value < 0)
				_entity.recordAuto("Backward", true);
			else
				_entity.recordAuto("Forward", true);

			Vector3f direction = _entity.getRotation().getRotationColumn(2);
			direction.normalizeLocal();
			direction = direction.mult(getSpeed() * value);

			Vector3f currVelocity = _physicsNode.getLinearVelocity(null);
			direction.y = currVelocity.y;

			_physicsNode.setLinearVelocity(direction);
			_physicsNode.setAngularVelocity(new Vector3f(0,0,0));
			if (_physicsNode.isResting()) {
				_physicsNode.unrest();
			}
		} else {

			Vector3f currentVelocity = _physicsNode.getLinearVelocity(null);
			currentVelocity.x = currentVelocity.x * 0.1f;
			currentVelocity.z = currentVelocity.z * 0.1f;
			_physicsNode.setLinearVelocity(currentVelocity);
		}
	}
}


text:
package application;

import java.util.HashMap;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.layout.StackPane;
import javafx.util.Duration;

/**
 *
 * @author Angie
 */
public class ScreenController  extends StackPane {
    //Holds the screens to be displayed

    private HashMap<String, Node> screens = new HashMap<>();

    public ScreenController() {
        super();
    }

    //Add the screen to the collection
    public void addScreen(String name, Node screen) {
        screens.put(name, screen);
    }

    //Returns the Node with the appropriate name
    public Node getScreen(String name) {
        return screens.get(name);
    }

    //Loads the fxml file, add the screen to the screens collection and
    //finally injects the screenPane to the controller.
    public boolean loadScreen(String name, String resource) {
        try {
            FXMLLoader myLoader = new FXMLLoader(getClass().getResource(resource));
            Parent loadScreen = (Parent) myLoader.load();
            ControlledScreen myScreenControler = ((ControlledScreen) myLoader.getController());
            myScreenControler.setScreenParent(this);
            addScreen(name, loadScreen);
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    //This method tries to displayed the screen with a predefined name.
    //First it makes sure the screen has been already loaded.  Then if there is more than
    //one screen the new screen is been added second, and then the current screen is removed.
    // If there isn't any screen being displayed, the new screen is just added to the root.
    public boolean setScreen(final String name) {
        if (screens.get(name) != null) {   //screen loaded
            final DoubleProperty opacity = opacityProperty();

            if (!getChildren().isEmpty()) {    //if there is more than one screen
                Timeline fade = new Timeline(
                        new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
                        new KeyFrame(new Duration(1000), new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent t) {
                        getChildren().remove(0);                    //remove the displayed screen
                        getChildren().add(0, screens.get(name));     //add the screen
                        Timeline fadeIn = new Timeline(
                                new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
                                new KeyFrame(new Duration(800), new KeyValue(opacity, 1.0)));
                        fadeIn.play();
                    }
                }, new KeyValue(opacity, 0.0)));
                fade.play();

            } else {
                setOpacity(0.0);
                getChildren().add(screens.get(name));       //no one else been displayed, then just show
                Timeline fadeIn = new Timeline(
                        new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
                        new KeyFrame(new Duration(2500), new KeyValue(opacity, 1.0)));
                fadeIn.play();
            }
            return true;
        } else {
            System.out.println("screen hasn't been loaded!!! \n");
            return false;
        }

        /*Node screenToRemove;
         if(screens.get(name) != null){   //screen loaded
         if(!getChildren().isEmpty()){    //if there is more than one screen
         getChildren().add(0, screens.get(name));     //add the screen
         screenToRemove = getChildren().get(1);
         getChildren().remove(1);                    //remove the displayed screen
         }else{
         getChildren().add(screens.get(name));       //no one else been displayed, then just show
         }
         return true;
         }else {
         System.out.println("screen hasn't been loaded!!! \n");
         return false;
         }*/
    }

    //This method will remove the screen with the given name from the collection of screens
    public boolean unloadScreen(String name) {
        if (screens.remove(name) == null) {
            System.out.println("Screen didn't exist");
            return false;
        } else {
            return true;
        }
    }
}


text:
package com.mysterionnh.tinker.umlgenerator;

import com.mysterionnh.util.IO;
import com.mysterionnh.util.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Objects;

class FileParser {

    private final Logger log;

    private int _attributes = 0;
    private int _methods = 0;

    private final ArrayList<String> _atts = new ArrayList<>();            // 0
    private final ArrayList<String> _attType = new ArrayList<>();         // 1
    private final ArrayList<String> _attLevel = new ArrayList<>();        // 2

    private final ArrayList<String> _meths = new ArrayList<>();           // 3
    private final ArrayList<String> _paras = new ArrayList<>();           // 4
    private final ArrayList<String> _methType = new ArrayList<>();        // 5
    private final ArrayList<String> _methLevel = new ArrayList<>();       // 6

    private final ArrayList<String> _classNames = new ArrayList<>();      // 7

    private final ArrayList<ArrayList<ArrayList<String>>> nodes = new ArrayList<>();

    public FileParser(Logger logger, int fileNum) {
        log = logger;
        nodes.set(fileNum, (ArrayList<ArrayList<String>>) (Arrays.asList(_atts, _attType, _attLevel, _meths, _paras, _methType, _methLevel)));
    }

    public void parseFile(String path) throws IOException {
        String temp = "";
        boolean cnDone = false;
        int lineCount = IO.countLines(path) + 1;

        char markerChar = ' ';

        File file = new File(path);
        String line;

        log.logString("Reading \"" + path + "\" (" + lineCount + " lines)...\n");

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            for (int i = 0; (line = br.readLine()) != null; i++) {

                switch (parseLine(line)) {
                    case "Class": {
                        if (!cnDone) {
                            parseClass(line);
                            cnDone = true;
                            markerChar = 'C';
                        }
                        break;
                    }
                    case "Method": {
                        parseMethod(line, i);
                        markerChar = 'M';
                        break;
                    }
                    case "Field": {
                        parseField(line, i);
                        markerChar = 'F';
                        break;
                    }
                    default: {
                        break;
                    }
                }

                if (((i + 1) >= 100) && ((i + 1) < 1000)) {
                    temp = "0";
                } else if (i + 1 >= 10) {
                    temp = "00";
                } else if (i + 1 >= 0) {
                    temp = "000";
                }

                log.logString(markerChar + " | " + temp + Integer.toString(i + 1) + " |" + line);
                temp = " ";
                markerChar = ' ';
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.logString("\nDone reading. Found " + _methods + " methods and " + _attributes + " fields.");
    }

    private String parseLine(String line) {
        int charLoc;
        boolean valid;

        // This makes sure that it could be a marked method/field
        if (line.contains("public")) {
            charLoc = line.indexOf("public");
        } else if (line.contains("private")) {
            charLoc = line.indexOf("private");
        } else if (line.contains("protected")) {
            charLoc = line.indexOf("protected");
        } else {
            charLoc = -1; // invalid
        }
        // This thing ones made sense, now it just works
        if (charLoc >= 0) {
            valid = true;
            while (charLoc - 1 >= 0) {
                // Moving to the beginning of the line, if we find anything that is not space, the line is invalid
                // (because fields and methods start with the access modifier
                if (line.charAt(charLoc - 1) != ' ') {
                    valid = false;
                    break;
                } else {
                    charLoc--;
                }
            }
        } else {
            valid = false;
        }
        if (valid) {
            if (line.contains("class")) {
                return "Class";
            } else if (line.contains("(") && line.contains(")") && !line.contains(";")) {
                return "Method";
            } else {
                return "Field";
            }
        } else {
            return "Line";
        }
    }

    private void parseClass(String line) {
        int start;
        int end;

        start = line.indexOf("class") + 5; // we need 5 to go to the end of "class"
        while (line.charAt(start) == ' ') {
            start++;
        }
        end = start;
        while (line.charAt(end) != ' ' && line.charAt(end) != '{' && end < line.length()) {
            end++;
        }
        _classNames.add(addModifiers(line, start) + line.substring(start, end));
    }

    private void parseMethod(String line, int lineNumber) {
        String temp = "";
        int start = line.indexOf('(');
        int end = line.lastIndexOf(')');
        _paras.add(_methods, line.substring(start + 1, end));

        // Parse name
        start--;
        while (line.charAt(start) == ' ') {
            start--;
        }
        end = start + 1;
        while (line.charAt(start) != ' ') {
            start--;
        }

        _meths.add(_methods, addModifiers(line, start + 1) + line.substring(start + 1, end));

        // black magic, don't touch
        while (line.charAt(start) == ' ' && start > 0) {
            start--;
        }
        end = start + 1;
        while (line.charAt(start - 1) != ' ') {
            start--;
        }
        _methType.add(_methods, line.substring(start, end));

        if (_methType.get(_methods).equals("public")) {
            _methType.add(_methods, "");
        }

        if (Objects.equals(temp, "new")) {
            _methType.set(_methods, _meths.get(_methods));
        }

        // Filter protection level
        start = 0;
        while (line.charAt(start) == ' ') {
            start++;
        }
        end = start;
        while (line.charAt(end) != ' ') {
            end++;
        }

        _methLevel.add(_methods, String.valueOf(getProChar(line.substring(start, end), lineNumber, true)));

        _methods++;
    }

    private void parseField(String line, int lineNumber) {
        //String parts[];
        int start;
        int end;
        //if (line.contains(",")) {
        //  parts = line.split(","); //TODO: continue
        //} else {
        if (line.contains("=")) {
            end = line.indexOf('=') - 1;
        } else {
            end = line.length() - 1;
        }
        while (line.charAt(end) == ' ') {
            end--;
        }
        start = end - 1;
        while (line.charAt(start) != ' ') {
            start--;
        }

        _atts.add(_attributes, addModifiers(line, start + 1) + line.substring(start + 1, end + 1));

        if (_atts.get(_attributes).contains(";")) {
            _atts.add(_attributes, _atts.get(_attributes).substring(0, _atts.get(_attributes).length() - 1));
        }

        // Return type
        while (line.charAt(start) == ' ') {
            start--;
        }
        end = start + 1;
        while (line.charAt(start - 1) != ' ') {
            start--;
        }
        _attType.add(_attributes, line.substring(start, end));

        // Filter protection level
        start = 0;
        while (line.charAt(start) == ' ') {
            start++;
        }
        end = start;
        while (line.charAt(end) != ' ') {
            end++;
        }
        _attLevel.add(_attributes, String.valueOf(getProChar(line.substring(start, end), lineNumber, false)));

        _attributes++;
        //}
    }

    private String addModifiers(String line, int nameIndex) {
        String temp = "";
        if (line.contains("abstract") && line.indexOf("abstract") < nameIndex) { //$NON-NLS-2$
            temp += "abstract ";
        }
        if (line.contains("final") && line.indexOf("final") < nameIndex) { //$NON-NLS-2$
            temp += "final ";
        }
        if (line.contains("native") && line.indexOf("native") < nameIndex) { //$NON-NLS-2$
            temp += "native ";
        }
        if (line.contains("strictfp") && line.indexOf("strictfp") < nameIndex) { //$NON-NLS-2$
            temp += "strictfp ";
        }
        if (line.contains("static") && line.indexOf("static") < nameIndex) { //$NON-NLS-2$
            temp += "";
        }
        if (line.contains("synchronized") && line.indexOf("synchronized") < nameIndex) { //$NON-NLS-2$
            temp += "synchronized ";
        }
        if (line.contains("transient") && line.indexOf("transient") < nameIndex) { //$NON-NLS-2$
            temp += "transient ";
        }
        if (line.contains("volatile") && line.indexOf("volatile") < nameIndex) { //$NON-NLS-2$
            temp += "volatile ";
        }
        return temp;
    }

    private char getProChar(String str, int line, boolean method) {
        switch (str) {
            case "public": {
                return '+';
            }
            case "private": {
                return '-';
            }
            case "protected": {
                return '~';
            }
            default: {
                log.logError(this, "Whoops, you sure your file is alright? (One " + ((method) ? "method" : "attribute") + " has a weird type, line: " + line + ")", true);
                return ' ';
            }
        }
    }

    public ArrayList<ArrayList<String>> getNode(int num) {
        return nodes.get(num);
    }
}


text:
Originally published: 2001-08-27 07:00:13
Last updated: 2001-08-28 09:34:52
Author: anurag uniyal

Dummy classes can be used to create dummy instances of class
which we can't create currently!


text:
<mxEditor defaultGroup="group" defaultEdge="edge"
	helpWindowImage="images/help.gif"
	tasksWindowImage="images/tasks.gif"
	forcedInserting="0"
	swimlaneRequired="0">
	<include name="config/editor-commons.xml"/>
	<add as="onInit">
		function ()
		{
			this.showTasks();
		}
	</add>
	<Array as="cycleAttributeValues">
		<add value="#83027F"/>
		<add value="#66B922"/>
		<add value="#808913"/>
		<add value="#CF0056"/>
		<add value="#4679B6"/>
	</Array>
	<Array as="templates">
		<add as="group">
			<Group label="" description="" href="">
				<mxCell vertex="1" style="group" connectable="0"/>
			</Group>
		</add>
		<add as="edge">
			<Edge label="" description="">
				<mxCell edge="1">
					<mxGeometry as="geometry" relative="1"/>
				</mxCell>
			</Edge>
		</add>
		<add as="swimlane">
			<Swimlane label="Swimlane" description="" href="">
				<mxCell vertex="1" style="swimlane" connectable="0">
					<mxGeometry as="geometry" width="300" height="160"/>
				</mxCell>
			</Swimlane>
		</add>
		<add as="task">
			<Task label="Task" description="" href="">
				<mxCell vertex="1">
					<mxGeometry as="geometry" width="72" height="32"/>
				</mxCell>
			</Task>
		</add>
		<add as="subprocess">
			<Subprocess label="Subprocess" description="" href="">
				<mxCell vertex="1" style="rounded">
					<mxGeometry as="geometry" width="72" height="32"/>
				</mxCell>
			</Subprocess>
		</add>
		<add as="shape">
			<Shape label="" description="" href="">
				<mxCell vertex="1" style="ellipse">
					<mxGeometry as="geometry" width="32" height="32"/>
				</mxCell>
			</Shape>
		</add>
		<add as="symbol">
			<Symbol label="Symbol" description="" href="">
				<mxCell vertex="1" style="symbol;image=images/symbols/event.png">
					<mxGeometry as="geometry" width="32" height="32"/>
				</mxCell>
			</Symbol>
		</add>
	</Array>
	<add as="createTasks"><![CDATA[
		function (div)
		{
			var off = 30;

			if (this.graph != null)
			{
				var layer = this.graph.model.root.getChildAt(0);
				mxUtils.para(div,  mxResources.get('examples'));
				mxUtils.linkInvoke(div, mxResources.get('newDiagram'), this,
					'open', 'diagrams/empty.xml', off);
				mxUtils.br(div);
				mxUtils.linkInvoke(div, mxResources.get('swimlanes'), this,
					'open', 'diagrams/swimlanes.xml', off);
				mxUtils.br(div);
				mxUtils.linkInvoke(div, mxResources.get('travelBooking'), this,
					'open', 'diagrams/travel-booking.xml', off);
				mxUtils.br(div);

				if (!this.graph.isSelectionEmpty())
				{
					var cell = this.graph.getSelectionCell();
					if (this.graph.getSelectionCount() == 1 &&
						(this.graph.model.isVertex(cell) &&
						cell.getEdgeCount() > 0) || this.graph.isSwimlane(cell))
					{
						mxUtils.para(div, mxResources.get('layout'));
						mxUtils.linkAction(div, mxResources.get('verticalTree'),
							this, 'verticalTree', off);
						mxUtils.br(div);
						mxUtils.linkAction(div, mxResources.get('horizontalTree'),
							this, 'horizontalTree', off);
						mxUtils.br(div);
					}

					mxUtils.para(div, mxResources.get('format'));

					if (mxUtils.isNode(cell.value, 'Symbol'))
					{
						mxUtils.linkAction(div, mxResources.get('image'),
							this, 'image', off);
						mxUtils.br(div);
					}
					else
					{
						mxUtils.linkAction(div, mxResources.get('opacity'),
							this, 'opacity', off);
						mxUtils.br(div);
						if (this.graph.model.isVertex(cell) ||
							(cell.style != null &&
							cell.style.indexOf("arrowEdge") >= 0))
						{
							mxUtils.linkAction(div, mxResources.get('gradientColor'),
								this, 'gradientColor', off);
							mxUtils.br(div);
						}
						if (this.graph.model.isEdge(cell))
						{
							mxUtils.linkAction(div, 'Straight Connector', this, 'straightConnector', off);
							mxUtils.br(div);
							mxUtils.linkAction(div, 'Elbow Connector', this, 'elbowConnector', off);
							mxUtils.br(div);
							mxUtils.linkAction(div, 'Arrow Connector', this, 'arrowConnector', off);
							mxUtils.br(div);
						}
					}

					mxUtils.linkAction(div, mxResources.get('toggleRounded'), this, 'toggleRounded', off);
					mxUtils.br(div);
					if (this.graph.isSwimlane(cell) || this.graph.model.isEdge(cell))
					{
						mxUtils.linkAction(div, mxResources.get('toggleOrientation'), this, 'toggleOrientation', off);
						mxUtils.br(div);
					}

					if (this.graph.getSelectionCount() > 1)
					{
						mxUtils.para(div, mxResources.get('align'));
						mxUtils.linkAction(div, mxResources.get('left'),
							this, 'alignCellsLeft', off);
						mxUtils.br(div);
						mxUtils.linkAction(div, mxResources.get('center'),
							this, 'alignCellsCenter', off);
						mxUtils.br(div);
						mxUtils.linkAction(div, mxResources.get('right'),
							this, 'alignCellsRight', off);
						mxUtils.br(div);
						mxUtils.linkAction(div, mxResources.get('top'),
							this, 'alignCellsTop', off);
						mxUtils.br(div);
						mxUtils.linkAction(div, mxResources.get('middle'),
							this, 'alignCellsMiddle', off);
						mxUtils.br(div);
						mxUtils.linkAction(div, mxResources.get('bottom'),
							this, 'alignCellsBottom', off);
						mxUtils.br(div);
					}

					mxUtils.para(div, mxResources.get('selection'));
					mxUtils.linkAction(div, mxResources.get('clearSelection'),
						this, 'selectNone', off);
					mxUtils.br(div);
				}
				else if (layer.getChildCount() > 0)
				{
					mxUtils.para(div, mxResources.get('selection'));
					mxUtils.linkAction(div, mxResources.get('selectAll'),
						this, 'selectAll', off);
					mxUtils.br(div);
				}

				mxUtils.br(div);
			}
		}
	]]></add>
</mxEditor>


text:
package org.mongodb.morphia.query;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.TestBase;
import org.mongodb.morphia.annotations.Reference;
import org.mongodb.morphia.annotations.Serialized;
import org.mongodb.morphia.entities.EntityWithListsAndArrays;
import org.mongodb.morphia.entities.SimpleEntity;
import org.mongodb.morphia.mapping.MappedClass;
import org.mongodb.morphia.mapping.MappedField;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mongodb.morphia.query.FilterOperator.ALL;
import static org.mongodb.morphia.query.FilterOperator.EQUAL;
import static org.mongodb.morphia.query.FilterOperator.EXISTS;
import static org.mongodb.morphia.query.FilterOperator.GEO_WITHIN;
import static org.mongodb.morphia.query.FilterOperator.IN;
import static org.mongodb.morphia.query.FilterOperator.MOD;
import static org.mongodb.morphia.query.FilterOperator.NOT_IN;
import static org.mongodb.morphia.query.FilterOperator.SIZE;
import static org.mongodb.morphia.query.QueryValidator.isCompatibleForOperator;
import static org.mongodb.morphia.query.QueryValidator.validateQuery;

public class QueryValidatorTest extends TestBase {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void shouldAllowAllOperatorForIterableMapAndArrayValues() {
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, ALL, Arrays.asList(1, 2),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, ALL, Collections.emptySet(),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, ALL, new HashMap<String, String>(),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, ALL, new int[0],
            new ArrayList<>()));
    }

    @Test
    public void shouldAllowBooleanValuesForExistsOperator() {
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, EXISTS, true, new ArrayList<>()));
    }

    @Test
//    @Ignore("Defer fixing the geo tests until after the core is fixed")
    public void shouldAllowGeoWithinOperatorWithAllAppropriateTrimmings() {
        MappedClass mappedClass = getMapper().getMappedClass(GeoEntity.class);
        MappedField mappedField = mappedClass.getMappedField("array");
        assertTrue(isCompatibleForOperator(mappedClass, mappedField, List.class, GEO_WITHIN, new Document("$box", 1),
            new ArrayList<>()));
    }

    @Test
    public void shouldAllowInOperatorForIterableMapAndArrayValues() {
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, IN, Arrays.asList(1, 2),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, IN, Collections.emptySet(),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, IN, new HashMap<String, String>(),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, IN, new int[0], new ArrayList<>()));
    }

    @Test
    public void shouldAllowModOperatorForArrayOfIntegerValues() {
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, MOD, new int[2], new ArrayList<>()));
    }

    @Test
    public void shouldAllowNotInOperatorForIterableMapAndArrayValues() {
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, NOT_IN, Arrays.asList(1, 2),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, NOT_IN, Collections.emptySet(),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, NOT_IN, new HashMap<String, String>(),
            new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, NOT_IN, new int[0], new ArrayList<>()));
    }

    @Test
    public void shouldAllowSizeOperatorForArrayListTypesAndIntegerValues() {
        MappedClass mappedClass = getMapper().getMappedClass(EntityWithListsAndArrays.class);
        MappedField mappedField = mappedClass.getMappedField("listOfIntegers");

        assertTrue(isCompatibleForOperator(mappedClass, mappedField, NullClass.class, SIZE, 3, new ArrayList<>()));
    }

    @Test
    public void shouldAllowSizeOperatorForArraysAndIntegerValues() {
        MappedClass mappedClass = getMapper().getMappedClass(EntityWithListsAndArrays.class);
        MappedField mappedField = mappedClass.getMappedField("arrayOfInts");

        assertTrue(isCompatibleForOperator(mappedClass, mappedField, NullClass.class, SIZE, 3, new ArrayList<>()));
    }

    @Test
    public void shouldAllowSizeOperatorForListTypesAndIntegerValues() {
        MappedClass mappedClass = getMapper().getMappedClass(EntityWithListsAndArrays.class);
        MappedField mappedField = mappedClass.getMappedField("listOfIntegers");

        assertTrue(isCompatibleForOperator(mappedClass, mappedField, NullClass.class, SIZE, 3, new ArrayList<>()));
    }

    @Test
    public void shouldAllowTypeThatMatchesKeyTypeValue() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("integer");
        assertTrue(isCompatibleForOperator(mappedClass, mappedField, Integer.class, EQUAL,
            new Key<Number>(Integer.class, "Integer", new ObjectId()), new ArrayList<>()));
    }

    @Test
    public void shouldAllowValueOfPatternWithTypeOfString() {
        assertTrue(isCompatibleForOperator(null, null, String.class, EQUAL, Pattern.compile("."),
            new ArrayList<>()));
    }

    @Test
    public void shouldAllowValueWithEntityAnnotationAndTypeOfKey() {
        assertTrue(isCompatibleForOperator(null, null, Key.class, EQUAL, new SimpleEntity(), new ArrayList<>()));
    }

    @Test
    public void shouldAllowValuesOfIntegerIfTypeIsDouble() {
        assertTrue(isCompatibleForOperator(null, null, Double.class, EQUAL, 1, new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, double.class, EQUAL, 1, new ArrayList<>()));
    }

    @Test
    public void shouldAllowValuesOfIntegerIfTypeIsInteger() {
        assertTrue(isCompatibleForOperator(null, null, int.class, EQUAL, 1, new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, Integer.class, EQUAL, 1, new ArrayList<>()));
    }

    @Test
    public void shouldAllowValuesOfIntegerOrLongIfTypeIsLong() {
        assertTrue(isCompatibleForOperator(null, null, Long.class, EQUAL, 1, new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, long.class, EQUAL, 1, new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, Long.class, EQUAL, 1L, new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, long.class, EQUAL, 1L, new ArrayList<>()));
    }

    @Test
    public void shouldAllowValuesOfList() {
        // expect
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertTrue(isCompatibleForOperator(mappedClass, mappedField, List.class, EQUAL, new ArrayList<String>(),
            new ArrayList<>()));
    }

    @Test
    public void shouldAllowValuesOfLongIfTypeIsDouble() {
        assertTrue(isCompatibleForOperator(null, null, Double.class, EQUAL, 1L, new ArrayList<>()));
        assertTrue(isCompatibleForOperator(null, null, double.class, EQUAL, 1L, new ArrayList<>()));
    }

    @Test
    public void shouldBeCompatibleIfTypeIsNull() {
        // expect
        // frankly not sure we should just let nulls through
        assertTrue(isCompatibleForOperator(null, null, null, EQUAL, "value", new ArrayList<>()));
    }

    @Test
    public void shouldBeCompatibleIfValueIsNull() {
        // frankly not sure we should just let nulls through
        assertTrue(isCompatibleForOperator(null, null, SimpleEntity.class, EQUAL, null, new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowGeoOperatorIfValueDoesNotContainCorrectField() {
        MappedClass mappedClass = getMapper().getMappedClass(GeoEntity.class);
        MappedField mappedField = mappedClass.getMappedField("array");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, List.class, GEO_WITHIN,
            new Document("name", "value"), new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowGeoOperatorIfValueIsNotDocument() {
        MappedClass mappedClass = getMapper().getMappedClass(GeoEntity.class);
        MappedField mappedField = mappedClass.getMappedField("array");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, List.class, GEO_WITHIN, "value",
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowGeoWithinWhenValueDoesNotContainKeyword() {
        MappedClass mappedClass = getMapper().getMappedClass(GeoEntity.class);
        MappedField mappedField = mappedClass.getMappedField("array");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, List.class, GEO_WITHIN,
            new Document("notValidKey", 1), new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowModOperatorWithNonArrayValue() {
        assertFalse(isCompatibleForOperator(null, null, String.class, MOD, "value", new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowModOperatorWithNonIntegerArray() {
        assertFalse(isCompatibleForOperator(null, null, SimpleEntity.class, MOD, new String[]{"value"},
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowNonBooleanValuesForExistsOperator() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, SimpleEntity.class, EXISTS, "value",
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowNonIntegerTypeIfValueIsInt() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, SimpleEntity.class, EQUAL, 1,
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowNonIntegerValueIfTypeIsInt() {
        assertFalse(isCompatibleForOperator(null, null, int.class, EQUAL, "some non int value",
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowNonKeyTypeWithKeyValue() {
        MappedClass mappedClass = getMapper().getMappedClass(EntityWithListsAndArrays.class);
        MappedField mappedField = mappedClass.getMappedField("listOfIntegers");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, SimpleEntity.class, EQUAL,
            new Key<>(String.class, "collection", new ObjectId()), new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowNonStringTypeWithValueOfPattern() {
        assertFalse(isCompatibleForOperator(null, null, Pattern.class, EQUAL, Pattern.compile("."),
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowOtherValuesForAllOperator() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");

        assertFalse(isCompatibleForOperator(mappedClass, mappedField, SimpleEntity.class, ALL, "value",
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowOtherValuesForInOperator() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, String.class, IN, "value", new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowOtherValuesForNotInOperator() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, SimpleEntity.class, NOT_IN, "value",
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowSizeOperatorForNonIntegerValues() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, ArrayList.class, SIZE, "value", new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowSizeOperatorForNonListTypes() {
        MappedClass mappedClass = getMapper().getMappedClass(EntityWithListsAndArrays.class);
        MappedField mappedField = mappedClass.getMappedField("notAnArrayOrList");

        assertFalse(isCompatibleForOperator(mappedClass, mappedField, NullClass.class, SIZE, 3, new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowStringValueWithTypeThatIsNotString() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, Integer.class, EQUAL, "value", new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowTypeThatDoesNotMatchKeyTypeValue() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, String.class, EQUAL,
            new Key<Number>(Integer.class, "Integer", new ObjectId()),
            new ArrayList<>()));
    }

    @Test
    public void shouldNotAllowValueWithoutEntityAnnotationAndTypeOfKey() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, Key.class, EQUAL, "value", new ArrayList<>()));
    }

    @Test
    public void shouldNotErrorIfModOperatorIsUsedWithZeroLengthArrayOfIntegerValues() {
        assertFalse(isCompatibleForOperator(null, null, SimpleEntity.class, MOD, new int[0], new ArrayList<>()));
    }

    @Test
    public void shouldNotErrorModOperatorWithArrayOfNullValues() {
        assertFalse(isCompatibleForOperator(null, null, SimpleEntity.class, MOD, new String[1], new ArrayList<>()));
    }

    @Test
    public void shouldNotErrorWhenValidateQueryCalledWithNullValue() {
        // this unit test is to drive fixing a null pointer in the logging code.  It's a bit stupid but it's an edge case that wasn't
        // caught. when this is called, don't error
        validateQuery(SimpleEntity.class, getMapper(), new StringBuilder("name"), EQUAL, null, true, true);
    }

    @Test
    public void shouldRejectNonDoubleValuesIfTypeIsDouble() {
        assertFalse(isCompatibleForOperator(null, null, Double.class, EQUAL, "Not a double",
            new ArrayList<>()));
    }

    @Test
    public void shouldRejectTypesAndValuesThatDoNotMatch() {
        MappedClass mappedClass = getMapper().getMappedClass(SimpleEntity.class);
        MappedField mappedField = mappedClass.getMappedField("name");
        assertFalse(isCompatibleForOperator(mappedClass, mappedField, String.class, EQUAL, 1,
            new ArrayList<>()));
    }

    @Test(expected = ValidationException.class)
    public void shouldReferToMappedClassInExceptionWhenFieldNotFound() {
        validateQuery(SimpleEntity.class, getMapper(), new StringBuilder("id.notAField"), FilterOperator.EQUAL, 1, true, true);
    }

    @Test
    public void shouldReferToMappedClassInExceptionWhenQueryingPastReferenceField() {
        thrown.expect(ValidationException.class);
        thrown.expectMessage("Cannot use dot-notation past 'reference' in 'org.mongodb.morphia.query.QueryValidatorTest$WithReference'");
        validateQuery(WithReference.class, getMapper(), new StringBuilder("reference.name"), FilterOperator.EQUAL, "", true,
            true);
    }

    private static class GeoEntity {
        private final int[] array = {1};
    }

    private static class NullClass {
    }

    private static class WithReference {
        @Reference
        private SimpleEntity reference;
    }

    private static class SerializableClass {
        private String name;
    }

    private static class WithSerializedField {
        @Serialized
        private SerializableClass serialized;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    internal partial struct SymbolKey
    {
        private abstract class Reader<TStringResult> : IDisposable
        {
            protected const char OpenParenChar = '(';
            protected const char CloseParenChar = ')';
            protected const char SpaceChar = ' ';
            protected const char DoubleQuoteChar = '"';

            private readonly Func<TStringResult> _readString;
            private readonly Func<int> _readInteger;
            private readonly Func<RefKind> _readRefKind;

            protected string Data { get; private set; }
            public CancellationToken CancellationToken { get; private set; }

            public int Position;

            public Reader()
            {
                _readString = ReadString;
                _readInteger = ReadInteger;
                _readRefKind = () => (RefKind)ReadInteger();
            }

            protected virtual void Initialize(string data, CancellationToken cancellationToken)
            {
                Data = data;
                CancellationToken = cancellationToken;
                Position = 0;
            }

            public virtual void Dispose()
            {
                Data = null;
                CancellationToken = default(CancellationToken);
            }

            protected char Eat(SymbolKeyType type)
            {
                return Eat((char)type);
            }

            protected char Eat(char c)
            {
                Debug.Assert(Data[Position] == c);
                Position++;
                return c;
            }

            protected void EatCloseParen()
            {
                Eat(CloseParenChar);
            }

            protected void EatOpenParen()
            {
                Eat(OpenParenChar);
            }

            public int ReadInteger()
            {
                EatSpace();
                Debug.Assert(char.IsNumber(Data[Position]));

                int value = 0;

                var start = Position;
                while (char.IsNumber(Data[Position]))
                {
                    var digit = Data[Position] - '0';

                    value *= 10;
                    value += digit;

                    Position++;
                }

                Debug.Assert(start != Position);
                return value;
            }

            protected char EatSpace()
            {
                return Eat(SpaceChar);
            }

            public bool ReadBoolean()
            {
                var val = ReadInteger();
                Debug.Assert(val == 0 || val == 1);
                return val == 1;
            }

            public TStringResult ReadString()
            {
                EatSpace();
                return ReadStringNoSpace();
            }

            protected TStringResult ReadStringNoSpace()
            {
                EatDoubleQuote();

                var start = Position;

                var hasEmbeddedQuote = false;
                while (true)
                {
                    if (Data[Position] != DoubleQuoteChar)
                    {
                        Position++;
                        continue;
                    }

                    // We have a quote.  See if it's the final quote, or if it's an escaped
                    // embedded quote.
                    if (Data[Position + 1] == DoubleQuoteChar)
                    {
                        hasEmbeddedQuote = true;
                        Position += 2;
                        continue;
                    }

                    break;
                }

                var end = Position;
                EatDoubleQuote();

                var result = CreateResultForString(start, end, hasEmbeddedQuote);

                return result;
            }

            protected abstract TStringResult CreateResultForString(int start, int end, bool hasEmbeddedQuote);

            private void EatDoubleQuote()
            {
                Eat(DoubleQuoteChar);
            }

            public ImmutableArray<TStringResult> ReadStringArray()
            {
                return ReadArray(_readString);
            }

            public ImmutableArray<RefKind> ReadRefKindArray()
            {
                return ReadArray(_readRefKind);
            }

            public ImmutableArray<T> ReadArray<T>(Func<T> readFunction)
            {
                EatSpace();

                if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
                {
                    Eat(SymbolKeyType.Null);
                    return default(ImmutableArray<T>);
                }

                EatOpenParen();
                Eat(SymbolKeyType.Array);

                var length = ReadInteger();
                var builder = ImmutableArray.CreateBuilder<T>(length);

                for (var i = 0; i < length; i++)
                {
                    CancellationToken.ThrowIfCancellationRequested();
                    builder.Add(readFunction());
                }

                EatCloseParen();

                return builder.MoveToImmutable();
            }
        }

        private abstract class Reader<TSymbolResult, TStringResult> : Reader<TStringResult>
        {
            private readonly Dictionary<int, TSymbolResult> _idToResult = new Dictionary<int, TSymbolResult>();
            private readonly Func<TSymbolResult> _readSymbolKey;

            public Reader()
            {
                _readSymbolKey = ReadSymbolKey;
            }

            protected override void Initialize(string data, CancellationToken cancellationToken)
            {
                base.Initialize(data, cancellationToken);
            }

            public override void Dispose()
            {
                base.Dispose();
                _idToResult.Clear();
            }

            public TSymbolResult ReadFirstSymbolKey()
            {
                return ReadSymbolKeyWorker(first: true);
            }

            public TSymbolResult ReadSymbolKey()
            {
                return ReadSymbolKeyWorker(first: false);
            }

            private TSymbolResult ReadSymbolKeyWorker(bool first)
            {
                CancellationToken.ThrowIfCancellationRequested();
                if (!first)
                {
                    EatSpace();
                }

                var type = (SymbolKeyType)Data[Position];
                if (type == SymbolKeyType.Null)
                {
                    Eat(type);
                    return default(TSymbolResult);
                }

                EatOpenParen();
                TSymbolResult result;

                type = (SymbolKeyType)Data[Position];
                Eat(type);

                if (type == SymbolKeyType.Reference)
                {
                    var id = ReadInteger();
                    result = _idToResult[id];
                }
                else
                {
                    result = ReadWorker(type);
                    var id = ReadInteger();
                    _idToResult[id] = result;
                }

                EatCloseParen();

                return result;
            }

            protected abstract TSymbolResult ReadWorker(SymbolKeyType type);

            public ImmutableArray<TSymbolResult> ReadSymbolKeyArray()
            {
                return ReadArray(_readSymbolKey);
            }
        }

        private class GetHashCodeReader : Reader<int, int>
        {
            private static readonly ObjectPool<GetHashCodeReader> s_pool =
                new ObjectPool<GetHashCodeReader>(() => new GetHashCodeReader());

            private GetHashCodeReader()
            {
            }

            public static GetHashCodeReader GetReader(string data)
            {
                var reader = s_pool.Allocate();
                reader.Initialize(data);
                return reader;
            }

            public override void Dispose()
            {
                base.Dispose();

                s_pool.Free(this);
            }

            private void Initialize(string data)
            {
                base.Initialize(data, CancellationToken.None);
            }

            protected override int CreateResultForString(int start, int end, bool hasEmbeddedQuote)
            {
                var result = 1;

                // Note: we hash all strings to lowercase. It will mean more collisions, but
                // it provides a uniform hashing strategy for all keys.
                for (var i = start; i < end; i++)
                {
                    result = Hash.Combine((int)char.ToLower(Data[i]), result);
                }
                return result;
            }

            public int ReadSymbolKeyArrayHashCode()
            {
                return HashArray(ReadSymbolKeyArray());
            }

            public int ReadRefKindArrayHashCode()
            {
                var array = ReadRefKindArray();
                var value = 1;
                if (!array.IsDefault)
                {
                    foreach (var v in array)
                    {
                        value = Hash.Combine((int)v, value);
                    }
                }
                return value;
            }

            private static int HashArray(ImmutableArray<int> array)
            {
                var value = 1;
                if (!array.IsDefault)
                {
                    foreach (var v in array)
                    {
                        value = Hash.Combine(value, v);
                    }
                }
                return value;
            }

            protected override int ReadWorker(SymbolKeyType type)
            {
                switch (type)
                {
                    case SymbolKeyType.Alias: return AliasSymbolKey.GetHashCode(this);
                    case SymbolKeyType.BodyLevel: return BodyLevelSymbolKey.GetHashCode(this);
                    case SymbolKeyType.ConstructedMethod: return ConstructedMethodSymbolKey.GetHashCode(this);
                    case SymbolKeyType.NamedType: return NamedTypeSymbolKey.GetHashCode(this);
                    case SymbolKeyType.ErrorType: return ErrorTypeSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Field: return FieldSymbolKey.GetHashCode(this);
                    case SymbolKeyType.DynamicType: return DynamicTypeSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Method: return MethodSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Namespace: return NamespaceSymbolKey.GetHashCode(this);
                    case SymbolKeyType.PointerType: return PointerTypeSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Parameter: return ParameterSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Property: return PropertySymbolKey.GetHashCode(this);
                    case SymbolKeyType.ArrayType: return ArrayTypeSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Assembly: return AssemblySymbolKey.GetHashCode(this);
                    case SymbolKeyType.TupleType: return TupleTypeSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Module: return ModuleSymbolKey.GetHashCode(this);
                    case SymbolKeyType.Event: return EventSymbolKey.GetHashCode(this);
                    case SymbolKeyType.ReducedExtensionMethod: return ReducedExtensionMethodSymbolKey.GetHashCode(this);
                    case SymbolKeyType.TypeParameter: return TypeParameterSymbolKey.GetHashCode(this);
                    case SymbolKeyType.TypeParameterOrdinal: return TypeParameterOrdinalSymbolKey.GetHashCode(this);
                }

                throw new NotImplementedException();
            }
        }

        private class RemoveAssemblySymbolKeysReader : Reader<object>
        {
            private readonly StringBuilder _builder = new StringBuilder();

            private bool _skipString = false;

            public RemoveAssemblySymbolKeysReader()
            {
            }

            public void Initialize(string data)
            {
                base.Initialize(data, CancellationToken.None);
            }

            public string RemoveAssemblySymbolKeys()
            {
                while (Position < Data.Length)
                {
                    var ch = Data[Position];
                    if (ch == OpenParenChar)
                    {
                        _builder.Append(Eat(OpenParenChar));

                        var type = (SymbolKeyType)Data[Position];
                        _builder.Append(Eat(type));
                        if (type == SymbolKeyType.Assembly)
                        {
                            Debug.Assert(_skipString == false);
                            _skipString = true;
                            ReadString();

                            Debug.Assert(_skipString == true);
                            _skipString = false;
                        }
                    }
                    else if (Data[Position] == DoubleQuoteChar)
                    {
                        ReadStringNoSpace();
                    }
                    else
                    {
                        // All ther characters we pass along directly to the string builder.
                        _builder.Append(Eat(ch));
                    }
                }

                return _builder.ToString();
            }

            protected override object CreateResultForString(int start, int end, bool hasEmbeddedQuote)
            {
                // 'start' is right after the open quote, and 'end' is right before the close quote.
                // However, we want to include both quotes in teh result.
                _builder.Append(DoubleQuoteChar);
                if (!_skipString)
                {
                    for (var i = start; i < end; i++)
                    {
                        _builder.Append(Data[i]);
                    }
                }
                _builder.Append(DoubleQuoteChar);
                return null;
            }
        }

        private class SymbolKeyReader : Reader<SymbolKeyResolution, string>
        {
            private static readonly ObjectPool<SymbolKeyReader> s_readerPool =
                new ObjectPool<SymbolKeyReader>(() => new SymbolKeyReader());

            public Compilation Compilation { get; private set; }
            public bool IgnoreAssemblyKey { get; private set; }
            public SymbolEquivalenceComparer Comparer { get; private set; }

            public IMethodSymbol CurrentMethod;

            private SymbolKeyReader()
            {
            }

            public static SymbolKeyReader GetReader(
                string data, Compilation compilation,
                bool ignoreAssemblyKey, CancellationToken cancellationToken)
            {
                var reader = s_readerPool.Allocate();
                reader.Initialize(data, compilation, ignoreAssemblyKey, cancellationToken);
                return reader;
            }

            public override void Dispose()
            {
                base.Dispose();
                Compilation = null;
                IgnoreAssemblyKey = false;
                Comparer = null;

                // Place us back in the pool for future use.
                s_readerPool.Free(this);
            }

            private void Initialize(
                string data,
                Compilation compilation,
                bool ignoreAssemblyKey,
                CancellationToken cancellationToken)
            {
                base.Initialize(data, cancellationToken);
                Compilation = compilation;
                IgnoreAssemblyKey = ignoreAssemblyKey;
                Comparer = ignoreAssemblyKey
                    ? SymbolEquivalenceComparer.IgnoreAssembliesInstance
                    : SymbolEquivalenceComparer.Instance;
            }

            protected override string CreateResultForString(int start, int end, bool hasEmbeddedQuote)
            {
                var substring = Data.Substring(start, end - start);
                var result = hasEmbeddedQuote
                    ? substring.Replace("\"\"", "\"")
                    : substring;
                return result;
            }

            protected override SymbolKeyResolution ReadWorker(SymbolKeyType type)
            {
                switch (type)
                {
                    case SymbolKeyType.Alias: return AliasSymbolKey.Resolve(this);
                    case SymbolKeyType.BodyLevel: return BodyLevelSymbolKey.Resolve(this);
                    case SymbolKeyType.ConstructedMethod: return ConstructedMethodSymbolKey.Resolve(this);
                    case SymbolKeyType.NamedType: return NamedTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.ErrorType: return ErrorTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Field: return FieldSymbolKey.Resolve(this);
                    case SymbolKeyType.DynamicType: return DynamicTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Method: return MethodSymbolKey.Resolve(this);
                    case SymbolKeyType.Namespace: return NamespaceSymbolKey.Resolve(this);
                    case SymbolKeyType.PointerType: return PointerTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Parameter: return ParameterSymbolKey.Resolve(this);
                    case SymbolKeyType.Property: return PropertySymbolKey.Resolve(this);
                    case SymbolKeyType.ArrayType: return ArrayTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Assembly: return AssemblySymbolKey.Resolve(this);
                    case SymbolKeyType.TupleType: return TupleTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Module: return ModuleSymbolKey.Resolve(this);
                    case SymbolKeyType.Event: return EventSymbolKey.Resolve(this);
                    case SymbolKeyType.ReducedExtensionMethod: return ReducedExtensionMethodSymbolKey.Resolve(this);
                    case SymbolKeyType.TypeParameter: return TypeParameterSymbolKey.Resolve(this);
                    case SymbolKeyType.TypeParameterOrdinal: return TypeParameterOrdinalSymbolKey.Resolve(this);
                }

                throw new NotImplementedException();
            }

            internal bool ParameterTypesMatch(
                ImmutableArray<IParameterSymbol> parameters,
                ITypeSymbol[] originalParameterTypes)
            {
                if (parameters.Length != originalParameterTypes.Length)
                {
                    return false;
                }

                // We are checking parameters for equality, if they refer to method type parameters,
                // then we don't want to recurse through the method (which would then recurse right
                // back into the parameters).  So we use a signature type comparer as it will properly
                // compare method type parameters by ordinal.
                var signatureComparer = Comparer.SignatureTypeEquivalenceComparer;

                for (int i = 0; i < originalParameterTypes.Length; i++)
                {
                    if (!signatureComparer.Equals(originalParameterTypes[i], parameters[i].Type))
                    {
                        return false;
                    }
                }

                return true;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:sws="http://www.springframework.org/schema/web-services"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <description>
      Base context for the web service endpoints.

      This is to be extended for each WS, which will register all the required
      interceptors, including the security interceptor to use.
   </description>

   <!-- Imports base context -->
   <import resource="classpath:context/endpoint/wsdl.xml" />

   <!-- SOAP logger interceptor -->
   <bean id="soapEnvelopeLoggingInterceptor" class="${interceptor.soapLogger.class}" />

   <!-- Payload validator interceptor -->
   <bean id="payloadValidatingInterceptor" class="${interceptor.payloadValidator.class}">
      <property name="schema" value="${schema.path}" />
      <property name="validateRequest"
         value="${interceptor.payloadValidator.validateRequest}" />
      <property name="validateResponse"
         value="${interceptor.payloadValidator.validateResponse}" />
   </bean>

</beans>


text:
set(VCPKG_TARGET_ARCHITECTURE x64)
set(VCPKG_CRT_LINKAGE dynamic)
set(VCPKG_LIBRARY_LINKAGE static)

set(VCPKG_BUILD_TYPE release)


text:
@interface AddressItemModel : JSONModel

@property (nonatomic, strong) NSString *name;           // 用户姓名
@property (nonatomic, strong) NSString *area_id;        // 区域id
@property (nonatomic, strong) NSString *addr;           // 地址详情
@property (nonatomic, strong) NSString *zipcode;        // 邮编
@property (nonatomic, strong) NSString *telephone;      // phone
@property (nonatomic, strong) NSString *mobile;         // phone
@property (nonatomic, strong) NSString *is_default;     // 是否为默认 0:非默认 1:默认

@property (nonatomic, strong) NSString<Optional> *addr_id;  // 用于修改地址~!@

@end


text:
class ProfilesController < Profiles::ApplicationController
  include ActionView::Helpers::SanitizeHelper

  before_action :user
  before_action :authorize_change_username!, only: :update_username
  skip_before_action :require_email, only: [:show, :update]

  def show
  end

  def update
    user_params.except!(:email) if @user.ldap_user?

    respond_to do |format|
      if @user.update_attributes(user_params)
        message = "Profile was successfully updated"
        format.html { redirect_back_or_default(default: { action: 'show' }, options: { notice: message }) }
        format.json { render json: { message: message } }
      else
        message = @user.errors.full_messages.uniq.join('. ')
        format.html { redirect_back_or_default(default: { action: 'show' }, options: { alert: "Failed to update profile. #{message}" }) }
        format.json { render json: { message: message }, status: :unprocessable_entity }
      end
    end
  end

  def reset_private_token
    if current_user.reset_authentication_token!
      flash[:notice] = "Token was successfully updated"
    end

    redirect_to profile_account_path
  end

  def audit_log
    @events = AuditEvent.where(entity_type: "User", entity_id: current_user.id).
      order("created_at DESC").
      page(params[:page])
  end

  def update_username
    @user.update_attributes(username: user_params[:username])

    respond_to do |format|
      format.js
    end
  end

  private

  def user
    @user = current_user
  end

  def authorize_change_username!
    return render_404 unless @user.can_change_username?
  end

  def user_params
    params.require(:user).permit(
      :avatar,
      :bio,
      :email,
      :hide_no_password,
      :hide_no_ssh_key,
      :hide_project_limit,
      :linkedin,
      :location,
      :name,
      :password,
      :password_confirmation,
      :public_email,
      :skype,
      :twitter,
      :username,
      :website_url,
      :organization
    )
  end
end