text:
// Copyright (C) Arctium.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Lappa.ORM.Constants
{
    public enum DatabaseType
    {
        MySql,
        MSSql,
        SQLite,
        Oracle,
        PostgreSql
    }
}


text:
package aws

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"
	"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
)

// buildEc2FiltersForCluster returns the set of filters we must use to find all resources
func buildEC2FiltersForCluster(clusterName string) [][]*ec2.Filter {
	var filterSets [][]*ec2.Filter

	// TODO: We could look for tag-key on the old & new tags, and then post-filter (we do this in k/k cloudprovider)

	filterSets = append(filterSets, []*ec2.Filter{
		{Name: aws.String("tag:" + awsup.TagClusterName), Values: aws.StringSlice([]string{clusterName})},
	})

	filterSets = append(filterSets, []*ec2.Filter{
		{Name: aws.String("tag-key"), Values: aws.StringSlice([]string{"kubernetes.io/cluster/" + clusterName})},
	})

	return filterSets
}

redpajama_set_name: RedPajamaGithub


text:
.class Lcom/android/server/hdmi/HdmiControlService$BinderService$11;
.super Ljava/lang/Object;
.source "HdmiControlService.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/server/hdmi/HdmiControlService$BinderService;->sendStandby(II)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

.field final synthetic val$deviceId:I

.field final synthetic val$deviceType:I

# direct methods
.method constructor <init>(Lcom/android/server/hdmi/HdmiControlService$BinderService;II)V
    .locals 0

    .prologue
    .line 1504
    iput-object p1, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

    iput p2, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->val$deviceId:I

    iput p3, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->val$deviceType:I

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 4

    .prologue
    .line 1507
    iget-object v2, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

    iget-object v2, v2, Lcom/android/server/hdmi/HdmiControlService$BinderService;->this$0:Lcom/android/server/hdmi/HdmiControlService;

    # getter for: Lcom/android/server/hdmi/HdmiControlService;->mMhlController:Lcom/android/server/hdmi/HdmiMhlControllerStub;
    invoke-static {v2}, Lcom/android/server/hdmi/HdmiControlService;->access$1200(Lcom/android/server/hdmi/HdmiControlService;)Lcom/android/server/hdmi/HdmiMhlControllerStub;

    move-result-object v2

    iget v3, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->val$deviceId:I

    invoke-virtual {v2, v3}, Lcom/android/server/hdmi/HdmiMhlControllerStub;->getLocalDeviceById(I)Lcom/android/server/hdmi/HdmiMhlLocalDeviceStub;

    move-result-object v1

    .line 1508
    .local v1, "mhlDevice":Lcom/android/server/hdmi/HdmiMhlLocalDeviceStub;
    if-eqz v1, :cond_0

    .line 1509
    invoke-virtual {v1}, Lcom/android/server/hdmi/HdmiMhlLocalDeviceStub;->sendStandby()V

    .line 1518
    :goto_0
    return-void

    .line 1512
    :cond_0
    iget-object v2, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->this$1:Lcom/android/server/hdmi/HdmiControlService$BinderService;

    iget-object v2, v2, Lcom/android/server/hdmi/HdmiControlService$BinderService;->this$0:Lcom/android/server/hdmi/HdmiControlService;

    # getter for: Lcom/android/server/hdmi/HdmiControlService;->mCecController:Lcom/android/server/hdmi/HdmiCecController;
    invoke-static {v2}, Lcom/android/server/hdmi/HdmiControlService;->access$1400(Lcom/android/server/hdmi/HdmiControlService;)Lcom/android/server/hdmi/HdmiCecController;

    move-result-object v2

    iget v3, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->val$deviceType:I

    invoke-virtual {v2, v3}, Lcom/android/server/hdmi/HdmiCecController;->getLocalDevice(I)Lcom/android/server/hdmi/HdmiCecLocalDevice;

    move-result-object v0

    .line 1513
    .local v0, "device":Lcom/android/server/hdmi/HdmiCecLocalDevice;
    if-nez v0, :cond_1

    .line 1514
    const-string v2, "HdmiControlService"

    const-string v3, "Local device not available"

    invoke-static {v2, v3}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_0

    .line 1517
    :cond_1
    iget v2, p0, Lcom/android/server/hdmi/HdmiControlService$BinderService$11;->val$deviceId:I

    invoke-virtual {v0, v2}, Lcom/android/server/hdmi/HdmiCecLocalDevice;->sendStandby(I)V

    goto :goto_0
.end method


text: Simple game to learn javascript


text:
namespace sol {
	class coroutine : public reference {
	private:
		call_status stats = call_status::yielded;

		void luacall(std::ptrdiff_t argcount, std::ptrdiff_t) {
#if SOL_LUA_VERSION < 502
			stats = static_cast<call_status>(lua_resume(lua_state(), static_cast<int>(argcount)));
#else
			stats = static_cast<call_status>(lua_resume(lua_state(), nullptr, static_cast<int>(argcount)));
#endif // Lua 5.1 compat
		}

		template<std::size_t... I, typename... Ret>
		auto invoke(types<Ret...>, std::index_sequence<I...>, std::ptrdiff_t n) {
			luacall(n, sizeof...(Ret));
			return stack::pop<std::tuple<Ret...>>(lua_state());
		}

		template<std::size_t I, typename Ret>
		Ret invoke(types<Ret>, std::index_sequence<I>, std::ptrdiff_t n) {
			luacall(n, 1);
			return stack::pop<Ret>(lua_state());
		}

		template <std::size_t I>
		void invoke(types<void>, std::index_sequence<I>, std::ptrdiff_t n) {
			luacall(n, 0);
		}

		protected_function_result invoke(types<>, std::index_sequence<>, std::ptrdiff_t n) {
			int stacksize = lua_gettop(lua_state());
			int firstreturn = (std::max)(1, stacksize - static_cast<int>(n));
			luacall(n, LUA_MULTRET);
			int poststacksize = lua_gettop(lua_state());
			int returncount = poststacksize - (firstreturn - 1);
			if (error()) {
				return protected_function_result(lua_state(), lua_absindex(lua_state(), -1), 1, returncount, status());
			}
			return protected_function_result(lua_state(), firstreturn, returncount, returncount, status());
		}

	public:
		coroutine() noexcept = default;
		coroutine(const coroutine&) noexcept = default;
		coroutine& operator=(const coroutine&) noexcept = default;
		coroutine(lua_State* L, int index = -1) : reference(L, index) {
#ifdef SOL_CHECK_ARGUMENTS
			stack::check<coroutine>(L, index, type_panic);
#endif // Safety
		}

		call_status status() const noexcept {
			return stats;
		}

		bool error() const noexcept {
			call_status cs = status();
			return cs != call_status::ok && cs != call_status::yielded;
		}

		bool runnable() const noexcept {
			return valid()
				&& (status() == call_status::yielded);
		}

		explicit operator bool() const noexcept {
			return runnable();
		}

		template<typename... Args>
		protected_function_result operator()(Args&&... args) {
			return call<>(std::forward<Args>(args)...);
		}

		template<typename... Ret, typename... Args>
		decltype(auto) operator()(types<Ret...>, Args&&... args) {
			return call<Ret...>(std::forward<Args>(args)...);
		}

		template<typename... Ret, typename... Args>
		decltype(auto) call(Args&&... args) {
			push();
			int pushcount = stack::multi_push(lua_state(), std::forward<Args>(args)...);
			return invoke(types<Ret...>(), std::make_index_sequence<sizeof...(Ret)>(), pushcount);
		}
	};
} // sol

#endif // SOL_COUROUTINE_HPP


text:
package apple.foundation;

import apple.NSObject;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;

@Generated
@Library("Foundation")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class NSMetadataQueryResultGroup extends NSObject {
    static {
        NatJ.register();
    }

    @Generated
    protected NSMetadataQueryResultGroup(Pointer peer) {
        super(peer);
    }

    @Generated
    @Selector("accessInstanceVariablesDirectly")
    public static native boolean accessInstanceVariablesDirectly();

    @Generated
    @Owned
    @Selector("alloc")
    public static native NSMetadataQueryResultGroup alloc();

    @Owned
    @Generated
    @Selector("allocWithZone:")
    public static native NSMetadataQueryResultGroup allocWithZone(VoidPtr zone);

    @Generated
    @Selector("automaticallyNotifiesObserversForKey:")
    public static native boolean automaticallyNotifiesObserversForKey(String key);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:")
    public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);

    @Generated
    @Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
    public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
            @Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
            @Mapped(ObjCObjectMapper.class) Object anArgument);

    @Generated
    @Selector("classFallbacksForKeyedArchiver")
    public static native NSArray<String> classFallbacksForKeyedArchiver();

    @Generated
    @Selector("classForKeyedUnarchiver")
    public static native Class classForKeyedUnarchiver();

    @Generated
    @Selector("debugDescription")
    public static native String debugDescription_static();

    @Generated
    @Selector("description")
    public static native String description_static();

    @Generated
    @Selector("hash")
    @NUInt
    public static native long hash_static();

    @Generated
    @Selector("instanceMethodForSelector:")
    @FunctionPtr(name = "call_instanceMethodForSelector_ret")
    public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);

    @Generated
    @Selector("instanceMethodSignatureForSelector:")
    public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);

    @Generated
    @Selector("instancesRespondToSelector:")
    public static native boolean instancesRespondToSelector(SEL aSelector);

    @Generated
    @Selector("isSubclassOfClass:")
    public static native boolean isSubclassOfClass(Class aClass);

    @Generated
    @Selector("keyPathsForValuesAffectingValueForKey:")
    public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);

    @Generated
    @Owned
    @Selector("new")
    public static native NSMetadataQueryResultGroup new_objc();

    @Generated
    @Selector("resolveClassMethod:")
    public static native boolean resolveClassMethod(SEL sel);

    @Generated
    @Selector("resolveInstanceMethod:")
    public static native boolean resolveInstanceMethod(SEL sel);

    @Generated
    @Selector("setVersion:")
    public static native void setVersion_static(@NInt long aVersion);

    @Generated
    @Selector("superclass")
    public static native Class superclass_static();

    @Generated
    @Selector("version")
    @NInt
    public static native long version_static();

    @Generated
    @Selector("attribute")
    public native String attribute();

    @Generated
    @Selector("init")
    public native NSMetadataQueryResultGroup init();

    /**
     * uncertain whether this will do anything useful for non-leaf groups
     */
    @Generated
    @Selector("resultAtIndex:")
    @MappedReturn(ObjCObjectMapper.class)
    public native Object resultAtIndex(@NUInt long idx);

    @Generated
    @Selector("resultCount")
    @NUInt
    public native long resultCount();

    /**
     * this is for K-V Bindings, and causes side-effects on the query
     */
    @Generated
    @Selector("results")
    public native NSArray<?> results();

    /**
     * nil if this is a leaf
     */
    @Generated
    @Selector("subgroups")
    public native NSArray<? extends NSMetadataQueryResultGroup> subgroups();

    @Generated
    @Selector("value")
    @MappedReturn(ObjCObjectMapper.class)
    public native Object value();
}


text:
namespace AlphaChiTech.VirtualizingCollection.Interfaces
{
    public interface IReclaimableService
    {
        void RunClaim(string sectionContext);
    }
}


text:
extern "C" NORETURN void os_start(stack_item_t* sp);

#if scmRTOS_CONTEXT_SWITCH_SCHEME == 0
extern "C" void os_context_switcher(stack_item_t** Curr_SP, stack_item_t* Next_SP);
#else
extern "C" stack_item_t* os_context_switch_hook(stack_item_t* sp);
#endif

#if scmRTOS_OBSOLETE_NAMES == 1

INLINE void OS_Start(stack_item_t* sp) { os_start(sp); }

#if scmRTOS_CONTEXT_SWITCH_SCHEME == 0
INLINE void OS_ContextSwitcher(stack_item_t** Curr_SP, stack_item_t* Next_SP) { os_context_switcher(Curr_SP, Next_SP); }
#else
INLINE stack_item_t* OS_ContextSwitchHook(stack_item_t* sp) { return os_context_switch_hook(sp); }
#endif

#endif // scmRTOS_OBSOLETE_NAMES

//==============================================================================

//------------------------------------------------------------------------------
//
//
//     NAME       :   OS
//
//     PURPOSE    :   Namespace for all OS stuff
//
//     DESCRIPTION:   Includes:  Kernel,
//                               Processes,
//                               Mutexes,
//                               Event Flags,
//                               Byte-wide Channels,
//                               Arbitrary-type Channels,
//                               Messages
//
namespace OS
{

    const uint_fast8_t PROCESS_COUNT         = scmRTOS_PROCESS_COUNT + 1;
    const stack_item_t STACK_DEFAULT_PATTERN = scmRTOS_STACK_PATTERN;

    class TBaseProcess;

    INLINE void set_prio_tag(volatile TProcessMap & pm, const TProcessMap PrioTag) { pm |=  PrioTag; }
    INLINE void clr_prio_tag(volatile TProcessMap & pm, const TProcessMap PrioTag) { pm &= ~PrioTag; }
    INLINE void set_prio_tag(TProcessMap & pm, const TProcessMap PrioTag) { pm |=  PrioTag; }
    INLINE void clr_prio_tag(TProcessMap & pm, const TProcessMap PrioTag) { pm &= ~PrioTag; }

#if scmRTOS_OBSOLETE_NAMES == 1

    INLINE void SetPrioTag(volatile TProcessMap & pm, const TProcessMap PrioTag) { set_prio_tag(pm, PrioTag); }
    INLINE void ClrPrioTag(volatile TProcessMap & pm, const TProcessMap PrioTag) { clr_prio_tag(pm, PrioTag); }
    INLINE void SetPrioTag(TProcessMap & pm, const TProcessMap PrioTag) { set_prio_tag(pm, PrioTag); }
    INLINE void ClrPrioTag(TProcessMap & pm, const TProcessMap PrioTag) { clr_prio_tag(pm, PrioTag); }

#endif

    //--------------------------------------------------------------------------
    //
    //     NAME       :   TKernel
    //
    ///  Implements kernel-level operations such as
    ///  process management, process-level scheduling,
    ///  ISR-level scheduling, system timing.
    //
    //     DESCRIPTION:
    //
    //
    class TKernel
    {
        //-----------------------------------------------------------
        //
        //     Declarations
        //
        friend class TISRW;
        friend class TISRW_SS;
        friend class TBaseProcess;
        friend class TKernelAgent;

        friend void                 run();
        friend const TBaseProcess * get_proc(uint_fast8_t Prio);
    #if scmRTOS_SYSTEM_TICKS_ENABLE == 1
        friend inline tick_count_t  get_tick_count();
    #endif

        //-----------------------------------------------------------
        //
        //      Data
        //
    private:
        uint_fast8_t          CurProcPriority;
        volatile TProcessMap  ReadyProcessMap;
        static TBaseProcess*  ProcessTable[PROCESS_COUNT];
        volatile uint_fast8_t ISR_NestCount;

    #if scmRTOS_CONTEXT_SWITCH_SCHEME == 1
        volatile uint_fast8_t SchedProcPriority;
    #endif

    #if scmRTOS_SYSTEM_TICKS_ENABLE == 1
        volatile tick_count_t SysTickCount;
    #endif

    //-----------------------------------------------------------
    //
    //      Functions
    //
    public:
    INLINE TKernel() : CurProcPriority(pr0)
                     , ReadyProcessMap( (1ul << (PROCESS_COUNT)) - 1)  // set all processes ready
                     , ISR_NestCount(0)
    {
    }

    private:
        INLINE static void register_process(TBaseProcess* const p);

               void sched();
        INLINE void scheduler() { if(ISR_NestCount) return; else  sched(); }
        INLINE void sched_isr();

    #if scmRTOS_CONTEXT_SWITCH_SCHEME == 1
        INLINE bool is_context_switch_done();
        #if scmRTOS_OBSOLETE_NAMES == 0
        INLINE void raise_context_switch() { OS::raise_context_switch(); }
        #else
        INLINE void raise_context_switch() { OS::RaiseContextSwitch(); }
        #endif
    #endif

        INLINE void set_process_ready  (const uint_fast8_t pr) { TProcessMap PrioTag = get_prio_tag(pr); set_prio_tag( ReadyProcessMap, PrioTag); }
        INLINE void set_process_unready(const uint_fast8_t pr) { TProcessMap PrioTag = get_prio_tag(pr); clr_prio_tag( ReadyProcessMap, PrioTag); }

    public:
        INLINE void system_timer();
    #if scmRTOS_CONTEXT_SWITCH_SCHEME == 1
        INLINE stack_item_t* context_switch_hook(stack_item_t* sp);
    #endif
    };  // End of TKernel class definition

    extern TKernel Kernel;

    //--------------------------------------------------------------------------
    //
    //  BaseProcess
    //
    //  Implements base class-type for application processes
    //
    //      DESCRIPTION:
    //
    //
    class TKernelAgent;
    class TService;

    class TBaseProcess
    {
        friend class TKernel;
        friend class TISRW;
        friend class TISRW_SS;
        friend class TKernelAgent;

        friend void run();

    public:
    #if SEPARATE_RETURN_STACK == 0

        TBaseProcess( stack_item_t * StackPoolEnd
                    , TPriority pr
                    , void (*exec)()
                #if scmRTOS_DEBUG_ENABLE == 1
                    , stack_item_t * aStackPool
                #endif
                    );

    protected:
        INLINE void set_unready() { Kernel.set_process_unready(this->Priority); }
        void init_stack_frame( stack_item_t * StackPoolEnd
                             , void (*exec)()
        #if scmRTOS_DEBUG_ENABLE == 1
                             , stack_item_t * StackPool
        #endif
                             );
    public:

    #else  // SEPARATE_RETURN_STACK

        TBaseProcess( stack_item_t* StackPoolEnd
                    , stack_item_t* RStack
                    , TPriority pr
                    , void (*exec)()
                #if scmRTOS_DEBUG_ENABLE == 1
                    , stack_item_t * aStackPool
                    , stack_item_t * aRStackPool
                #endif
                    );

    protected:
        void init_stack_frame( stack_item_t * Stack
                             , stack_item_t * RStack
                             , void (*exec)()
        #if scmRTOS_DEBUG_ENABLE == 1
                             , stack_item_t * StackPool
                             , stack_item_t * RStackPool
        #endif
                             );

    public:

    #endif // SEPARATE_RETURN_STACK

        static void sleep(timeout_t timeout = 0);
               void wake_up();
               void force_wake_up();
        INLINE void start() { force_wake_up(); }

        INLINE bool is_sleeping() const;
        INLINE bool is_suspended() const;

    #if scmRTOS_DEBUG_ENABLE == 1
        INLINE TService * waiting_for() const { return WaitingFor; }
    public:
               size_t     stack_slack() const;
        #if SEPARATE_RETURN_STACK == 1
               size_t     rstack_slack() const;
        #endif
    #endif // scmRTOS_DEBUG_ENABLE

    #if scmRTOS_PROCESS_RESTART_ENABLE == 1
    protected:
               void reset_controls();
    #endif

    public:

    #if scmRTOS_OBSOLETE_NAMES == 1
        INLINE static void Sleep(timeout_t timeout = 0) { sleep(timeout); }
    #endif

        //-----------------------------------------------------
        //
        //    Data members
        //
    protected:
        stack_item_t *     StackPointer;
        volatile timeout_t Timeout;
        const TPriority    Priority;
    #if scmRTOS_DEBUG_ENABLE == 1
        TService           * volatile WaitingFor;
        const stack_item_t * const StackPool;
        #if SEPARATE_RETURN_STACK == 1
            const stack_item_t * const RStackPool;
        #endif
    #endif // scmRTOS_DEBUG_ENABLE

    #if scmRTOS_PROCESS_RESTART_ENABLE == 1
        volatile TProcessMap * WaitingProcessMap;
    #endif
    };
    //--------------------------------------------------------------------------

    //--------------------------------------------------------------------------
    //
    //   process
    //
    //   Implements template for application processes instantiation
    //
    //      DESCRIPTION:
    //
    //
    #if SEPARATE_RETURN_STACK == 0

        template<TPriority pr, size_t stack_size>
        class process : public TBaseProcess
        {
        public:
            INLINE_PROCESS_CTOR process();

            OS_PROCESS static void exec();

        #if scmRTOS_PROCESS_RESTART_ENABLE == 1
            INLINE void terminate();
        #endif

        private:
            stack_item_t Stack[stack_size/sizeof(stack_item_t)];
        };

        template<TPriority pr, size_t stack_size>
        OS::process<pr, stack_size>::process() : TBaseProcess( &Stack[stack_size/sizeof(stack_item_t)]
                                                             , pr
                                                             , reinterpret_cast<void (*)()>(exec)
                                                         #if scmRTOS_DEBUG_ENABLE == 1
                                                             , Stack
                                                         #endif
                                                             )
        {
        }

        #if scmRTOS_PROCESS_RESTART_ENABLE == 1
        template<TPriority pr, size_t stack_size>
        void OS::process<pr, stack_size>::terminate()
        {
            TCritSect cs;

            reset_controls();
            init_stack_frame( &Stack[stack_size/sizeof(stack_item_t)]
                              , reinterpret_cast<void (*)()>(exec)
                          #if scmRTOS_DEBUG_ENABLE == 1
                              , Stack
                          #endif
                            );
        }
        #endif // scmRTOS_RESTART_ENABLE

        typedef OS::process<OS::prIDLE, scmRTOS_IDLE_PROCESS_STACK_SIZE> TIdleProc;

    #else  // SEPARATE_RETURN_STACK

        template<TPriority pr, size_t stack_size, size_t rstack_size>
        class process : public TBaseProcess
        {
        public:
            INLINE_PROCESS_CTOR process();

            OS_PROCESS static void exec();

        #if scmRTOS_PROCESS_RESTART_ENABLE == 1
            INLINE void terminate();
        #endif

        private:
            stack_item_t Stack [stack_size/sizeof(stack_item_t)];
            stack_item_t RStack[rstack_size/sizeof(stack_item_t)];
        };

        template<TPriority pr, size_t stack_size, size_t rstack_size>
        process<pr, stack_size, rstack_size>::process() : TBaseProcess( &Stack[stack_size/sizeof(stack_item_t)]
                                                                      , &RStack[rstack_size/sizeof(stack_item_t)]
                                                                      , pr
                                                                      , reinterpret_cast<void (*)()>(exec)
                                                                 #if scmRTOS_DEBUG_ENABLE == 1
                                                                      , Stack
                                                                      , RStack
                                                                 #endif
                                                                      )
        {
        }

        #if scmRTOS_PROCESS_RESTART_ENABLE == 1
        template<TPriority pr, size_t stack_size, size_t rstack_size>
        void OS::process<pr, stack_size, rstack_size>::terminate()
        {
            TCritSect cs;

            reset_controls();
            init_stack_frame( &Stack[stack_size/sizeof(stack_item_t)]
                            , &RStack[rstack_size/sizeof(stack_item_t)]
                            , reinterpret_cast<void (*)()>(exec)
                        #if scmRTOS_DEBUG_ENABLE == 1
                            , Stack
                            , RStack
                        #endif
                            );
        }
        #endif // scmRTOS_RESTART_ENABLE

        typedef OS::process< OS::prIDLE
                           , scmRTOS_IDLE_PROCESS_DATA_STACK_SIZE
                           , scmRTOS_IDLE_PROCESS_RETURN_STACK_SIZE> TIdleProc;

    #endif    // SEPARATE_RETURN_STACK
    //--------------------------------------------------------------------------

    extern TIdleProc IdleProc;

    //--------------------------------------------------------------------------
    //
    //   TKernelAgent
    //
    //   Grants access to some RTOS kernel internals for services implementation
    //
    //      DESCRIPTION:
    //
    //
    class TKernelAgent
    {
        INLINE static TBaseProcess * cur_proc()                        { return Kernel.ProcessTable[cur_proc_priority()]; }

    protected:
        TKernelAgent() { }
        INLINE static uint_fast8_t const   & cur_proc_priority()       { return Kernel.CurProcPriority;  }
        INLINE static volatile TProcessMap & ready_process_map()       { return Kernel.ReadyProcessMap;  }
        INLINE static volatile timeout_t   & cur_proc_timeout()        { return cur_proc()->Timeout;     }
        INLINE static void reschedule()                                { Kernel.scheduler();             }

    #if scmRTOS_DEBUG_ENABLE == 1
        INLINE static TService * volatile & cur_proc_waiting_for()     { return cur_proc()->WaitingFor;  }
    #endif

    #if scmRTOS_PROCESS_RESTART_ENABLE == 1
        INLINE static volatile TProcessMap * & cur_proc_waiting_map()  { return cur_proc()->WaitingProcessMap; }
    #endif
    };

    //--------------------------------------------------------------------------
    //
    //       Miscellaneous
    //
    //
    INLINE NORETURN void run();
    INLINE void lock_system_timer()    { TCritSect cs; LOCK_SYSTEM_TIMER();   }
    INLINE void unlock_system_timer()  { TCritSect cs; UNLOCK_SYSTEM_TIMER(); }
    INLINE void sleep(timeout_t t = 0) { TBaseProcess::sleep(t); }
    INLINE const TBaseProcess * get_proc(uint_fast8_t Prio) { return Kernel.ProcessTable[Prio]; }

#if scmRTOS_OBSOLETE_NAMES == 1
    INLINE void Run()               { run();                 }
    INLINE void LockSystemTimer()   { lock_system_timer();   }
    INLINE void UnlockSystemTimer() { unlock_system_timer(); }
#endif

    //--------------------------------------------------------------------------

#if scmRTOS_SYSTEM_TICKS_ENABLE == 1
    INLINE tick_count_t get_tick_count() { TCritSect cs; return Kernel.SysTickCount; }
#if scmRTOS_OBSOLETE_NAMES == 1
    INLINE tick_count_t GetTickCount() { return get_tick_count(); }
#endif
#endif

#if scmRTOS_TARGET_IDLE_HOOK_ENABLE == 1
    void idle_process_target_hook();
#endif // scmRTOS_TARGET_IDLE_HOOK_ENABLE

#if scmRTOS_OBSOLETE_NAMES == 1

#if scmRTOS_SYSTIMER_HOOK_ENABLE == 1
    INLINE_SYS_TIMER_HOOK void SystemTimerUserHook();
    INLINE void system_timer_user_hook() { SystemTimerUserHook(); }
#endif // scmRTOS_SYSTIMER_HOOK_ENABLE

#if scmRTOS_CONTEXT_SWITCH_USER_HOOK_ENABLE == 1
    INLINE_CONTEXT_SWITCH_HOOK void ContextSwitchUserHook();
    INLINE void context_switch_user_hook() { ContextSwitchUserHook(); }
#endif // scmRTOS_CONTEXT_SWITCH_USER_HOOK_ENABLE

#if scmRTOS_IDLE_HOOK_ENABLE == 1
    void IdleProcessUserHook();
    INLINE void idle_process_user_hook() { IdleProcessUserHook(); }
#endif // scmRTOS_IDLE_HOOK_ENABLE

#else // scmRTOS_OBSOLETE_NAMES

#if scmRTOS_SYSTIMER_HOOK_ENABLE == 1
    INLINE_SYS_TIMER_HOOK void system_timer_user_hook();
#endif // scmRTOS_SYSTIMER_HOOK_ENABLE

#if scmRTOS_CONTEXT_SWITCH_USER_HOOK_ENABLE == 1
    INLINE_CONTEXT_SWITCH_HOOK void context_switch_user_hook();
#endif // scmRTOS_CONTEXT_SWITCH_USER_HOOK_ENABLE

#if scmRTOS_IDLE_HOOK_ENABLE == 1
    void idle_process_user_hook();
#endif // scmRTOS_IDLE_HOOK_ENABLE

#endif // scmRTOS_OBSOLETE_NAMES

}   // namespace OS
//------------------------------------------------------------------------------

#include "scmRTOS_extensions.h"

//------------------------------------------------------------------------------
//
//   Register Process
//
//   Places pointer to process in kernel's process table
//
void OS::TKernel::register_process(OS::TBaseProcess* const p)
{
    Kernel.ProcessTable[p->Priority] = p;
}
//------------------------------------------------------------------------------
//
//    System Timer Implementation
//
//    Performs process's timeouts checking and
//    moving processes to ready-to-run state
//
void OS::TKernel::system_timer()
{
    SYS_TIMER_CRIT_SECT();
#if scmRTOS_SYSTEM_TICKS_ENABLE == 1
    SysTickCount++;
#endif

#if scmRTOS_PRIORITY_ORDER == 0
    const uint_fast8_t BaseIndex = 0;
#else
    const uint_fast8_t BaseIndex = 1;
#endif

    for(uint_fast8_t i = BaseIndex; i < (PROCESS_COUNT - 1 + BaseIndex); i++)
    {
        TBaseProcess* p = ProcessTable[i];

        if(p->Timeout > 0)
        {
            if(--p->Timeout == 0)
            {
                set_process_ready(p->Priority);
            }
        }
    }
}
//------------------------------------------------------------------------------
//
//     ISR optimized scheduler
//
//     !!! IMPORTANT: This function must be call from ISR services only !!!
//
//
#if scmRTOS_CONTEXT_SWITCH_SCHEME == 0
void OS::TKernel::sched_isr()
{
    uint_fast8_t NextPrty = highest_priority(ReadyProcessMap);
    if(NextPrty != CurProcPriority)
    {
    #if scmRTOS_CONTEXT_SWITCH_USER_HOOK_ENABLE == 1
        context_switch_user_hook();
    #endif

        stack_item_t*  Next_SP = ProcessTable[NextPrty]->StackPointer;
        stack_item_t** Curr_SP_addr = &(ProcessTable[CurProcPriority]->StackPointer);
        CurProcPriority = NextPrty;
        os_context_switcher(Curr_SP_addr, Next_SP);
    }
}
#else
void OS::TKernel::sched_isr()
{
    uint_fast8_t NextPrty = highest_priority(ReadyProcessMap);
    if(NextPrty != CurProcPriority)
    {
        SchedProcPriority = NextPrty;
        raise_context_switch();
    }
}
//------------------------------------------------------------------------------
#ifndef CONTEXT_SWITCH_HOOK_CRIT_SECT
#define CONTEXT_SWITCH_HOOK_CRIT_SECT()
#endif

stack_item_t* OS::TKernel::context_switch_hook(stack_item_t* sp)
{
    CONTEXT_SWITCH_HOOK_CRIT_SECT();

    ProcessTable[CurProcPriority]->StackPointer = sp;
    sp = ProcessTable[SchedProcPriority]->StackPointer;

#if scmRTOS_CONTEXT_SWITCH_USER_HOOK_ENABLE == 1
    context_switch_user_hook();
#endif

    CurProcPriority = SchedProcPriority;
    return sp;
}
//------------------------------------------------------------------------------
#endif // scmRTOS_CONTEXT_SWITCH_SCHEME

//-----------------------------------------------------------------------------
bool OS::TBaseProcess::is_sleeping() const
{
    TCritSect cs;
    return this->Timeout != 0;
}
//-----------------------------------------------------------------------------
bool OS::TBaseProcess::is_suspended() const
{
    TCritSect cs;
    return (Kernel.ReadyProcessMap & get_prio_tag(this->Priority)) == 0;
}

//-----------------------------------------------------------------------------
INLINE void OS::run()
{
    stack_item_t *sp = Kernel.ProcessTable[pr0]->StackPointer;
    os_start(sp);
}

#if scmRTOS_OBSOLETE_NAMES == 1
namespace OS
{
    INLINE void Sleep(timeout_t t = 0) { sleep(t); }

    INLINE bool IsProcessSleeping(const TBaseProcess& p) { return p.is_sleeping(); }
    INLINE bool IsProcessSuspended(const TBaseProcess& p) { return p.is_suspended(); }
}   // namespace OS
#endif

#include <OS_Services.h>

#endif // OS_KERNEL_H


text:
package org.typetopaste.key;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Implementation of {@link KeyCommandFactory} that holds a map of other {@code KeyCommandFactories} and forwards calls to one of them
 * according to current value of switch key retrieved from given {@code switchGetter}.
 *
 * @author alex
 *
 * @param <K>
 */
public class SwitchKeyCommandFactory<K> implements KeyCommandFactory {
	private final Map<K, KeyCommandFactory> commandFactories;
	private final Callable<K> switchGetter;

	public SwitchKeyCommandFactory(Map<K, KeyCommandFactory> commandFactories, Callable<K> switchGetter) {
		this.commandFactories = commandFactories;
		this.switchGetter = switchGetter;
	}

	@Override
	public Iterable<KeyCommand> createCommands(char c) {
		try {
			KeyCommandFactory commandFactory = commandFactories.get(switchGetter.call());
			if (commandFactory == null) {
				return null;
			}
			return commandFactory.createCommands(c);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}

}


text:
var assert = require('assert');
var should = require('should');
var nano = require('../');
var nn = nano._bindings;

var test = require('tape');

test('bind returns non-zero endpoint number for valid INPROC address', function (t) {
    t.plan(1);

    var sock = nano.socket('pub');
    var rc = sock.bind('inproc://some_address');

    if(rc < 0) {
        t.fail('INPROC endpoint number invalid');
    } else {
        t.pass('INPROC endpoint number valid');
    }

    sock.close();
});

test('bind returns non-zero endpoint number for valid IPC address', function (t) {
    t.plan(1);

    var sock = nano.socket('pub');
    var rc = sock.bind('ipc:///tmp/some_address.ipc');

    if(rc < 0) {
        t.fail('IPC endpoint number invalid');
    } else {
        t.pass('IPC endpoint number valid');
    }

    sock.close();
});

test('bind returns non-zero endpoint number for valid TCP address', function (t) {
    t.plan(1);

    var sock = nano.socket('pub');
    var rc = sock.bind('tcp://127.0.0.1:5555');

    if(rc < 0) {
        t.fail('TCP endpoint number invalid');
    } else {
        t.pass('TCP endpoint number valid');
    }

    sock.close();
});

test('bind throws for invalid INPROC address', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'exception thrown for invalid INPROC address (missing slash)');
        t.equal(nn.Errno(), nn.EINVAL);
        sock.close();
    });

    sock.bind('inproc:/missing_first_slash');
});

test('bind throws for invalid INPROC address (too long)', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'exception thrown for invalid INPROC address (too long)');
        t.equal(nn.Errno(), nn.ENAMETOOLONG);
        sock.close();
    });

    var addr = new Array(nn.NN_SOCKADDR_MAX + 1).join('a');
    sock.bind('inproc://' + addr);
});

test('bind throws for invalid IPC address', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'exception thrown for invalid IPC address');
        t.equal(nn.Errno(), nn.EINVAL);
        sock.close();
    });

    sock.bind('ipc:/missing_first_slash');
});

test('bind throws for invalid TCP address (missing address)', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'exception thrown for missing TCP address');
        t.equal(nn.Errno(), nn.EINVAL);
        sock.close();
    });

    sock.bind('tcp://');
});

test('bind throws for invalid TCP address (non-numeric port)', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'exception thrown for TCP non-numeric port');
        t.equal(nn.Errno(), nn.EINVAL);
        sock.close();
    });

    sock.bind('tcp://127.0.0.1:port');
});

test('bind throws for invalid TCP address (port out of range)', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'exception thrown for invalid TCP port');
        t.equal(nn.Errno(), nn.EINVAL);
        sock.close();
    });

    sock.bind('tcp://127.0.0.1:65536');
});

test('bind throws for unsupported transport', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'exception thrown for unsupported transport');
        t.equal(nn.Errno(), nn.EPROTONOSUPPORT);
        sock.close();
    });

    sock.bind('zmq://127.0.0.1:6000');
});

test('bind throws for TCP on non-existent device', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');

    sock.on('error', function (err) {
        t.ok(err, 'error thrown on non-existent TCP device');
        t.equal(nn.Errno(), nn.ENODEV);
        sock.close();
    });

    sock.bind('tcp://eth99:555');
});

test('bind throws for INPROC rebind to existing endpoint', function (t) {
    t.plan(2);

    var sock = nano.socket('pub');
    var sock2 = nano.socket('pub');
    var addr ='inproc://some_endpoint';

    sock2.on('error', function (err) {
        t.ok(err, 'error thrown on INPROC multiple binds');
        t.equal(nn.Errno(), nn.EADDRINUSE);
        sock.close();
        sock2.close();
    });

    sock.bind(addr);
    sock2.bind(addr);
});


text:
require 'spec_helper'
require 'sitemap_generator/interpreter'

describe SitemapGenerator::Interpreter do
  let(:link_set)    { SitemapGenerator::LinkSet.new }
  let(:interpreter) { SitemapGenerator::Interpreter.new(:link_set => link_set) }

  # The interpreter doesn't have the URL helpers included for some reason, so it
  # fails when adding links.  That messes up later specs unless we reset the sitemap object.
  after :all do
    SitemapGenerator::Sitemap.reset!
  end

  it "should find the config file if Rails.root doesn't end in a slash" do
    SitemapGenerator::Utilities.with_warnings(nil) do
      Rails = stub(:root => SitemapGenerator.app.root.to_s.sub(/\/$/, ''))
    end
    # Rails.expects(:root).returns(rails_root).at_least_once
    lambda { SitemapGenerator::Interpreter.run }.should_not raise_exception(Errno::ENOENT)
  end

  it "should set the verbose option" do
    SitemapGenerator::Interpreter.any_instance.expects(:instance_eval)
    interpreter = SitemapGenerator::Interpreter.run(:verbose => true)
    interpreter.instance_variable_get(:@linkset).verbose.should be_true
  end

  describe "link_set" do
    it "should default to the default LinkSet" do
      SitemapGenerator::Interpreter.new.sitemap.should be(SitemapGenerator::Sitemap)
    end

    it "should allow setting the LinkSet as an option" do
      interpreter.sitemap.should be(link_set)
    end
  end

  describe "public interface" do
    describe "add" do
      it "should add a link to the sitemap" do
        link_set.expects(:add).with('test', :option => 'value')
        interpreter.add('test', :option => 'value')
      end
    end

    describe "group" do
      it "should start a new group" do
        link_set.expects(:group).with('test', :option => 'value')
        interpreter.group('test', :option => 'value')
      end
    end

    describe "sitemap" do
      it "should return the LinkSet" do
        interpreter.sitemap.should be(link_set)
      end
    end

    describe "add_to_index" do
      it "should add a link to the sitemap index" do
        link_set.expects(:add_to_index).with('test', :option => 'value')
        interpreter.add_to_index('test', :option => 'value')
      end
    end
  end

  describe "eval" do
    it "should yield the LinkSet to the block" do
      interpreter.eval(:yield_sitemap => true) do |sitemap|
        sitemap.should be(link_set)
      end
    end

    it "should not yield the LinkSet to the block" do
      local = interpreter         # prevent undefined method
      local_be = self.method(:be) # prevent undefined method
      local.eval(:yield_sitemap => false) do
        self.should local_be.call(local)
      end
    end

    it "should not yield the LinkSet to the block by default" do
      local = interpreter         # prevent undefined method
      local_be = self.method(:be) # prevent undefined method
      local.eval do
        self.should local_be.call(local)
      end
    end
  end
end


text:
package com.CSU.Syx.configuration.websocketConfig;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import com.CSU.Syx.model.User;
import com.CSU.Syx.modelRepository.UserRepository;

/**
 * 实现了握手的具体动作
 *
 * @author Rouzip
 * @date 2017.11.18
 */
public class HandShake implements HandshakeInterceptor {
    @Autowired
    private UserRepository userRepository;

    /**
     * 用于握手前,实现了用户id检测
     * 为用户制定好UID
     *
     * @param serverHttpRequest  用于第一次握手HTTP请求
     * @param serverHttpResponse 回复请求
     * @param webSocketHandler   处理webSocket
     * @param map                不懂
     * @return 返回是否握手成功
     * @throws Exception 抛出所有异常
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
//        System.out.println("握手成功");
    }
}


text:
"""@package src.wi.urls.admin_cm.vm

@author Krzysztof Danielowski, Piotr Wojcik
@date 17.03.2011
"""

from django.conf.urls import url, patterns, include
from django.utils.translation import ungettext, ugettext_lazy as _

from wi.forms.vm import EditVMForm
from wi.utils.decorators import admin_cm_permission
from wi.utils.views import generic_multiple_id, simple_generic_id, form_generic_id

vm_patterns = patterns('wi.views.admin_cm.vm',
    url(r'^vms/$', 'cma_vms', name='cma_vms'),
    url(r'^ajax/cm/vms_get_table/(?P<user_id>\d+)/$', 'cma_vms_ajax_get_table', name='cma_vms_ajax_get_table'),
    url(r'^ajax/cm/vm_details/(?P<vm_id>\d+)/$', 'cma_vms_ajax_vm_details', name='cma_vms_ajax_vm_details'),
    url(r'^ajax/cm/vm_destroy/$', admin_cm_permission(generic_multiple_id),
        {'template_name':       'generic/simple.html',
         'success_msg':         (lambda desc, count: ungettext('You have successfully destroyed virtual machine %(desc)s.', 'You have successfully destroyed %(count)d virtual machines (%(desc)s).', count) % {'desc': desc, 'count': count}),
         'ask_msg':             (lambda desc, count: ungettext('Do you want to destroy virtual machine %(desc)s?', 'Do you want to destroy %(count)d virtual machines %(desc)s?', count) % {'desc': desc, 'count': count}),
         'request_url':         'admin_cm/vm/destroy/',
         'id_key':              'vm_id_list'
         },
        name='cma_vms_ajax_destroy'),
    url(r'^ajax/cm/vm_erase/$', admin_cm_permission(generic_multiple_id),
        {'template_name':       'generic/simple.html',
         'success_msg':         (lambda desc, count: ungettext('You have successfully erased virtual machine %(desc)s.', 'You have successfully erased %(count)d virtuals machines (%(desc)s).', count) % {'desc': desc, 'count': count}),
         'ask_msg':             (lambda desc, count: ungettext('Do you want to erase virtual machine %(desc)s?', 'Do you want to erase %(count)d virtual machines %(desc)s?', count) % {'desc': desc, 'count': count}),
         'request_url':         'admin_cm/vm/erase/',
         'id_key':              'vm_id_list'
         },
        name='cma_vms_ajax_erase'),
    url(r'^ajax/cm/revoke_ip/(?P<id1>\d+)/$', admin_cm_permission(simple_generic_id),
        {'template_name':   'generic/simple.html',
         'success_msg':     (lambda desc: _('You have successfully revoked IP address.') % {'desc': desc}),
         'ask_msg':         (lambda desc: _('Do you want to revoke IP address?') % {'desc': desc}),
         'request_url':     'admin_cm/public_ip/unassign/',
         'id_key':          'lease_id', },
        name='cma_vms_ajax_revoke_ip'),
    url(r'^ajax/cm/vm_save_and_shutdown/(?P<id1>\d+)/$', admin_cm_permission(form_generic_id),
        {'template_name':        'generic/form.html',
         'success_msg':          (lambda desc, data: _('Virtual machine will be saved.') % {'desc': desc}),
         'confirmation':         _('Save and shutdown'),
         'request_url_post':     'admin_cm/vm/save_and_shutdown/',
         'request_url_get':      'admin_cm/vm/get_by_id/',
         'id_key':               'vm_id',
         'form_class':           EditVMForm},
        name='cma_vms_ajax_save_and_shutdown'),

    url(r'^ajax/cm/set_vnc/(?P<id1>\d+)/$', admin_cm_permission(simple_generic_id),
        {'template_name':   'generic/simple.html',
         'success_msg':     (lambda desc: _('You have successfully enabled VNC.') % {'desc': desc}),
         'ask_msg':         (lambda desc: _('Do you want to enable VNC?') % {'desc': desc}),
         'request_url':     'admin_cm/vm/attach_vnc/',
         'id_key':          'vm_id'
         },
        name='cma_vms_ajax_set_vnc'),
    url(r'^ajax/cm/unset_vnc/(?P<id1>\d+)/$', admin_cm_permission(simple_generic_id),
        {'template_name':   'generic/simple.html',
         'success_msg':     (lambda desc: _('You have successfully disabled VNC.') % {'desc': desc}),
         'ask_msg':         (lambda desc: _('Do you want to disable VNC?') % {'desc': desc}),
         'request_url':     'admin_cm/vm/detach_vnc/',
         'id_key':          'vm_id'
        },
        name='cma_vms_ajax_unset_vnc'),

)

urlpatterns = patterns('',
    url(r'^admin_cm/', include(vm_patterns)),
)


text:
package com.github.bluenote

import org.lwjgl.opengl.GL11._
import org.lwjgl.opengl.GL12._
import org.lwjgl.opengl.GL14._
import org.lwjgl.opengl.GL20._
import org.lwjgl.opengl.GL30._

object FramebufferUtils {

  def checkFramebuffer() {
    val status = glCheckFramebufferStatus(GL_FRAMEBUFFER)
    val error = status match {
      case GL_FRAMEBUFFER_COMPLETE => None
      case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT => Some("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT")
      case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER => Some("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER")
      case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => Some("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT")
      case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE => Some("GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE")
      case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER => Some("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER")
      case GL_FRAMEBUFFER_UNSUPPORTED => Some("GL_FRAMEBUFFER_UNSUPPORTED")
      case GL_FRAMEBUFFER_UNDEFINED => Some("GL_FRAMEBUFFER_UNDEFINED")
      case x => Some(x.toString)
    }
    error.foreach{ msg =>
      println("Framebuffer status is not complete: " + msg)
    }
  }

}

class FramebufferTexture(val fboW: Int, val fboH: Int, useMipMap: Boolean = false) {

  GlWrapper.checkGlError("before FBO initialization", true)
  println(f"creating framebuffer texture of resolution: $fboW x $fboH")

  // create FBO
  val framebufferId = glGenFramebuffers()

  activate()

  // gen & bind texture (for colors)
  val textureId = glGenTextures()
  glBindTexture(GL_TEXTURE_2D, textureId)
  //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
  //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) // GL_NEAREST, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, if (!useMipMap) GL_LINEAR else GL_LINEAR_MIPMAP_LINEAR ) // GL_NEAREST, GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
  // Allocate space for the texture
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, fboW, fboH, 0, GL_RGBA, GL_UNSIGNED_BYTE, null.asInstanceOf[java.nio.ByteBuffer])

  // gen & bind renderbuffer (for depth)
  val depthBufferId = glGenRenderbuffers()
  glBindRenderbuffer(GL_RENDERBUFFER, depthBufferId)
  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, fboW, fboH) // or GL_DEPTH_COMPONENT ? or 32 ? or 32F ? seems to improve z-fighting

  // attach texture to FBO
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureId, 0) // last parameter is the mipmap level
  glDrawBuffers(GL_COLOR_ATTACHMENT0)

  // attach renderbuffer to FBO
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBufferId)

  // what does this?
  //glEnable(GL_TEXTURE_2D)

  deactivate()

  GlWrapper.checkGlError()

  def activate() {
    //glEnable(GL_TEXTURE_2D)
    glViewport(0, 0, fboW, fboH)
    glBindTexture(GL_TEXTURE_2D, 0)
    glBindFramebuffer(GL_FRAMEBUFFER, framebufferId)
  }

  def deactivate() {
    glBindFramebuffer(GL_FRAMEBUFFER, 0)
    if (useMipMap) {
      glBindTexture(GL_TEXTURE_2D, textureId)
      glEnable(GL_TEXTURE_2D)
      glGenerateMipmap(GL_TEXTURE_2D)
      glBindTexture(GL_TEXTURE_2D, 0)
      GlWrapper.checkGlError()
    }
  }
}


text:
package org.apache.metamodel.spring;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import org.apache.metamodel.DataContext;
import org.apache.metamodel.csv.CsvDataContext;
import org.apache.metamodel.util.Resource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:examples/csv-using-spring-resource.xml")
public class CsvDefaultConfigurationFromResourceTest {

    @Autowired
    private DataContext dataContext;

    @Test
    public void testReadDataContext() {
        assertEquals(CsvDataContext.class, dataContext.getClass());

        CsvDataContext csv = (CsvDataContext) dataContext;
        Resource resource = csv.getResource();

        assertEquals(SpringResource.class, resource.getClass());

        SpringResource springResource = (SpringResource) resource;
        Assert.assertTrue(springResource.isExists());

        assertEquals("example.csv", resource.getName());

        assertEquals("[foo, bar]", Arrays.toString(csv.getDefaultSchema().getTable(0).getColumnNames()));
    }
}


text:
namespace blink {

class CloseWatcherOptions;
class LocalDOMWindow;
class KeyboardEvent;

class CloseWatcher final : public EventTargetWithInlineData,
                           public ExecutionContextClient {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static CloseWatcher* Create(ScriptState*,
                              CloseWatcherOptions*,
                              ExceptionState&);

  static CloseWatcher* Create(LocalDOMWindow*);

  explicit CloseWatcher(LocalDOMWindow*);
  void Trace(Visitor*) const override;

  bool IsClosed() const { return state_ == State::kClosed; }
  bool IsGroupedWithPrevious() const { return grouped_with_previous_; }

  void close();
  void destroy();

  DEFINE_ATTRIBUTE_EVENT_LISTENER(cancel, kCancel)
  DEFINE_ATTRIBUTE_EVENT_LISTENER(close, kClose)

  // EventTargetWithInlineData overrides:
  const AtomicString& InterfaceName() const final;
  ExecutionContext* GetExecutionContext() const final {
    return ExecutionContextClient::GetExecutionContext();
  }

  // If multiple CloseWatchers are active in a given window, they form a
  // stack, and a close signal will pop the top watcher. If the stack is empty,
  // the first CloseWatcher is "free", but creating a new
  // CloseWatcher when the stack is non-empty requires a user activation.
  class WatcherStack final : public GarbageCollected<WatcherStack>,
                             public mojom::blink::CloseListener {
   public:
    explicit WatcherStack(LocalDOMWindow*);

    void Add(CloseWatcher*);
    void Remove(CloseWatcher*);
    bool HasActiveWatcher() const { return !watchers_.empty(); }
    bool HasConsumedFreeWatcher() const;

    void Trace(Visitor*) const;

    void EscapeKeyHandler(KeyboardEvent*);

   private:
    // mojom::blink::CloseListener override:
    void Signal() final;

    HeapLinkedHashSet<Member<CloseWatcher>> watchers_;

    // Holds a pipe which the service uses to notify this object
    // when the idle state has changed.
    HeapMojoReceiver<mojom::blink::CloseListener, WatcherStack> receiver_;
    Member<LocalDOMWindow> window_;
  };

 private:
  static CloseWatcher* CreateInternal(LocalDOMWindow*,
                                      WatcherStack&,
                                      CloseWatcherOptions*);

  enum class State { kActive, kClosed };
  State state_ = State::kActive;
  bool dispatching_cancel_ = false;
  bool grouped_with_previous_ = false;
  bool created_with_user_activation_ = false;
  Member<AbortSignal::AlgorithmHandle> abort_handle_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_CLOSEWATCHER_CLOSE_WATCHER_H_


text:
@implementation FLEXArgumentInputStringView

- (instancetype)initWithArgumentTypeEncoding:(const char *)typeEncoding
{
    self = [super initWithArgumentTypeEncoding:typeEncoding];
    if (self) {
        self.targetSize = FLEXArgumentInputViewSizeLarge;
    }
    return self;
}

- (void)setInputValue:(id)inputValue
{
    self.inputTextView.text = inputValue;
}

- (id)inputValue
{
    // Interpret empty string as nil. We loose the ability to set empty string as a string value,
    // but we accept that tradeoff in exchange for not having to type quotes for every string.
    return self.inputTextView.text.length > 0 ? [self.inputTextView.text copy] : nil;
}

// TODO: Support using object address for strings, as in the object arg view.

#pragma mark -

+ (BOOL)supportsObjCType:(const char *)type withCurrentValue:(id)value
{
    BOOL supported = type && strcmp(type, FLEXEncodeClass(NSString)) == 0;
    supported = supported || (value && [value isKindOfClass:[NSString class]]);
    return supported;
}

@end


text:
title: Accessing RadForm Elements
page_title: Accessing RadForm Elements - WinForms RadForm
description: Learn how to access and modify RadFormTitleBarElement, FormBorderPrimitive and FormImageBorderPrimitive.
slug: winforms/forms-and-dialogs/form/accessing-radform-elements
tags: accessing,radform,elements
published: True
position: 3
previous_url: forms-and-dialogs-form-accessing-radform-elements
---

# Accessing RadForm Elements

The __RadForm__ is build of a __RadFormTitleBarElement__, __FormBorderPrimitive__ and a __FormImageBorderPrimitive.__ The following topic demonstrates how to access and modify these elements.

## Accessing the RadTitleBarElement

The __RadFormTitleBarElement__ is positioned on the top of the form and its default behavior is to display an icon, text, and the help, minimize, maximize/restore and close buttons. You can access the __RadFormTitleBarElement__ the following way:

#### Accessing RadForm elements

{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=accessingRadFormElements}}
{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=accessingRadFormElements}}

````C#
void Form1_Shown(object sender, EventArgs e)
{
    this.FormElement.TitleBar.MaximizeButton.Enabled = false;
    this.FormElement.TitleBar.MinimizeButton.Enabled = false;
    this.FormElement.TitleBar.HelpButton.Visibility = Telerik.WinControls.ElementVisibility.Visible;
}

````
````VB.NET
Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
    Me.FormElement.TitleBar.MaximizeButton.Enabled = False
    Me.FormElement.TitleBar.MinimizeButton.Enabled = False
    Me.FormElement.TitleBar.HelpButton.Visibility = Telerik.WinControls.ElementVisibility.Visible
End Sub

````

{{endregion}}

>caption Figure 1: TitleBar

![forms-and-dialogs-accessing-radform-elements 001](images/forms-and-dialogs-accessing-radform-elements001.png)

>note By default, the __HelpButton__ is not shown. Set the __HelpButton__ property to *true* to display a Help button in the form's caption bar.The value of the __HelpButton__ property is ignored if the Maximize or Minimize buttons are shown.
> An alternative solution is to set its __Visibility__ property to *ElementVisibility.Visible* in order to be displayed. The __HelpButtonClicked__ event is fired when Help button in the title bar is clicked. It can be canceled. However, if it is not canceled, the __HelpRequested__ event will be fired when the Help cursor is clicked on any Control.

## Adding a new button to the title bar

You can easily extend the __RadFormTitleBarElement__ 's functionality by adding new elements to its hierarchy. The following code snippet demonstrated how to add a __RadButtonElement__ before the minimize button in the __RadFormTitleBarElement__:

#### Adding new button to the title bar

{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=addingNewButtonToTheTitleBar}}
{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=addingNewButtonToTheTitleBar}}

````C#
void Form1_Load(object sender, EventArgs e)
{
    RadButtonElement buttonElement = new RadButtonElement();
    buttonElement.Text = "TitleBar Button";
    this.FormElement.TitleBar.Children[2].Children[0].Children.Insert(0, buttonElement);
}

````
````VB.NET
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim buttonElement As New RadButtonElement()
    buttonElement.Text = "TitleBar Button"
    Me.FormElement.TitleBar.Children(2).Children(0).Children.Insert(0, buttonElement)
End Sub

````

{{endregion}}

## Accessing the Form Borders

The border of a __RadForm__ control is composed of two border primitives which, together, define the visual appearance of the whole border: __FormBorderPrimitive__ and __FormImageBorderPrimitive__.

## Accessing the FormBorderPrimitive

The __FormBorderPrimitive__ represents the outer thin border that surrounds a __RadForm__ control. The following code snippet demonstrates how to modify the color of this primitive:

#### Accessing the FormBorderPrimitive

{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=accessingTheFormBorderPrimitive}}
{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=accessingTheFormBorderPrimitive}}

````C#
this.FormElement.Border.ForeColor = System.Drawing.Color.Green;

````
````VB.NET
Me.FormElement.Border.ForeColor = System.Drawing.Color.Green

````

{{endregion}}

>note The visual appearance of the border and also for the whole RadForm control can be designed in the Visual Style Builder.
>

## Accessing the FormImageBorderPrimitive

The __FormImageBorderPrimitive__ represents the inner thick border that starts from the bottom-left corner of the title bar, surrounds the __RadForm__ control and ends at the bottom-right corner of the title bar. The __FormImageBorderPrimitive__ provides you with the possibility to define borders for your form which are built of images and thus achieve better look-and-feel for your form. Without images set, the __FormImageBorderPrimitive__ paints as a one-color-border with the color set to the __BackColor__ property of the primitive.

The following code snippet demonstrates how to set the __BackColor__ of the __FormImageBorderPrimitive__ which is painted when no images are defined:

#### Accessing the FormImageBorderPrimitive

{{source=..\SamplesCS\Forms and Dialogs\Form1.cs region=accessingTheFormImageBorderPrimitive}}
{{source=..\SamplesVB\Forms and Dialogs\Form1.vb region=accessingTheFormImageBorderPrimitive}}

````C#
this.FormElement.ImageBorder.BackColor = Color.Lime;

````
````VB.NET
Me.FormElement.ImageBorder.BackColor = Color.Lime

````

{{endregion}}

>note More information on how to use the __FormImageBorderPrimitive__ can be found in the separate topic: [Using the FormImageBorderPrimitive]({%slug winforms/forms-and-dialogs/form/using-the-formimageborderprimitive%}).
>


text:
layout: post
microblog: true
audio:
photo:
date: 2013-04-15 20:12:56 -0600
guid: http://craigmcclellan.micro.blog/2013/04/16/t323982309835563009.html
---
I was literally cowering under my bed sheets watching The Hounds of Baskerville. #Sherlock #brilliant


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />

        <meta charset="utf-8" />
        <title>Dashboard</title>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta content="width=device-width, initial-scale=1.0" name="viewport" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8">
        <meta content="" name="description" />
        <meta content="" name="author" />

        <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:300italic,400italic,700italic,400,300,700&subset=all' rel='stylesheet' type='text/css'>
        <link href="plugins/socicon/socicon.css" rel="stylesheet" type="text/css" />
        <link href="plugins/bootstrap-social/bootstrap-social.css" rel="stylesheet" type="text/css" />
        <link href="plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
        <link href="plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
        <link href="plugins/animate/animate.min.css" rel="stylesheet" type="text/css" />
        <link href="plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

        <link href="plugins/cubeportfolio/css/cubeportfolio.min.css" rel="stylesheet" type="text/css" />
        <link href="plugins/owl-carousel/assets/owl.carousel.css" rel="stylesheet" type="text/css" />
        <link href="plugins/fancybox/jquery.fancybox.css" rel="stylesheet" type="text/css" />
        <link href="plugins/slider-for-bootstrap/css/slider.css" rel="stylesheet" type="text/css" />

        <link href="base/css/plugins.css" rel="stylesheet" type="text/css" />
        <link href="base/css/components.css" id="style_components" rel="stylesheet" type="text/css" />
        <link href="base/css/themes/default.css" rel="stylesheet" id="style_theme" type="text/css" />
        <link href="base/css/custom.css" rel="stylesheet" type="text/css" />

        <link rel="shortcut icon" href="favicon.ico" />

<link rel="stylesheet" href="plugins/imagezoom/css/imagezoom/imagezoom.css" />
<link rel="stylesheet" href="plugins/imagezoom/css/elastislide/es-cus.css" />
<link type="text/css" rel="stylesheet" href="lib/css/DT_bootstrap.css"/>

                                        2

                                         Sign Out

                                INVENTORY SYSTEM

                        <button class="c-topbar-toggler" type="button">

                        </button>
                        <button class="c-hor-nav-toggler" type="button" data-target=".c-mega-menu">

                        </button>

                                    Dashboard

                                    Inventory

                                    Exports

                                    Imports

                                    Zakat

                                    Users

                                    Reports

                                                Sales Report

                                                Purchase Report

                                    ×

                                Vehicle Exported To Your Destination...

                                    ×

                                Vehicle Received Successfully At Destination...

Dashboard

                            Admin

/

Dashboard

Sales

Assets

 Copyright © 2017


text:
    <meta charset="utf-8">

This is the test for window.internals.counterValueForElementById


text:
__all__ = ['TProtocol',
           'TBinaryProtocol',
           'fastproto',
           'TSimpleJSONProtocol',
           'TCompactProtocol',
           'THeaderProtocol',
           ]


text:
package org.apache.spark.sql.hive.thriftserver

import java.util.UUID
import java.util.regex.Pattern

import org.apache.commons.lang3.exception.ExceptionUtils
import org.apache.hadoop.hive.ql.security.authorization.plugin.HiveOperationType
import org.apache.hive.service.cli._
import org.apache.hive.service.cli.operation.GetSchemasOperation
import org.apache.hive.service.cli.operation.MetadataOperation.DEFAULT_HIVE_CATALOG
import org.apache.hive.service.cli.session.HiveSession

import org.apache.spark.internal.Logging
import org.apache.spark.sql.SQLContext
import org.apache.spark.util.{Utils => SparkUtils}

/**
 * Spark's own GetSchemasOperation
 *
 * @param sqlContext SQLContext to use
 * @param parentSession a HiveSession from SessionManager
 * @param catalogName catalog name. null if not applicable.
 * @param schemaName database name, null or a concrete database name
 */
private[hive] class SparkGetSchemasOperation(
    val sqlContext: SQLContext,
    parentSession: HiveSession,
    catalogName: String,
    schemaName: String)
  extends GetSchemasOperation(parentSession, catalogName, schemaName)
  with SparkOperation
  with Logging {

  override def runInternal(): Unit = {
    // Do not change cmdStr. It's used for Hive auditing and authorization.
    val cmdStr = s"catalog : $catalogName, schemaPattern : $schemaName"
    val logMsg = s"Listing databases '$cmdStr'"
    logInfo(s"$logMsg with $statementId")
    setState(OperationState.RUNNING)
    // Always use the latest class loader provided by executionHive's state.
    val executionHiveClassLoader = sqlContext.sharedState.jarClassLoader
    Thread.currentThread().setContextClassLoader(executionHiveClassLoader)

    if (isAuthV2Enabled) {
      authorizeMetaGets(HiveOperationType.GET_TABLES, null, cmdStr)
    }

    HiveThriftServer2.eventManager.onStatementStart(
      statementId,
      parentSession.getSessionHandle.getSessionId.toString,
      logMsg,
      statementId,
      parentSession.getUsername)

    try {
      val schemaPattern = convertSchemaPattern(schemaName)
      sqlContext.sessionState.catalog.listDatabases(schemaPattern).foreach { dbName =>
        rowSet.addRow(Array[AnyRef](dbName, DEFAULT_HIVE_CATALOG))
      }

      val globalTempViewDb = sqlContext.sessionState.catalog.globalTempViewManager.database
      val databasePattern = Pattern.compile(CLIServiceUtils.patternToRegex(schemaName))
      if (databasePattern.matcher(globalTempViewDb).matches()) {
        rowSet.addRow(Array[AnyRef](globalTempViewDb, DEFAULT_HIVE_CATALOG))
      }
      setState(OperationState.FINISHED)
    } catch onError()

    HiveThriftServer2.eventManager.onStatementFinish(statementId)
  }
}


text:
package com.walletudo.ui.hacky;

import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Fix for this issue: https://code.google.com/p/android/issues/detail?id=60464
 */
public class HackyDrawerLayout extends DrawerLayout {

    public HackyDrawerLayout(Context context) {
        super(context);
    }

    public HackyDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HackyDrawerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}


text:
<?php

namespace Controllers;

require '../vendor/autoload.php';

use \Slim\Http\Request as Request;
use \Slim\Http\Response as Response;

class Domains
{
    /** @var \Monolog\Logger */
    private $logger;

    /** @var \Slim\Container */
    private $c;

    public function __construct(\Slim\Container $c)
    {
        $this->logger = $c->logger;
        $this->c = $c;
    }

    public function getList(Request $req, Response $res, array $args)
    {
        $domains = new \Operations\Domains($this->c);

        $paging = new \Utils\PagingInfo($req->getQueryParam('page'), $req->getQueryParam('pagesize'));
        $query = $req->getQueryParam('query');
        $sort = $req->getQueryParam('sort');
        $type = $req->getQueryParam('type');

        $userId = $req->getAttribute('userId');

        $results = $domains->getDomains($paging, $userId, $query, $sort, $type);

        return $res->withJson([
            'paging' => $paging->toArray(),
            'results' => $results
        ], 200);
    }

    public function postNew(Request $req, Response $res, array $args)
    {
        $ac = new \Operations\AccessControl($this->c);
        if (!$ac->isAdmin($req->getAttribute('userId'))) {
            $this->logger->info('Non admin user tries to add domain');
            return $res->withJson(['error' => 'You must be admin to use this feature'], 403);
        }

        $body = $req->getParsedBody();

        if (!array_key_exists('name', $body) ||
            !array_key_exists('type', $body) || ($body['type'] === 'SLAVE' && !array_key_exists('master', $body))) {
            $this->logger->debug('One of the required fields is missing');
            return $res->withJson(['error' => 'One of the required fields is missing'], 422);
        }

        $name = $body['name'];
        $type = $body['type'];
        $master = isset($body['master']) ? $body['master'] : null;

        $domains = new \Operations\Domains($this->c);

        try {
            $result = $domains->addDomain($name, $type, $master);

            $this->logger->info('Created domain', $result);
            return $res->withJson($result, 201);
        } catch (\Exceptions\AlreadyExistentException $e) {
            $this->logger->debug('Zone with name ' . $name . ' already exists.');
            return $res->withJson(['error' => 'Zone with name ' . $name . ' already exists.'], 409);
        } catch (\Exceptions\SemanticException $e) {
            $this->logger->info('Invalid type for new domain', ['type' => $type]);
            return $res->withJson(['error' => 'Invalid type allowed are MASTER, NATIVE and SLAVE'], 400);
        }
    }

    public function delete(Request $req, Response $res, array $args)
    {
        $ac = new \Operations\AccessControl($this->c);
        if (!$ac->isAdmin($req->getAttribute('userId'))) {
            $this->logger->info('Non admin user tries to delete domain');
            return $res->withJson(['error' => 'You must be admin to use this feature'], 403);
        }

        $domains = new \Operations\Domains($this->c);

        $domainId = intval($args['domainId']);

        try {
            $domains->deleteDomain($domainId);

            $this->logger->info('Deleted domain', ['id' => $domainId]);
            return $res->withStatus(204);
        } catch (\Exceptions\NotFoundException $e) {
            return $res->withJson(['error' => 'No domain found for id ' . $domainId], 404);
        }
    }

    public function getSingle(Request $req, Response $res, array $args)
    {
        $userId = $req->getAttribute('userId');
        $domainId = intval($args['domainId']);

        $ac = new \Operations\AccessControl($this->c);
        if (!$ac->canAccessDomain($userId, $domainId)) {
            $this->logger->info('Non admin user tries to get domain without permission.');
            return $res->withJson(['error' => 'You have no permissions for this domain.'], 403);
        }

        $domains = new \Operations\Domains($this->c);

        try {
            $result = $domains->getDomain($domainId);

            $this->logger->debug('Get domain info', ['id' => $domainId]);
            return $res->withJson($result, 200);
        } catch (\Exceptions\NotFoundException $e) {
            return $res->withJson(['error' => 'No domain found for id ' . $domainId], 404);
        }
    }

    public function put(Request $req, Response $res, array $args)
    {
        $userId = $req->getAttribute('userId');
        $domainId = intval($args['domainId']);
        $ac = new \Operations\AccessControl($this->c);
        if (!$ac->canAccessDomain($userId, $domainId)) {
            $this->logger->info('User tries to update domain without permission');
            return $res->withJson(['error' => 'You have no permissions for this domain.'], 403);
        }

        $body = $req->getParsedBody();

        if (!array_key_exists('master', $body)) {
            $this->logger->debug('One of the required fields is missing');
            return $res->withJson(['error' => 'One of the required fields is missing'], 422);
        }

        $master = $body['master'];

        $domains = new \Operations\Domains($this->c);

        try {
            $result = $domains->updateSlave($domainId, $master);

            $this->logger->debug('Update master', ['id' => $domainId]);
            return $res->withStatus(204);
        } catch (\Exceptions\NotFoundException $e) {
            $this->logger->debug('Trying to update non existing slave zone', ['id' => $domainId]);
            return $res->withJson(['error' => 'No domain found for id ' . $domainId], 404);
        } catch (\Exceptions\SemanticException $e) {
            $this->logger->debug('Trying to update non slave zone', ['id' => $domainId]);
            return $res->withJson(['error' => 'Domain is not a slave zone'], 405);
        }
    }

    public function putSoa(Request $req, Response $res, array $args)
    {
        $userId = $req->getAttribute('userId');
        $domainId = $args['domainId'];

        $ac = new \Operations\AccessControl($this->c);
        if (!$ac->canAccessDomain($userId, $domainId)) {
            $this->logger->info('Non admin user tries to get domain without permission.');
            return $res->withJson(['error' => 'You have no permissions for this domain.'], 403);
        }

        $body = $req->getParsedBody();

        if (!array_key_exists('primary', $body) ||
            !array_key_exists('email', $body) ||
            !array_key_exists('refresh', $body) ||
            !array_key_exists('retry', $body) ||
            !array_key_exists('expire', $body) ||
            !array_key_exists('ttl', $body)) {
            $this->logger->debug('One of the required fields is missing');
            return $res->withJson(['error' => 'One of the required fields is missing'], 422);
        }

        $soa = new \Operations\Soa($this->c);

        try {
            $soa->setSoa(
                intval($domainId),
                $body['email'],
                $body['primary'],
                intval($body['refresh']),
                intval($body['retry']),
                intval($body['expire']),
                intval($body['ttl'])
            );

            return $res->withStatus(204);
        } catch (\Exceptions\NotFoundException $e) {
            $this->logger->warning('Trying to set soa for not existing domain.', ['domainId' => $domainId]);
            return $res->withJson(['error' => 'No domain found for id ' . $domainId], 404);
        } catch (\Exceptions\SemanticException $e) {
            $this->logger->warning('Trying to set soa for slave domain.', ['domainId' => $domainId]);
            return $res->withJson(['error' => 'SOA can not be set for slave domains'], 405);
        }
    }

    public function getSoa(Request $req, Response $res, array $args)
    {
        $userId = $req->getAttribute('userId');
        $domainId = $args['domainId'];

        $ac = new \Operations\AccessControl($this->c);
        if (!$ac->canAccessDomain($userId, $domainId)) {
            $this->logger->info('Non admin user tries to get domain without permission.');
            return $res->withJson(['error' => 'You have no permissions for this domain.'], 403);
        }

        $soa = new \Operations\Soa($this->c);

        try {
            $soaArray = $soa->getSoa($domainId);

            return $res->withJson($soaArray, 200);
        } catch (\Exceptions\NotFoundException $e) {
            $this->logger->debug('User tried to get non existing soa.', ['domainId' => $domainId]);
            return $res->withJson(['error' => 'This domain has no soa record.'], 404);
        }
    }
}


text:
import { Routes, RouterModule } from '@angular/router';
import { CoursesListComponent }    from './courses-list.component';
import { CoursesGuard } from '../../../core/services/guards/courses.guard';

// Route Configuration
const coursesListRoutes: Routes = [
	{ path: 'courses', component: CoursesListComponent, canActivate: [CoursesGuard], data: { breadcrumb: "Courses list" } },
];

export const routes = RouterModule.forChild(coursesListRoutes);


text:
package com.easemob.tsdb.thrift.rpc;

import com.easemob.tsdb.thrift.rpc.service.TSDBDelegate;
import com.stumbleupon.async.Deferred;
import net.opentsdb.core.TSDB;

import java.util.Map;

/**
 * @author stliu <stliu@apache.org>
 * @date 3/11/15
 */
public class TSDBWrapper implements TSDBDelegate {
    private final TSDB tsdb;

    public TSDBWrapper(TSDB tsdb) {
        this.tsdb = tsdb;
    }

    @Override
    public Deferred<Object> addPoint(String name, long timestamp, double value, Map<String, String> tags) {
        return tsdb.addPoint(name, timestamp, value, tags);
    }

    @Override
    public ConfigDelegate getConfig() {
        return new ConfigWrapper(tsdb.getConfig().getMap());
    }

    public static class ConfigWrapper implements ConfigDelegate{
        private final Map<String, String> map;

        public ConfigWrapper(Map<String, String> map) {
            this.map = map;
        }

        @Override
        public Map<String, String> getMap() {
            return map;
        }
    }
}


text:
package org.olat.login.auth;

import org.olat.core.gui.control.Event;
import org.olat.core.id.Identity;

/**
 * Initial Date:  04.08.2004
 *
 * @author Mike Stock
 */
public class AuthenticationEvent extends Event {

	private static final long serialVersionUID = -5353574564474813721L;
	Identity identity;

	/**
	 * @param identity
	 */
	public AuthenticationEvent(Identity identity) {
		super("authevent");
		this.identity = identity;
	}

	/**
	 * @return the identity that was authenticated.
	 */
	public Identity getIdentity() {
		return identity;
	}
}


text:
package li.people.record;

import li.annotation.Bean;
import li.annotation.Table;
import li.dao.Record;

@Bean
@Table("t_bill")
public class Bill extends Record<Bill, Integer> {
    private static final long serialVersionUID = -3885011391270927891L;
}


text:
package reactivemongo.core.protocol

import shaded.netty.buffer._

/**
 * Helper methods to write tuples of supported types into a [[http://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html ChannelBuffer]].
 */
private[protocol] object BufferAccessors {
  /**
   * Typeclass for types that can be written into a [[http://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html ChannelBuffer]]
   * via writeTupleToBufferN methods.
   *
   * @tparam T type to be written via BufferAccessors.writeTupleToBufferN(...) methods.
   */
  sealed trait BufferInteroperable[T] {
    def apply(buffer: ChannelBuffer, t: T): Unit
  }

  implicit object IntChannelInteroperable extends BufferInteroperable[Int] {
    def apply(buffer: ChannelBuffer, i: Int) = buffer writeInt i
  }

  implicit object LongChannelInteroperable extends BufferInteroperable[Long] {
    def apply(buffer: ChannelBuffer, l: Long) = buffer writeLong l
  }

  implicit object StringChannelInteroperable
      extends BufferInteroperable[String] {

    private def writeCString(buffer: ChannelBuffer, s: String): ChannelBuffer = {
      val bytes = s.getBytes("utf-8")
      buffer writeBytes bytes
      buffer writeByte 0
      buffer
    }

    def apply(buffer: ChannelBuffer, s: String) = {
      writeCString(buffer, s); ()
    }
  }

  /**
   * Write the given tuple into the given [[http://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html ChannelBuffer]].
   *
   * @tparam A type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   * @tparam B type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   */
  def writeTupleToBuffer2[A, B](t: (A, B))(buffer: ChannelBuffer)(implicit i1: BufferInteroperable[A], i2: BufferInteroperable[B]): Unit = {
    i1(buffer, t._1)
    i2(buffer, t._2)
  }

  /**
   * Write the given tuple into the given [[http://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html ChannelBuffer]].
   *
   * @tparam A type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   * @tparam B type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   * @tparam C type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   */
  def writeTupleToBuffer3[A, B, C](t: (A, B, C))(buffer: ChannelBuffer)(implicit i1: BufferInteroperable[A], i2: BufferInteroperable[B], i3: BufferInteroperable[C]): Unit = {
    i1(buffer, t._1)
    i2(buffer, t._2)
    i3(buffer, t._3)
  }

  /**
   * Write the given tuple into the given [[http://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html ChannelBuffer]].
   *
   * @tparam A type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   * @tparam B type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   * @tparam C type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   * @tparam D type that have an implicit typeclass [[reactivemongo.core.protocol.BufferAccessors.BufferInteroperable]].
   */
  def writeTupleToBuffer4[A, B, C, D](t: (A, B, C, D))(buffer: ChannelBuffer)(implicit i1: BufferInteroperable[A], i2: BufferInteroperable[B], i3: BufferInteroperable[C], i4: BufferInteroperable[D]): Unit = {
    i1(buffer, t._1)
    i2(buffer, t._2)
    i3(buffer, t._3)
    i4(buffer, t._4)
  }
}

import BufferAccessors._

/** A Mongo Wire Protocol operation */
sealed trait Op {
  /** operation code */
  val code: Int
}

/**
 * A Mongo Wire Protocol request operation.
 *
 * Actually, all operations excepted Reply are requests.
 */
sealed trait RequestOp extends Op with ChannelBufferWritable {
  /** States if this request expects a response. */
  val expectsResponse: Boolean = false

  /** States if this request has to be run on a primary. */
  val requiresPrimary: Boolean = false
}

/** A request that needs to know the full collection name. */
sealed trait CollectionAwareRequestOp extends RequestOp {
  /** The full collection name (''<dbname.collectionname>'') */
  val fullCollectionName: String

  /** Database and collection name */
  lazy val (db: String, collectionName: String) = fullCollectionName.span(_ != '.')
}

/** A request that will perform a write on the database */
sealed trait WriteRequestOp extends CollectionAwareRequestOp

/**
 * Reply operation.
 *
 * @param flags The flags of this response.
 * @param cursorID The cursor id. Strictly positive if a cursor has been created server side, 0 if none or exhausted.
 * @param startingFrom The index the returned documents start from.
 * @param numberReturned The number of documents that are present in this reply.
 */
case class Reply(
    flags: Int,
    cursorID: Long,
    startingFrom: Int,
    numberReturned: Int
) extends Op {
  override val code = 1

  /** States whether the cursor given in the request was found */
  lazy val cursorNotFound = (flags & 0x01) != 0

  /** States if the request encountered an error */
  lazy val queryFailure = (flags & 0x02) != 0

  /** States if the answering server supports the AwaitData query option */
  lazy val awaitCapable = (flags & 0x08) != 0

  private def str(b: Boolean, s: String) = if (b) s else ""

  /** States if this reply is in error */
  lazy val inError = cursorNotFound || queryFailure

  lazy val stringify = toString + " [" + str(cursorNotFound, "CursorNotFound;") + str(queryFailure, "QueryFailure;") + str(awaitCapable, "AwaitCapable") + "]"
}

object Reply extends ChannelBufferReadable[Reply] {
  def readFrom(buffer: ChannelBuffer) = Reply(
    buffer.readInt,
    buffer.readLong,
    buffer.readInt,
    buffer.readInt
  )
}

/**
 * Update operation.
 *
 * @param flags Operation flags.
 */
case class Update(
    fullCollectionName: String,
    flags: Int
) extends WriteRequestOp {
  override val code = 2001
  override val writeTo = writeTupleToBuffer3((0, fullCollectionName, flags)) _
  override def size = 4 /* int32 = ZERO */ + 4 + fullCollectionName.length + 1
  override val requiresPrimary = true
}

object UpdateFlags {
  /** If set, the database will insert the supplied object into the collection if no matching document is found. */
  val Upsert = 0x01

  /** If set, the database will update all matching objects in the collection. Otherwise only updates first matching doc. */
  val MultiUpdate = 0x02
}

/**
 * Insert operation.
 *
 * @param flags Operation flags.
 */
case class Insert(
    flags: Int,
    fullCollectionName: String
) extends WriteRequestOp {
  override val code = 2002
  override val writeTo = writeTupleToBuffer2((flags, fullCollectionName)) _
  override def size = 4 + fullCollectionName.length + 1
  override val requiresPrimary = true
}

/**
 * Query operation.
 *
 * @param flags the operation flags
 * @param fullCollectionName the full name of the queried collection
 * @param numberToSkip the number of documents to skip in the response.
 * @param numberToReturn The number of documents to return in the response. 0 means the server will choose.
 */
case class Query(
    flags: Int,
    fullCollectionName: String,
    numberToSkip: Int,
    numberToReturn: Int
) extends CollectionAwareRequestOp {
  override val expectsResponse = true
  override val code = 2004
  override val writeTo = writeTupleToBuffer4((flags, fullCollectionName, numberToSkip, numberToReturn)) _
  override def size = 4 + fullCollectionName.length + 1 + 4 + 4
}

/**
 * Query flags.
 */
object QueryFlags {
  /** Makes the cursor not to close after all the data is consumed. */
  val TailableCursor = 0x02

  /** The query is might be run on a secondary. */
  val SlaveOk = 0x04

  /** OplogReplay */
  val OplogReplay = 0x08

  /** The cursor will not expire automatically */
  val NoCursorTimeout = 0x10

  /**
   * Block a little while waiting for more data instead of returning immediately if no data.
   * Use along with TailableCursor.
   */
  val AwaitData = 0x20

  /** Exhaust */
  val Exhaust = 0x40

  /** The response can be partial - if a shard is down, no error will be thrown. */
  val Partial = 0x80
}

/**
 * GetMore operation.
 *
 * Allows to get more data from a cursor.
 * @param numberToReturn number of documents to return in the response. 0 means the server will choose.
 * @param cursorId id of the cursor.
 */
case class GetMore(
    fullCollectionName: String,
    numberToReturn: Int,
    cursorID: Long
) extends CollectionAwareRequestOp {
  override val expectsResponse = true
  override val code = 2005
  override val writeTo = writeTupleToBuffer4((0, fullCollectionName, numberToReturn, cursorID)) _
  override def size = 4 /* int32 ZERO */ + fullCollectionName.length + 1 + 4 + 8
}

/**
 * Delete operation.
 *
 * @param flags operation flags.
 */
case class Delete(
    fullCollectionName: String,
    flags: Int
) extends WriteRequestOp {
  override val code = 2006
  override val writeTo = writeTupleToBuffer3((0, fullCollectionName, flags)) _
  override def size = 4 /* int32 ZERO */ + fullCollectionName.length + 1 + 4
  override val requiresPrimary = true
}

/**
 * KillCursors operation.
 *
 * @param cursorIDs ids of the cursors to kill. Should not be empty.
 */
case class KillCursors(
    cursorIDs: Set[Long]
) extends RequestOp {
  override val code = 2007
  override val writeTo = { buffer: ChannelBuffer =>
    buffer writeInt 0
    buffer writeInt cursorIDs.size
    for (cursorID <- cursorIDs) {
      buffer writeLong cursorID
    }
  }
  override def size = 4 /* int32 ZERO */ + 4 + cursorIDs.size * 8
}


text:
"""
Script for building the example.

Usage:
    python setup.py py2app
"""
from setuptools import setup

plist = dict(
    NSPrincipalClass='HotKeyApp',
)

setup(
    app=["HotKey.py"],
    data_files=["English.lproj"],
    setup_requires=["py2app"],
    options=dict(py2app=dict(plist=plist)),
)