text:
from builtins import str

from ctypes import *
from ctypes import util

from .runtime import send_message, ObjCInstance
from .cocoatypes import *

######################################################################

# CORE FOUNDATION

cf = cdll.LoadLibrary(util.find_library('CoreFoundation'))

kCFStringEncodingUTF8 = 0x08000100

CFAllocatorRef = c_void_p
CFStringEncoding = c_uint32

cf.CFStringCreateWithCString.restype = c_void_p
cf.CFStringCreateWithCString.argtypes = [CFAllocatorRef, c_char_p, CFStringEncoding]

cf.CFRelease.restype = c_void_p
cf.CFRelease.argtypes = [c_void_p]

cf.CFStringGetLength.restype = CFIndex
cf.CFStringGetLength.argtypes = [c_void_p]

cf.CFStringGetMaximumSizeForEncoding.restype = CFIndex
cf.CFStringGetMaximumSizeForEncoding.argtypes = [CFIndex, CFStringEncoding]

cf.CFStringGetCString.restype = c_bool
cf.CFStringGetCString.argtypes = [c_void_p, c_char_p, CFIndex, CFStringEncoding]

cf.CFStringGetTypeID.restype = CFTypeID
cf.CFStringGetTypeID.argtypes = []

cf.CFAttributedStringCreate.restype = c_void_p
cf.CFAttributedStringCreate.argtypes = [CFAllocatorRef, c_void_p, c_void_p]

# Core Foundation type to Python type conversion functions

def CFSTR(string):
    return ObjCInstance(c_void_p(cf.CFStringCreateWithCString(
            None, string.encode('utf8'), kCFStringEncodingUTF8)))

# Other possible names for this method:
# at, ampersat, arobe, apenstaartje (little monkey tail), strudel,
# klammeraffe (spider monkey), little_mouse, arroba, sobachka (doggie)
# malpa (monkey), snabel (trunk), papaki (small duck), afna (monkey),
# kukac (caterpillar).
def get_NSString(string):
    """Autoreleased version of CFSTR"""
    return CFSTR(string).autorelease()

def cfstring_to_string(cfstring):
    length = cf.CFStringGetLength(cfstring)
    size = cf.CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8)
    buffer = c_buffer(size + 1)
    result = cf.CFStringGetCString(cfstring, buffer, len(buffer), kCFStringEncodingUTF8)
    if result:
        return str(buffer.value, 'utf-8')

cf.CFDataCreate.restype = c_void_p
cf.CFDataCreate.argtypes = [c_void_p, c_void_p, CFIndex]

cf.CFDataGetBytes.restype = None
cf.CFDataGetBytes.argtypes = [c_void_p, CFRange, c_void_p]

cf.CFDataGetLength.restype = CFIndex
cf.CFDataGetLength.argtypes = [c_void_p]

cf.CFDictionaryGetValue.restype = c_void_p
cf.CFDictionaryGetValue.argtypes = [c_void_p, c_void_p]

cf.CFDictionaryAddValue.restype = None
cf.CFDictionaryAddValue.argtypes = [c_void_p, c_void_p, c_void_p]

cf.CFDictionaryCreateMutable.restype = c_void_p
cf.CFDictionaryCreateMutable.argtypes = [CFAllocatorRef, CFIndex, c_void_p, c_void_p]

cf.CFNumberCreate.restype = c_void_p
cf.CFNumberCreate.argtypes = [CFAllocatorRef, CFNumberType, c_void_p]

cf.CFNumberGetType.restype = CFNumberType
cf.CFNumberGetType.argtypes = [c_void_p]

cf.CFNumberGetValue.restype = c_ubyte
cf.CFNumberGetValue.argtypes = [c_void_p, CFNumberType, c_void_p]

cf.CFNumberGetTypeID.restype = CFTypeID
cf.CFNumberGetTypeID.argtypes = []

cf.CFGetTypeID.restype = CFTypeID
cf.CFGetTypeID.argtypes = [c_void_p]

# CFNumber.h
kCFNumberSInt8Type     = 1
kCFNumberSInt16Type    = 2
kCFNumberSInt32Type    = 3
kCFNumberSInt64Type    = 4
kCFNumberFloat32Type   = 5
kCFNumberFloat64Type   = 6
kCFNumberCharType      = 7
kCFNumberShortType     = 8
kCFNumberIntType       = 9
kCFNumberLongType      = 10
kCFNumberLongLongType  = 11
kCFNumberFloatType     = 12
kCFNumberDoubleType    = 13
kCFNumberCFIndexType   = 14
kCFNumberNSIntegerType = 15
kCFNumberCGFloatType   = 16
kCFNumberMaxType       = 16

def cfnumber_to_number(cfnumber):
    """Convert CFNumber to python int or float."""
    numeric_type = cf.CFNumberGetType(cfnumber)
    cfnum_to_ctype = {kCFNumberSInt8Type:c_int8, kCFNumberSInt16Type:c_int16,
                      kCFNumberSInt32Type:c_int32, kCFNumberSInt64Type:c_int64,
                      kCFNumberFloat32Type:c_float, kCFNumberFloat64Type:c_double,
                      kCFNumberCharType:c_byte, kCFNumberShortType:c_short,
                      kCFNumberIntType:c_int, kCFNumberLongType:c_long,
                      kCFNumberLongLongType:c_longlong, kCFNumberFloatType:c_float,
                      kCFNumberDoubleType:c_double, kCFNumberCFIndexType:CFIndex,
                      kCFNumberCGFloatType:CGFloat}

    if numeric_type in cfnum_to_ctype:
        t = cfnum_to_ctype[numeric_type]
        result = t()
        if cf.CFNumberGetValue(cfnumber, numeric_type, byref(result)):
            return result.value
    else:
        raise Exception('cfnumber_to_number: unhandled CFNumber type %d' % numeric_type)

# Dictionary of cftypes matched to the method converting them to python values.
known_cftypes = { cf.CFStringGetTypeID() : cfstring_to_string,
                  cf.CFNumberGetTypeID() : cfnumber_to_number
                  }

def cftype_to_value(cftype):
    """Convert a CFType into an equivalent python type.
    The convertible CFTypes are taken from the known_cftypes
    dictionary, which may be added to if another library implements
    its own conversion methods."""
    if not cftype:
        return None
    typeID = cf.CFGetTypeID(cftype)
    if typeID in known_cftypes:
        convert_function = known_cftypes[typeID]
        return convert_function(cftype)
    else:
        return cftype

cf.CFSetGetCount.restype = CFIndex
cf.CFSetGetCount.argtypes = [c_void_p]

cf.CFSetGetValues.restype = None
# PyPy 1.7 is fine with 2nd arg as POINTER(c_void_p),
# but CPython ctypes 1.1.0 complains, so just use c_void_p.
cf.CFSetGetValues.argtypes = [c_void_p, c_void_p]

def cfset_to_set(cfset):
    """Convert CFSet to python set."""
    count = cf.CFSetGetCount(cfset)
    buffer = (c_void_p * count)()
    cf.CFSetGetValues(cfset, byref(buffer))
    return set([ cftype_to_value(c_void_p(buffer[i])) for i in range(count) ])

cf.CFArrayGetCount.restype = CFIndex
cf.CFArrayGetCount.argtypes = [c_void_p]

cf.CFArrayGetValueAtIndex.restype = c_void_p
cf.CFArrayGetValueAtIndex.argtypes = [c_void_p, CFIndex]

def cfarray_to_list(cfarray):
    """Convert CFArray to python list."""
    count = cf.CFArrayGetCount(cfarray)
    return [ cftype_to_value(c_void_p(cf.CFArrayGetValueAtIndex(cfarray, i)))
             for i in range(count) ]

kCFRunLoopDefaultMode = c_void_p.in_dll(cf, 'kCFRunLoopDefaultMode')

cf.CFRunLoopGetCurrent.restype = c_void_p
cf.CFRunLoopGetCurrent.argtypes = []

cf.CFRunLoopGetMain.restype = c_void_p
cf.CFRunLoopGetMain.argtypes = []

######################################################################

# APPLICATION KIT

# Even though we don't use this directly, it must be loaded so that
# we can find the NSApplication, NSWindow, and NSView classes.
appkit = cdll.LoadLibrary(util.find_library('AppKit'))

NSDefaultRunLoopMode = c_void_p.in_dll(appkit, 'NSDefaultRunLoopMode')
NSEventTrackingRunLoopMode = c_void_p.in_dll(appkit, 'NSEventTrackingRunLoopMode')
NSApplicationDidHideNotification = c_void_p.in_dll(appkit, 'NSApplicationDidHideNotification')
NSApplicationDidUnhideNotification = c_void_p.in_dll(appkit, 'NSApplicationDidUnhideNotification')

# /System/Library/Frameworks/AppKit.framework/Headers/NSEvent.h
NSAnyEventMask = 0xFFFFFFFF     # NSUIntegerMax

NSKeyDown            = 10
NSKeyUp              = 11
NSFlagsChanged       = 12
NSApplicationDefined = 15

NSAlphaShiftKeyMask         = 1 << 16
NSShiftKeyMask              = 1 << 17
NSControlKeyMask            = 1 << 18
NSAlternateKeyMask          = 1 << 19
NSCommandKeyMask            = 1 << 20
NSNumericPadKeyMask         = 1 << 21
NSHelpKeyMask               = 1 << 22
NSFunctionKeyMask           = 1 << 23

NSInsertFunctionKey   = 0xF727
NSDeleteFunctionKey   = 0xF728
NSHomeFunctionKey     = 0xF729
NSBeginFunctionKey    = 0xF72A
NSEndFunctionKey      = 0xF72B
NSPageUpFunctionKey   = 0xF72C
NSPageDownFunctionKey = 0xF72D

# /System/Library/Frameworks/AppKit.framework/Headers/NSWindow.h
NSBorderlessWindowMask		= 0
NSTitledWindowMask		= 1 << 0
NSClosableWindowMask		= 1 << 1
NSMiniaturizableWindowMask	= 1 << 2
NSResizableWindowMask		= 1 << 3

# /System/Library/Frameworks/AppKit.framework/Headers/NSPanel.h
NSUtilityWindowMask		= 1 << 4

# /System/Library/Frameworks/AppKit.framework/Headers/NSGraphics.h
NSBackingStoreRetained	        = 0
NSBackingStoreNonretained	= 1
NSBackingStoreBuffered	        = 2

# /System/Library/Frameworks/AppKit.framework/Headers/NSTrackingArea.h
NSTrackingMouseEnteredAndExited  = 0x01
NSTrackingMouseMoved             = 0x02
NSTrackingCursorUpdate 		 = 0x04
NSTrackingActiveInActiveApp 	 = 0x40

# /System/Library/Frameworks/AppKit.framework/Headers/NSOpenGL.h
NSOpenGLPFAAllRenderers       =   1   # choose from all available renderers
NSOpenGLPFADoubleBuffer       =   5   # choose a double buffered pixel format
NSOpenGLPFAStereo             =   6   # stereo buffering supported
NSOpenGLPFAAuxBuffers         =   7   # number of aux buffers
NSOpenGLPFAColorSize          =   8   # number of color buffer bits
NSOpenGLPFAAlphaSize          =  11   # number of alpha component bits
NSOpenGLPFADepthSize          =  12   # number of depth buffer bits
NSOpenGLPFAStencilSize        =  13   # number of stencil buffer bits
NSOpenGLPFAAccumSize          =  14   # number of accum buffer bits
NSOpenGLPFAMinimumPolicy      =  51   # never choose smaller buffers than requested
NSOpenGLPFAMaximumPolicy      =  52   # choose largest buffers of type requested
NSOpenGLPFAOffScreen          =  53   # choose an off-screen capable renderer
NSOpenGLPFAFullScreen         =  54   # choose a full-screen capable renderer
NSOpenGLPFASampleBuffers      =  55   # number of multi sample buffers
NSOpenGLPFASamples            =  56   # number of samples per multi sample buffer
NSOpenGLPFAAuxDepthStencil    =  57   # each aux buffer has its own depth stencil
NSOpenGLPFAColorFloat         =  58   # color buffers store floating point pixels
NSOpenGLPFAMultisample        =  59   # choose multisampling
NSOpenGLPFASupersample        =  60   # choose supersampling
NSOpenGLPFASampleAlpha        =  61   # request alpha filtering
NSOpenGLPFARendererID         =  70   # request renderer by ID
NSOpenGLPFASingleRenderer     =  71   # choose a single renderer for all screens
NSOpenGLPFANoRecovery         =  72   # disable all failure recovery systems
NSOpenGLPFAAccelerated        =  73   # choose a hardware accelerated renderer
NSOpenGLPFAClosestPolicy      =  74   # choose the closest color buffer to request
NSOpenGLPFARobust             =  75   # renderer does not need failure recovery
NSOpenGLPFABackingStore       =  76   # back buffer contents are valid after swap
NSOpenGLPFAMPSafe             =  78   # renderer is multi-processor safe
NSOpenGLPFAWindow             =  80   # can be used to render to an onscreen window
NSOpenGLPFAMultiScreen        =  81   # single window can span multiple screens
NSOpenGLPFACompliant          =  83   # renderer is opengl compliant
NSOpenGLPFAScreenMask         =  84   # bit mask of supported physical screens
NSOpenGLPFAPixelBuffer        =  90   # can be used to render to a pbuffer
NSOpenGLPFARemotePixelBuffer  =  91   # can be used to render offline to a pbuffer
NSOpenGLPFAAllowOfflineRenderers = 96 # allow use of offline renderers
NSOpenGLPFAAcceleratedCompute =  97   # choose a hardware accelerated compute device
NSOpenGLPFAOpenGLProfile      =  99   # specify an OpenGL Profile to use
NSOpenGLPFAVirtualScreenCount = 128   # number of virtual screens in this format

NSOpenGLProfileVersionLegacy  = 0x1000    # choose a Legacy/Pre-OpenGL 3.0 Implementation
NSOpenGLProfileVersion3_2Core = 0x3200    # choose an OpenGL 3.2 Core Implementation
NSOpenGLProfileVersion4_1Core = 0x4100    # choose an OpenGL 4.1 Core Implementation

NSOpenGLCPSwapInterval        = 222

# /System/Library/Frameworks/ApplicationServices.framework/Frameworks/...
#     CoreGraphics.framework/Headers/CGImage.h
kCGImageAlphaNone                   = 0
kCGImageAlphaPremultipliedLast      = 1
kCGImageAlphaPremultipliedFirst     = 2
kCGImageAlphaLast                   = 3
kCGImageAlphaFirst                  = 4
kCGImageAlphaNoneSkipLast           = 5
kCGImageAlphaNoneSkipFirst          = 6
kCGImageAlphaOnly                   = 7

kCGImageAlphaPremultipliedLast = 1

kCGBitmapAlphaInfoMask              = 0x1F
kCGBitmapFloatComponents            = 1 << 8

kCGBitmapByteOrderMask              = 0x7000
kCGBitmapByteOrderDefault           = 0 << 12
kCGBitmapByteOrder16Little          = 1 << 12
kCGBitmapByteOrder32Little          = 2 << 12
kCGBitmapByteOrder16Big             = 3 << 12
kCGBitmapByteOrder32Big             = 4 << 12

# NSApplication.h
NSApplicationPresentationDefault = 0
NSApplicationPresentationHideDock = 1 << 1
NSApplicationPresentationHideMenuBar = 1 << 3
NSApplicationPresentationDisableProcessSwitching = 1 << 5
NSApplicationPresentationDisableHideApplication = 1 << 8

# NSRunningApplication.h
NSApplicationActivationPolicyRegular = 0
NSApplicationActivationPolicyAccessory = 1
NSApplicationActivationPolicyProhibited = 2

######################################################################

# QUARTZ / COREGRAPHICS

quartz = cdll.LoadLibrary(util.find_library('quartz'))

CGDirectDisplayID = c_uint32     # CGDirectDisplay.h
CGError = c_int32                # CGError.h
CGBitmapInfo = c_uint32          # CGImage.h

# /System/Library/Frameworks/ApplicationServices.framework/Frameworks/...
#     ImageIO.framework/Headers/CGImageProperties.h
kCGImagePropertyGIFDictionary = c_void_p.in_dll(quartz, 'kCGImagePropertyGIFDictionary')
kCGImagePropertyGIFDelayTime = c_void_p.in_dll(quartz, 'kCGImagePropertyGIFDelayTime')

# /System/Library/Frameworks/ApplicationServices.framework/Frameworks/...
#     CoreGraphics.framework/Headers/CGColorSpace.h
kCGRenderingIntentDefault = 0

quartz.CGDisplayIDToOpenGLDisplayMask.restype = c_uint32
quartz.CGDisplayIDToOpenGLDisplayMask.argtypes = [c_uint32]

quartz.CGMainDisplayID.restype = CGDirectDisplayID
quartz.CGMainDisplayID.argtypes = []

quartz.CGShieldingWindowLevel.restype = c_int32
quartz.CGShieldingWindowLevel.argtypes = []

quartz.CGCursorIsVisible.restype = c_bool

quartz.CGDisplayCopyAllDisplayModes.restype = c_void_p
quartz.CGDisplayCopyAllDisplayModes.argtypes = [CGDirectDisplayID, c_void_p]

quartz.CGDisplaySetDisplayMode.restype = CGError
quartz.CGDisplaySetDisplayMode.argtypes = [CGDirectDisplayID, c_void_p, c_void_p]

quartz.CGDisplayCapture.restype = CGError
quartz.CGDisplayCapture.argtypes = [CGDirectDisplayID]

quartz.CGDisplayRelease.restype = CGError
quartz.CGDisplayRelease.argtypes = [CGDirectDisplayID]

quartz.CGDisplayCopyDisplayMode.restype = c_void_p
quartz.CGDisplayCopyDisplayMode.argtypes = [CGDirectDisplayID]

quartz.CGDisplayModeGetRefreshRate.restype = c_double
quartz.CGDisplayModeGetRefreshRate.argtypes = [c_void_p]

quartz.CGDisplayModeRetain.restype = c_void_p
quartz.CGDisplayModeRetain.argtypes = [c_void_p]

quartz.CGDisplayModeRelease.restype = None
quartz.CGDisplayModeRelease.argtypes = [c_void_p]

quartz.CGDisplayModeGetWidth.restype = c_size_t
quartz.CGDisplayModeGetWidth.argtypes = [c_void_p]

quartz.CGDisplayModeGetHeight.restype = c_size_t
quartz.CGDisplayModeGetHeight.argtypes = [c_void_p]

quartz.CGDisplayModeCopyPixelEncoding.restype = c_void_p
quartz.CGDisplayModeCopyPixelEncoding.argtypes = [c_void_p]

quartz.CGGetActiveDisplayList.restype = CGError
quartz.CGGetActiveDisplayList.argtypes = [c_uint32, POINTER(CGDirectDisplayID), POINTER(c_uint32)]

quartz.CGDisplayBounds.restype = CGRect
quartz.CGDisplayBounds.argtypes = [CGDirectDisplayID]

quartz.CGImageSourceCreateWithData.restype = c_void_p
quartz.CGImageSourceCreateWithData.argtypes = [c_void_p, c_void_p]

quartz.CGImageSourceCreateImageAtIndex.restype = c_void_p
quartz.CGImageSourceCreateImageAtIndex.argtypes = [c_void_p, c_size_t, c_void_p]

quartz.CGImageSourceCopyPropertiesAtIndex.restype = c_void_p
quartz.CGImageSourceCopyPropertiesAtIndex.argtypes = [c_void_p, c_size_t, c_void_p]

quartz.CGImageGetDataProvider.restype = c_void_p
quartz.CGImageGetDataProvider.argtypes = [c_void_p]

quartz.CGDataProviderCopyData.restype = c_void_p
quartz.CGDataProviderCopyData.argtypes = [c_void_p]

quartz.CGDataProviderCreateWithCFData.restype = c_void_p
quartz.CGDataProviderCreateWithCFData.argtypes = [c_void_p]

quartz.CGImageCreate.restype = c_void_p
quartz.CGImageCreate.argtypes = [c_size_t, c_size_t, c_size_t, c_size_t, c_size_t, c_void_p, c_uint32, c_void_p, c_void_p, c_bool, c_int]

quartz.CGImageRelease.restype = None
quartz.CGImageRelease.argtypes = [c_void_p]

quartz.CGImageGetBytesPerRow.restype = c_size_t
quartz.CGImageGetBytesPerRow.argtypes = [c_void_p]

quartz.CGImageGetWidth.restype = c_size_t
quartz.CGImageGetWidth.argtypes = [c_void_p]

quartz.CGImageGetHeight.restype = c_size_t
quartz.CGImageGetHeight.argtypes = [c_void_p]

quartz.CGImageGetBitsPerPixel.restype = c_size_t
quartz.CGImageGetBitsPerPixel.argtypes = [c_void_p]

quartz.CGImageGetBitmapInfo.restype = CGBitmapInfo
quartz.CGImageGetBitmapInfo.argtypes = [c_void_p]

quartz.CGColorSpaceCreateDeviceRGB.restype = c_void_p
quartz.CGColorSpaceCreateDeviceRGB.argtypes = []

quartz.CGDataProviderRelease.restype = None
quartz.CGDataProviderRelease.argtypes = [c_void_p]

quartz.CGColorSpaceRelease.restype = None
quartz.CGColorSpaceRelease.argtypes = [c_void_p]

quartz.CGWarpMouseCursorPosition.restype = CGError
quartz.CGWarpMouseCursorPosition.argtypes = [CGPoint]

quartz.CGDisplayMoveCursorToPoint.restype = CGError
quartz.CGDisplayMoveCursorToPoint.argtypes = [CGDirectDisplayID, CGPoint]

quartz.CGAssociateMouseAndMouseCursorPosition.restype = CGError
quartz.CGAssociateMouseAndMouseCursorPosition.argtypes = [c_bool]

quartz.CGBitmapContextCreate.restype = c_void_p
quartz.CGBitmapContextCreate.argtypes = [c_void_p, c_size_t, c_size_t, c_size_t, c_size_t, c_void_p, CGBitmapInfo]

quartz.CGBitmapContextCreateImage.restype = c_void_p
quartz.CGBitmapContextCreateImage.argtypes = [c_void_p]

quartz.CGFontCreateWithDataProvider.restype = c_void_p
quartz.CGFontCreateWithDataProvider.argtypes = [c_void_p]

quartz.CGFontCreateWithFontName.restype = c_void_p
quartz.CGFontCreateWithFontName.argtypes = [c_void_p]

quartz.CGContextDrawImage.restype = None
quartz.CGContextDrawImage.argtypes = [c_void_p, CGRect, c_void_p]

quartz.CGContextRelease.restype = None
quartz.CGContextRelease.argtypes = [c_void_p]

quartz.CGContextSetTextPosition.restype = None
quartz.CGContextSetTextPosition.argtypes = [c_void_p, CGFloat, CGFloat]

quartz.CGContextSetShouldAntialias.restype = None
quartz.CGContextSetShouldAntialias.argtypes = [c_void_p, c_bool]

######################################################################

# CORETEXT
ct = cdll.LoadLibrary(util.find_library('CoreText'))

# Types
CTFontOrientation = c_uint32      # CTFontDescriptor.h
CTFontSymbolicTraits = c_uint32   # CTFontTraits.h

# CoreText constants
kCTFontAttributeName = c_void_p.in_dll(ct, 'kCTFontAttributeName')
kCTFontFamilyNameAttribute = c_void_p.in_dll(ct, 'kCTFontFamilyNameAttribute')
kCTFontSymbolicTrait = c_void_p.in_dll(ct, 'kCTFontSymbolicTrait')
kCTFontWeightTrait = c_void_p.in_dll(ct, 'kCTFontWeightTrait')
kCTFontTraitsAttribute = c_void_p.in_dll(ct, 'kCTFontTraitsAttribute')

# constants from CTFontTraits.h
kCTFontItalicTrait = (1 << 0)
kCTFontBoldTrait   = (1 << 1)

ct.CTLineCreateWithAttributedString.restype = c_void_p
ct.CTLineCreateWithAttributedString.argtypes = [c_void_p]

ct.CTLineDraw.restype = None
ct.CTLineDraw.argtypes = [c_void_p, c_void_p]

ct.CTFontGetBoundingRectsForGlyphs.restype = CGRect
ct.CTFontGetBoundingRectsForGlyphs.argtypes = [c_void_p, CTFontOrientation, POINTER(CGGlyph), POINTER(CGRect), CFIndex]

ct.CTFontGetAdvancesForGlyphs.restype = c_double
ct.CTFontGetAdvancesForGlyphs.argtypes = [c_void_p, CTFontOrientation, POINTER(CGGlyph), POINTER(CGSize), CFIndex]

ct.CTFontGetAscent.restype = CGFloat
ct.CTFontGetAscent.argtypes = [c_void_p]

ct.CTFontGetDescent.restype = CGFloat
ct.CTFontGetDescent.argtypes = [c_void_p]

ct.CTFontGetSymbolicTraits.restype = CTFontSymbolicTraits
ct.CTFontGetSymbolicTraits.argtypes = [c_void_p]

ct.CTFontGetGlyphsForCharacters.restype = c_bool
ct.CTFontGetGlyphsForCharacters.argtypes = [c_void_p, POINTER(UniChar), POINTER(CGGlyph), CFIndex]

ct.CTFontCreateWithGraphicsFont.restype = c_void_p
ct.CTFontCreateWithGraphicsFont.argtypes = [c_void_p, CGFloat, c_void_p, c_void_p]

ct.CTFontCopyFamilyName.restype = c_void_p
ct.CTFontCopyFamilyName.argtypes = [c_void_p]

ct.CTFontCopyFullName.restype = c_void_p
ct.CTFontCopyFullName.argtypes = [c_void_p]

ct.CTFontCreateWithFontDescriptor.restype = c_void_p
ct.CTFontCreateWithFontDescriptor.argtypes = [c_void_p, CGFloat, c_void_p]

ct.CTFontDescriptorCreateWithAttributes.restype = c_void_p
ct.CTFontDescriptorCreateWithAttributes.argtypes = [c_void_p]

######################################################################

# FOUNDATION

foundation = cdll.LoadLibrary(util.find_library('Foundation'))

foundation.NSMouseInRect.restype = c_bool
foundation.NSMouseInRect.argtypes = [NSPoint, NSRect, c_bool]


text:
"""This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_terminate_job_flow`."""

import warnings

# pylint: disable=unused-import
from airflow.providers.amazon.aws.operators.emr_terminate_job_flow import EmrTerminateJobFlowOperator  # noqa

warnings.warn(
    "This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_terminate_job_flow`.",
    DeprecationWarning,
    stacklevel=2,
)

redpajama_set_name: RedPajamaGithub


text:
import { CSSProperties, ReactNode, useState } from 'react';
import classNames from 'classnames';
import { useLitformPopperWithAutoClosing, useToggleOpen } from '@neinteractiveliterature/litform';

import useAutoCloseOnNavigate from '../NavigationBar/useAutoCloseOnNavigate';

export type DropdownMenuProps = {
  buttonContent: ReactNode;
  buttonClassName?: string;
  buttonStyle?: CSSProperties;
  children: ReactNode;
  dropdownClassName?: string;
  dropdownStyle?: CSSProperties;
  popperOptions?: Parameters<typeof useLitformPopperWithAutoClosing>[4];
  shouldAutoCloseOnNavigate?: Parameters<typeof useAutoCloseOnNavigate>[1];
};

export function DropdownMenu({
  children,
  buttonContent,
  buttonClassName,
  buttonStyle,
  dropdownClassName,
  dropdownStyle,
  popperOptions,
  shouldAutoCloseOnNavigate,
}: DropdownMenuProps): JSX.Element {
  const [dropdownButton, setDropdownButton] = useState<HTMLButtonElement | null>(null);
  const [dropdownMenu, setDropdownMenu] = useState<HTMLDivElement | null>(null);
  const [dropdownOpen, setDropdownOpen] = useState<boolean>(false);

  const { styles, attributes, update } = useLitformPopperWithAutoClosing(
    dropdownMenu,
    dropdownButton,
    undefined,
    setDropdownOpen,
    {
      placement: 'bottom-start',
      modifiers: [{ name: 'offset', options: { offset: [0, 2] } }, ...(popperOptions?.modifiers ?? [])],
      ...popperOptions,
    },
  );

  const toggleOpen = useToggleOpen(setDropdownOpen, update);
  useAutoCloseOnNavigate(setDropdownOpen, shouldAutoCloseOnNavigate);

  return (
    <>
      <button
        type="button"
        className={buttonClassName ?? 'btn dropdown-toggle'}
        ref={setDropdownButton}
        onClick={toggleOpen}
        style={buttonStyle}
      >
        {buttonContent}
      </button>
      <div
        className={classNames('dropdown-menu m-0', dropdownClassName, { show: dropdownOpen })}
        ref={setDropdownMenu}
        style={{ ...styles.popper, ...dropdownStyle }}
        {...attributes.popper}
      >
        {children}
      </div>
    </>
  );
}


text:
<?php

final class DifferentialRevisionRequiredActionResultBucket
  extends DifferentialRevisionResultBucket {

  const BUCKETKEY = 'action';

  const KEY_MUSTREVIEW = 'must-review';
  const KEY_SHOULDREVIEW = 'should-review';

  private $objects;

  public function getResultBucketName() {
    return pht('Bucket by Required Action');
  }

  protected function buildResultGroups(
    PhabricatorSavedQuery $query,
    array $objects) {

    $this->objects = $objects;

    $phids = $query->getEvaluatedParameter('responsiblePHIDs');
    if (!$phids) {
      throw new Exception(
        pht(
          'You can not bucket results by required action without '.
          'specifying "Responsible Users".'));
    }
    $phids = array_fuse($phids);

    // Before continuing, throw away any revisions which responsible users
    // have explicitly resigned from.

    // The goal is to allow users to resign from revisions they don't want to
    // review to get these revisions off their dashboard, even if there are
    // other project or package reviewers which they have authority over.
    $this->filterResigned($phids);

    // We also throw away draft revisions which you aren't the author of.
    $this->filterOtherDrafts($phids);

    $groups = array();

    $groups[] = $this->newGroup()
      ->setName(pht('Must Review'))
      ->setKey(self::KEY_MUSTREVIEW)
      ->setNoDataString(pht('No revisions are blocked on your review.'))
      ->setObjects($this->filterMustReview($phids));

    $groups[] = $this->newGroup()
      ->setName(pht('Ready to Review'))
      ->setKey(self::KEY_SHOULDREVIEW)
      ->setNoDataString(pht('No revisions are waiting on you to review them.'))
      ->setObjects($this->filterShouldReview($phids));

    $groups[] = $this->newGroup()
      ->setName(pht('Ready to Land'))
      ->setNoDataString(pht('No revisions are ready to land.'))
      ->setObjects($this->filterShouldLand($phids));

    $groups[] = $this->newGroup()
      ->setName(pht('Ready to Update'))
      ->setNoDataString(pht('No revisions are waiting for updates.'))
      ->setObjects($this->filterShouldUpdate($phids));

    $groups[] = $this->newGroup()
      ->setName(pht('Drafts'))
      ->setNoDataString(pht('You have no draft revisions.'))
      ->setObjects($this->filterDrafts($phids));

    $groups[] = $this->newGroup()
      ->setName(pht('Waiting on Review'))
      ->setNoDataString(pht('None of your revisions are waiting on review.'))
      ->setObjects($this->filterWaitingForReview($phids));

    $groups[] = $this->newGroup()
      ->setName(pht('Waiting on Authors'))
      ->setNoDataString(pht('No revisions are waiting on author action.'))
      ->setObjects($this->filterWaitingOnAuthors($phids));

    $groups[] = $this->newGroup()
      ->setName(pht('Waiting on Other Reviewers'))
      ->setNoDataString(pht('No revisions are waiting for other reviewers.'))
      ->setObjects($this->filterWaitingOnOtherReviewers($phids));

    // Because you can apply these buckets to queries which include revisions
    // that have been closed, add an "Other" bucket if we still have stuff
    // that didn't get filtered into any of the previous buckets.
    if ($this->objects) {
      $groups[] = $this->newGroup()
        ->setName(pht('Other Revisions'))
        ->setObjects($this->objects);
    }

    return $groups;
  }

  private function filterMustReview(array $phids) {
    $blocking = array(
      DifferentialReviewerStatus::STATUS_BLOCKING,
      DifferentialReviewerStatus::STATUS_REJECTED,
      DifferentialReviewerStatus::STATUS_REJECTED_OLDER,
    );
    $blocking = array_fuse($blocking);

    $objects = $this->getRevisionsUnderReview($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$this->hasReviewersWithStatus($object, $phids, $blocking)) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterShouldReview(array $phids) {
    $reviewing = array(
      DifferentialReviewerStatus::STATUS_ADDED,
      DifferentialReviewerStatus::STATUS_COMMENTED,

      // If an author has used "Request Review" to put an accepted revision
      // back into the "Needs Review" state, include "Accepted" reviewers
      // whose reviews have been voided in the "Should Review" bucket.

      // If we don't do this, they end up in "Waiting on Other Reviewers",
      // even if there are no other reviewers.
      DifferentialReviewerStatus::STATUS_ACCEPTED,
    );
    $reviewing = array_fuse($reviewing);

    $objects = $this->getRevisionsUnderReview($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$this->hasReviewersWithStatus($object, $phids, $reviewing, true)) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterShouldLand(array $phids) {
    $objects = $this->getRevisionsAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$object->isAccepted()) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterShouldUpdate(array $phids) {
    $statuses = array(
      DifferentialRevisionStatus::NEEDS_REVISION,
      DifferentialRevisionStatus::CHANGES_PLANNED,
    );
    $statuses = array_fuse($statuses);

    $objects = $this->getRevisionsAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (empty($statuses[$object->getModernRevisionStatus()])) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterWaitingForReview(array $phids) {
    $objects = $this->getRevisionsAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$object->isNeedsReview()) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterWaitingOnAuthors(array $phids) {
    $statuses = array(
      DifferentialRevisionStatus::ACCEPTED,
      DifferentialRevisionStatus::NEEDS_REVISION,
      DifferentialRevisionStatus::CHANGES_PLANNED,
    );
    $statuses = array_fuse($statuses);

    $objects = $this->getRevisionsNotAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (empty($statuses[$object->getModernRevisionStatus()])) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterWaitingOnOtherReviewers(array $phids) {
    $objects = $this->getRevisionsNotAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$object->isNeedsReview()) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterResigned(array $phids) {
    $resigned = array(
      DifferentialReviewerStatus::STATUS_RESIGNED,
    );
    $resigned = array_fuse($resigned);

    $objects = $this->getRevisionsNotAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$this->hasReviewersWithStatus($object, $phids, $resigned)) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterOtherDrafts(array $phids) {
    $objects = $this->getRevisionsNotAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$object->isDraft()) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

  private function filterDrafts(array $phids) {
    $objects = $this->getRevisionsAuthored($this->objects, $phids);

    $results = array();
    foreach ($objects as $key => $object) {
      if (!$object->isDraft()) {
        continue;
      }

      $results[$key] = $object;
      unset($this->objects[$key]);
    }

    return $results;
  }

}


text:
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Javascript for DeviceTable UI, served from chrome://bluetooth-internals/.
 */
import {assert} from 'chrome://resources/js/assert.js';
import {CustomElement} from 'chrome://resources/js/custom_element.js';

import {DeviceInfo} from './device.mojom-webui.js';
import {DeviceCollection} from './device_collection.js';
import {getTemplate} from './device_table.html.js';
import {formatManufacturerDataMap, formatServiceUuids} from './device_utils.js';

const COLUMNS = {
  NAME: 0,
  ADDRESS: 1,
  RSSI: 2,
  MANUFACTURER_DATA: 3,
  SERVICE_UUIDS: 4,
  CONNECTION_STATE: 5,
  LINKS: 6,
};

/**
 * A table that lists the devices and responds to changes in the given
 * DeviceCollection. Fires events for inspection requests from listed
 * devices.
 */
export class DeviceTableElement extends CustomElement {
  static get template() {
    return getTemplate();
  }

  static get is() {
    return 'device-table';
  }

  constructor() {
    super();

    /** @private {?DeviceCollection} */
    this.devices_ = null;

    /** @private {?HTMLTBodyElement} */
    this.body_ = null;

    /** @private {?NodeListOf<Element>} */
    this.headers_ = null;

    /** @private {!Map<!DeviceInfo, boolean>} */
    this.inspectionMap_ = new Map();
  }

  /**
   * Decorates an element as a UI element class. Caches references to the
   *    table body and headers.
   */
  connectedCallback() {
    this.body_ = this.shadowRoot.querySelector('tbody');
    this.headers_ = this.shadowRoot.querySelector('thead').rows[0].cells;
  }

  /**
   * Sets the tables device collection.
   * @param {!DeviceCollection} deviceCollection
   */
  setDevices(deviceCollection) {
    assert(!this.devices_, 'Devices can only be set once.');

    this.devices_ = deviceCollection;
    this.devices_.addEventListener(
        'device-update', this.handleDeviceUpdate_.bind(this));
    this.devices_.addEventListener(
        'device-added', this.handleDeviceAdded_.bind(this));
    this.devices_.addEventListener(
        'devices-reset-for-test', this.redraw_.bind(this));

    this.redraw_();
  }

  /**
   * Updates the inspect status of the row matching the given |deviceInfo|.
   * If |isInspecting| is true, the forget link is enabled otherwise it's
   * disabled.
   * @param {!DeviceInfo} deviceInfo
   * @param {boolean} isInspecting
   */
  setInspecting(deviceInfo, isInspecting) {
    this.inspectionMap_.set(deviceInfo, isInspecting);
    this.updateRow_(deviceInfo, this.devices_.getByAddress(deviceInfo.address));
  }

  /**
   * Fires a forget pressed event for the row |index|.
   * @param {number} index
   * @private
   */
  handleForgetClick_(index) {
    const event = new CustomEvent('forgetpressed', {
      bubbles: true,
      composed: true,
      detail: {
        address: this.devices_.item(index).address,
      },
    });
    this.dispatchEvent(event);
  }

  /**
   * Updates table row on change event of the device collection.
   * @param {!CustomEvent<number>} event
   * @private
   */
  handleDeviceUpdate_(event) {
    this.updateRow_(
        /** @type {!DeviceInfo} */ (this.devices_.item(event.detail)),
        event.detail);
  }

  /**
   * Fires an inspect pressed event for the row |index|.
   * @param {number} index
   * @private
   */
  handleInspectClick_(index) {
    const event = new CustomEvent('inspectpressed', {
      bubbles: true,
      composed: true,
      detail: {
        address: this.devices_.item(index).address,
      },
    });
    this.dispatchEvent(event);
  }

  /**
   * Updates table row on splice event of the device collection.
   * @param {!CustomEvent<device: DeviceInfo, index: number>} event
   * @private
   */
  handleDeviceAdded_(event) {
    this.insertRow_(event.detail.device, event.detail.index);
  }

  /**
   * Inserts a new row at |index| and updates it with info from |device|.
   * @param {!DeviceInfo} device
   * @param {?number} index
   * @private
   */
  insertRow_(device, index) {
    const row = this.body_.insertRow(index);
    row.id = device.address;

    for (let i = 0; i < this.headers_.length; i++) {
      // Skip the LINKS column. It has no data-field attribute.
      if (i === COLUMNS.LINKS) {
        continue;
      }
      row.insertCell();
    }

    // Make two extra cells for the inspect link and connect errors.
    const inspectCell = row.insertCell();

    const inspectLink = document.createElement('a', {is: 'action-link'});
    inspectLink.setAttribute('is', 'action-link');
    inspectLink.textContent = 'Inspect';
    inspectCell.appendChild(inspectLink);
    inspectLink.addEventListener('click', function() {
      this.handleInspectClick_(row.sectionRowIndex);
    }.bind(this));

    const forgetLink = document.createElement('a', {is: 'action-link'});
    forgetLink.setAttribute('is', 'action-link');
    forgetLink.textContent = 'Forget';
    inspectCell.appendChild(forgetLink);
    forgetLink.addEventListener('click', function() {
      this.handleForgetClick_(row.sectionRowIndex);
    }.bind(this));

    this.updateRow_(device, row.sectionRowIndex);
  }

  /**
   * Deletes and recreates the table using the cached |devices_|.
   * @private
   */
  redraw_() {
    const table = this.shadowRoot.querySelector('table');
    table.removeChild(this.body_);
    table.appendChild(document.createElement('tbody'));
    this.body_ = this.shadowRoot.querySelector('tbody');
    this.body_.classList.add('table-body');

    for (let i = 0; i < this.devices_.length; i++) {
      this.insertRow_(
          /** @type {!DeviceInfo} */ (this.devices_.item(i)), null);
    }
  }

  /**
   * Updates the row at |index| with the info from |device|.
   * @param {!DeviceInfo} device
   * @param {number} index
   * @private
   */
  updateRow_(device, index) {
    const row = this.body_.rows[index];
    assert(row, 'Row ' + index + ' is not in the table.');

    row.classList.toggle('removed', this.devices_.isRemoved(device));

    const forgetLink = row.cells[COLUMNS.LINKS].children[1];

    if (this.inspectionMap_.has(device)) {
      forgetLink.disabled = !this.inspectionMap_.get(device);
    } else {
      forgetLink.disabled = true;
    }

    // Update the properties based on the header field path.
    for (let i = 0; i < this.headers_.length; i++) {
      // Skip the LINKS column. It has no data-field attribute.
      if (i === COLUMNS.LINKS) {
        continue;
      }

      const header = this.headers_[i];
      const propName = header.dataset.field;

      const parts = propName.split('.');
      let obj = device;
      while (obj != null && parts.length > 0) {
        const part = parts.shift();
        obj = obj[part];
      }

      if (propName === 'isGattConnected') {
        obj = obj ? 'Connected' : 'Not Connected';
      } else if (propName === 'serviceUuids') {
        obj = formatServiceUuids(obj);
      } else if (propName === 'manufacturerDataMap') {
        obj = formatManufacturerDataMap(obj);
      }

      const cell = row.cells[i];
      cell.textContent = obj == null ? 'Unknown' : obj;
      cell.dataset.label = header.textContent;
    }
  }
}

customElements.define('device-table', DeviceTableElement);


text:
package pl.com.softproject.utils.payu.model;

/**
 *
 * @author Leszek Bednorz <lbednorz@softproject.com.pl>
 */
public enum PaymentStatus {

    S1("1", "nowa"),
    S2("2", "anulowana"),
    S3("3", "odrzucona"),
    S4("4", "rozpoczeta"),
    S5("5", "oczekuje na odbior"),
    S6("6", "autoryzacja odmowna"),
    S7("7", "platnosc odrzucona"),
    S99("99", "platnosc odebrana - zakonczona"),
    S888("888", "bledny status"), S0("0", "błąd");

    private String code;
    private String message;
    private ErrorMessage error;

    private PaymentStatus(String code, String message) {
        this.code = code;
        this.message = message;
    }

    public String getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.message;
    }

    public static PaymentStatus getByCode(String code) {
        return valueOf("S" + code);
    }

    public ErrorMessage getError() {
        return this.error;
    }

    public void setError(ErrorMessage error) {
        this.error = error;
    }

    public String toString() {
        return "PaymentStatus{code=" + this.code + ", message=" + this.message + ", error=" + this.error + '}';
    }
}


text:
This is a Clojure[Script] application which parses Harrisburg City
crime report PDFs and stores and displays them.

## License

Copyright © 2013-2015 Joshua Miller

Distributed under the MIT License.


text:
Factory.define :moip_payment, :parent => :payment do |record|
  record.association(:order, factory: :moip_order)
  record.association(:payment_method, factory: :moip_payment_method)
end


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

#nullable enable

using System.Threading;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Classification
{
    internal static class ClassificationHelpers
    {
        private const string FromKeyword = "from";
        private const string ValueKeyword = "value";
        private const string VarKeyword = "var";
        private const string UnmanagedKeyword = "unmanaged";
        private const string NotNullKeyword = "notnull";
        private const string DynamicKeyword = "dynamic";
        private const string AwaitKeyword = "await";

        /// <summary>
        /// Determine the classification type for a given token.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns>The correct syntactic classification for the token.</returns>
        public static string? GetClassification(SyntaxToken token)
        {
            if (IsControlKeyword(token))
            {
                return ClassificationTypeNames.ControlKeyword;
            }
            else if (SyntaxFacts.IsKeywordKind(token.Kind()) || token.IsKind(SyntaxKind.DiscardDesignation))
            {
                // When classifying `_`, IsKeywordKind handles UnderscoreToken, but need to additional check for DiscardDesignation
                return ClassificationTypeNames.Keyword;
            }
            else if (SyntaxFacts.IsPunctuation(token.Kind()))
            {
                return GetClassificationForPunctuation(token);
            }
            else if (token.Kind() == SyntaxKind.IdentifierToken)
            {
                return GetClassificationForIdentifier(token);
            }
            else if (IsStringToken(token))
            {
                return IsVerbatimStringToken(token)
                    ? ClassificationTypeNames.VerbatimStringLiteral
                    : ClassificationTypeNames.StringLiteral;
            }
            else if (token.Kind() == SyntaxKind.NumericLiteralToken)
            {
                return ClassificationTypeNames.NumericLiteral;
            }

            return null;
        }

        private static bool IsControlKeyword(SyntaxToken token)
        {
            if (token.Parent is null || !IsControlKeywordKind(token.Kind()))
            {
                return false;
            }

            return IsControlStatementKind(token.Parent.Kind());
        }

        private static bool IsControlKeywordKind(SyntaxKind kind)
        {
            switch (kind)
            {
                case SyntaxKind.IfKeyword:
                case SyntaxKind.ElseKeyword:
                case SyntaxKind.WhileKeyword:
                case SyntaxKind.ForKeyword:
                case SyntaxKind.ForEachKeyword:
                case SyntaxKind.DoKeyword:
                case SyntaxKind.SwitchKeyword:
                case SyntaxKind.CaseKeyword:
                case SyntaxKind.TryKeyword:
                case SyntaxKind.CatchKeyword:
                case SyntaxKind.FinallyKeyword:
                case SyntaxKind.GotoKeyword:
                case SyntaxKind.BreakKeyword:
                case SyntaxKind.ContinueKeyword:
                case SyntaxKind.ReturnKeyword:
                case SyntaxKind.ThrowKeyword:
                case SyntaxKind.YieldKeyword:
                case SyntaxKind.DefaultKeyword: // Include DefaultKeyword as it can be part of a DefaultSwitchLabel
                case SyntaxKind.InKeyword: // Include InKeyword as it can be part of an ForEachStatement
                case SyntaxKind.WhenKeyword: // Include WhenKeyword as it can be part of a CatchFilterClause or a pattern WhenClause
                    return true;
                default:
                    return false;
            }
        }

        private static bool IsControlStatementKind(SyntaxKind kind)
        {
            switch (kind)
            {
                // Jump Statements
                case SyntaxKind.GotoStatement:
                case SyntaxKind.GotoCaseStatement:
                case SyntaxKind.GotoDefaultStatement:
                case SyntaxKind.BreakStatement:
                case SyntaxKind.ContinueStatement:
                case SyntaxKind.ReturnStatement:
                case SyntaxKind.YieldReturnStatement:
                case SyntaxKind.YieldBreakStatement:
                case SyntaxKind.ThrowStatement:
                case SyntaxKind.WhileStatement:
                case SyntaxKind.DoStatement:
                case SyntaxKind.ForStatement:
                case SyntaxKind.ForEachStatement:
                case SyntaxKind.ForEachVariableStatement:
                // Checked Statements
                case SyntaxKind.IfStatement:
                case SyntaxKind.ElseClause:
                case SyntaxKind.SwitchStatement:
                case SyntaxKind.SwitchSection:
                case SyntaxKind.CaseSwitchLabel:
                case SyntaxKind.CasePatternSwitchLabel:
                case SyntaxKind.DefaultSwitchLabel:
                case SyntaxKind.TryStatement:
                case SyntaxKind.CatchClause:
                case SyntaxKind.CatchFilterClause:
                case SyntaxKind.FinallyClause:
                case SyntaxKind.SwitchExpression:
                case SyntaxKind.ThrowExpression:
                case SyntaxKind.WhenClause:
                    return true;
                default:
                    return false;
            }
        }

        private static bool IsStringToken(SyntaxToken token)
        {
            return token.IsKind(SyntaxKind.StringLiteralToken)
                || token.IsKind(SyntaxKind.CharacterLiteralToken)
                || token.IsKind(SyntaxKind.InterpolatedStringStartToken)
                || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken)
                || token.IsKind(SyntaxKind.InterpolatedStringTextToken)
                || token.IsKind(SyntaxKind.InterpolatedStringEndToken);
        }

        private static bool IsVerbatimStringToken(SyntaxToken token)
        {
            if (token.IsVerbatimStringLiteral())
            {
                return true;
            }

            switch (token.Kind())
            {
                case SyntaxKind.InterpolatedVerbatimStringStartToken:
                    return true;
                case SyntaxKind.InterpolatedStringStartToken:
                    return false;

                case SyntaxKind.InterpolatedStringEndToken:
                    {
                        return token.Parent is InterpolatedStringExpressionSyntax interpolatedString
                            && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
                    }

                case SyntaxKind.InterpolatedStringTextToken:
                    {
                        if (!(token.Parent is InterpolatedStringTextSyntax interpolatedStringText))
                        {
                            return false;
                        }

                        return interpolatedStringText.Parent is InterpolatedStringExpressionSyntax interpolatedString
                            && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken);
                    }
            }

            return false;
        }

        private static string? GetClassificationForIdentifier(SyntaxToken token)
        {
            if (token.Parent is BaseTypeDeclarationSyntax typeDeclaration && typeDeclaration.Identifier == token)
            {
                return GetClassificationForTypeDeclarationIdentifier(token);
            }
            else if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration) && ((DelegateDeclarationSyntax)token.Parent).Identifier == token)
            {
                return ClassificationTypeNames.DelegateName;
            }
            else if (token.Parent.IsKind(SyntaxKind.TypeParameter) && ((TypeParameterSyntax)token.Parent).Identifier == token)
            {
                return ClassificationTypeNames.TypeParameterName;
            }
            else if (token.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.Identifier == token)
            {
                return IsExtensionMethod(methodDeclaration) ? ClassificationTypeNames.ExtensionMethodName : ClassificationTypeNames.MethodName;
            }
            else if (token.Parent is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.Identifier == token)
            {
                return constructorDeclaration.IsParentKind(SyntaxKind.ClassDeclaration)
                    ? ClassificationTypeNames.ClassName
                    : ClassificationTypeNames.StructName;
            }
            else if (token.Parent is DestructorDeclarationSyntax destructorDeclaration && destructorDeclaration.Identifier == token)
            {
                return destructorDeclaration.IsParentKind(SyntaxKind.ClassDeclaration)
                    ? ClassificationTypeNames.ClassName
                    : ClassificationTypeNames.StructName;
            }
            else if (token.Parent is LocalFunctionStatementSyntax localFunctionStatement && localFunctionStatement.Identifier == token)
            {
                return ClassificationTypeNames.MethodName;
            }
            else if (token.Parent is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Identifier == token)
            {
                return ClassificationTypeNames.PropertyName;
            }
            else if (token.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration && enumMemberDeclaration.Identifier == token)
            {
                return ClassificationTypeNames.EnumMemberName;
            }
            else if (token.Parent is CatchDeclarationSyntax catchDeclaration && catchDeclaration.Identifier == token)
            {
                return ClassificationTypeNames.LocalName;
            }
            else if (token.Parent is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Identifier == token)
            {
                var varDecl = variableDeclarator.Parent as VariableDeclarationSyntax;
                return varDecl?.Parent switch
                {
                    FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.FieldName,
                    LocalDeclarationStatementSyntax localDeclarationStatement => localDeclarationStatement.IsConst ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.LocalName,
                    EventFieldDeclarationSyntax aventFieldDeclarationSyntax => ClassificationTypeNames.EventName,
                    _ => ClassificationTypeNames.LocalName,
                };
            }
            else if (token.Parent is SingleVariableDesignationSyntax singleVariableDesignation && singleVariableDesignation.Identifier == token)
            {
                var parent = singleVariableDesignation.Parent;

                // Handle nested Tuple deconstruction
                while (parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation))
                {
                    parent = parent.Parent;
                }

                // Checking for DeclarationExpression covers the following cases:
                // - Out parameters used within a field initializer or within a method. `int.TryParse("1", out var x)`
                // - Tuple deconstruction. `var (x, _) = (1, 2);`
                //
                // Checking for DeclarationPattern covers the following cases:
                // - Is patterns. `if (foo is Action action)`
                // - Switch patterns. `case int x when x > 0:`
                if (parent.IsKind(SyntaxKind.DeclarationExpression) ||
                    parent.IsKind(SyntaxKind.DeclarationPattern))
                {
                    return ClassificationTypeNames.LocalName;
                }

                return ClassificationTypeNames.Identifier;
            }
            else if (token.Parent is ParameterSyntax parameterSyntax && parameterSyntax.Identifier == token)
            {
                return ClassificationTypeNames.ParameterName;
            }
            else if (token.Parent is ForEachStatementSyntax forEachStatementSyntax && forEachStatementSyntax.Identifier == token)
            {
                return ClassificationTypeNames.LocalName;
            }
            else if (token.Parent is EventDeclarationSyntax eventDeclarationSyntax && eventDeclarationSyntax.Identifier == token)
            {
                return ClassificationTypeNames.EventName;
            }
            else if (IsActualContextualKeyword(token))
            {
                return ClassificationTypeNames.Keyword;
            }
            else if (token.Parent is IdentifierNameSyntax identifierNameSyntax && IsNamespaceName(identifierNameSyntax))
            {
                return ClassificationTypeNames.NamespaceName;
            }
            else if (token.Parent is ExternAliasDirectiveSyntax externAliasDirectiveSyntax && externAliasDirectiveSyntax.Identifier == token)
            {
                return ClassificationTypeNames.NamespaceName;
            }
            else if (token.Parent is LabeledStatementSyntax labledStatementSyntax && labledStatementSyntax.Identifier == token)
            {
                return ClassificationTypeNames.LabelName;
            }
            else
            {
                return ClassificationTypeNames.Identifier;
            }
        }

        private static bool IsNamespaceName(IdentifierNameSyntax identifierSyntax)
        {
            var parent = identifierSyntax.Parent;

            while (parent is QualifiedNameSyntax)
            {
                parent = parent.Parent;
            }

            return parent is NamespaceDeclarationSyntax;
        }

        public static bool IsStaticallyDeclared(SyntaxToken token)
        {
            SyntaxNode? parentNode = token.Parent;

            if (parentNode.IsKind(SyntaxKind.EnumMemberDeclaration))
            {
                // EnumMembers are not classified as static since there is no
                // instance equivalent of the concept and they have their own
                // classification type.
                return false;
            }
            else if (parentNode.IsKind(SyntaxKind.VariableDeclarator))
            {
                // The parent of a VariableDeclarator is a VariableDeclarationSyntax node.
                // It's parent will be the declaration syntax node.
                parentNode = parentNode!.Parent!.Parent;

                // Check if this is a field constant declaration
                if (parentNode.GetModifiers().Any(SyntaxKind.ConstKeyword))
                {
                    return true;
                }
            }

            return parentNode.GetModifiers().Any(SyntaxKind.StaticKeyword);
        }

        private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration)
        {
            return methodDeclaration.ParameterList.Parameters.FirstOrDefault()?.Modifiers.Any(SyntaxKind.ThisKeyword) == true;
        }

        private static string? GetClassificationForTypeDeclarationIdentifier(SyntaxToken identifier)
            => identifier.Parent!.Kind() switch
            {
                SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName,
                SyntaxKind.EnumDeclaration => ClassificationTypeNames.EnumName,
                SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName,
                SyntaxKind.InterfaceDeclaration => ClassificationTypeNames.InterfaceName,
                _ => null,
            };

        private static string GetClassificationForPunctuation(SyntaxToken token)
        {
            if (token.Kind().IsOperator())
            {
                // special cases...
                switch (token.Kind())
                {
                    case SyntaxKind.LessThanToken:
                    case SyntaxKind.GreaterThanToken:
                        // the < and > tokens of a type parameter list should be classified as
                        // punctuation; otherwise, they're operators.
                        if (token.Parent != null)
                        {
                            if (token.Parent.Kind() == SyntaxKind.TypeParameterList ||
                                token.Parent.Kind() == SyntaxKind.TypeArgumentList)
                            {
                                return ClassificationTypeNames.Punctuation;
                            }
                        }

                        break;
                    case SyntaxKind.ColonToken:
                        // the : for inheritance/implements or labels should be classified as
                        // punctuation; otherwise, it's from a conditional operator.
                        if (token.Parent != null)
                        {
                            if (token.Parent.Kind() != SyntaxKind.ConditionalExpression)
                            {
                                return ClassificationTypeNames.Punctuation;
                            }
                        }

                        break;
                }

                return ClassificationTypeNames.Operator;
            }
            else
            {
                return ClassificationTypeNames.Punctuation;
            }
        }

        private static bool IsOperator(this SyntaxKind kind)
        {
            switch (kind)
            {
                case SyntaxKind.TildeToken:
                case SyntaxKind.ExclamationToken:
                case SyntaxKind.PercentToken:
                case SyntaxKind.CaretToken:
                case SyntaxKind.AmpersandToken:
                case SyntaxKind.AsteriskToken:
                case SyntaxKind.MinusToken:
                case SyntaxKind.PlusToken:
                case SyntaxKind.EqualsToken:
                case SyntaxKind.BarToken:
                case SyntaxKind.ColonToken:
                case SyntaxKind.LessThanToken:
                case SyntaxKind.GreaterThanToken:
                case SyntaxKind.DotToken:
                case SyntaxKind.QuestionToken:
                case SyntaxKind.SlashToken:
                case SyntaxKind.BarBarToken:
                case SyntaxKind.AmpersandAmpersandToken:
                case SyntaxKind.MinusMinusToken:
                case SyntaxKind.PlusPlusToken:
                case SyntaxKind.ColonColonToken:
                case SyntaxKind.QuestionQuestionToken:
                case SyntaxKind.MinusGreaterThanToken:
                case SyntaxKind.ExclamationEqualsToken:
                case SyntaxKind.EqualsEqualsToken:
                case SyntaxKind.EqualsGreaterThanToken:
                case SyntaxKind.LessThanEqualsToken:
                case SyntaxKind.LessThanLessThanToken:
                case SyntaxKind.LessThanLessThanEqualsToken:
                case SyntaxKind.GreaterThanEqualsToken:
                case SyntaxKind.GreaterThanGreaterThanToken:
                case SyntaxKind.GreaterThanGreaterThanEqualsToken:
                case SyntaxKind.SlashEqualsToken:
                case SyntaxKind.AsteriskEqualsToken:
                case SyntaxKind.BarEqualsToken:
                case SyntaxKind.AmpersandEqualsToken:
                case SyntaxKind.PlusEqualsToken:
                case SyntaxKind.MinusEqualsToken:
                case SyntaxKind.CaretEqualsToken:
                case SyntaxKind.PercentEqualsToken:
                    return true;

                default:
                    return false;
            }
        }

        private static bool IsActualContextualKeyword(SyntaxToken token)
        {
            if (token.Parent.IsKind(SyntaxKind.LabeledStatement))
            {
                var statement = (LabeledStatementSyntax)token.Parent;
                if (statement.Identifier == token)
                {
                    return false;
                }
            }

            // Ensure that the text and value text are the same. Otherwise, the identifier might
            // be escaped. I.e. "var", but not "@var"
            if (token.ToString() != token.ValueText)
            {
                return false;
            }

            // Standard cases.  We can just check the parent and see if we're
            // in the right position to be considered a contextual keyword
            if (token.Parent != null)
            {
                switch (token.ValueText)
                {
                    case AwaitKeyword:
                        return token.GetNextToken(includeZeroWidth: true).IsMissing;

                    case FromKeyword:
                        var fromClause = token.Parent.FirstAncestorOrSelf<FromClauseSyntax>();
                        return fromClause != null && fromClause.FromKeyword == token;

                    case VarKeyword:
                        // var
                        if (token.Parent is IdentifierNameSyntax && token.Parent?.Parent is ExpressionStatementSyntax)
                        {
                            return true;
                        }

                        // we allow var any time it looks like a variable declaration, and is not in a
                        // field or event field.
                        return
                            token.Parent is IdentifierNameSyntax &&
                            token.Parent.Parent is VariableDeclarationSyntax &&
                            !(token.Parent.Parent.Parent is FieldDeclarationSyntax) &&
                            !(token.Parent.Parent.Parent is EventFieldDeclarationSyntax);

                    case UnmanagedKeyword:
                    case NotNullKeyword:
                        return token.Parent is IdentifierNameSyntax
                            && token.Parent.Parent is TypeConstraintSyntax
                            && token.Parent.Parent.Parent is TypeParameterConstraintClauseSyntax;
                }
            }

            return false;
        }

        internal static void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken)
        {
            var text2 = text.ToString(textSpan);
            var tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition: textSpan.Start);

            Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken);
        }

        internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan)
        {
            // If we marked this as an identifier and it should now be a keyword
            // (or vice versa), then fix this up and return it.
            var classificationType = classifiedSpan.ClassificationType;

            // Check if the token's type has changed.  Note: we don't check for "wasPPKeyword &&
            // !isPPKeyword" here.  That's because for fault tolerance any identifier will end up
            // being parsed as a PP keyword eventually, and if we have the check here, the text
            // flickers between blue and black while typing.  See
            // http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details.
            var wasKeyword = classificationType == ClassificationTypeNames.Keyword;
            var wasIdentifier = classificationType == ClassificationTypeNames.Identifier;

            // We only do this for identifiers/keywords.
            if (wasKeyword || wasIdentifier)
            {
                // Get the current text under the tag.
                var span = classifiedSpan.TextSpan;
                var text = rawText.ToString(span);

                // Now, try to find the token that corresponds to that text.  If
                // we get 0 or 2+ tokens, then we can't do anything with this.
                // Also, if that text includes trivia, then we can't do anything.
                var token = SyntaxFactory.ParseToken(text);
                if (token.Span.Length == span.Length)
                {
                    // var, dynamic, and unmanaged are not contextual keywords.  They are always identifiers
                    // (that we classify as keywords).  Because we are just parsing a token we don't
                    // know if we're in the right context for them to be identifiers or keywords.
                    // So, we base on decision on what they were before.  i.e. if we had a keyword
                    // before, then assume it stays a keyword if we see 'var', 'dynamic', or 'unmanaged'.
                    var tokenString = token.ToString();
                    var isKeyword = SyntaxFacts.IsKeywordKind(token.Kind())
                        || (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None)
                        || (wasKeyword && (tokenString == VarKeyword || tokenString == DynamicKeyword || tokenString == UnmanagedKeyword || tokenString == NotNullKeyword));

                    var isIdentifier = token.Kind() == SyntaxKind.IdentifierToken;

                    // We only do this for identifiers/keywords.
                    if (isKeyword || isIdentifier)
                    {
                        if ((wasKeyword && !isKeyword) ||
                            (wasIdentifier && !isIdentifier))
                        {
                            // It changed!  Return the new type of tagspan.
                            return new ClassifiedSpan(
                                isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span);
                        }
                    }
                }
            }

            // didn't need to do anything to this one.
            return classifiedSpan;
        }
    }
}


text:
package net.tridentsdk.world.gen;

import net.tridentsdk.base.Substance;

/**
 * This class represents the generation context in which a
 * world generator creates chunks and features.
 *
 * @author TridentSDK
 * @since 0.5-alpha
 */
public interface GeneratorContext {
    /**
     * Obtains the next random long value that this context
     * provides.
     *
     * @return the next random long
     */
    long nextLong();

    /**
     * Obtains the next random long value that this context
     * provides within the given bound.
     *
     * @param max the largest number, non-inclusive
     * @return the next long within the given bound
     */
    long nextLong(long max);

    /**
     * Obtains the next random integer that this context
     * provides.
     *
     * @return the next random integer
     */
    int nextInt();

    /**
     * Obtains the next random integer value that this
     * context provides within the given bound.
     *
     * @param max the largest number, non-inclusive
     * @return the next integer within the given bound
     */
    int nextInt(int max);

    /**
     * Obtains the seed that is used to generate the chunk
     * which uses this context.
     *
     * @return the seed used to generate the chunk
     */
    long seed();

    /**
     * Obtains the height of the max Y value at the given
     * x and z coordinates.
     *
     * @param x the x coordinate
     * @param z the z coordinate
     * @return the max generated Y value
     */
    int maxHeight(int x, int z);

    /**
     * Sets the block at the coordinates relative to the
     * chunk (0-15) to the given block substance and
     * metadata.
     *
     * @param x the x value
     * @param y the y value
     * @param z the z value
     * @param substance the substance of the block
     * @param meta the block meta
     */
    void set(int x, int y, int z, Substance substance, byte meta);

    /**
     * Sets the block at the coordinates relative to the
     * chunk (0-15) to the given block substance and
     * no metadata.
     *
     * @param x the x value
     * @param y the y value
     * @param z the z value
     * @param substance the substance of the block
     */
    void set(int x, int y, int z, Substance substance);

    /**
     * Sets the block at the coordinates relative to the
     * chunk (0-15) to the given block ID and metadata.
     *
     * @param x the x value
     * @param y the y value
     * @param z the z value
     * @param id the block ID
     * @param meta the block meta
     */
    void set(int x, int y, int z, int id, byte meta);

    /**
     * Schedules the given generation task to be run when
     * the command is given for the generator to proceed.
     *
     * @param r the task to run
     */
    void run(Runnable r);
}


text:
package com.indignado.games.states.game.system.render;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.ilargia.games.entitas.api.IContext;
import com.ilargia.games.entitas.api.system.IInitializeSystem;
import com.ilargia.games.entitas.api.system.IRenderSystem;
import com.ilargia.games.entitas.collector.Collector;
import com.ilargia.games.entitas.systems.ReactiveSystem;
import com.indignado.games.states.game.gen.Entitas;
import com.indignado.games.states.game.gen.scene.SceneContext;
import com.indignado.games.states.game.gen.scene.SceneEntity;
import com.indignado.games.states.game.gen.scene.SceneMatcher;

import java.util.List;

public class GuiRendererSystem extends ReactiveSystem<SceneEntity> implements IInitializeSystem, IRenderSystem {

    private Stage stage;
    private SceneContext context;
    private OrthographicCamera cam;

    public GuiRendererSystem(Entitas entitas, Stage stage) {
        super(entitas.scene);
        this.context = entitas.scene;
        this.stage = stage;

    }

    @Override
    public void initialize() {
        this.cam = context.getCamera().camera;

    }

    @Override
    protected Collector<SceneEntity> getTrigger(IContext<SceneEntity> context) {
        return context.createCollector(SceneMatcher.Tiled());
    }

    @Override
    protected boolean filter(SceneEntity entity) {
        return entity.hasTiled();
    }

    @Override
    protected void execute(List<SceneEntity> gameEntities) {

    }

    @Override
    public void render() {

    }

}


text:
package monitor

import (
	"fmt"

	"github.com/influxdb/influxdb/influxql"
	"github.com/influxdb/influxdb/models"
)

// StatementExecutor translates InfluxQL queries to Monitor methods.
type StatementExecutor struct {
	Monitor interface {
		Statistics(map[string]string) ([]*statistic, error)
		Diagnostics() (map[string]*Diagnostic, error)
	}
}

// ExecuteStatement executes monitor-related query statements.
func (s *StatementExecutor) ExecuteStatement(stmt influxql.Statement) *influxql.Result {
	switch stmt := stmt.(type) {
	case *influxql.ShowStatsStatement:
		return s.executeShowStatistics(stmt.Module)
	case *influxql.ShowDiagnosticsStatement:
		return s.executeShowDiagnostics(stmt.Module)
	default:
		panic(fmt.Sprintf("unsupported statement type: %T", stmt))
	}
}

func (s *StatementExecutor) executeShowStatistics(module string) *influxql.Result {
	stats, err := s.Monitor.Statistics(nil)
	if err != nil {
		return &influxql.Result{Err: err}
	}
	rows := make([]*models.Row, 0)

	for _, stat := range stats {
		if module != "" && stat.Name != module {
			continue
		}
		row := &models.Row{Name: stat.Name, Tags: stat.Tags}

		values := make([]interface{}, 0, len(stat.Values))
		for _, k := range stat.valueNames() {
			row.Columns = append(row.Columns, k)
			values = append(values, stat.Values[k])
		}
		row.Values = [][]interface{}{values}
		rows = append(rows, row)
	}
	return &influxql.Result{Series: rows}
}

func (s *StatementExecutor) executeShowDiagnostics(module string) *influxql.Result {
	diags, err := s.Monitor.Diagnostics()
	if err != nil {
		return &influxql.Result{Err: err}
	}
	rows := make([]*models.Row, 0, len(diags))

	for k, v := range diags {
		if module != "" && k != module {
			continue
		}

		row := &models.Row{Name: k}

		row.Columns = v.Columns
		row.Values = v.Rows
		rows = append(rows, row)
	}
	return &influxql.Result{Series: rows}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Eukary. Microbiol. 55(3): 226 (2008)

#### Original name
Euplotespora binucleata Fokin, Di Giuseppe, Erra & Dini

### Remarks
null


text:
void import_1_5_uchar()
{
	NumpyEigenConverter<Eigen::Matrix< boost::uint8_t, 1, 5 > >::register_converter();
}


text:
import { Injectable } from '@angular/core';

import { HelixService } from '../../core/helix.service';
import { Node } from '../../shared/models/node.model';

@Injectable()
export class ConfigurationService extends HelixService {
  public getClusterConfig(name: string) {
    return this.request(`/clusters/${name}/configs`);
  }

  public setClusterConfig(name: string, config: Node) {
    return this.post(
      `/clusters/${name}/configs?command=update`,
      JSON.parse(config.json(name))
    );
  }

  public deleteClusterConfig(name: string, config: Node) {
    return this.post(
      `/clusters/${name}/configs?command=delete`,
      JSON.parse(config.json(name))
    );
  }

  public getInstanceConfig(clusterName: string, instanceName: string) {
    return this.request(
      `/clusters/${clusterName}/instances/${instanceName}/configs`
    );
  }

  public setInstanceConfig(
    clusterName: string,
    instanceName: string,
    config: Node
  ) {
    return this.post(
      `/clusters/${clusterName}/instances/${instanceName}/configs?command=update`,
      JSON.parse(config.json(instanceName))
    );
  }

  public deleteInstanceConfig(
    clusterName: string,
    instanceName: string,
    config: Node
  ) {
    return this.post(
      `/clusters/${clusterName}/instances/${instanceName}/configs?command=delete`,
      JSON.parse(config.json(instanceName))
    );
  }

  public getResourceConfig(clusterName: string, resourceName: string) {
    return this.request(
      `/clusters/${clusterName}/resources/${resourceName}/configs`
    );
  }

  public setResourceConfig(
    clusterName: string,
    resourceName: string,
    config: Node
  ) {
    return this.post(
      `/clusters/${clusterName}/resources/${resourceName}/configs?command=update`,
      JSON.parse(config.json(resourceName))
    );
  }

  public deleteResourceConfig(
    clusterName: string,
    resourceName: string,
    config: Node
  ) {
    return this.post(
      `/clusters/${clusterName}/resources/${resourceName}/configs?command=delete`,
      JSON.parse(config.json(resourceName))
    );
  }
}


text:
class EditorGUI
{
public:
	EditorGUI();
	~EditorGUI();

	void Initialise();
	void Update();

	void SetSelectedActor(Actor *arg_actor);
	void RefreshActorInspector();
	void RefreshSceneHierarchyBar();

private:
	static EditorGUI *editorGUI;

	Actor *mSelectedActor; // BURK DENNE til ?endre p?actor / components!
	TwBar *mEditorBar;
	TwBar *mActorInspectorBar;
	TwBar *mSceneHierarchyBar;
	TwBar *mScriptTerminalyBar;

	std::string mScript;

	float pos_x, pos_y, pos_z;
	float rotQuat[4];
	glm::quat *q;

	//glm::vec3 actorPos, actorScale;

	static void TW_CALL callbaclSceenWidthChanged(const void *value, void *clientData);
	static void TW_CALL callbaclSceenHeightChanged(const void *value, void *clientData);
	static void TW_CALL callbackGetScreenWidth(void *value, void *clientData);
	static void TW_CALL callbackGetScreenHeight(void *value, void *clientData);

	static void TW_CALL callbackRecompileShaders(void *clientData);
	static void TW_CALL callbackRecompileScripts(void *clientData);
	static void TW_CALL callbackPrintTimeLog(void *clientData);
	static void TW_CALL callbackSetPaused(void *clientData);

	static void TW_CALL callbackActorChanged(void *clientData);
	static void TW_CALL callbackSetFullscreen(void *clientData);
	static void TW_CALL callbackSetWireframe(void *clientData);
	static void TW_CALL callbackExecuteScript(void *clientData);

	static void TW_CALL callbackRemoveComponent(void *clientData);

public:
	static void RefreshSceneHierarchy();

	//static float getActorPosX() { editorGUI->actorPos = editorGUI->mSelectedActor->GetTransform().GetGlobalPosition(); return editorGUI->actorPos.x; }
	//static float getActorPosY() { editorGUI->actorPos = editorGUI->mSelectedActor->GetTransform().GetGlobalPosition(); return editorGUI->actorPos.y; }
	//static float getActorPosZ() { return editorGUI->mSelectedActor->GetTransform().GetGlobalPosition().z; }
};

#endif


text:
package griffon.util;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;

import static griffon.util.ConfigUtils.collectKeys;
import static griffon.util.GriffonNameUtils.requireNonBlank;

/**
 * @author Andres Almiray
 * @since 2.0.0
 */
public abstract class AbstractMapResourceBundle extends ResourceBundle {
    private final Map<String, Object> entries = new LinkedHashMap<>();
    private volatile Set<String> keys;

    public AbstractMapResourceBundle() {
        initialize(entries);
        keys = collectKeys(entries);
        // keys = new HashSet<>(entries.keySet());
    }

    protected abstract void initialize(@Nonnull Map<String, Object> entries);

    @Nullable
    @Override
    protected final Object handleGetObject(@Nonnull String key) {
        return entries.get(requireNonBlank(key, "Argument 'key' cannot be blank"));
    }

    @Nonnull
    @Override
    public final Enumeration<String> getKeys() {
        return new IteratorAsEnumeration<>(keys.iterator());
    }

    private static class IteratorAsEnumeration<E> implements Enumeration<E> {
        private final Iterator<E> iterator;

        public IteratorAsEnumeration(Iterator<E> iterator) {
            this.iterator = iterator;
        }

        public boolean hasMoreElements() {
            return iterator.hasNext();
        }

        public E nextElement() {
            return iterator.next();
        }
    }

    @Override
    protected Set<String> handleKeySet() {
        return keys;
    }
}


text:
require 'rattler/util/graphviz'

module Rattler::Util::GraphViz

  # +NodeBuilder+ is used by {DigraphBuilder} to build nodes for a GraphViz
  # digraph object representing a tree of nodes.
  module NodeBuilder

    # Run the block with any children of +o+ that should be represented as
    # separate nodes in the graph.
    #
    # @param o an object
    # @yield [child] each child of +o+ that should be represented as a separate
    #   node in the graph
    def each_child_node_of(o)
      if array_like? o and not record_like? o
        if o.respond_to? :to_hash
          o.each {|k, v| yield Mapping.new(k, v) }
        else
          o.each {|_| yield _ }
        end
      end
    end

    # @param o an object
    # @return the options for a node representing +o+.
    def node_options(o)
      { :shape => node_shape(o), :label => node_label(o) }
    end

    # @param o an object
    # @return the shape option for a node representing +o+.
    def node_shape(o)
      case o
      when Array, Hash, Mapping
        'circle'
      when String, Numeric, Symbol
        'plaintext'
      else
        'Mrecord'
      end
    end

    # @param o an object
    # @return the label option for a node representing +o+.
    def node_label(o)
      if o.is_a? ::Rattler::Util::Node
        record_label(o, parse_node_fields(o.attrs))
      elsif record_like? o
        record_label(o, o)
      elsif array_like? o
        type_label(o)
      elsif o.respond_to? :to_str
        string_label(o)
      else
        o.inspect
      end
    end

    # @param o an object
    # @return whether +o+ should be represented as a record
    def record_like?(o)
      o.respond_to? :each_pair and
      o.none? {|k, v| array_like? v or record_like? v }
    end

    # @param o an object
    # @return whether +o+ should be represented as an array
    def array_like?(o)
      o.respond_to? :each and
      not o.respond_to? :to_str
    end

    private

    def string_label(s)
      "\"#{s}\""
    end

    def record_label(o, fields)
      '{' + ([type_label(o)] + hash_content_labels(fields)).join('|') + '}'
    end

    def hash_content_labels(h)
      h.sort_by { |k,| k.to_s }.map {|k, v| "{#{k.inspect}|#{record_value v}}" }
    end

    def record_value(v)
      if v.respond_to? :to_str
        string_label(v)
      else
        v.inspect
      end.gsub(/([|<>\\])/) { "\\#{$1}" }
    end

    def type_label(o)
      case o
      when Hash then '\\{\\}'
      when Array then '\\[\\]'
      when Mapping then '->'
      else o.respond_to?(:name) ? o.name : o.class.name
      end
    end

    def parse_node_fields(attrs)
      attrs.reject {|k,| k == :name || k == :labeled }
    end

    # @private
    class Mapping #:nodoc:
      def initialize(key, value)
        @key = key
        @value = value
      end
      attr_reader :key, :value
      def each
        yield key
        yield value
      end
    end

    extend self
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Encog.Neural.Networks.Training
{
    /// <summary>
    /// The batch size. Specify 1 for pure online training. Specify 0 for pure batch
    /// training (complete training set in one batch). Otherwise specify the batch
    /// size for batch training.
    /// </summary>
    public interface IBatchSize
    {
        /// <summary>
        /// The batch size. Specify 1 for pure online training. Specify 0 for pure
	    /// batch training (complete training set in one batch). Otherwise specify
	    /// the batch size for batch training.
        /// </summary>
        int BatchSize { get; set; }

    }
}


text:
package com.google.devtools.deviceinfra.shared.util.path;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Utility methods for manipulation of UNIX-like paths. See PathUtilTest for examples.
 *
 *
Mind that this class does not work on Windows due to / to \ and different root (C: etc)
 * issues.
 */
public final class PathUtil {
  private static final Pattern SLASH_PREFIX_PATTERN = Pattern.compile("^/+");
  private static final Pattern TWO_OR_MORE_SLASH_PATTERN = Pattern.compile("/{2,}");
  private static final Pattern NON_SLASH_SUFFIX_PATTERN = Pattern.compile("(.*[^/])/+$");

  /**
   * Gets the final component from a path. Trailing slashes are removed.
   *
   *
Examples:
   *
   *
{@code
   * basename("/foo/bar/") = "bar"
   * basename("/foo/bar") = "bar"
   * basename("/foo") = "foo"
   * basename("/") = ""
   * }

   *
   *
The last example is inconsistent with Unix basename(1) which returns "/" as the basename of
   * "/".
   *
   * @param path The path to apply the basename operation to.
   * @return path, with any leading directory elements removed.
   */
  public static String basename(String path) {
    path = removeLeadingSlashes(removeExtraneousSlashes(path));

    if (path.length() == 0) {
      return path;
    }

    int pos = path.lastIndexOf("/");
    if (pos == -1) {
      return path;
    } else {
      return path.substring(pos + 1);
    }
  }

  /**
   * Joins a set of path components into a single path. Empty path components are ignored.
   *
   * @param components the components of the path
   * @return the components joined into a string, delimited by slashes. Runs of slashes are reduced
   *     to a single slash. If present, leading slashes on the first non-empty component and
   *     trailing slash on the last non-empty component are preserved.
   */
  public static String join(String... components) {
    int len = components.length - 1;
    if (len == -1) {
      return "";
    }
    for (String component : components) {
      len += component.length();
    }
    char[] path = new char[len];
    int i = 0;
    for (String component : components) {
      if (!component.isEmpty()) {
        if (i > 0 && path[i - 1] != '/') {
          path[i++] = '/';
        }
        for (int j = 0, end = component.length(); j < end; j++) {
          char c = component.charAt(j);
          if (!(c == '/' && i > 0 && path[i - 1] == '/')) {
            path[i++] = c;
          }
        }
      }
    }
    return new String(path, 0, i);
  }

  /**
   * Removes extra slashes from a path. Leading slash is preserved, trailing slash is stripped, and
   * any runs of more than one slash in the middle is replaced by a single slash.
   */
  public static String removeExtraneousSlashes(String s) {
    Matcher m = NON_SLASH_SUFFIX_PATTERN.matcher(s);

    if (m.matches()) {
      s = s.substring(0, m.end(1));
    }

    return TWO_OR_MORE_SLASH_PATTERN.matcher(s).replaceAll("/");
  }

  /** Removes leading slashes from a string. */
  public static String removeLeadingSlashes(String path) {
    return SLASH_PREFIX_PATTERN.matcher(path).replaceFirst("");
  }

  private PathUtil() {}
}


text:
package org.judo;

import java.util.*;

/**
 * Class FixEnumImpl implements the Enumeration interface
 * given that the number of elements in an enumeration is known
 * at enumeration construction time.
 *
 * The enumeration retrieval operations are synchronized for
 * concurrent access.
 *
 * @see java.util.Enumeration
 *
 * @author Thomas Wang
 * @version 0.55
 */
public class FixEnumImpl
  implements Enumeration
{
  protected int capacity;
  protected int read_index;
  protected int write_index;
  protected Object enum_array[];

  /**
   * Constructor for class SynFixEnumImpl.
   * @param total_num total number of elements in the enumeration
   */
  public FixEnumImpl(int total_num)
  {
    this.capacity = total_num;
    this.read_index = this.write_index = 0;
    if (total_num > 0)
    {
      this.capacity = total_num;
      this.enum_array = new Object[total_num];
    }
    else
    {
      this.capacity = 0;
      this.enum_array = null;
    }
  }

  /**
   * Add an element to the enumeration.  This method is used
   * inside the package to populate the enumeration.
   *
   * @param elem the element to be added to the enumeration
   */
  void addMember(Object elem)
  {
    this.enum_array[this.write_index++] = elem;
  }

  /**
   * Method hasMoreElements() returns true if there are more
   * values to be enumerated, and can be used to determine whether
   * a loop should continue.
   *
   * @see java.util.Enumeration#hasMoreElements
   */
  public synchronized boolean hasMoreElements()
  {
    return this.read_index < this.capacity;
  }

  /**
   * Method nextElement() will return the next element in the
   * enumeration.  If no more elements are available, the exception
   * NoSuchElementException will be thrown.
   *
   * @exception NoSuchElementException thrown when no more items
   * available
   * @see java.util.Enumeration#nextElement
   */
  public synchronized Object nextElement()
  {
    return this.enum_array[this.read_index++];
  }
}


text:
<!DOCTYPE html>

    <title>
        Pop PHP Framework : Documentation
    </title>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="author" content="Pop PHP Framework" />
    <meta name="keywords" content="pop php framework, php, php framework, php library, documentation" />
    <meta name="description" content="This is the Pop PHP Framework documentation." />
    <meta name="robots" content="all" />

    <link rel="stylesheet" type="text/css" href="http://www.popphp.org/css/docs.css" />

Pop PHP Framework

Documentation : Service

            Home

            Le composant de service agit comme un service de localisation pour l'application en cours d'exécution ou d'un projet. Il prend en charge chargement paresseux d'instances de service, de sorte que les services ne seront pas créés tant que l'application a besoin d'eux. Il ya beaucoup d'options pour la façon dont vous pouvez appeler les services, de la définition des classes d'utilisation des fermetures.

use Pop\Service\Locator;

// Load the services config via the constructor
$locator = new Locator(array(
    'config' => array(
        'call'   => 'Pop\Config',
        'params' => array(array('test' => 123), true)
    ),
    'rgb' => array(
        'call'   => 'Pop\Color\Space\Rgb',
        'params' => function() { return array(255, 0, 0); }
    ),
    'color' => function($locator) {
        return new \Pop\Color\Color($locator->get('rgb'));
    }
));

// Get a service
$config = $locator->get('config');  // Returns a config object
$rgb    = $locator->get('rgb');     // Returns an RGB colorspace object
$color  = $locator->get('color');   // Returns a color object that is loaded with the RGB object

            © 2009-2014 Moc 10 Media, LLC. All Rights Reserved.


text:
<?xml version="1.0"?>

<cd:cd xmlns:cd="http://www.wyona.org/continuous-deployment/1.0.0" class="org.wyona.yanel.continuous.meta.JUnitMeta">
  <cd:environment id="development">
    <cd:tests>
<!-- INFO: Not implemented yet
      <cd:test type="wyona-auto">javadoc</cd:test>
-->
<!--
      <cd:test type="auto" language="shell-script" file="build-resource-and-run-junit-tests.sh" arguments="image org.wyona.yanel.impl.resources.image.ImageResource">Build resource and run junit tests</cd:test>
-->
<!--
      <cd:test type="auto" language="shell-script" file="build-resource-and-run-junit-tests.sh" arguments="xml org.wyona.yanel.impl.resources.XMLResource">Build resource and run junit tests</cd:test>
-->
    </cd:tests>
  </cd:environment>
  <cd:environment id="staging"/>
  <cd:environment id="production"/>
</cd:cd>


text:
package com.taobao.zeus.web.platform.client.module.word.toolbar;

import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.History;
import com.sencha.gxt.core.client.Style.LayoutRegion;
import com.sencha.gxt.widget.core.client.FramedPanel;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.BoxLayoutContainer.BoxLayoutPack;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.menu.MenuItem;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
import com.taobao.zeus.web.platform.client.app.PlacePath;
import com.taobao.zeus.web.platform.client.app.PlacePath.App;
import com.taobao.zeus.web.platform.client.app.PlacePath.JobType;
import com.taobao.zeus.web.platform.client.app.PlatformPlace;
import com.taobao.zeus.web.platform.client.lib.codemirror.CodeMirror;
import com.taobao.zeus.web.platform.client.module.filemanager.FileModel;
import com.taobao.zeus.web.platform.client.module.jobdisplay.job.DefaultPanel;
import com.taobao.zeus.web.platform.client.module.jobdisplay.job.FileUploadWidget;
import com.taobao.zeus.web.platform.client.module.jobdisplay.job.FileUploadWidget.UploadCallback;
import com.taobao.zeus.web.platform.client.module.jobmanager.HostGroupWindow;
import com.taobao.zeus.web.platform.client.module.profile.QuickHadoopConfig;
import com.taobao.zeus.web.platform.client.module.word.Word;
import com.taobao.zeus.web.platform.client.module.word.component.EditTab;
import com.taobao.zeus.web.platform.client.theme.ResourcesTool;
import com.taobao.zeus.web.platform.client.util.RPCS;
import com.taobao.zeus.web.platform.client.util.async.AbstractAsyncCallback;
import com.taobao.zeus.web.platform.client.util.async.PlatformAsyncCallback;

public abstract class AbstractToolBar extends ToolBar{

	protected TextButton run=new TextButton("运行",new SelectHandler() {
		public void onSelect(SelectEvent event) {
			run(getEditTab().getNewContent());
		}
	});

	private void run(String content){
		String name=getFileModel().getName();
		if(name.indexOf(".")!=-1){
			String mode=null;
			String postfix=name.substring(name.lastIndexOf("."));
			if(".hive".equalsIgnoreCase(postfix)){
				mode="hive";
			}else if(".sh".equalsIgnoreCase(postfix)){
				mode="shell";
			}
			if(mode!=null){
				RPCS.getJobDebugService().debug(getFileModel().getId(),mode,
						content, getFileModel().getHostGroupId(), new AbstractAsyncCallback<String>() {
					@Override
					public void onSuccess(final String debugId) {
						getEditTab().getLogTabPanel().onStartDebug(debugId);
						getEditTab().show(LayoutRegion.SOUTH);
						getEditTab().expand(LayoutRegion.SOUTH);
					}
				});
			}
		}
	}
	protected TextButton selectRun=new TextButton("运行选中代码",new SelectHandler() {
		public void onSelect(SelectEvent event) {
			run(getEditTab().getCodeMirror().getSelection());
		}
	});

	protected TextButton sync=new TextButton("同步任务",ResourcesTool.iconResources.icon_sync());
	protected TextButton syncJump=new TextButton("跳转调度任务",new SelectHandler() {
		public void onSelect(SelectEvent event) {
			PlatformPlace pp=new PlacePath().toApp(App.Schedule).toJobType(JobType.MyJob).toDisplayJob(jumpJobId).create();
			History.newItem(pp.getToken());
		}
	});
	protected String jumpJobId;

	protected TextButton config=new TextButton("全局配置",new SelectHandler() {
		public void onSelect(SelectEvent event) {
			QuickHadoopConfig win=new QuickHadoopConfig();
			win.setModal(true);
			win.show();
		}
	});

	protected TextButton extend=new TextButton("扩展功能",ResourcesTool.iconResources.icon_extends());

	protected TextButton lingoes=new TextButton("datax配置工具",new SelectHandler() {
		public void onSelect(SelectEvent event) {

			new DefaultPanel(getFileModel().getId()).show();
		}
	});
	protected MenuItem upload=new MenuItem("上传资源",new SelectionHandler<MenuItem>() {
		@Override
		public void onSelection(SelectionEvent<MenuItem> event) {
			new FileUploadWidget("debug", getFileModel().getId(),
					new UploadCallback() {
						@Override
						public void call(final String name, final String uri) {
							StringBuffer sb = new StringBuffer();
							sb.append("download[").append(uri).append(' ').append(name)
								.append("]\n")
								.append(getCodeMirror().getValue());
							getCodeMirror().setValue(sb.toString());
						}
					}).show();
		}
	});
	protected MenuItem hostgroup=new MenuItem("选择host组",new SelectionHandler<MenuItem>() {
		@Override
		public void onSelection(SelectionEvent<MenuItem> event) {
			final HostGroupWindow chdwnd = new HostGroupWindow();
			chdwnd.setSelectHandler(new SelectHandler() {
				@Override
				public void onSelect(SelectEvent event) {
					if (chdwnd.getGrid().getSelectionModel()!=null) {
						String id = chdwnd.getGrid().getSelectionModel().getSelectedItem().getId();
						getFileModel().setHostGroupId(id);
						getEditTab().refreshHostGroupStatus(id);
						getEditTab().getContext().getFileSystem().updateHostGroupId(getFileModel().getId(), id, new PlatformAsyncCallback<Void>() {
							public void callback(Void t) {
							}
						});
					}
					chdwnd.hide();
				}
			});
			chdwnd.show();
		}
	});
	protected MouseUpHandler mouseUpHandler=new MouseUpHandler() {
		public void onMouseUp(MouseUpEvent event) {
			String selection=getCodeMirror().getSelection();
			if(selection!=null && !"".equals(selection.trim())){
				selectRun.enable();
			}else{
				selectRun.disable();
			}
		}
	};
	{
		run.setIcon(ResourcesTool.iconResources.icon_run());
		selectRun.setIcon(ResourcesTool.iconResources.icon_run());
		config.setIcon(ResourcesTool.iconResources.icon_config());
		lingoes.setIcon(ResourcesTool.iconResources.icon_code());
		upload.setIcon(ResourcesTool.iconResources.icon_upload());
		syncJump.setIcon(ResourcesTool.iconResources.icon_jump());
	}
	public abstract void onWordChange(Word word);

	protected abstract CodeMirror getCodeMirror();
	protected abstract FileModel getFileModel();
	protected abstract EditTab getEditTab();

}


text:
import expect from 'expect';
import date from './date';

describe('The date inputField Type', () => {
	it('to exist', function() {
		expect(date).toExist();
	});
});