text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>selenium.webdriver.common.keys — Selenium 2.0 documentation</title>

    <link rel="stylesheet" href="../../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="Selenium 2.0 documentation" href="../../../../index.html" />
    <link rel="up" title="Module code" href="../../../index.html" />

Navigation

          index

          modules |

Selenium 2.0 documentation »

Module code »

Source code for selenium.webdriver.common.keys

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

"""
The Keys implementation.
"""

from __future__ import unicode_literals

[docs]class Keys(object):
    """
    Set of special keys codes.
    """

    NULL         = '\ue000'
    CANCEL       = '\ue001' #  ^break
    HELP         = '\ue002'
    BACKSPACE    = '\ue003'
    BACK_SPACE   = '\ue003' #  alias
    TAB          = '\ue004'
    CLEAR        = '\ue005'
    RETURN       = '\ue006'
    ENTER        = '\ue007'
    SHIFT        = '\ue008'
    LEFT_SHIFT   = '\ue008' #  alias
    CONTROL      = '\ue009'
    LEFT_CONTROL = '\ue009' #  alias
    ALT          = '\ue00a'
    LEFT_ALT     = '\ue00a' #  alias
    PAUSE        = '\ue00b'
    ESCAPE       = '\ue00c'
    SPACE        = '\ue00d'
    PAGE_UP      = '\ue00e'
    PAGE_DOWN    = '\ue00f'
    END          = '\ue010'
    HOME         = '\ue011'
    LEFT         = '\ue012'
    ARROW_LEFT   = '\ue012' # alias
    UP           = '\ue013'
    ARROW_UP     = '\ue013' # alias
    RIGHT        = '\ue014'
    ARROW_RIGHT  = '\ue014' #  alias
    DOWN         = '\ue015'
    ARROW_DOWN   = '\ue015' #  alias
    INSERT       = '\ue016'
    DELETE       = '\ue017'
    SEMICOLON    = '\ue018'
    EQUALS       = '\ue019'

    NUMPAD0      = '\ue01a' #  numbe pad  keys
    NUMPAD1      = '\ue01b'
    NUMPAD2      = '\ue01c'
    NUMPAD3      = '\ue01d'
    NUMPAD4      = '\ue01e'
    NUMPAD5      = '\ue01f'
    NUMPAD6      = '\ue020'
    NUMPAD7      = '\ue021'
    NUMPAD8      = '\ue022'
    NUMPAD9      = '\ue023'
    MULTIPLY     = '\ue024'
    ADD          = '\ue025'
    SEPARATOR    = '\ue026'
    SUBTRACT     = '\ue027'
    DECIMAL      = '\ue028'
    DIVIDE       = '\ue029'

    F1           = '\ue031' #  function  keys
    F2           = '\ue032'
    F3           = '\ue033'
    F4           = '\ue034'
    F5           = '\ue035'
    F6           = '\ue036'
    F7           = '\ue037'
    F8           = '\ue038'
    F9           = '\ue039'
    F10          = '\ue03a'
    F11          = '\ue03b'
    F12          = '\ue03c'

    META         = '\ue03d'
    COMMAND      = '\ue03d'

Quick search

    <form class="search" action="../../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

Selenium 2.0 documentation »

Module code »

        © Copyright 2011, plightbo, simon.m.stewart, hbchai, jrhuggins, et al..


text:
@interface GrowlBoxcar2PreferencePane : GrowlPluginPreferencePane <NSURLConnectionDelegate>

@property (nonatomic, retain) NSString *errorMessage;
@property (nonatomic) BOOL validating;

-(NSString*)accessToken;
-(void)setAccessToken:(NSString*)newToken;

-(NSString*)prefixString;
-(void)setPrefixString:(NSString *)newPrefix;

-(BOOL)usePrefix;
-(void)setUsePrefix:(BOOL)prefix;

-(BOOL)pushIdle;
-(void)setPushIdle:(BOOL)push;

-(BOOL)usePriority;
-(void)setUsePriority:(BOOL)use;

-(int)minPriority;
-(void)setMinPriority:(int)min;

@end

redpajama_set_name: RedPajamaGithub


text:
WINRT_EXPORT namespace winrt {

namespace ABI::Windows::Foundation::Collections {

#ifndef WINRT_GENERIC_1a81ec3e_5afb_5e10_92bb_c843fec70887
#define WINRT_GENERIC_1a81ec3e_5afb_5e10_92bb_c843fec70887
template <> struct __declspec(uuid("1a81ec3e-5afb-5e10-92bb-c843fec70887")) __declspec(novtable) IVectorView<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> : impl_IVectorView<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> {};
#endif

}

namespace ABI::Windows::Foundation {

#ifndef WINRT_GENERIC_4be29c7e_449c_576e_a7b8_3a40f2f01dc8
#define WINRT_GENERIC_4be29c7e_449c_576e_a7b8_3a40f2f01dc8
template <> struct __declspec(uuid("4be29c7e-449c-576e-a7b8-3a40f2f01dc8")) __declspec(novtable) TypedEventHandler<Windows::Media::Effects::AudioRenderEffectsManager, Windows::IInspectable> : impl_TypedEventHandler<Windows::Media::Effects::AudioRenderEffectsManager, Windows::IInspectable> {};
#endif

}

namespace ABI::Windows::Foundation::Collections {

#ifndef WINRT_GENERIC_cdcbc9e7_53d8_5e66_9e45_31d5a23fd01d
#define WINRT_GENERIC_cdcbc9e7_53d8_5e66_9e45_31d5a23fd01d
template <> struct __declspec(uuid("cdcbc9e7-53d8-5e66-9e45-31d5a23fd01d")) __declspec(novtable) IVectorView<Windows::Media::Effects::AudioEffect> : impl_IVectorView<Windows::Media::Effects::AudioEffect> {};
#endif

}

namespace ABI::Windows::Foundation {

#ifndef WINRT_GENERIC_a1c5e803_a275_5bb1_9d44_2ac8ae9ffb89
#define WINRT_GENERIC_a1c5e803_a275_5bb1_9d44_2ac8ae9ffb89
template <> struct __declspec(uuid("a1c5e803-a275-5bb1-9d44-2ac8ae9ffb89")) __declspec(novtable) TypedEventHandler<Windows::Media::Effects::AudioCaptureEffectsManager, Windows::IInspectable> : impl_TypedEventHandler<Windows::Media::Effects::AudioCaptureEffectsManager, Windows::IInspectable> {};
#endif

}

namespace ABI::Windows::Foundation::Collections {

#ifndef WINRT_GENERIC_04c7baba_04d7_51db_a4e3_5147963ec5ff
#define WINRT_GENERIC_04c7baba_04d7_51db_a4e3_5147963ec5ff
template <> struct __declspec(uuid("04c7baba-04d7-51db-a4e3-5147963ec5ff")) __declspec(novtable) IVectorView<Windows::Media::MediaProperties::VideoEncodingProperties> : impl_IVectorView<Windows::Media::MediaProperties::VideoEncodingProperties> {};
#endif

#ifndef WINRT_GENERIC_64ac506c_ccd0_56cb_b088_b1a36e8755df
#define WINRT_GENERIC_64ac506c_ccd0_56cb_b088_b1a36e8755df
template <> struct __declspec(uuid("64ac506c-ccd0-56cb-b088-b1a36e8755df")) __declspec(novtable) IVectorView<Windows::Media::MediaProperties::AudioEncodingProperties> : impl_IVectorView<Windows::Media::MediaProperties::AudioEncodingProperties> {};
#endif

#ifndef WINRT_GENERIC_bdfb6d0b_e785_5d5a_abd2_fe1b18c43257
#define WINRT_GENERIC_bdfb6d0b_e785_5d5a_abd2_fe1b18c43257
template <> struct __declspec(uuid("bdfb6d0b-e785-5d5a-abd2-fe1b18c43257")) __declspec(novtable) IIterator<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> : impl_IIterator<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> {};
#endif

#ifndef WINRT_GENERIC_cc63bf9c_e16a_5a75_a5aa_2b53f975b0b0
#define WINRT_GENERIC_cc63bf9c_e16a_5a75_a5aa_2b53f975b0b0
template <> struct __declspec(uuid("cc63bf9c-e16a-5a75-a5aa-2b53f975b0b0")) __declspec(novtable) IIterable<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> : impl_IIterable<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> {};
#endif

#ifndef WINRT_GENERIC_673ce717_a3cf_5d68_a80b_5ed3e7b93fed
#define WINRT_GENERIC_673ce717_a3cf_5d68_a80b_5ed3e7b93fed
template <> struct __declspec(uuid("673ce717-a3cf-5d68-a80b-5ed3e7b93fed")) __declspec(novtable) IIterator<Windows::Media::Effects::AudioEffect> : impl_IIterator<Windows::Media::Effects::AudioEffect> {};
#endif

#ifndef WINRT_GENERIC_07af9afd_25b8_579d_be7e_8acc03418d0b
#define WINRT_GENERIC_07af9afd_25b8_579d_be7e_8acc03418d0b
template <> struct __declspec(uuid("07af9afd-25b8-579d-be7e-8acc03418d0b")) __declspec(novtable) IIterable<Windows::Media::Effects::AudioEffect> : impl_IIterable<Windows::Media::Effects::AudioEffect> {};
#endif

#ifndef WINRT_GENERIC_094166ef_ae5f_5315_a3bf_fe54e8c35fcd
#define WINRT_GENERIC_094166ef_ae5f_5315_a3bf_fe54e8c35fcd
template <> struct __declspec(uuid("094166ef-ae5f-5315-a3bf-fe54e8c35fcd")) __declspec(novtable) IIterator<Windows::Media::MediaProperties::VideoEncodingProperties> : impl_IIterator<Windows::Media::MediaProperties::VideoEncodingProperties> {};
#endif

#ifndef WINRT_GENERIC_73c7317c_8682_5f81_84a2_30c425fa2d24
#define WINRT_GENERIC_73c7317c_8682_5f81_84a2_30c425fa2d24
template <> struct __declspec(uuid("73c7317c-8682-5f81-84a2-30c425fa2d24")) __declspec(novtable) IIterable<Windows::Media::MediaProperties::VideoEncodingProperties> : impl_IIterable<Windows::Media::MediaProperties::VideoEncodingProperties> {};
#endif

#ifndef WINRT_GENERIC_064b6aef_3bd0_5463_8450_72c6169af5d4
#define WINRT_GENERIC_064b6aef_3bd0_5463_8450_72c6169af5d4
template <> struct __declspec(uuid("064b6aef-3bd0-5463-8450-72c6169af5d4")) __declspec(novtable) IIterator<Windows::Media::MediaProperties::AudioEncodingProperties> : impl_IIterator<Windows::Media::MediaProperties::AudioEncodingProperties> {};
#endif

#ifndef WINRT_GENERIC_00939468_25d8_533f_854e_4f20f36c51dc
#define WINRT_GENERIC_00939468_25d8_533f_854e_4f20f36c51dc
template <> struct __declspec(uuid("00939468-25d8-533f-854e-4f20f36c51dc")) __declspec(novtable) IIterable<Windows::Media::MediaProperties::AudioEncodingProperties> : impl_IIterable<Windows::Media::MediaProperties::AudioEncodingProperties> {};
#endif

}

namespace Windows::Media::Effects {

template <typename D>
struct WINRT_EBO impl_IAudioCaptureEffectsManager
{
    event_token AudioCaptureEffectsChanged(const Windows::Foundation::TypedEventHandler<Windows::Media::Effects::AudioCaptureEffectsManager, Windows::IInspectable> & handler) const;
    using AudioCaptureEffectsChanged_revoker = event_revoker<IAudioCaptureEffectsManager>;
    AudioCaptureEffectsChanged_revoker AudioCaptureEffectsChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Media::Effects::AudioCaptureEffectsManager, Windows::IInspectable> & handler) const;
    void AudioCaptureEffectsChanged(event_token token) const;
    Windows::Foundation::Collections::IVectorView<Windows::Media::Effects::AudioEffect> GetAudioCaptureEffects() const;
};

template <typename D>
struct WINRT_EBO impl_IAudioEffect
{
    Windows::Media::Effects::AudioEffectType AudioEffectType() const;
};

template <typename D>
struct WINRT_EBO impl_IAudioEffectDefinition
{
    hstring ActivatableClassId() const;
    Windows::Foundation::Collections::IPropertySet Properties() const;
};

template <typename D>
struct WINRT_EBO impl_IAudioEffectDefinitionFactory
{
    Windows::Media::Effects::AudioEffectDefinition Create(hstring_ref activatableClassId) const;
    Windows::Media::Effects::AudioEffectDefinition CreateWithProperties(hstring_ref activatableClassId, const Windows::Foundation::Collections::IPropertySet & props) const;
};

template <typename D>
struct WINRT_EBO impl_IAudioEffectsManagerStatics
{
    Windows::Media::Effects::AudioRenderEffectsManager CreateAudioRenderEffectsManager(hstring_ref deviceId, Windows::Media::Render::AudioRenderCategory category) const;
    Windows::Media::Effects::AudioRenderEffectsManager CreateAudioRenderEffectsManager(hstring_ref deviceId, Windows::Media::Render::AudioRenderCategory category, Windows::Media::AudioProcessing mode) const;
    Windows::Media::Effects::AudioCaptureEffectsManager CreateAudioCaptureEffectsManager(hstring_ref deviceId, Windows::Media::Capture::MediaCategory category) const;
    Windows::Media::Effects::AudioCaptureEffectsManager CreateAudioCaptureEffectsManager(hstring_ref deviceId, Windows::Media::Capture::MediaCategory category, Windows::Media::AudioProcessing mode) const;
};

template <typename D>
struct WINRT_EBO impl_IAudioRenderEffectsManager
{
    event_token AudioRenderEffectsChanged(const Windows::Foundation::TypedEventHandler<Windows::Media::Effects::AudioRenderEffectsManager, Windows::IInspectable> & handler) const;
    using AudioRenderEffectsChanged_revoker = event_revoker<IAudioRenderEffectsManager>;
    AudioRenderEffectsChanged_revoker AudioRenderEffectsChanged(auto_revoke_t, const Windows::Foundation::TypedEventHandler<Windows::Media::Effects::AudioRenderEffectsManager, Windows::IInspectable> & handler) const;
    void AudioRenderEffectsChanged(event_token token) const;
    Windows::Foundation::Collections::IVectorView<Windows::Media::Effects::AudioEffect> GetAudioRenderEffects() const;
};

template <typename D>
struct WINRT_EBO impl_IAudioRenderEffectsManager2
{
    Windows::Storage::Streams::IRandomAccessStreamWithContentType EffectsProviderThumbnail() const;
    hstring EffectsProviderSettingsLabel() const;
    void ShowSettingsUI() const;
};

template <typename D>
struct WINRT_EBO impl_IBasicAudioEffect
{
    bool UseInputFrameForOutput() const;
    Windows::Foundation::Collections::IVectorView<Windows::Media::MediaProperties::AudioEncodingProperties> SupportedEncodingProperties() const;
    void SetEncodingProperties(const Windows::Media::MediaProperties::AudioEncodingProperties & encodingProperties) const;
    void ProcessFrame(const Windows::Media::Effects::ProcessAudioFrameContext & context) const;
    void Close(Windows::Media::Effects::MediaEffectClosedReason reason) const;
    void DiscardQueuedFrames() const;
};

template <typename D>
struct WINRT_EBO impl_IBasicVideoEffect
{
    bool IsReadOnly() const;
    Windows::Media::Effects::MediaMemoryTypes SupportedMemoryTypes() const;
    bool TimeIndependent() const;
    Windows::Foundation::Collections::IVectorView<Windows::Media::MediaProperties::VideoEncodingProperties> SupportedEncodingProperties() const;
    void SetEncodingProperties(const Windows::Media::MediaProperties::VideoEncodingProperties & encodingProperties, const Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice & device) const;
    void ProcessFrame(const Windows::Media::Effects::ProcessVideoFrameContext & context) const;
    void Close(Windows::Media::Effects::MediaEffectClosedReason reason) const;
    void DiscardQueuedFrames() const;
};

template <typename D>
struct WINRT_EBO impl_ICompositeVideoFrameContext
{
    Windows::Foundation::Collections::IVectorView<Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface> SurfacesToOverlay() const;
    Windows::Media::VideoFrame BackgroundFrame() const;
    Windows::Media::VideoFrame OutputFrame() const;
    Windows::Media::Editing::MediaOverlay GetOverlayForSurface(const Windows::Graphics::DirectX::Direct3D11::IDirect3DSurface & surfaceToOverlay) const;
};

template <typename D>
struct WINRT_EBO impl_IProcessAudioFrameContext
{
    Windows::Media::AudioFrame InputFrame() const;
    Windows::Media::AudioFrame OutputFrame() const;
};

template <typename D>
struct WINRT_EBO impl_IProcessVideoFrameContext
{
    Windows::Media::VideoFrame InputFrame() const;
    Windows::Media::VideoFrame OutputFrame() const;
};

template <typename D>
struct WINRT_EBO impl_ISlowMotionEffectDefinition
{
    double TimeStretchRate() const;
    void TimeStretchRate(double value) const;
};

template <typename D>
struct WINRT_EBO impl_IVideoCompositor
{
    bool TimeIndependent() const;
    void SetEncodingProperties(const Windows::Media::MediaProperties::VideoEncodingProperties & backgroundProperties, const Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice & device) const;
    void CompositeFrame(const Windows::Media::Effects::CompositeVideoFrameContext & context) const;
    void Close(Windows::Media::Effects::MediaEffectClosedReason reason) const;
    void DiscardQueuedFrames() const;
};

template <typename D>
struct WINRT_EBO impl_IVideoCompositorDefinition
{
    hstring ActivatableClassId() const;
    Windows::Foundation::Collections::IPropertySet Properties() const;
};

template <typename D>
struct WINRT_EBO impl_IVideoCompositorDefinitionFactory
{
    Windows::Media::Effects::VideoCompositorDefinition Create(hstring_ref activatableClassId) const;
    Windows::Media::Effects::VideoCompositorDefinition CreateWithProperties(hstring_ref activatableClassId, const Windows::Foundation::Collections::IPropertySet & props) const;
};

template <typename D>
struct WINRT_EBO impl_IVideoEffectDefinition
{
    hstring ActivatableClassId() const;
    Windows::Foundation::Collections::IPropertySet Properties() const;
};

template <typename D>
struct WINRT_EBO impl_IVideoEffectDefinitionFactory
{
    Windows::Media::Effects::VideoEffectDefinition Create(hstring_ref activatableClassId) const;
    Windows::Media::Effects::VideoEffectDefinition CreateWithProperties(hstring_ref activatableClassId, const Windows::Foundation::Collections::IPropertySet & props) const;
};

template <typename D>
struct WINRT_EBO impl_IVideoTransformEffectDefinition
{
    Windows::UI::Color PaddingColor() const;
    void PaddingColor(const Windows::UI::Color & value) const;
    Windows::Foundation::Size OutputSize() const;
    void OutputSize(const Windows::Foundation::Size & value) const;
    Windows::Foundation::Rect CropRectangle() const;
    void CropRectangle(const Windows::Foundation::Rect & value) const;
    Windows::Media::MediaProperties::MediaRotation Rotation() const;
    void Rotation(Windows::Media::MediaProperties::MediaRotation value) const;
    Windows::Media::MediaProperties::MediaMirroringOptions Mirror() const;
    void Mirror(Windows::Media::MediaProperties::MediaMirroringOptions value) const;
    void ProcessingAlgorithm(Windows::Media::Transcoding::MediaVideoProcessingAlgorithm value) const;
    Windows::Media::Transcoding::MediaVideoProcessingAlgorithm ProcessingAlgorithm() const;
};

struct IAudioCaptureEffectsManager :
    Windows::IInspectable,
    impl::consume<IAudioCaptureEffectsManager>
{
    IAudioCaptureEffectsManager(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IAudioCaptureEffectsManager>(m_ptr); }
};

struct IAudioEffect :
    Windows::IInspectable,
    impl::consume<IAudioEffect>
{
    IAudioEffect(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IAudioEffect>(m_ptr); }
};

struct IAudioEffectDefinition :
    Windows::IInspectable,
    impl::consume<IAudioEffectDefinition>
{
    IAudioEffectDefinition(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IAudioEffectDefinition>(m_ptr); }
};

struct IAudioEffectDefinitionFactory :
    Windows::IInspectable,
    impl::consume<IAudioEffectDefinitionFactory>
{
    IAudioEffectDefinitionFactory(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IAudioEffectDefinitionFactory>(m_ptr); }
};

struct IAudioEffectsManagerStatics :
    Windows::IInspectable,
    impl::consume<IAudioEffectsManagerStatics>
{
    IAudioEffectsManagerStatics(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IAudioEffectsManagerStatics>(m_ptr); }
};

struct IAudioRenderEffectsManager :
    Windows::IInspectable,
    impl::consume<IAudioRenderEffectsManager>
{
    IAudioRenderEffectsManager(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IAudioRenderEffectsManager>(m_ptr); }
};

struct IAudioRenderEffectsManager2 :
    Windows::IInspectable,
    impl::consume<IAudioRenderEffectsManager2>
{
    IAudioRenderEffectsManager2(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IAudioRenderEffectsManager2>(m_ptr); }
};

struct IBasicAudioEffect :
    Windows::IInspectable,
    impl::consume<IBasicAudioEffect>,
    impl::require<IBasicAudioEffect, Windows::Media::IMediaExtension>
{
    IBasicAudioEffect(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IBasicAudioEffect>(m_ptr); }
};

struct IBasicVideoEffect :
    Windows::IInspectable,
    impl::consume<IBasicVideoEffect>,
    impl::require<IBasicVideoEffect, Windows::Media::IMediaExtension>
{
    IBasicVideoEffect(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IBasicVideoEffect>(m_ptr); }
};

struct ICompositeVideoFrameContext :
    Windows::IInspectable,
    impl::consume<ICompositeVideoFrameContext>
{
    ICompositeVideoFrameContext(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<ICompositeVideoFrameContext>(m_ptr); }
};

struct IProcessAudioFrameContext :
    Windows::IInspectable,
    impl::consume<IProcessAudioFrameContext>
{
    IProcessAudioFrameContext(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IProcessAudioFrameContext>(m_ptr); }
};

struct IProcessVideoFrameContext :
    Windows::IInspectable,
    impl::consume<IProcessVideoFrameContext>
{
    IProcessVideoFrameContext(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IProcessVideoFrameContext>(m_ptr); }
};

struct ISlowMotionEffectDefinition :
    Windows::IInspectable,
    impl::consume<ISlowMotionEffectDefinition>,
    impl::require<ISlowMotionEffectDefinition, Windows::Media::Effects::IVideoEffectDefinition>
{
    ISlowMotionEffectDefinition(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<ISlowMotionEffectDefinition>(m_ptr); }
};

struct IVideoCompositor :
    Windows::IInspectable,
    impl::consume<IVideoCompositor>,
    impl::require<IVideoCompositor, Windows::Media::IMediaExtension>
{
    IVideoCompositor(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IVideoCompositor>(m_ptr); }
};

struct IVideoCompositorDefinition :
    Windows::IInspectable,
    impl::consume<IVideoCompositorDefinition>
{
    IVideoCompositorDefinition(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IVideoCompositorDefinition>(m_ptr); }
};

struct IVideoCompositorDefinitionFactory :
    Windows::IInspectable,
    impl::consume<IVideoCompositorDefinitionFactory>
{
    IVideoCompositorDefinitionFactory(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IVideoCompositorDefinitionFactory>(m_ptr); }
};

struct IVideoEffectDefinition :
    Windows::IInspectable,
    impl::consume<IVideoEffectDefinition>
{
    IVideoEffectDefinition(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IVideoEffectDefinition>(m_ptr); }
};

struct IVideoEffectDefinitionFactory :
    Windows::IInspectable,
    impl::consume<IVideoEffectDefinitionFactory>
{
    IVideoEffectDefinitionFactory(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IVideoEffectDefinitionFactory>(m_ptr); }
};

struct IVideoTransformEffectDefinition :
    Windows::IInspectable,
    impl::consume<IVideoTransformEffectDefinition>,
    impl::require<IVideoTransformEffectDefinition, Windows::Media::Effects::IVideoEffectDefinition>
{
    IVideoTransformEffectDefinition(std::nullptr_t = nullptr) noexcept {}
    auto operator->() const noexcept { return ptr<IVideoTransformEffectDefinition>(m_ptr); }
};

}

}


text:
module.exports.setupBufferJS = function(target, internal) {
  module.exports.createBuffer = function(nettyBuffer) {
    var b = new target(nettyBuffer.readableBytes());
    io.nodyn.buffer.Buffer.inject( b, nettyBuffer );
    return b;
  }

  module.exports.extractBuffer = function(obj) {
    return io.nodyn.buffer.Buffer.extract(obj);
  }

  module.exports.extractByteArray = function(obj) {
    return io.nodyn.buffer.Buffer.extractByteArray(obj);
  }

  // ----------------------------------------
  // Prototype
  // ----------------------------------------

  // Slice

  target.prototype.asciiSlice = function(start, end) {
    return io.nodyn.buffer.Buffer.asciiSlice( this, start, end );
  };

  target.prototype.base64Slice = function(start, end) {
    return io.nodyn.buffer.Buffer.base64Slice( this, start, end);
  };

  target.prototype.binarySlice = function(start, end) {
    return io.nodyn.buffer.Buffer.binarySlice( this, start, end);
  };

  target.prototype.hexSlice = function(start, end) {
    return io.nodyn.buffer.Buffer.hexSlice( this, start, end );
  };

  target.prototype.ucs2Slice = function(start, end) {
    return io.nodyn.buffer.Buffer.ucs2Slice( this, start, end );
  };

  target.prototype.utf8Slice = function(start, end) {
    return io.nodyn.buffer.Buffer.utf8Slice( this, start, end )
  };

  // Write

  target.prototype.asciiWrite = function(str, offset, len) {
    offset = offset || 0;
    len    = len    || this.length;
    var l = io.nodyn.buffer.Buffer.asciiWrite( this, start, end );
    Buffer._charsWritten = l;
    return l;
  };

  target.prototype.base64Write = function(str, offset, len) {
    offset = offset || 0;
    len    = len    || this.length;
    var l = io.nodyn.buffer.Buffer.base64Write( this, str, offset, len );
    Buffer._charsWritten = len;
    return l;
  };

  target.prototype.binaryWrite = function(str, offset, len) {
    offset = offset || 0;
    len    = len    || this.length;
    var l = io.nodyn.buffer.Buffer.binaryWrite( this, str, offset, len );
    Buffer._charsWritten = l;
    return l;
  };

  target.prototype.hexWrite = function(str, offset, len) {
    offset = offset || 0;
    len    = len    || this.length;
    var l = io.nodyn.buffer.Buffer.hexWrite( this, str, offset, len );
    Buffer._charsWritten = l * 2;
    return;
  };

  target.prototype.ucs2Write = function(str, offset, len) {
    offset = offset || 0;
    len    = len    || this.length;
    var l = io.nodyn.buffer.Buffer.ucs2Write( this, str, offset, len );
    Buffer._charsWritten = l / 2;
    return l;
  };

  target.prototype.utf8Write = function(str, offset, len) {
    offset = offset || 0;
    len    = len    || this.length;
    var l = io.nodyn.buffer.Buffer.utf8Write(this, str, offset, len);
    Buffer._charsWritten = l[0];
    return l[1];
  };

  target.prototype.readDoubleBE = function(offset, noAssert) {
    return io.nodyn.buffer.Buffer.readDoubleBE( this, offset );
  };

  target.prototype.readDoubleLE = function(offset, noAssert) {
    return io.nodyn.buffer.Buffer.readDoubleLE( this, offset );
  };

  target.prototype.readFloatBE = function(offset, noAssert) {
    return io.nodyn.buffer.Buffer.readFloatBE( this, offset );
  };

  target.prototype.readFloatLE = function(offset, noAssert) {
    return io.nodyn.buffer.Buffer.readFloatLE( this, offset );
  };

  target.prototype.writeDoubleBE = function(value, offset, noAssert) {
    return io.nodyn.buffer.Buffer.writeDoubleBE( this, value, offset );
  };

  target.prototype.writeDoubleLE = function(value, offset, noAssert) {
    return io.nodyn.buffer.Buffer.writeDoubleLE( this, value, offset );
  };

  target.prototype.writeFloatBE = function(value, offset, noAssert) {
    return io.nodyn.buffer.Buffer.writeFloatBE( this, value, offset );
  };

  target.prototype.writeFloatLE = function(value, offset, noAssert) {
    return io.nodyn.buffer.Buffer.writeFloatLE( this, value, offset );
  };

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

  target.prototype._nettyBuffer = function() {
    return module.exports.extractBuffer(this);
  }

  target.prototype._byteArray = function() {
    return module.exports.extractByteArray(this);
  }

  // TODO: remove this
  target.prototype._vertxBuffer = function() {
    return new org.vertx.java.core.buffer.Buffer( this._nettyBuffer() );
  }

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

  target.prototype.copy = function(target, targetStart, sourceStart, sourceEnd) {
    targetStart = targetStart || 0;
    sourceStart = sourceStart || 0;
    sourceEnd   = sourceEnd   || this.length;

    if ( targetStart >= target.length ) {
      throw new RangeError( "targetStart out of bounds" );
    }

    return io.nodyn.buffer.Buffer.copy( this, target, targetStart, sourceStart, sourceEnd );
  };

  target.prototype.fill = function(value, offset, end) {
    offset = offset || 0;
    end    = end || this.length;

    if ( end > this.length ) {
      throw new RangeError( "end out of bounds" );
    }
    return io.nodyn.buffer.Buffer.fill( this, value, offset, end );
  };

  // ----------------------------------------
  // Internal
  // ----------------------------------------

  internal.compare = function(a,b) {

  };

  internal.byteLength = io.nodyn.buffer.Internal.byteLength;
}


text: Miscellaneous classes, implementations with gradle and jmh set up


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:text="Update Text"
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
namespace content {

MockNativeFileSystemPermissionContext::MockNativeFileSystemPermissionContext() =
    default;
MockNativeFileSystemPermissionContext::
    ~MockNativeFileSystemPermissionContext() = default;

void MockNativeFileSystemPermissionContext::ConfirmDirectoryReadAccess(
    const url::Origin& origin,
    const base::FilePath& path,
    int process_id,
    int frame_id,
    base::OnceCallback<void(PermissionStatus)> callback) {
  ConfirmDirectoryReadAccess_(origin, path, process_id, frame_id, callback);
}

void MockNativeFileSystemPermissionContext::ConfirmSensitiveDirectoryAccess(
    const url::Origin& origin,
    const std::vector<base::FilePath>& paths,
    bool is_directory,
    int process_id,
    int frame_id,
    base::OnceCallback<void(SensitiveDirectoryResult)> callback) {
  ConfirmSensitiveDirectoryAccess_(origin, paths, is_directory, process_id,
                                   frame_id, callback);
}

void MockNativeFileSystemPermissionContext::PerformAfterWriteChecks(
    std::unique_ptr<NativeFileSystemWriteItem> item,
    int process_id,
    int frame_id,
    base::OnceCallback<void(AfterWriteCheckResult)> callback) {
  PerformAfterWriteChecks_(item.get(), process_id, frame_id, callback);
}

}  // namespace content


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Schema = mongoose.Schema;

/**
 * Customer Schema
 */
var CustomerSchema = new Schema({
	name: {
		type: String,
		default: '',
		required: 'Please fill Customer name',
		trim: true
	},
	email: {
		type: String,
		default: '',
		required: 'Please fill email',
		trim: true
	},
	created: {
		type: Date,
		default: Date.now
	},
	user: {
		type: Schema.ObjectId,
		ref: 'User'
	},
	tenantid:{
		type:Number,
		required:true,
		ref:'Tenant'
	}
});

mongoose.model('Customer', CustomerSchema);


text:
import express from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import session from 'express-session';
import cors from 'cors';
import passport from 'passport';
import routes from './routes';
import connectMongo from './databases/connectMongo';

// MongoDB Setup
connectMongo();

// Express App setup
const app = express();

// Middleware for logging
app.use(morgan('combined'));

// Middleware parses incoming requests into JSON
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ type: '*/*' }));

// Express session middleware
app.use(session({
  secret: 'this is a secret',
  resave: true,
  saveUninitialized: true
}));

// Passport Setup
app.use(passport.initialize());
app.use(passport.session());

// CORS Middleware for handling requests coming from different IPs/ports
app.use(cors());

// Pass in our app to make it available to all routes
routes(app);

export default app;


text:
//============================================================================
// voronoi_site_polyline.h
//============================================================================

#ifndef _VORONOIPOLYLINESITE_
#define _VORONOIPOLYLINESITE_

#include "voronoi_site.h"

class VoronoiPolylineSite : public VoronoiSite
{
  public:

    float *Pts;   // POINTERS TO LOCATION OF SITE COORDINATES
    int NumPts;

    float dist_mesh_color[4];

    VoronoiPolylineSite(float *pts, int numpts);
    void DrawDistMesh(const float SiteRadius, const float SiteMaxAng, const int OutsideOnly=0);
    void DrawSite();
    void CalcMinMax(float *MinX, float *MinY, float *MaxX, float *MaxY);
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace LiteMVVMForms
{
    public class Navigator : INavigator
    {
        private readonly INavigation _navigation;
        public Navigator(INavigation navigation)
        {
            _navigation = navigation;
        }

        public INavigation Navigation { get { return _navigation; } }

        #region Navigation

        public virtual async Task<IViewModel> PopAsync()
        {
            Page view = await Navigation.PopAsync();
            return view.BindingContext as IViewModel;
        }

        public async Task<IViewModel> PopModalAsync()
        {
            Page view = await Navigation.PopModalAsync();
            return view.BindingContext as IViewModel;
        }

        public async Task PopToRootAsync()
        {
            await Navigation.PopToRootAsync();
        }

        public async Task<TViewModel> PushAsync<TViewModel>(TViewModel viewModel) where TViewModel : class, IViewModel
        {
            var view = ViewFactory.Resolve<TViewModel>(viewModel);
            await Navigation.PushAsync(view);
            return viewModel;
        }

        public async Task<TViewModel> PushAsync<TViewModel>() where TViewModel : class, IViewModel
        {
            var vm = Activator.CreateInstance(typeof(TViewModel));
            return await PushAsync<TViewModel>(vm as TViewModel);
        }

        public async Task<TViewModel> PushModalAsync<TViewModel>(TViewModel viewModel) where TViewModel : class, IViewModel
        {
            var view = ViewFactory.Resolve<TViewModel>(viewModel);
            await Navigation.PushModalAsync(view);
            return viewModel;
        }

        public async Task<TViewModel> PushModalAsync<TViewModel>() where TViewModel : class, IViewModel
        {
            var vm = Activator.CreateInstance(typeof(TViewModel));
            return await PushModalAsync<TViewModel>(vm as TViewModel);
        }

        #endregion

        #region Display Alerts

        public Task DisplayAlert(string title, string message, string okbutton)
        {
            return Application.Current.MainPage?.DisplayAlert(title, message, okbutton);
        }

        public Task<bool> DisplayAlert(string title, string message, string okbutton, string cancelbutton)
        {
            return Application.Current.MainPage?.DisplayAlert(title, message, okbutton, cancelbutton);
        }

        public Task<string> DisplayActionSheet(string title, string cancel, string desctruction, string[] buttons)
        {
            return Application.Current.MainPage?.DisplayActionSheet(title, cancel, desctruction, buttons);
        }

        #endregion

    }
}


text:
import { resolve } from 'quiver-promise'

import {
  simpleToStreamHandler,
  streamToSimpleHandler,
  validateSimpleTypes
} from 'quiver-simple-handler'

import { simpleHandlerLoader } from './util/loader'
import { safeBuilder, safeHandler } from './util/wrap'
import { StreamHandler, StreamHandlerBuilder } from './stream-handler'

const _inType = Symbol('inputType')
const _outType = Symbol('outputType')
const _simpleHandler = Symbol('_simpleHandler')
const _simpleHandlerBuilder = Symbol('_simpleHandlerBuilder')

export class SimpleHandlerBuilder extends StreamHandlerBuilder {
  constructor(simpleHandlerBuilder, inType, outType, options={}) {
    super(null, options)

    this[_inType] = inType
    this[_outType] = outType
    this[_simpleHandlerBuilder] = simpleHandlerBuilder
  }

  toStreamHandlerBuilder() {
    const { inType, outType } = this

    const simpleHandlerBuilder = this.toSimpleHandlerBuilder()

    return config =>
      simpleHandlerBuilder(config)
      .then(simpleHandler =>
        simpleToStreamHandler(simpleHandler, inType, outType))
  }

  toSimpleHandlerBuilder() {
    const {
      [_inType]: inputType,
      [_outType]: outputType
    } = this

    const err = validateSimpleTypes([inputType, outputType])
    if(err) throw err

    return safeBuilder(this[_simpleHandlerBuilder])
  }

  get defaultLoader() {
    return simpleHandlerLoader(this[_inType], this[_outType])
  }

  get inType() {
    return this[_inType]
  }

  get outType() {
    return this[_outType]
  }

  inputType(inType) {
    if(this[_inType]) {
      throw new Error('simple input type is already defined as ' + this[_inType])
    }

    const err = validateSimpleTypes([inType])
    if(err) throw err

    this[_inType] = inType
    return this
  }

  outputType(outType) {
    if(this[_outType]) {
      throw new Error('simple input type is already defined as ' + this[outType])
    }

    const err = validateSimpleTypes([outType])
    if(err) throw err

    this[_outType] = outType
    return this
  }

  get componentType() {
    return 'SimpleHandlerBuilder'
  }
}

export class SimpleHandler extends SimpleHandlerBuilder {
  constructor(simpleHandler, inType, outType, options={}) {
    super(null, inType, outType, options)
    this[_simpleHandler] = simpleHandler
  }

  toSimpleHandlerBuilder() {
    const simpleHandler = this.toSimpleHandler()

    return config =>
      resolve(simpleHandler)
  }

  toSimpleHandler() {
    return safeHandler(this[_simpleHandler])
  }

  get componentType() {
    return 'SimpleHandler'
  }
}

export const simpleHandlerBuilder = (builder, inType, outType, options) =>
  new SimpleHandlerBuilder(builder, inType, outType, options)

export const simpleHandler = (handler, inType, outType, options) =>
  new SimpleHandler(handler, inType, outType, options)


text:
package route_test

import (
	"os"
	"reflect"
	"testing"
	"time"

	envoyroute "github.com/envoyproxy/go-control-plane/envoy/api/v2/route"
	"github.com/golang/protobuf/ptypes"
	"github.com/onsi/gomega"

	networking "istio.io/api/networking/v1alpha3"

	"istio.io/istio/pilot/pkg/features"
	"istio.io/istio/pilot/pkg/model"
	"istio.io/istio/pilot/pkg/networking/core/v1alpha3/route"
	"istio.io/istio/pkg/config/host"
	"istio.io/istio/pkg/config/mesh"
	"istio.io/istio/pkg/config/protocol"
	"istio.io/istio/pkg/config/schemas"
)

func TestBuildHTTPRoutes(t *testing.T) {
	serviceRegistry := map[host.Name]*model.Service{
		"*.example.org": {
			Hostname:    "*.example.org",
			Address:     "1.1.1.1",
			ClusterVIPs: make(map[string]string),
			Ports: model.PortList{
				&model.Port{
					Name:     "default",
					Port:     8080,
					Protocol: protocol.HTTP,
				},
			},
		},
	}

	node := &model.Proxy{
		Type:         model.SidecarProxy,
		IPAddresses:  []string{"1.1.1.1"},
		ID:           "someID",
		DNSDomain:    "foo.com",
		Metadata:     &model.NodeMetadata{IstioVersion: "1.3.0"},
		IstioVersion: &model.IstioVersion{Major: 1, Minor: 3},
	}
	gatewayNames := map[string]bool{"some-gateway": true}

	t.Run("for virtual service", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		routes, err := route.BuildHTTPRoutesForVirtualService(node, nil, virtualServicePlain, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))
	})

	t.Run("for virtual service with regex matching on URI", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		routes, err := route.BuildHTTPRoutesForVirtualService(node, nil, virtualServiceWithRegexMatchingOnURI, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))
		g.Expect(routes[0].GetMatch().GetSafeRegex().GetRegex()).To(gomega.Equal("\\/(.?)\\/status"))
	})

	t.Run("for virtual service with unsafe regex matching on URI", func(t *testing.T) {
		os.Setenv(features.EnableUnsafeRegex.Name, "true")
		defer os.Unsetenv(features.EnableUnsafeRegex.Name)
		g := gomega.NewGomegaWithT(t)

		routes, err := route.BuildHTTPRoutesForVirtualService(node, nil, virtualServiceWithRegexMatchingOnURI, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))
		//nolint: staticcheck
		g.Expect(routes[0].GetMatch().GetRegex()).To(gomega.Equal("\\/(.?)\\/status"))
	})

	t.Run("for virtual service with regex matching on header", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		routes, err := route.BuildHTTPRoutesForVirtualService(node, nil, virtualServiceWithRegexMatchingOnHeader, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))
		g.Expect(routes[0].GetMatch().GetHeaders()[0].GetSafeRegexMatch().GetRegex()).To(gomega.Equal("Bearer .+?\\..+?\\..+?"))
	})

	t.Run("for virtual service with unsafe regex matching on header", func(t *testing.T) {
		os.Setenv(features.EnableUnsafeRegex.Name, "true")
		defer os.Unsetenv(features.EnableUnsafeRegex.Name)
		g := gomega.NewGomegaWithT(t)

		routes, err := route.BuildHTTPRoutesForVirtualService(node, nil, virtualServiceWithRegexMatchingOnHeader, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))
		//nolint: staticcheck
		g.Expect(routes[0].GetMatch().GetHeaders()[0].GetRegexMatch()).To(gomega.Equal("Bearer .+?\\..+?\\..+?"))
	})

	t.Run("for virtual service with ring hash", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		ttl := time.Nanosecond * 100
		meshConfig := mesh.DefaultMeshConfig()
		push := &model.PushContext{
			Env: &model.Environment{
				Mesh: &meshConfig,
			},
		}
		push.SetDestinationRules([]model.Config{
			{
				ConfigMeta: model.ConfigMeta{
					Type:    schemas.DestinationRule.Type,
					Version: schemas.DestinationRule.Version,
					Name:    "acme",
				},
				Spec: &networking.DestinationRule{
					Host: "*.example.org",
					TrafficPolicy: &networking.TrafficPolicy{
						LoadBalancer: &networking.LoadBalancerSettings{
							LbPolicy: &networking.LoadBalancerSettings_ConsistentHash{
								ConsistentHash: &networking.LoadBalancerSettings_ConsistentHashLB{
									HashKey: &networking.LoadBalancerSettings_ConsistentHashLB_HttpCookie{
										HttpCookie: &networking.LoadBalancerSettings_ConsistentHashLB_HTTPCookie{
											Name: "hash-cookie",
											Ttl:  &ttl,
										},
									},
								},
							},
						},
					},
				},
			},
		})

		routes, err := route.BuildHTTPRoutesForVirtualService(node, push, virtualServicePlain, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))

		hashPolicy := &envoyroute.RouteAction_HashPolicy{
			PolicySpecifier: &envoyroute.RouteAction_HashPolicy_Cookie_{
				Cookie: &envoyroute.RouteAction_HashPolicy_Cookie{
					Name: "hash-cookie",
					Ttl:  ptypes.DurationProto(ttl),
				},
			},
		}
		g.Expect(routes[0].GetRoute().GetHashPolicy()).To(gomega.ConsistOf(hashPolicy))
	})

	t.Run("for virtual service with subsets with ring hash", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		virtualService := model.Config{
			ConfigMeta: model.ConfigMeta{
				Type:    schemas.VirtualService.Type,
				Version: schemas.VirtualService.Version,
				Name:    "acme",
			},
			Spec: virtualServiceWithSubset,
		}

		meshConfig := mesh.DefaultMeshConfig()
		push := &model.PushContext{
			Env: &model.Environment{
				Mesh: &meshConfig,
			},
		}
		push.SetDestinationRules([]model.Config{
			{
				ConfigMeta: model.ConfigMeta{
					Type:    schemas.DestinationRule.Type,
					Version: schemas.DestinationRule.Version,
					Name:    "acme",
				},
				Spec: &networking.DestinationRule{
					Host:    "*.example.org",
					Subsets: []*networking.Subset{networkingSubset},
				},
			},
		})

		routes, err := route.BuildHTTPRoutesForVirtualService(node, push, virtualService, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))

		hashPolicy := &envoyroute.RouteAction_HashPolicy{
			PolicySpecifier: &envoyroute.RouteAction_HashPolicy_Cookie_{
				Cookie: &envoyroute.RouteAction_HashPolicy_Cookie{
					Name: "other-cookie",
					Ttl:  nil,
				},
			},
		}
		g.Expect(routes[0].GetRoute().GetHashPolicy()).To(gomega.ConsistOf(hashPolicy))
	})

	t.Run("for virtual service with subsets with port level settings with ring hash", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		virtualService := model.Config{ConfigMeta: model.ConfigMeta{Type: schemas.VirtualService.Type,
			Version: schemas.VirtualService.Version,
			Name:    "acme",
		},
			Spec: virtualServiceWithSubsetWithPortLevelSettings,
		}

		meshConfig := mesh.DefaultMeshConfig()
		push := &model.PushContext{
			Env: &model.Environment{
				Mesh: &meshConfig,
			},
		}

		push.SetDestinationRules([]model.Config{
			{

				ConfigMeta: model.ConfigMeta{
					Type:    schemas.DestinationRule.Type,
					Version: schemas.DestinationRule.Version,
					Name:    "acme",
				},
				Spec: portLevelDestinationRuleWithSubsetPolicy,
			}})

		routes, err := route.BuildHTTPRoutesForVirtualService(node, push, virtualService, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))

		hashPolicy := &envoyroute.RouteAction_HashPolicy{
			PolicySpecifier: &envoyroute.RouteAction_HashPolicy_Cookie_{
				Cookie: &envoyroute.RouteAction_HashPolicy_Cookie{
					Name: "port-level-settings-cookie",
					Ttl:  nil,
				},
			},
		}
		g.Expect(routes[0].GetRoute().GetHashPolicy()).To(gomega.ConsistOf(hashPolicy))
	})

	t.Run("for virtual service with subsets and top level traffic policy with ring hash", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		virtualService := model.Config{
			ConfigMeta: model.ConfigMeta{
				Type:    schemas.VirtualService.Type,
				Version: schemas.VirtualService.Version,
				Name:    "acme",
			},
			Spec: virtualServiceWithSubset,
		}

		cnfg := model.Config{
			ConfigMeta: model.ConfigMeta{
				Type:    schemas.DestinationRule.Type,
				Version: schemas.DestinationRule.Version,
				Name:    "acme",
			},
		}
		rule := networkingDestinationRule
		rule.Subsets = []*networking.Subset{networkingSubset}
		cnfg.Spec = networkingDestinationRule

		meshConfig := mesh.DefaultMeshConfig()
		push := &model.PushContext{
			Env: &model.Environment{
				Mesh: &meshConfig,
			},
		}

		push.SetDestinationRules([]model.Config{
			cnfg})

		routes, err := route.BuildHTTPRoutesForVirtualService(node, push, virtualService, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))

		hashPolicy := &envoyroute.RouteAction_HashPolicy{
			PolicySpecifier: &envoyroute.RouteAction_HashPolicy_Cookie_{
				Cookie: &envoyroute.RouteAction_HashPolicy_Cookie{
					Name: "other-cookie",
					Ttl:  nil,
				},
			},
		}
		g.Expect(routes[0].GetRoute().GetHashPolicy()).To(gomega.ConsistOf(hashPolicy))
	})

	t.Run("port selector based traffic policy", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		meshConfig := mesh.DefaultMeshConfig()
		push := &model.PushContext{
			Env: &model.Environment{
				Mesh: &meshConfig,
			},
		}

		push.SetDestinationRules([]model.Config{
			{
				ConfigMeta: model.ConfigMeta{
					Type:    schemas.DestinationRule.Type,
					Version: schemas.DestinationRule.Version,
					Name:    "acme",
				},
				Spec: portLevelDestinationRule,
			}})

		gatewayNames := map[string]bool{"some-gateway": true}
		routes, err := route.BuildHTTPRoutesForVirtualService(node, push, virtualServicePlain, serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))

		hashPolicy := &envoyroute.RouteAction_HashPolicy{
			PolicySpecifier: &envoyroute.RouteAction_HashPolicy_Cookie_{
				Cookie: &envoyroute.RouteAction_HashPolicy_Cookie{
					Name: "hash-cookie",
					Ttl:  nil,
				},
			},
		}
		g.Expect(routes[0].GetRoute().GetHashPolicy()).To(gomega.ConsistOf(hashPolicy))
	})

	t.Run("for redirect code", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)

		routes, err := route.BuildHTTPRoutesForVirtualService(node, nil, virtualServiceWithRedirect,
			serviceRegistry, 8080, gatewayNames)
		g.Expect(err).NotTo(gomega.HaveOccurred())
		g.Expect(len(routes)).To(gomega.Equal(1))

		redirectAction, ok := routes[0].Action.(*envoyroute.Route_Redirect)
		g.Expect(ok).NotTo(gomega.BeFalse())
		g.Expect(redirectAction.Redirect.ResponseCode).To(gomega.Equal(envoyroute.RedirectAction_PERMANENT_REDIRECT))
	})
	t.Run("for no virtualservice but has destinationrule with consistentHash loadbalancer", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)
		meshConfig := mesh.DefaultMeshConfig()
		push := &model.PushContext{
			Env: &model.Environment{
				Mesh: &meshConfig,
			},
		}
		push.SetDestinationRules([]model.Config{
			{
				ConfigMeta: model.ConfigMeta{
					Type:    schemas.DestinationRule.Type,
					Version: schemas.DestinationRule.Version,
					Name:    "acme",
				},
				Spec: networkingDestinationRule,
			}})
		vhosts := route.BuildSidecarVirtualHostsFromConfigAndRegistry(node, push, serviceRegistry, []model.Config{}, 8080)
		g.Expect(vhosts[0].Routes[0].Action.(*envoyroute.Route_Route).Route.HashPolicy).NotTo(gomega.BeNil())
	})
	t.Run("for no virtualservice but has destinationrule with portLevel consistentHash loadbalancer", func(t *testing.T) {
		g := gomega.NewGomegaWithT(t)
		meshConfig := mesh.DefaultMeshConfig()
		push := &model.PushContext{
			Env: &model.Environment{
				Mesh: &meshConfig,
			},
		}
		push.SetDestinationRules([]model.Config{
			{
				ConfigMeta: model.ConfigMeta{
					Type:    schemas.DestinationRule.Type,
					Version: schemas.DestinationRule.Version,
					Name:    "acme",
				},
				Spec: networkingDestinationRuleWithPortLevelTrafficPolicy,
			}})

		vhosts := route.BuildSidecarVirtualHostsFromConfigAndRegistry(node, push, serviceRegistry, []model.Config{}, 8080)

		hashPolicy := &envoyroute.RouteAction_HashPolicy{
			PolicySpecifier: &envoyroute.RouteAction_HashPolicy_Cookie_{
				Cookie: &envoyroute.RouteAction_HashPolicy_Cookie{
					Name: "hash-cookie-1",
				},
			},
		}
		g.Expect(vhosts[0].Routes[0].Action.(*envoyroute.Route_Route).Route.HashPolicy).To(gomega.ConsistOf(hashPolicy))
	})
}

func loadBalancerPolicy(name string) *networking.LoadBalancerSettings_ConsistentHash {
	return &networking.LoadBalancerSettings_ConsistentHash{
		ConsistentHash: &networking.LoadBalancerSettings_ConsistentHashLB{
			HashKey: &networking.LoadBalancerSettings_ConsistentHashLB_HttpCookie{
				HttpCookie: &networking.LoadBalancerSettings_ConsistentHashLB_HTTPCookie{
					Name: name,
				},
			},
		},
	}
}

var virtualServiceWithSubset = &networking.VirtualService{
	Hosts:    []string{},
	Gateways: []string{"some-gateway"},
	Http: []*networking.HTTPRoute{
		{
			Route: []*networking.HTTPRouteDestination{
				{
					Destination: &networking.Destination{
						Subset: "some-subset",
						Host:   "*.example.org",
						Port: &networking.PortSelector{
							Number: 65000,
						},
					},
					Weight: 100,
				},
			},
		},
	},
}

var virtualServiceWithSubsetWithPortLevelSettings = &networking.VirtualService{
	Hosts:    []string{},
	Gateways: []string{"some-gateway"},
	Http: []*networking.HTTPRoute{
		{
			Route: []*networking.HTTPRouteDestination{
				{
					Destination: &networking.Destination{
						Subset: "port-level-settings-subset",
						Host:   "*.example.org",
						Port: &networking.PortSelector{
							Number: 8484,
						},
					},
					Weight: 100,
				},
			},
		},
	},
}

var virtualServicePlain = model.Config{
	ConfigMeta: model.ConfigMeta{
		Type:    schemas.VirtualService.Type,
		Version: schemas.VirtualService.Version,
		Name:    "acme",
	},
	Spec: &networking.VirtualService{
		Hosts:    []string{},
		Gateways: []string{"some-gateway"},
		Http: []*networking.HTTPRoute{
			{
				Route: []*networking.HTTPRouteDestination{
					{
						Destination: &networking.Destination{
							Host: "*.example.org",
							Port: &networking.PortSelector{
								Number: 8484,
							},
						},
						Weight: 100,
					},
				},
			},
		},
	},
}

var virtualServiceWithRedirect = model.Config{
	ConfigMeta: model.ConfigMeta{
		Type:    schemas.VirtualService.Type,
		Version: schemas.VirtualService.Version,
		Name:    "acme",
	},
	Spec: &networking.VirtualService{
		Hosts:    []string{},
		Gateways: []string{"some-gateway"},
		Http: []*networking.HTTPRoute{
			{
				Redirect: &networking.HTTPRedirect{
					Uri:          "example.org",
					Authority:    "some-authority.default.svc.cluster.local",
					RedirectCode: 308,
				},
			},
		},
	},
}

var virtualServiceWithRegexMatchingOnURI = model.Config{
	ConfigMeta: model.ConfigMeta{
		Type:    schemas.VirtualService.Type,
		Version: schemas.VirtualService.Version,
		Name:    "acme",
	},
	Spec: &networking.VirtualService{
		Hosts:    []string{},
		Gateways: []string{"some-gateway"},
		Http: []*networking.HTTPRoute{
			{
				Match: []*networking.HTTPMatchRequest{
					{
						Name: "status",
						Uri: &networking.StringMatch{
							MatchType: &networking.StringMatch_Regex{
								Regex: "\\/(.?)\\/status",
							},
						},
					},
				},
				Redirect: &networking.HTTPRedirect{
					Uri:          "example.org",
					Authority:    "some-authority.default.svc.cluster.local",
					RedirectCode: 308,
				},
			},
		},
	},
}

var virtualServiceWithRegexMatchingOnHeader = model.Config{
	ConfigMeta: model.ConfigMeta{
		Type:    schemas.VirtualService.Type,
		Version: schemas.VirtualService.Version,
		Name:    "acme",
	},
	Spec: &networking.VirtualService{
		Hosts:    []string{},
		Gateways: []string{"some-gateway"},
		Http: []*networking.HTTPRoute{
			{
				Match: []*networking.HTTPMatchRequest{
					{
						Name: "auth",
						Headers: map[string]*networking.StringMatch{
							"Authentication": {
								MatchType: &networking.StringMatch_Regex{
									Regex: "Bearer .+?\\..+?\\..+?",
								},
							},
						},
					},
				},
				Redirect: &networking.HTTPRedirect{
					Uri:          "example.org",
					Authority:    "some-authority.default.svc.cluster.local",
					RedirectCode: 308,
				},
			},
		},
	},
}

var portLevelDestinationRule = &networking.DestinationRule{
	Host:    "*.example.org",
	Subsets: []*networking.Subset{},
	TrafficPolicy: &networking.TrafficPolicy{
		PortLevelSettings: []*networking.TrafficPolicy_PortTrafficPolicy{
			{
				LoadBalancer: &networking.LoadBalancerSettings{
					LbPolicy: loadBalancerPolicy("hash-cookie"),
				},
				Port: &networking.PortSelector{
					Number: 8484,
				},
			},
		},
	},
}

var portLevelDestinationRuleWithSubsetPolicy = &networking.DestinationRule{
	Host:    "*.example.org",
	Subsets: []*networking.Subset{networkingSubsetWithPortLevelSettings},
	TrafficPolicy: &networking.TrafficPolicy{
		PortLevelSettings: []*networking.TrafficPolicy_PortTrafficPolicy{
			{
				LoadBalancer: &networking.LoadBalancerSettings{
					LbPolicy: loadBalancerPolicy("hash-cookie"),
				},
				Port: &networking.PortSelector{
					Number: 8484,
				},
			},
		},
	},
}

var networkingDestinationRule = &networking.DestinationRule{
	Host:    "*.example.org",
	Subsets: []*networking.Subset{},
	TrafficPolicy: &networking.TrafficPolicy{
		LoadBalancer: &networking.LoadBalancerSettings{
			LbPolicy: loadBalancerPolicy("hash-cookie"),
		},
	},
}
var networkingDestinationRuleWithPortLevelTrafficPolicy = &networking.DestinationRule{
	Host: "*.example.org",
	TrafficPolicy: &networking.TrafficPolicy{
		LoadBalancer: &networking.LoadBalancerSettings{
			LbPolicy: loadBalancerPolicy("hash-cookie"),
		},
		PortLevelSettings: []*networking.TrafficPolicy_PortTrafficPolicy{
			{
				LoadBalancer: &networking.LoadBalancerSettings{
					LbPolicy: loadBalancerPolicy("hash-cookie-1"),
				},
				Port: &networking.PortSelector{
					Number: 8080,
				},
			},
		},
	},
}
var networkingSubset = &networking.Subset{
	Name:   "some-subset",
	Labels: map[string]string{},
	TrafficPolicy: &networking.TrafficPolicy{
		LoadBalancer: &networking.LoadBalancerSettings{
			LbPolicy: &networking.LoadBalancerSettings_ConsistentHash{
				ConsistentHash: &networking.LoadBalancerSettings_ConsistentHashLB{
					HashKey: &networking.LoadBalancerSettings_ConsistentHashLB_HttpCookie{
						HttpCookie: &networking.LoadBalancerSettings_ConsistentHashLB_HTTPCookie{
							Name: "other-cookie",
						},
					},
				},
			},
		},
	},
}

var networkingSubsetWithPortLevelSettings = &networking.Subset{
	Name:   "port-level-settings-subset",
	Labels: map[string]string{},
	TrafficPolicy: &networking.TrafficPolicy{
		PortLevelSettings: []*networking.TrafficPolicy_PortTrafficPolicy{
			{
				LoadBalancer: &networking.LoadBalancerSettings{
					LbPolicy: loadBalancerPolicy("port-level-settings-cookie"),
				},
				Port: &networking.PortSelector{
					Number: 8484,
				},
			},
		},
	},
}

func TestCombineVHostRoutes(t *testing.T) {
	first := []*envoyroute.Route{
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Path{Path: "/path1"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Prefix{Prefix: "/prefix1"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Regex{Regex: ".*?regex1"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Prefix{Prefix: "/"}}},
	}
	second := []*envoyroute.Route{
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Path{Path: "/path12"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Prefix{Prefix: "/prefix12"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Regex{Regex: ".*?regex12"}}},
		{Match: &envoyroute.RouteMatch{
			PathSpecifier: &envoyroute.RouteMatch_Regex{Regex: "*"},
			Headers: []*envoyroute.HeaderMatcher{
				{
					Name:                 "foo",
					HeaderMatchSpecifier: &envoyroute.HeaderMatcher_ExactMatch{ExactMatch: "bar"},
					InvertMatch:          false,
				},
			},
		}},
	}

	want := []*envoyroute.Route{
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Path{Path: "/path1"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Prefix{Prefix: "/prefix1"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Regex{Regex: ".*?regex1"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Path{Path: "/path12"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Prefix{Prefix: "/prefix12"}}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Regex{Regex: ".*?regex12"}}},
		{Match: &envoyroute.RouteMatch{
			PathSpecifier: &envoyroute.RouteMatch_Regex{Regex: "*"},
			Headers: []*envoyroute.HeaderMatcher{
				{
					Name:                 "foo",
					HeaderMatchSpecifier: &envoyroute.HeaderMatcher_ExactMatch{ExactMatch: "bar"},
					InvertMatch:          false,
				},
			},
		}},
		{Match: &envoyroute.RouteMatch{PathSpecifier: &envoyroute.RouteMatch_Prefix{Prefix: "/"}}},
	}

	got := route.CombineVHostRoutes(first, second)
	if !reflect.DeepEqual(want, got) {
		t.Errorf("CombineVHostRoutes: \n")
		t.Errorf("got: \n")
		for _, g := range got {
			t.Errorf("%v\n", g.Match.PathSpecifier)
		}
		t.Errorf("want: \n")
		for _, g := range want {
			t.Errorf("%v\n", g.Match.PathSpecifier)
		}
	}
}


text:
namespace Enmarcha.SharePoint.Helpers.Data
{
   public class FieldBase
    {
        public string Key { get; set; }
        public string Value { get; set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="VisualShaderNodeIntFunc" inherits="VisualShaderNode" version="4.0">
	<brief_description>
		A scalar integer function to be used within the visual shader graph.
	</brief_description>
	<description>
		Accept an integer scalar ([code]x[/code]) to the input port and transform it according to [member function].
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<members>
		<member name="function" type="int" setter="set_function" getter="get_function" enum="VisualShaderNodeIntFunc.Function" default="2">
			A function to be applied to the scalar. See [enum Function] for options.
		</member>
	</members>
	<constants>
		<constant name="FUNC_ABS" value="0" enum="Function">
			Returns the absolute value of the parameter. Translates to [code]abs(x)[/code] in the Godot Shader Language.
		</constant>
		<constant name="FUNC_NEGATE" value="1" enum="Function">
			Negates the [code]x[/code] using [code]-(x)[/code].
		</constant>
		<constant name="FUNC_SIGN" value="2" enum="Function">
			Extracts the sign of the parameter. Translates to [code]sign(x)[/code] in the Godot Shader Language.
		</constant>
	</constants>
</class>


text:
const Promise = require('bluebird'),
    ghostBookshelf = require('./base'),
    common = require('../lib/common');

let Subscriber,
    Subscribers;

Subscriber = ghostBookshelf.Model.extend({
    tableName: 'subscribers',

    emitChange: function emitChange(event, options) {
        const eventToTrigger = 'subscriber' + '.' + event;
        ghostBookshelf.Model.prototype.emitChange.bind(this)(this, eventToTrigger, options);
    },

    defaults: function defaults() {
        return {
            status: 'subscribed'
        };
    },

    onCreated: function onCreated(model, response, options) {
        model.emitChange('added', options);
    },

    onUpdated: function onUpdated(model, response, options) {
        model.emitChange('edited', options);
    },

    onDestroyed: function onDestroyed(model, options) {
        model.emitChange('deleted', options);
    }
}, {

    orderDefaultOptions: function orderDefaultOptions() {
        return {};
    },
    /**
     * @deprecated in favour of filter
     */
    processOptions: function processOptions(options) {
        return options;
    },

    permittedOptions: function permittedOptions(methodName) {
        var options = ghostBookshelf.Model.permittedOptions(),

            // whitelists for the `options` hash argument on methods, by method name.
            // these are the only options that can be passed to Bookshelf / Knex.
            validOptions = {
                findPage: ['page', 'limit', 'columns', 'filter', 'order'],
                findAll: ['columns']
            };

        if (validOptions[methodName]) {
            options = options.concat(validOptions[methodName]);
        }

        return options;
    },

    permissible: function permissible(postModelOrId, action, context, unsafeAttrs, loadedPermissions, hasUserPermission, hasAppPermission) {
        // CASE: external is only allowed to add and edit subscribers
        if (context.external) {
            if (['add', 'edit'].indexOf(action) !== -1) {
                return Promise.resolve();
            }
        }

        if (hasUserPermission && hasAppPermission) {
            return Promise.resolve();
        }

        return Promise.reject(new common.errors.NoPermissionError({message: common.i18n.t('errors.models.subscriber.notEnoughPermission')}));
    },

    // TODO: This is a copy paste of models/user.js!
    getByEmail: function getByEmail(email, unfilteredOptions) {
        var options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'getByEmail');
        options.require = true;

        return Subscribers.forge().fetch(options).then(function then(subscribers) {
            var subscriberWithEmail = subscribers.find(function findSubscriber(subscriber) {
                return subscriber.get('email').toLowerCase() === email.toLowerCase();
            });

            if (subscriberWithEmail) {
                return subscriberWithEmail;
            }
        }).catch(function (error) {
            if (error.message === 'NotFound' || error.message === 'EmptyResponse') {
                return Promise.resolve();
            }

            return Promise.reject(error);
        });
    }
});

Subscribers = ghostBookshelf.Collection.extend({
    model: Subscriber
});

module.exports = {
    Subscriber: ghostBookshelf.model('Subscriber', Subscriber),
    Subscribers: ghostBookshelf.collection('Subscriber', Subscribers)
};


text:
  Bénesse-lès-Dax est
       un village
       situé dans le département des Landes en Aquitaine. On dénombrait 496 habitants en 2008.

Le nombre d'habitations, à Bénesse-lès-Dax, se décomposait en 2011 en 23 appartements et 217 maisons soit
 un marché plutôt équilibré.

À coté de Bénesse-lès-Dax sont situées les villes de
Gaas située à 3 km, 450 habitants,
Saugnac-et-Cambran située à 4 km, 1 390 habitants,
Pouillon située à 5 km, 2 746 habitants,
Mimbaste située à 5 km, 1 011 habitants,
Tercis-les-Bains située à 6 km, 1 146 habitants,
Saint-Pandelon située à 3 km, 736 habitants,
 entre autres. De plus, Bénesse-lès-Dax est située à seulement sept km de Dax.

Si vous pensez demenager à Bénesse-lès-Dax, vous pourrez aisément trouver une maison à vendre.


text:
package org.apache.spark.sql.avro

import org.apache.avro.Schema
import org.apache.hadoop.mapreduce.TaskAttemptContext

import org.apache.spark.sql.execution.datasources.{OutputWriter, OutputWriterFactory}
import org.apache.spark.sql.types.StructType

/**
 * A factory that produces [[AvroOutputWriter]].
 * @param catalystSchema Catalyst schema of input data.
 * @param avroSchemaAsJsonString Avro schema of output result, in JSON string format.
 */
private[avro] class AvroOutputWriterFactory(
    catalystSchema: StructType,
    avroSchemaAsJsonString: String) extends OutputWriterFactory {

  private lazy val avroSchema = new Schema.Parser().parse(avroSchemaAsJsonString)

  override def getFileExtension(context: TaskAttemptContext): String = ".avro"

  override def newInstance(
      path: String,
      dataSchema: StructType,
      context: TaskAttemptContext): OutputWriter = {
    new AvroOutputWriter(path, context, catalystSchema, avroSchema)
  }
}


text:
import sys
sys.path.append("..")
from ParseTree import *

class BootstrapHTMLGenerator(HTMLGenerator):
    def __init__(self):
        self.cssRules = {}
        pass

    def Generate(self,htmlTree):
        self.generateCSSRules(htmlTree.rootBodyNode,"a")
        style = self.generateCSSStyle(self.cssRules)
        style = "" % style
        bootstrap = "<link href='http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css' rel='stylesheet'>" + ""
        body = "
%s
" % (htmlTree.rootBodyNode.boundingBox.width, htmlTree.rootBodyNode.boundingBox.height, str(htmlTree))
        html = "<!DOCTYPE html><title>A First Draft</title> %s %s %s" % (bootstrap,style,body)
        return html

    def generateCSSRules(self,node,node_id):
        node_id = node_id + "a"
        bbox = node.boundingBox
        rules = {}
        rules['position'] = 'absolute'
        rules['top'] = '%dpx' % bbox.offsetY
        rules['left'] = '%dpx' % bbox.offsetX
        rules['width'] = '%dpx' % bbox.width
        rules['height'] = '%dpx' % bbox.height
        self.cssRules[node_id] = rules
        node.tagAttributes = "id='%s'" % node_id
        node_id_counter = 0;
        for i,child in enumerate(node.children):
            self.generateCSSRules(child,node_id+chr(ord(node_id[-1])+node_id_counter))
            node_id_counter += 1

    def generateCSSStyle(self,rules):
        style = ""
        for nid, rl in rules.iteritems():
            style += "#%s { \n" % nid
            for prop, val in rl.iteritems():
                style += "%s: %s;\n" % (prop,val)
            style += "}\n\n"
        return style


text:
"""Utility module shared by the SDK unit tests."""

from __future__ import absolute_import
from utils.cmdopts import *
from splunklib import six

def config(option, opt, value, parser):
    assert opt == "--config"
    parser.load(value)

# Default Splunk cmdline rules
RULES_SPLUNK = {
    'config': {
        'flags': ["--config"],
        'action': "callback",
        'callback': config,
        'type': "string",
        'nargs': "1",
        'help': "Load options from config file"
    },
    'scheme': {
        'flags': ["--scheme"],
        'default': "https",
        'help': "Scheme (default 'https')",
    },
    'host': {
        'flags': ["--host"],
        'default': "localhost",
        'help': "Host name (default 'localhost')"
    },
    'port': {
        'flags': ["--port"],
        'default': "8089",
        'help': "Port number (default 8089)"
    },
    'app': {
        'flags': ["--app"],
        'help': "The app context (optional)"
    },
    'owner': {
        'flags': ["--owner"],
        'help': "The user context (optional)"
    },
    'username': {
        'flags': ["--username"],
        'default': None,
        'help': "Username to login with"
    },
    'password': {
        'flags': ["--password"],
        'default': None,
        'help': "Password to login with"
    },
    'version': {
        'flags': ["--version"],
        'default': None,
        'help': 'Ignore. Used by JavaScript SDK.'
    },
    'splunkToken': {
        'flags': ["--bearerToken"],
        'default': None,
        'help': 'Bearer token for authentication'
    },
    'token': {
        'flags': ["--sessionKey"],
        'default': None,
        'help': 'Session key for authentication'
    }
}

FLAGS_SPLUNK = list(RULES_SPLUNK.keys())

# value: dict, args: [(dict | list | str)*]
def dslice(value, *args):
    """Returns a 'slice' of the given dictionary value containing only the
       requested keys. The keys can be requested in a variety of ways, as an
       arg list of keys, as a list of keys, or as a dict whose key(s) represent
       the source keys and whose corresponding values represent the resulting
       key(s) (enabling key rename), or any combination of the above."""
    result = {}
    for arg in args:
        if isinstance(arg, dict):
            for k, v in six.iteritems(arg):
                if k in value:
                    result[v] = value[k]
        elif isinstance(arg, list):
            for k in arg:
                if k in value:
                    result[k] = value[k]
        else:
            if arg in value:
                result[arg] = value[arg]
    return result

def parse(argv, rules=None, config=None, **kwargs):
    """Parse the given arg vector with the default Splunk command rules."""
    parser_ = parser(rules, **kwargs)
    if config is not None:
        parser_.loadenv(config)
    return parser_.parse(argv).result

def parser(rules=None, **kwargs):
    """Instantiate a parser with the default Splunk command rules."""
    rules = RULES_SPLUNK if rules is None else dict(RULES_SPLUNK, **rules)
    return Parser(rules, **kwargs)


text:
package com.jinglingtec.ijiazu.util.SMS;

import java.util.Random;

/**
 * 生成验证码
 */
public class GenerateValidation
{

    public static String getValidation(int verifyCodeLen)
    {
        StringBuilder buffer = new StringBuilder();

        for (int i = 0; i < verifyCodeLen; i++)
        {
            Random r = new Random();
            buffer.append(r.nextInt(10));//[0,10)
        }

        return buffer.toString();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:osgi="http://www.springframework.org/schema/osgi"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                      http://www.springframework.org/schema/osgi http://www.springframework.org/schema/osgi/spring-osgi.xsd"
	default-lazy-init="false">

	<bean id="props" class="java.util.Properties" destroy-method="clear" scope="bundle"/>

	<osgi:service interface="java.util.Map" ref="props"/>

	<bean id="object" class="java.lang.Object" scope="prototype"/>
	<osgi:service auto-export="all-classes" ref="object"/>
</beans>


text:
class XMLHttp
{
    static get(url)
    {
        let xhr = new XMLHttpRequest();

        xhr.open('GET', url);
        xhr.onload = function ()
        {
            if (xhr.status === 200)
            {
                alert('User\'s name is ' + xhr.responseText);
            }

            if (xhr.status !== 200)
            {
                alert('Request failed.  Returned status of ' + xhr.status);
            }
         };
         xhr.send()
    }

    static post(url, contentType)
    {
        contentType = contentType || 'application/x-www-form-urlencoded';

        let newName = 'John Smith',
            xhr     = new XMLHttpRequest();

        xhr.open('POST', url);
        xhr.setRequestHeader('Content-Type', contentType);
        xhr.onload = function ()
        {
            if (xhr.status === 200 && xhr.responseText !== newName)
            {
                alert('Something went wrong.  Name is now ' + xhr.responseText);
            }

            if (xhr.status !== 200)
            {
                alert('Request failed.  Returned status of ' + xhr.status);
            }
        };
        xhr.send(encodeURI('name=' + newName));
    }

    /**
     * sends a request to the specified url from a form
     * this will change the window location
     *
     * @param {string} path the path to send the post request to
     * @param {object} params the parameters to add to the url
     * @param {string} [method=post] the method to use on the form
     */
    static submit(path, params, method)
    {
        // set method to post by default if not specified
        method = method || 'post';

        // the rest of this code assumes you are not using a library
        // it can be made less wordy if you use one
        let form = document.createElement('form');
            form.setAttribute('method', method);
            form.setAttribute('action', path);

        for(let key in params)
        {
            if(params.hasOwnProperty(key))
            {
                let hiddenField = document.createElement('input');
                    hiddenField.setAttribute('type', 'hidden');
                    hiddenField.setAttribute('name', key);
                    hiddenField.setAttribute('value', params[key]);

                form.appendChild(hiddenField);
            }
        }

        document.body.appendChild(form);
        form.submit();
    }
}


text:
package com.java110.api.listener.floor;

import com.alibaba.fastjson.JSONObject;
import com.java110.api.bmo.floorAttr.IFloorAttrBMO;
import com.java110.api.listener.AbstractServiceApiPlusListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.utils.constant.ServiceCodeFloorAttrConstant;
import com.java110.utils.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;

/**
 * 保存小区侦听
 * add by wuxw 2019-06-30
 */
@Java110Listener("deleteFloorAttrListener")
public class DeleteFloorAttrListener extends AbstractServiceApiPlusListener {

    @Autowired
    private IFloorAttrBMO floorAttrBMOImpl;

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
        //Assert.hasKeyAndValue(reqJson, "xxx", "xxx");

        Assert.hasKeyAndValue(reqJson, "attrId", "attrId不能为空");

    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {

        floorAttrBMOImpl.deleteFloorAttr(reqJson, context);
    }

    @Override
    public String getServiceCode() {
        return ServiceCodeFloorAttrConstant.DELETE_FLOORATTR;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }

}


text:
package workflow

import org.apache.spark.rdd.RDD

import scala.reflect.ClassTag

/**
 * This transformer performs a no-op on its input.
 *
 * @tparam T Type of the input and, by definition, output.
 */
case class Identity[T : ClassTag]() extends Transformer[T,T] {
  override def apply(in: T): T = in
  override def apply(in: RDD[T]): RDD[T] = in
}


text:
@interface SCTemplateVC ()

@end

@implementation SCTemplateVC

@end


text:
package org.gosulang.gradle;

import org.codehaus.groovy.runtime.InvokerHelper;
import org.gosulang.gradle.tasks.DefaultGosuSourceSet;
import org.gosulang.gradle.tasks.GosuRuntime;
import org.gosulang.gradle.tasks.GosuSourceSet;
import org.gosulang.gradle.tasks.compile.GosuCompile;
import org.gosulang.gradle.tasks.gosudoc.GosuDoc;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.SourceDirectorySet;
import org.gradle.api.internal.ConventionMapping;
import org.gradle.api.internal.file.SourceDirectorySetFactory;  //TODO unavoidable use of internal API
import org.gradle.api.plugins.Convention;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.plugins.internal.SourceSetUtil;
import org.gradle.api.reporting.ReportingExtension;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.compile.AbstractCompile;
import org.gradle.util.VersionNumber;

import javax.inject.Inject;
import java.io.File;
import java.util.concurrent.Callable;

public class GosuBasePlugin implements Plugin<Project> {
  public static final String GOSU_RUNTIME_EXTENSION_NAME = "gosuRuntime";

  private final SourceDirectorySetFactory _sourceDirectorySetFactory;

  private Project _project;
  private GosuRuntime _gosuRuntime;

  @Inject
  GosuBasePlugin(SourceDirectorySetFactory sourceDirectorySetFactory) {
    _sourceDirectorySetFactory = sourceDirectorySetFactory;
  }

  @Override
  public void apply(Project project) {
    _project = project;
    _project.getPluginManager().apply(JavaBasePlugin.class);

    JavaBasePlugin javaBasePlugin = _project.getPlugins().getPlugin(JavaBasePlugin.class);

    configureGosuRuntimeExtension();
    configureCompileDefaults();
    configureSourceSetDefaults(javaBasePlugin);
    configureGosuDoc();
  }

  private void configureGosuRuntimeExtension() {
    _gosuRuntime = _project.getExtensions().create(GOSU_RUNTIME_EXTENSION_NAME, GosuRuntime.class, _project);
  }

  /**
   * Sets the gosuClasspath property for all GosuCompile tasks: compileGosu and compileTestGosu
   */
  private void configureCompileDefaults() {

    _project.getTasks().withType(GosuCompile.class, gosuCompile ->
        gosuCompile.getConventionMapping().map("gosuClasspath", () -> _gosuRuntime.inferGosuClasspath(gosuCompile.getClasspath())));
  }

  private void configureSourceSetDefaults(final JavaBasePlugin javaBasePlugin) {
    _project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().all(sourceSet -> {
      GosuSourceSet gosuSourceSet = new DefaultGosuSourceSet(sourceSet.getName(), _sourceDirectorySetFactory);

      Convention sourceSetConvention = (Convention) InvokerHelper.getProperty(sourceSet, "convention");
      sourceSetConvention.getPlugins().put("gosu", gosuSourceSet);

      gosuSourceSet.getGosu().srcDir("src/" + sourceSet.getName() + "/gosu");

      sourceSet.getResources().getFilter().exclude(element -> gosuSourceSet.getGosu().contains(element.getFile()));

      sourceSet.getAllSource().source(gosuSourceSet.getGosu());

      configureGosuCompile(javaBasePlugin, sourceSet, gosuSourceSet);
    });
  }

  /**
   * Create and configure default compileGosu and compileTestGosu tasks
   * Gradle 4.0+: call local equivalent of o.g.a.p.i.SourceSetUtil.configureForSourceSet(sourceSet, gosuSourceSet.getGosu(), gosuCompile, _project)
   * Gradle 2.x, 3.x: call javaPlugin.configureForSourceSet(sourceSet, gosuCompile);
   */
  private void configureGosuCompile(JavaBasePlugin javaPlugin, SourceSet sourceSet, GosuSourceSet gosuSourceSet) {
    String compileTaskName = sourceSet.getCompileTaskName("gosu");
    GosuCompile gosuCompile = _project.getTasks().create(compileTaskName, GosuCompile.class);

    VersionNumber gradleVersion = VersionNumber.parse(_project.getGradle().getGradleVersion());
    if(gradleVersion.compareTo(VersionNumber.parse("4.0")) >= 0) {
      //Gradle 4.0+
      configureForSourceSet(sourceSet, gosuSourceSet.getGosu(), gosuCompile, _project);
    } else {
      //javaPlugin.configureForSourceSet(sourceSet, gosuCompile);
      ConventionMapping conventionMapping = gosuCompile.getConventionMapping();
      gosuCompile.setSource(sourceSet.getJava());
      conventionMapping.map("classpath", new Callable<Object>() {
        public Object call() throws Exception {
          return sourceSet.getCompileClasspath().plus(gosuCompile.getProject().files(new Object[]{sourceSet.getJava().getOutputDir()}));
        }
      });
      SourceSetUtil.configureAnnotationProcessorPath(sourceSet, gosuCompile.getOptions(), _project);
      gosuCompile.setDestinationDir(_project.provider(new Callable<File>() {
        public File call() {
          return sourceSet.getJava().getOutputDir();
        }
      }));
      gosuCompile.setDescription("Compiles the " + gosuSourceSet.getGosu() + ".");
    }
    gosuCompile.dependsOn(sourceSet.getCompileJavaTaskName());
    gosuCompile.setSource((Object) gosuSourceSet.getGosu()); // Gradle 4.0 overloads setSource; must upcast to Object for backwards compatibility

    _project.getTasks().getByName(sourceSet.getClassesTaskName()).dependsOn(compileTaskName);
  }

  private void configureGosuDoc() {
    _project.getTasks().withType(GosuDoc.class, gosudoc -> {
      gosudoc.getConventionMapping().map("gosuClasspath", () -> _gosuRuntime.inferGosuClasspath(gosudoc.getClasspath()));
      gosudoc.getConventionMapping().map("destinationDir", () -> new File(_project.getConvention().getPlugin(JavaPluginConvention.class).getDocsDir(), "gosudoc"));
      gosudoc.getConventionMapping().map("title", () -> _project.getExtensions().getByType(ReportingExtension.class).getApiDocTitle());
      //gosudoc.getConventionMapping().map("windowTitle", (Callable<Object>) () -> _project.getExtensions().getByType(ReportingExtension.class).getApiDocTitle());
    });
  }

  private static void configureForSourceSet(final SourceSet sourceSet, final SourceDirectorySet sourceDirectorySet, AbstractCompile compile, final Project target) {
    compile.setDescription("Compiles the " + sourceDirectorySet.getDisplayName() + ".");
    compile.setSource(sourceSet.getJava());
    compile.getConventionMapping().map("classpath", () -> sourceSet.getCompileClasspath().plus(target.files(sourceSet.getJava().getOutputDir())));
    configureOutputDirectoryForSourceSet(sourceSet, sourceDirectorySet, compile, target);
  }

  private static void configureOutputDirectoryForSourceSet(final SourceSet sourceSet, final SourceDirectorySet sourceDirectorySet, AbstractCompile compile, final Project target) {
    final String sourceSetChildPath = "classes/" + sourceDirectorySet.getName() + "/" + sourceSet.getName();
    sourceDirectorySet.setOutputDir(target.provider(() -> {
      if (sourceSet.getOutput().isLegacyLayout()) {
        return sourceSet.getJava().getOutputDir();
      }
      return new File(target.getBuildDir(), sourceSetChildPath);
    }));

    ((ConfigurableFileCollection) sourceSet.getOutput().getClassesDirs()).from(target.provider( sourceDirectorySet::getOutputDir));

    compile.setDestinationDir(target.provider(sourceDirectorySet::getOutputDir));
  }

}


text:
Athens\Core\Field\FieldInterface
===============

* Interface name: FieldInterface
* Namespace: Athens\Core\Field
* This is an **interface**
* This interface extends: [Athens\Core\Writer\WritableInterface](Athens-Core-Writer-WritableInterface.md)

Methods
-------

### getSubmitted

    string Athens\Core\Field\FieldInterface::getSubmitted()

* Visibility: **public**

### wasSubmitted

    boolean Athens\Core\Field\FieldInterface::wasSubmitted()

* Visibility: **public**

### getLabel

    string Athens\Core\Field\FieldInterface::getLabel()

* Visibility: **public**

### setLabel

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setLabel(string $label)

* Visibility: **public**

#### Arguments
* $label **string**

### getChoices

    array<mixed,string> Athens\Core\Field\FieldInterface::getChoices()

* Visibility: **public**

### getChoiceSlugs

    array<mixed,string> Athens\Core\Field\FieldInterface::getChoiceSlugs()

* Visibility: **public**

### setChoices

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setChoices(array $choices)

* Visibility: **public**

#### Arguments
* $choices **array**

### getSize

    integer Athens\Core\Field\FieldInterface::getSize()

* Visibility: **public**

### setSize

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setSize(integer $size)

* Visibility: **public**

#### Arguments
* $size **integer**

### getType

    string Athens\Core\Field\FieldInterface::getType()

* Visibility: **public**

### setType

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setType(string $type)

* Visibility: **public**

#### Arguments
* $type **string**

### addSuffix

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::addSuffix(string $suffix)

* Visibility: **public**

#### Arguments
* $suffix **string**

### getSuffixes

    array<mixed,string> Athens\Core\Field\FieldInterface::getSuffixes()

* Visibility: **public**

### addPrefix

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::addPrefix(string $prefix)

* Visibility: **public**

#### Arguments
* $prefix **string**

### getPrefixes

    array<mixed,string> Athens\Core\Field\FieldInterface::getPrefixes()

* Visibility: **public**

### getLabelSlug

    string Athens\Core\Field\FieldInterface::getLabelSlug()

* Visibility: **public**

### getSlug

    string Athens\Core\Field\FieldInterface::getSlug()

* Visibility: **public**

### setInitial

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setInitial(string|array<mixed,string> $value)

* Visibility: **public**

#### Arguments
* $value **string|array<mixed,string>**

### getInitial

    string|array<mixed,string> Athens\Core\Field\FieldInterface::getInitial()

* Visibility: **public**

### addError

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::addError(string $error)

* Visibility: **public**

#### Arguments
* $error **string**

### getErrors

    array<mixed,string> Athens\Core\Field\FieldInterface::getErrors()

* Visibility: **public**

### removeErrors

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::removeErrors()

* Visibility: **public**

### validate

    void Athens\Core\Field\FieldInterface::validate()

* Visibility: **public**

### isRequired

    boolean Athens\Core\Field\FieldInterface::isRequired()

* Visibility: **public**

### setRequired

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setRequired(boolean $required)

* Visibility: **public**

#### Arguments
* $required **boolean**

### isValid

    boolean Athens\Core\Field\FieldInterface::isValid()

* Visibility: **public**

### setValidatedData

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setValidatedData(string $data)

* Visibility: **public**

#### Arguments
* $data **string**

### hasValidatedData

    boolean Athens\Core\Field\FieldInterface::hasValidatedData()

* Visibility: **public**

### getValidatedData

    string Athens\Core\Field\FieldInterface::getValidatedData()

* Visibility: **public**

### getHelptext

    string Athens\Core\Field\FieldInterface::getHelptext()

* Visibility: **public**

### setHelptext

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setHelptext(string $helptext)

* Visibility: **public**

#### Arguments
* $helptext **string**

### getPlaceholder

    string Athens\Core\Field\FieldInterface::getPlaceholder()

* Visibility: **public**

### setPlaceholder

    \Athens\Core\Field\FieldInterface Athens\Core\Field\FieldInterface::setPlaceholder(string $placeholder)

* Visibility: **public**

#### Arguments
* $placeholder **string**

### getId

    string Athens\Core\Writer\WritableInterface::getId()

Return a unique identifier that will be consistent between requests.

* Visibility: **public**
* This method is defined by [Athens\Core\Writer\WritableInterface](Athens-Core-Writer-WritableInterface.md)

### getClasses

    array<mixed,string> Athens\Core\Writer\WritableInterface::getClasses()

* Visibility: **public**
* This method is defined by [Athens\Core\Writer\WritableInterface](Athens-Core-Writer-WritableInterface.md)

### getData

    array<mixed,string> Athens\Core\Writer\WritableInterface::getData()

* Visibility: **public**
* This method is defined by [Athens\Core\Writer\WritableInterface](Athens-Core-Writer-WritableInterface.md)

### accept

    mixed Athens\Core\Visitor\VisitableInterface::accept(\Athens\Core\Visitor\Visitor $visitor)

Accept a visitor, per the Visitor pattern.

* Visibility: **public**
* This method is defined by [Athens\Core\Visitor\VisitableInterface](Athens-Core-Visitor-VisitableInterface.md)

#### Arguments
* $visitor **[Athens\Core\Visitor\Visitor](Athens-Core-Visitor-Visitor.md)**


text:
from multiprocessing import Pool

import requests
import logging

__author__ = 'Jeff.West@yahoo.com'

# utility for deleting indexes that are no longer needed.  Given:
# A) a set of strings to include when evaluating the index names to delete
# B) a set of strings to Exclude when evaluating the index names to delete
#
# The general logic is:
# 1) If the include set is empty, or if the index name contains a string in the 'include' set, then delete
# 2) If the index contains a string in the exclude list, do not delete

url_base = 'http://localhost:9200'

r = requests.get(url_base + "/_stats")

indices = r.json()['indices']

print 'retrieved %s indices' % len(indices)

NUMBER_VALUE = 0

includes = [
    'cluster1',
    # 'b6768a08-b5d5-11e3-a495-10ddb1de66c3',
    # 'b6768a08-b5d5-11e3-a495-11ddb1de66c9',
]

excludes = [
    # 'b6768a08-b5d5-11e3-a495-11ddb1de66c8',
    # 'b6768a08-b5d5-11e3-a495-10ddb1de66c3',
    # 'b6768a08-b5d5-11e3-a495-11ddb1de66c9',
    # 'a34ad389-b626-11e4-848f-06b49118d7d0'
]

counter = 0
process = False
delete_counter = 0

indexes_to_delete = []

def delete_index(index_name):
    url_template = '%s/%s' % (url_base, index_name)
    print 'DELETING Index [%s] %s at URL %s' % (delete_counter, index_name, url_template)
    response = requests.delete('%s/%s' % (url_base, index))

for index in indices:
    process = False
    counter += 1

    print 'index %s of %s' % (counter, len(indices))

    if len(includes) == 0:
        process = True
    else:
        for include in includes:

            if include in index:
                process = True

    if len(excludes) > 0:
        for exclude in excludes:
            if exclude in index:
                process = False

    if process:
        indexes_to_delete.append(index)

print 'Found [%s] indexes to delete: %s' % (len(indexes_to_delete), indexes_to_delete)

if len(indexes_to_delete) > 0:
    pool = Pool(4)
    pool.map(delete_index, indexes_to_delete)

print 'Done!'


text:
package com.github.perf;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.Reader;
import java.util.Map;

import org.junit.Test;

import com.github.perf.Action;
import com.github.perf.App;
import com.github.perf.AppConf;
import com.github.perf.UserGroup;
import com.github.perf.http.HttpClient;

public class AppConfTest {

	static Reader[] getConfFiles() {
		return App.getConfFiles(new String[] { "conf/junit.conf.js", "conf/junit.run.js" });
	}

	@Test
	public void testConf() {
		AppConf conf = AppConf.initConf(getConfFiles());

		Map<String, String> events = conf.getEvents();
		Map<String, Action> mappings = conf.getMappings();

		assertTrue(!conf.isStatEnabled());
		assertTrue(!conf.isLocalStatEnabled());
		Map<String, Object> hostMap = conf.getRemoteStatHost();
		assertEquals("localhost", hostMap.get("host"));
		assertEquals(9999.0d, hostMap.get("port"));
		assertEquals("http://localhost:8888/test", conf.getUrl());
		assertTrue(!conf.isHttpStatEnabled());
		assertTrue(!conf.isActionStatEnabled());

		Map<String, String> params = conf.getMandatoryHttpParams();
		assertNotNull(params);
		assertTrue(params.containsKey("sessionid"));
		assertEquals("user.sessionid", params.get("sessionid"));
		for (UserGroup group : conf.getUserGroups())
			for (Map<String, Object> user : group.getUsers()) {
				if ("tes".equals(user.get("name"))) {
					assertEquals("fail", user.get("password"));
					assertEquals("ru", user.get("language"));
				}
				if ("test".equals(user.get("name"))) {
					assertEquals("password", user.get("password"));
					assertEquals("en", user.get("language"));
				}
				if ("test_00".equals(user.get("name"))) {
					assertEquals("pass_00", user.get("password"));
					assertEquals("en", user.get("language"));
					assertEquals(1.0, user.get("first"));
					assertEquals(3.0, user.get("last"));
					assertEquals(true, user.get("pattern"));
				}
			}

		assertEquals("login", events.get("onStart"));
		assertEquals("logout", events.get("onStop"));

		Action action;
		Action.Param param;

		action = mappings.get("login");
		assertEquals("login", action.getUri());
		assertEquals(HttpClient.HttpMethod.POST, action.getMethod());
		param = action.getParam("username");
		assertNotNull(param);
		assertEquals(Action.ParamType.USER, param.getType());
		assertEquals("name", param.getValue());
		param = action.getParam("password");
		assertNotNull(param);
		assertEquals(Action.ParamType.USER, param.getType());
		assertEquals("password", param.getValue());
		param = action.getParam("dummy");
		assertNotNull(param);
		assertEquals(Action.ParamType.STRING, param.getType());
		assertEquals("empty", param.getValue());
		assertNotNull(action.getHandlers().get(App.AFTER_HANDLER));

		action = mappings.get("logout");
		assertEquals("logout", action.getUri());
		assertEquals(HttpClient.HttpMethod.GET, action.getMethod());
		assertEquals(1, action.getParams().size());
		assertNotNull(action.getHandlers().get(App.AFTER_HANDLER));

		action = mappings.get("setState");
		assertEquals("state", action.getUri());
		assertEquals(HttpClient.HttpMethod.GET, action.getMethod());
		param = action.getParam("state");
		assertNotNull(param);
		assertEquals(Action.ParamType.ARG, param.getType());
		assertEquals("state", param.getValue());
		assertNotNull(action.getHandlers().get(App.AFTER_HANDLER));

	}

}


text:
NS_ASSUME_NONNULL_BEGIN

@implementation SDLSingleTireStatus

- (void)setStatus:(SDLComponentVolumeStatus)status {
    [self.store sdl_setObject:status forName:SDLRPCParameterNameStatus];
}

- (SDLComponentVolumeStatus)status {
    NSError *error = nil;
    return [self.store sdl_enumForName:SDLRPCParameterNameStatus error:&error];
}

- (void)setMonitoringSystemStatus:(nullable SDLTPMS)monitoringSystemStatus {
    [self.store sdl_setObject:monitoringSystemStatus forName:SDLRPCParameterNameTPMS];
}

- (nullable SDLTPMS)monitoringSystemStatus {
    return [self.store sdl_enumForName:SDLRPCParameterNameTPMS error:nil];
}

- (void)setPressure:(nullable NSNumber<SDLFloat> *)pressure {
    [self.store sdl_setObject:pressure forName:SDLRPCParameterNamePressure];
}

- (nullable NSNumber<SDLFloat> *)pressure {
    return [self.store sdl_objectForName:SDLRPCParameterNamePressure ofClass:NSNumber.class error:nil];
}

@end

NS_ASSUME_NONNULL_END


text:
'use strict';

var notifications = require('./notifications.module');

function NotificationService($log, toaster, strings) {
  var self = this;

  var defaultTitle = 'System Notification';

  var defaultUserMessage = 'The system was unable to process your request. ' +
    'If the problem persists, please contact technical support.';

  self.notifyError = function notifyError(notificationData) {
    var body = notificationData.userMessage || defaultUserMessage;
    toaster.pop({
      type: 'error',
      title: notificationData.title || defaultTitle,
      body: body,
      timeout: 0
    });

    if (!notificationData.noLog) {
      if (notificationData.technicalMessage) {
        $log.error(notificationData.technicalMessage);
      } else {
        var technicalMessageFormat =
          'No technical message was provided for the following error: \'{body}\'';
        var technicalMessage = strings.format(technicalMessageFormat, { body: body });
        $log.error(technicalMessage);
      }
    }
  };

  self.notifyWarning = function notifyWarning(notificationData) {
    toaster.pop({
      type: 'warning',
      title: notificationData.title || defaultTitle,
      body: notificationData.userMessage || defaultUserMessage,
      timeout: 0
    });

    if (notificationData.technicalMessage) {
      $log.warn(notificationData.technicalMessage);
    }
  };

  self.notifyInfo = function notifyInfo(notificationData) {
    toaster.pop({
      type: 'info',
      title: notificationData.title || defaultTitle,
      body: notificationData.userMessage || defaultUserMessage,
      timeout: 0
    });

    if (notificationData.technicalMessage) {
      $log.info(notificationData.technicalMessage);
    }
  };

  self.notifySuccess = function notifySuccess(notificationData) {
    toaster.pop({
      type: 'success',
      title: notificationData.title || defaultTitle,
      body: notificationData.userMessage || defaultUserMessage
    });

    if (notificationData.technicalMessage) {
      $log.info(notificationData.technicalMessage);
    }
  };

  return self;
}

NotificationService.$inject = ['$log', 'toaster', 'strings'];

notifications.factory('faNotificationService', NotificationService);