text:
.class Landroid/view/ViewRootImpl$W;
.super Landroid/view/IWindow$Stub;
.source "ViewRootImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/ViewRootImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "W"
.end annotation

# instance fields
.field private final mViewAncestor:Ljava/lang/ref/WeakReference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/WeakReference",
            "<",
            "Landroid/view/ViewRootImpl;",
            ">;"
        }
    .end annotation
.end field

.field private final mWindowSession:Landroid/view/IWindowSession;

# direct methods
.method constructor <init>(Landroid/view/ViewRootImpl;)V
    .locals 1

    invoke-direct {p0}, Landroid/view/IWindow$Stub;-><init>()V

    new-instance v0, Ljava/lang/ref/WeakReference;

    invoke-direct {v0, p1}, Ljava/lang/ref/WeakReference;-><init>(Ljava/lang/Object;)V

    iput-object v0, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    iget-object v0, p1, Landroid/view/ViewRootImpl;->mWindowSession:Landroid/view/IWindowSession;

    iput-object v0, p0, Landroid/view/ViewRootImpl$W;->mWindowSession:Landroid/view/IWindowSession;

    return-void
.end method

.method private static checkCallingPermission(Ljava/lang/String;)I
    .locals 4

    :try_start_0
    invoke-static {}, Landroid/app/ActivityManager;->getService()Landroid/app/IActivityManager;

    move-result-object v1

    invoke-static {}, Landroid/os/Binder;->getCallingPid()I

    move-result v2

    invoke-static {}, Landroid/os/Binder;->getCallingUid()I

    move-result v3

    invoke-interface {v1, p0, v2, v3}, Landroid/app/IActivityManager;->checkPermission(Ljava/lang/String;II)I
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    move-result v1

    return v1

    :catch_0
    move-exception v0

    const/4 v1, -0x1

    return v1
.end method

# virtual methods
.method public closeSystemDialogs(Ljava/lang/String;)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1}, Landroid/view/ViewRootImpl;->dispatchCloseSystemDialogs(Ljava/lang/String;)V

    :cond_0
    return-void
.end method

.method public dispatchAppVisibility(Z)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1}, Landroid/view/ViewRootImpl;->dispatchAppVisibility(Z)V

    :cond_0
    return-void
.end method

.method public dispatchCoverStateChanged(Z)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-static {v0, p1}, Landroid/view/ViewRootImpl;->-wrap6(Landroid/view/ViewRootImpl;Z)V

    :cond_0
    return-void
.end method

.method public dispatchDragEvent(Landroid/view/DragEvent;)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1}, Landroid/view/ViewRootImpl;->dispatchDragEvent(Landroid/view/DragEvent;)V

    :cond_0
    return-void
.end method

.method public dispatchFinishMovingTask()V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0}, Landroid/view/ViewRootImpl;->dispatchFinishMovingTask()V

    :cond_0
    return-void
.end method

.method public dispatchGetNewSurface()V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0}, Landroid/view/ViewRootImpl;->dispatchGetNewSurface()V

    :cond_0
    return-void
.end method

.method public dispatchPointerCaptureChanged(Z)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1}, Landroid/view/ViewRootImpl;->dispatchPointerCaptureChanged(Z)V

    :cond_0
    return-void
.end method

.method public dispatchSmartClipRemoteRequest(Lcom/samsung/android/content/smartclip/SmartClipRemoteRequestInfo;)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1}, Landroid/view/ViewRootImpl;->dispatchSmartClipRemoteRequest(Lcom/samsung/android/content/smartclip/SmartClipRemoteRequestInfo;)V

    :cond_0
    return-void
.end method

.method public dispatchSystemUiVisibilityChanged(IIII)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1, p2, p3, p4}, Landroid/view/ViewRootImpl;->dispatchSystemUiVisibilityChanged(IIII)V

    :cond_0
    return-void
.end method

.method public dispatchWallpaperCommand(Ljava/lang/String;IIILandroid/os/Bundle;Z)V
    .locals 4

    if-eqz p6, :cond_0

    :try_start_0
    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mWindowSession:Landroid/view/IWindowSession;

    invoke-virtual {p0}, Landroid/view/ViewRootImpl$W;->asBinder()Landroid/os/IBinder;

    move-result-object v2

    const/4 v3, 0x0

    invoke-interface {v1, v2, v3}, Landroid/view/IWindowSession;->wallpaperCommandComplete(Landroid/os/IBinder;Landroid/os/Bundle;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    :cond_0
    :goto_0
    return-void

    :catch_0
    move-exception v0

    goto :goto_0
.end method

.method public dispatchWallpaperOffsets(FFFFZ)V
    .locals 3

    if-eqz p5, :cond_0

    :try_start_0
    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mWindowSession:Landroid/view/IWindowSession;

    invoke-virtual {p0}, Landroid/view/ViewRootImpl$W;->asBinder()Landroid/os/IBinder;

    move-result-object v2

    invoke-interface {v1, v2}, Landroid/view/IWindowSession;->wallpaperOffsetsComplete(Landroid/os/IBinder;)V
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    :cond_0
    :goto_0
    return-void

    :catch_0
    move-exception v0

    goto :goto_0
.end method

.method public dispatchWindowShown()V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0}, Landroid/view/ViewRootImpl;->dispatchWindowShown()V

    :cond_0
    return-void
.end method

.method public executeCommand(Ljava/lang/String;Ljava/lang/String;Landroid/os/ParcelFileDescriptor;)V
    .locals 8

    iget-object v5, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v5}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v4

    check-cast v4, Landroid/view/ViewRootImpl;

    if-eqz v4, :cond_1

    iget-object v3, v4, Landroid/view/ViewRootImpl;->mView:Landroid/view/View;

    if-eqz v3, :cond_1

    const-string/jumbo v5, "android.permission.DUMP"

    invoke-static {v5}, Landroid/view/ViewRootImpl$W;->checkCallingPermission(Ljava/lang/String;)I

    move-result v5

    if-eqz v5, :cond_0

    new-instance v5, Ljava/lang/SecurityException;

    new-instance v6, Ljava/lang/StringBuilder;

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

    const-string/jumbo v7, "Insufficient permissions to invoke executeCommand() from pid="

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-static {}, Landroid/os/Binder;->getCallingPid()I

    move-result v7

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v6

    const-string/jumbo v7, ", uid="

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-static {}, Landroid/os/Binder;->getCallingUid()I

    move-result v7

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v6

    invoke-direct {v5, v6}, Ljava/lang/SecurityException;-><init>(Ljava/lang/String;)V

    throw v5

    :cond_0
    const/4 v0, 0x0

    :try_start_0
    new-instance v1, Landroid/os/ParcelFileDescriptor$AutoCloseOutputStream;

    invoke-direct {v1, p3}, Landroid/os/ParcelFileDescriptor$AutoCloseOutputStream;-><init>(Landroid/os/ParcelFileDescriptor;)V
    :try_end_0
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_1
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    :try_start_1
    invoke-static {v3, p1, p2, v1}, Landroid/view/ViewDebug;->dispatchCommand(Landroid/view/View;Ljava/lang/String;Ljava/lang/String;Ljava/io/OutputStream;)V
    :try_end_1
    .catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_4
    .catchall {:try_start_1 .. :try_end_1} :catchall_1

    if-eqz v1, :cond_1

    :try_start_2
    invoke-virtual {v1}, Ljava/io/OutputStream;->close()V
    :try_end_2
    .catch Ljava/io/IOException; {:try_start_2 .. :try_end_2} :catch_0

    :cond_1
    :goto_0
    return-void

    :catch_0
    move-exception v2

    invoke-virtual {v2}, Ljava/io/IOException;->printStackTrace()V

    goto :goto_0

    :catch_1
    move-exception v2

    :goto_1
    :try_start_3
    invoke-virtual {v2}, Ljava/io/IOException;->printStackTrace()V
    :try_end_3
    .catchall {:try_start_3 .. :try_end_3} :catchall_0

    if-eqz v0, :cond_1

    :try_start_4
    invoke-virtual {v0}, Ljava/io/OutputStream;->close()V
    :try_end_4
    .catch Ljava/io/IOException; {:try_start_4 .. :try_end_4} :catch_2

    goto :goto_0

    :catch_2
    move-exception v2

    invoke-virtual {v2}, Ljava/io/IOException;->printStackTrace()V

    goto :goto_0

    :catchall_0
    move-exception v5

    :goto_2
    if-eqz v0, :cond_2

    :try_start_5
    invoke-virtual {v0}, Ljava/io/OutputStream;->close()V
    :try_end_5
    .catch Ljava/io/IOException; {:try_start_5 .. :try_end_5} :catch_3

    :cond_2
    :goto_3
    throw v5

    :catch_3
    move-exception v2

    invoke-virtual {v2}, Ljava/io/IOException;->printStackTrace()V

    goto :goto_3

    :catchall_1
    move-exception v5

    move-object v0, v1

    goto :goto_2

    :catch_4
    move-exception v2

    move-object v0, v1

    goto :goto_1
.end method

.method public moved(II)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1, p2}, Landroid/view/ViewRootImpl;->dispatchMoved(II)V

    :cond_0
    return-void
.end method

.method public requestAppKeyboardShortcuts(Lcom/android/internal/os/IResultReceiver;I)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1, p2}, Landroid/view/ViewRootImpl;->dispatchRequestKeyboardShortcuts(Lcom/android/internal/os/IResultReceiver;I)V

    :cond_0
    return-void
.end method

.method public resized(Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;ZLandroid/util/MergedConfiguration;Landroid/graphics/Rect;ZZI)V
    .locals 13

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    move-object v1, p1

    move-object v2, p2

    move-object/from16 v3, p3

    move-object/from16 v4, p4

    move-object/from16 v5, p5

    move-object/from16 v6, p6

    move/from16 v7, p7

    move-object/from16 v8, p8

    move-object/from16 v9, p9

    move/from16 v10, p10

    move/from16 v11, p11

    move/from16 v12, p12

    invoke-static/range {v0 .. v12}, Landroid/view/ViewRootImpl;->-wrap7(Landroid/view/ViewRootImpl;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Rect;ZLandroid/util/MergedConfiguration;Landroid/graphics/Rect;ZZI)V

    :cond_0
    return-void
.end method

.method public touchFocusTransferred()V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0}, Landroid/view/ViewRootImpl;->touchFocusTransferred()V

    :cond_0
    return-void
.end method

.method public updatePointerIcon(FF)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1, p2}, Landroid/view/ViewRootImpl;->updatePointerIcon(FF)V

    :cond_0
    return-void
.end method

.method public windowFocusChanged(ZZ)V
    .locals 2

    iget-object v1, p0, Landroid/view/ViewRootImpl$W;->mViewAncestor:Ljava/lang/ref/WeakReference;

    invoke-virtual {v1}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/view/ViewRootImpl;

    if-eqz v0, :cond_0

    invoke-virtual {v0, p1, p2}, Landroid/view/ViewRootImpl;->windowFocusChanged(ZZ)V

    :cond_0
    return-void
.end method


text:
<?php

namespace Sylius\Component\Product\Model;

use Doctrine\Common\Collections\Collection;
use Sylius\Component\Association\Model\AssociableInterface;
use Sylius\Component\Attribute\Model\AttributeSubjectInterface;
use Sylius\Component\Resource\Model\CodeAwareInterface;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Model\SlugAwareInterface;
use Sylius\Component\Resource\Model\TimestampableInterface;
use Sylius\Component\Resource\Model\ToggleableInterface;
use Sylius\Component\Resource\Model\TranslatableInterface;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk>
 */
interface ProductInterface extends
    AssociableInterface,
    AttributeSubjectInterface,
    CodeAwareInterface,
    ResourceInterface,
    SlugAwareInterface,
    TimestampableInterface,
    ToggleableInterface,
    TranslatableInterface
{
    /**
     * @return string
     */
    public function getName();

    /**
     * @param string $name
     */
    public function setName($name);

    /**
     * @return string
     */
    public function getDescription();

    /**
     * @param string $description
     */
    public function setDescription($description);

    /**
     * @return string
     */
    public function getMetaKeywords();

    /**
     * @param string $metaKeywords
     */
    public function setMetaKeywords($metaKeywords);

    /**
     * @return string
     */
    public function getMetaDescription();

    /**
     * @param string $metaDescription
     */
    public function setMetaDescription($metaDescription);

    /**
     * @return bool
     */
    public function hasVariants();

    /**
     * @return Collection|ProductVariantInterface[]
     */
    public function getVariants();

    /**
     * @param ProductVariantInterface $variant
     */
    public function addVariant(ProductVariantInterface $variant);

    /**
     * @param ProductVariantInterface $variant
     */
    public function removeVariant(ProductVariantInterface $variant);

    /**
     * @param ProductVariantInterface $variant
     *
     * @return bool
     */
    public function hasVariant(ProductVariantInterface $variant);

    /**
     * @return bool
     */
    public function hasOptions();

    /**
     * @return Collection|ProductOptionInterface[]
     */
    public function getOptions();

    /**
     * @param ProductOptionInterface $option
     */
    public function addOption(ProductOptionInterface $option);

    /**
     * @param ProductOptionInterface $option
     */
    public function removeOption(ProductOptionInterface $option);

    /**
     * @param ProductOptionInterface $option
     *
     * @return bool
     */
    public function hasOption(ProductOptionInterface $option);

    /**
     * @return bool
     */
    public function isAvailable();

    /**
     * @return \DateTime
     */
    public function getAvailableOn();

    /**
     * @param \DateTime|null $availableOn
     */
    public function setAvailableOn(\DateTime $availableOn = null);

    /**
     * @return \DateTime
     */
    public function getAvailableUntil();

    /**
     * @param \DateTime|null $availableUntil
     */
    public function setAvailableUntil(\DateTime $availableUntil = null);

    /**
     * @param ProductAssociationInterface $association
     */
    public function addAssociation(ProductAssociationInterface $association);

    /**
     * @return ProductAssociationInterface[]
     */
    public function getAssociations();

    /**
     * @param ProductAssociationInterface $association
     */
    public function removeAssociation(ProductAssociationInterface $association);

    /**
     * @return bool
     */
    public function isSimple();

    /**
     * @return bool
     */
    public function isConfigurable();
}

redpajama_set_name: RedPajamaGithub


text:
/* Generated by ./xlat/gen.sh from ./xlat/sockipoptions.in; do not edit. */

static const struct xlat sockipoptions[] = {
#if defined(IP_TOS) || (defined(HAVE_DECL_IP_TOS) && HAVE_DECL_IP_TOS)
	XLAT(IP_TOS),
#endif
#if defined(IP_TTL) || (defined(HAVE_DECL_IP_TTL) && HAVE_DECL_IP_TTL)
	XLAT(IP_TTL),
#endif
#if defined(IP_HDRINCL) || (defined(HAVE_DECL_IP_HDRINCL) && HAVE_DECL_IP_HDRINCL)
	XLAT(IP_HDRINCL),
#endif
#if defined(IP_OPTIONS) || (defined(HAVE_DECL_IP_OPTIONS) && HAVE_DECL_IP_OPTIONS)
	XLAT(IP_OPTIONS),
#endif
#if defined(IP_ROUTER_ALERT) || (defined(HAVE_DECL_IP_ROUTER_ALERT) && HAVE_DECL_IP_ROUTER_ALERT)
	XLAT(IP_ROUTER_ALERT),
#endif
#if defined(IP_RECVOPTIONS) || (defined(HAVE_DECL_IP_RECVOPTIONS) && HAVE_DECL_IP_RECVOPTIONS)
	XLAT(IP_RECVOPTIONS),
#endif
#if defined(IP_RECVOPTS) || (defined(HAVE_DECL_IP_RECVOPTS) && HAVE_DECL_IP_RECVOPTS)
	XLAT(IP_RECVOPTS),
#endif
#if defined(IP_RECVRETOPTS) || (defined(HAVE_DECL_IP_RECVRETOPTS) && HAVE_DECL_IP_RECVRETOPTS)
	XLAT(IP_RECVRETOPTS),
#endif
#if defined(IP_RECVDSTADDR) || (defined(HAVE_DECL_IP_RECVDSTADDR) && HAVE_DECL_IP_RECVDSTADDR)
	XLAT(IP_RECVDSTADDR),
#endif
#if defined(IP_RETOPTS) || (defined(HAVE_DECL_IP_RETOPTS) && HAVE_DECL_IP_RETOPTS)
	XLAT(IP_RETOPTS),
#endif
#if defined(IP_PKTINFO) || (defined(HAVE_DECL_IP_PKTINFO) && HAVE_DECL_IP_PKTINFO)
	XLAT(IP_PKTINFO),
#endif
#if defined(IP_PKTOPTIONS) || (defined(HAVE_DECL_IP_PKTOPTIONS) && HAVE_DECL_IP_PKTOPTIONS)
	XLAT(IP_PKTOPTIONS),
#endif
#if defined(IP_MTU_DISCOVER) || (defined(HAVE_DECL_IP_MTU_DISCOVER) && HAVE_DECL_IP_MTU_DISCOVER)
	XLAT(IP_MTU_DISCOVER),
#endif
#if defined(IP_RECVERR) || (defined(HAVE_DECL_IP_RECVERR) && HAVE_DECL_IP_RECVERR)
	XLAT(IP_RECVERR),
#endif
#if defined(IP_RECVTTL) || (defined(HAVE_DECL_IP_RECVTTL) && HAVE_DECL_IP_RECVTTL)
	XLAT(IP_RECVTTL),
#endif
#if defined(IP_RECVTOS) || (defined(HAVE_DECL_IP_RECVTOS) && HAVE_DECL_IP_RECVTOS)
	XLAT(IP_RECVTOS),
#endif
#if defined(IP_MTU) || (defined(HAVE_DECL_IP_MTU) && HAVE_DECL_IP_MTU)
	XLAT(IP_MTU),
#endif
#if defined(IP_MULTICAST_IF) || (defined(HAVE_DECL_IP_MULTICAST_IF) && HAVE_DECL_IP_MULTICAST_IF)
	XLAT(IP_MULTICAST_IF),
#endif
#if defined(IP_MULTICAST_TTL) || (defined(HAVE_DECL_IP_MULTICAST_TTL) && HAVE_DECL_IP_MULTICAST_TTL)
	XLAT(IP_MULTICAST_TTL),
#endif
#if defined(IP_MULTICAST_LOOP) || (defined(HAVE_DECL_IP_MULTICAST_LOOP) && HAVE_DECL_IP_MULTICAST_LOOP)
	XLAT(IP_MULTICAST_LOOP),
#endif
#if defined(IP_ADD_MEMBERSHIP) || (defined(HAVE_DECL_IP_ADD_MEMBERSHIP) && HAVE_DECL_IP_ADD_MEMBERSHIP)
	XLAT(IP_ADD_MEMBERSHIP),
#endif
#if defined(IP_DROP_MEMBERSHIP) || (defined(HAVE_DECL_IP_DROP_MEMBERSHIP) && HAVE_DECL_IP_DROP_MEMBERSHIP)
	XLAT(IP_DROP_MEMBERSHIP),
#endif
#if defined(IP_BROADCAST_IF) || (defined(HAVE_DECL_IP_BROADCAST_IF) && HAVE_DECL_IP_BROADCAST_IF)
	XLAT(IP_BROADCAST_IF),
#endif
#if defined(IP_RECVIFINDEX) || (defined(HAVE_DECL_IP_RECVIFINDEX) && HAVE_DECL_IP_RECVIFINDEX)
	XLAT(IP_RECVIFINDEX),
#endif
#if defined(IP_MSFILTER) || (defined(HAVE_DECL_IP_MSFILTER) && HAVE_DECL_IP_MSFILTER)
	XLAT(IP_MSFILTER),
#endif
#if defined(MCAST_MSFILTER) || (defined(HAVE_DECL_MCAST_MSFILTER) && HAVE_DECL_MCAST_MSFILTER)
	XLAT(MCAST_MSFILTER),
#endif
#if defined(IP_FREEBIND) || (defined(HAVE_DECL_IP_FREEBIND) && HAVE_DECL_IP_FREEBIND)
	XLAT(IP_FREEBIND),
#endif
#if defined(IP_IPSEC_POLICY) || (defined(HAVE_DECL_IP_IPSEC_POLICY) && HAVE_DECL_IP_IPSEC_POLICY)
	XLAT(IP_IPSEC_POLICY),
#endif
#if defined(IP_XFRM_POLICY) || (defined(HAVE_DECL_IP_XFRM_POLICY) && HAVE_DECL_IP_XFRM_POLICY)
	XLAT(IP_XFRM_POLICY),
#endif
#if defined(IP_PASSSEC) || (defined(HAVE_DECL_IP_PASSSEC) && HAVE_DECL_IP_PASSSEC)
	XLAT(IP_PASSSEC),
#endif
#if defined(IP_TRANSPARENT) || (defined(HAVE_DECL_IP_TRANSPARENT) && HAVE_DECL_IP_TRANSPARENT)
	XLAT(IP_TRANSPARENT),
#endif
#if defined(IP_ORIGDSTADDR) || (defined(HAVE_DECL_IP_ORIGDSTADDR) && HAVE_DECL_IP_ORIGDSTADDR)
	XLAT(IP_ORIGDSTADDR),
#endif
#if defined(IP_RECVORIGDSTADDR) || (defined(HAVE_DECL_IP_RECVORIGDSTADDR) && HAVE_DECL_IP_RECVORIGDSTADDR)
	XLAT(IP_RECVORIGDSTADDR),
#endif
#if defined(IP_MINTTL) || (defined(HAVE_DECL_IP_MINTTL) && HAVE_DECL_IP_MINTTL)
	XLAT(IP_MINTTL),
#endif
#if defined(IP_NODEFRAG) || (defined(HAVE_DECL_IP_NODEFRAG) && HAVE_DECL_IP_NODEFRAG)
	XLAT(IP_NODEFRAG),
#endif
#if defined(IP_UNBLOCK_SOURCE) || (defined(HAVE_DECL_IP_UNBLOCK_SOURCE) && HAVE_DECL_IP_UNBLOCK_SOURCE)
	XLAT(IP_UNBLOCK_SOURCE),
#endif
#if defined(IP_BLOCK_SOURCE) || (defined(HAVE_DECL_IP_BLOCK_SOURCE) && HAVE_DECL_IP_BLOCK_SOURCE)
	XLAT(IP_BLOCK_SOURCE),
#endif
#if defined(IP_ADD_SOURCE_MEMBERSHIP) || (defined(HAVE_DECL_IP_ADD_SOURCE_MEMBERSHIP) && HAVE_DECL_IP_ADD_SOURCE_MEMBERSHIP)
	XLAT(IP_ADD_SOURCE_MEMBERSHIP),
#endif
#if defined(IP_DROP_SOURCE_MEMBERSHIP) || (defined(HAVE_DECL_IP_DROP_SOURCE_MEMBERSHIP) && HAVE_DECL_IP_DROP_SOURCE_MEMBERSHIP)
	XLAT(IP_DROP_SOURCE_MEMBERSHIP),
#endif
#if defined(MCAST_JOIN_GROUP) || (defined(HAVE_DECL_MCAST_JOIN_GROUP) && HAVE_DECL_MCAST_JOIN_GROUP)
	XLAT(MCAST_JOIN_GROUP),
#endif
#if defined(MCAST_BLOCK_SOURCE) || (defined(HAVE_DECL_MCAST_BLOCK_SOURCE) && HAVE_DECL_MCAST_BLOCK_SOURCE)
	XLAT(MCAST_BLOCK_SOURCE),
#endif
#if defined(MCAST_UNBLOCK_SOURCE) || (defined(HAVE_DECL_MCAST_UNBLOCK_SOURCE) && HAVE_DECL_MCAST_UNBLOCK_SOURCE)
	XLAT(MCAST_UNBLOCK_SOURCE),
#endif
#if defined(MCAST_LEAVE_GROUP) || (defined(HAVE_DECL_MCAST_LEAVE_GROUP) && HAVE_DECL_MCAST_LEAVE_GROUP)
	XLAT(MCAST_LEAVE_GROUP),
#endif
#if defined(MCAST_JOIN_SOURCE_GROUP) || (defined(HAVE_DECL_MCAST_JOIN_SOURCE_GROUP) && HAVE_DECL_MCAST_JOIN_SOURCE_GROUP)
	XLAT(MCAST_JOIN_SOURCE_GROUP),
#endif
#if defined(MCAST_LEAVE_SOURCE_GROUP) || (defined(HAVE_DECL_MCAST_LEAVE_SOURCE_GROUP) && HAVE_DECL_MCAST_LEAVE_SOURCE_GROUP)
	XLAT(MCAST_LEAVE_SOURCE_GROUP),
#endif
#if defined(IP_MULTICAST_ALL) || (defined(HAVE_DECL_IP_MULTICAST_ALL) && HAVE_DECL_IP_MULTICAST_ALL)
	XLAT(IP_MULTICAST_ALL),
#endif
#if defined(IP_UNICAST_IF) || (defined(HAVE_DECL_IP_UNICAST_IF) && HAVE_DECL_IP_UNICAST_IF)
	XLAT(IP_UNICAST_IF),
#endif
	XLAT_END
};


text:
require 'spec_helper'

describe EmailController do
  describe "POST 'post'" do
    before (:each) do
      @from_user = Factory.create(:user)
      @to_user = Factory.create(:user2)
      @file = @to_user.todo_files.build(Factory.attributes_for(:file))
      @file.save!
      text = "this is a test\n--\nreply_to_id:" + @file.file_uuid + "\nmorejunk"
      post :post, :from=>"Douglas Tarr <douxx@example.com>", :recipient => "jamy@example.com", :subject => "Test", "stripped-text"=>text,"body-plain"=>text
    end

    it 'should be successful' do
      response.should be_success
    end

    it 'should have an email object' do
      received_email = assigns(:received_email)
      received_email.should_not be_nil
      received_email.valid?.should be_true
      received_email.to_user_copy.should_not be_nil
      received_email.to_user_copy.reply_to.should_not be_nil
      received_email.to_user_copy.in_reply_to.should_not be_nil
    end

  end
end


text:
module Finicity
  class Client
    ##
    # Attributes
    #
    attr_accessor :mfa_session, :token

    ##
    # Constructor
    #
    def initialize(token = nil, mfa_session = nil)
      @token = token
      @mfa_session = mfa_session
    end

    ##
    # Instance Methods
    #
    # The accounts parameter is an array of Finicity::V1::Reponse::Account
    def activate_accounts(customer_id, institution_id, accounts)
      request = ::Finicity::V1::Request::ActivateAccounts.new(token, customer_id, institution_id, accounts)
      request.log_request
      response = request.activate_accounts
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return parsed_response.accounts
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return parsed_response.questions
      else
        raise_generic_error!(response)
      end
    end

    # The accounts parameter is an array of Finicity::V1::Reponse::Account
    # The mfa_credentials parameter is an array of hashes with keys :text, :answer
    def activate_accounts_with_mfa(customer_id, institution_id, accounts, mfa_credentials)
      request = ::Finicity::V1::Request::ActivateAccountsWithMfa.new(token, mfa_session, customer_id, institution_id, accounts, mfa_credentials)
      request.log_request
      response = request.activate_accounts_with_mfa
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return parsed_response.accounts
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return parsed_response.questions
      else
        raise_generic_error!(response)
      end
    end

    def add_customer(user_guid, options={})
      request = ::Finicity::V1::Request::AddCustomer.new(token, user_guid, options)
      request.log_request
      response = request.add_customer
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Customer.parse(response.body)
        return parsed_response
      else
        raise_generic_error!(response)
      end
    end

    def add_testing_customer(user_guid, options={})
      request = ::Finicity::V1::Request::AddCustomer.new(token, user_guid, options)
      request.log_request
      response = request.add_testing_customer
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Customer.parse(response.body)
        return parsed_response
      else
        raise_generic_error!(response)
      end
    end

    def authenticate!
      request = ::Finicity::V2::Request::PartnerAuthentication.new
      response = request.authenticate

      if response.ok?
        parsed_response = ::Finicity::V2::Response::PartnerAuthentication.parse(response.body)
        @token = parsed_response.token
        parsed_response
      else
        fail ::Finicity::AuthenticationError.new(response.body, response.status_code)
      end
    end

    def delete_account(customer_id, account_id)
      request = ::Finicity::V1::Request::DeleteAccount.new(token, customer_id, account_id)
      request.log_request
      response = request.delete_account
      log_response(response)

      if response.ok?
        # No data to parse, so return a hash for consistent return type
        return {:status => 200, :sucess => true,  :message => "Account successfully deleted." }
      else
        raise_generic_error!(response)
      end
    end

    def delete_customer(customer_id)
      request = ::Finicity::V1::Request::DeleteCustomer.new(token, customer_id)
      response = request.delete_customer

      if response.ok?
        # No data to parse, so return a hash for consistent return type
        return {}
      else
        raise_generic_error!(response)
      end
    end

    def add_all_accounts(customer_id, institution_id, login_credentials)
      request = ::Finicity::V1::Request::AddAllAccounts.new(token, customer_id, institution_id, login_credentials)
      request.log_request
      response = request.add_accounts
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return {:status => 200, :data => parsed_response.accounts}
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return {:status => 203, :mfa_session => response.headers["MFA-Session"] ,:data => parsed_response.questions}
      else
        raise_generic_error!(response)
      end
    end

    def add_all_accounts_with_mfa(customer_id, institution_id, mfa_session, mfa_credentials)
      request = ::Finicity::V1::Request::AddAllAccountsWithMfa.new(token, mfa_session, customer_id, institution_id, mfa_credentials)
      request.log_request
      response = request.add_all_accounts_with_mfa
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return {:status => 200, :data => parsed_response.accounts}
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return {:status => 203, :mfa_session => response.headers["MFA-Session"], :data => parsed_response.questions}
      else
        raise_generic_error!(response)
      end
    end

    # The login_credentials parameter is an array of hashes with the keys :id, :name, :value
    def discover_accounts(customer_id, institution_id, login_credentials)
      request = ::Finicity::V1::Request::DiscoverAccounts.new(token, customer_id, institution_id, login_credentials)
      request.log_request
      response = request.discover_accounts
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return parsed_response.accounts
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return parsed_response.questions
      else
        raise_generic_error!(response)
      end
    end

    # The login_credentials parameter is an array of hashes with the keys :id, :name, :value
    # The mfa_credentials parameter is an array of hashes with keys :text, :answer
    def discover_accounts_with_mfa(customer_id, institution_id, login_credentials, mfa_credentials)
      request = ::Finicity::V1::Request::DiscoverAccountsWithMfa.new(token, mfa_session, customer_id, institution_id, login_credentials, mfa_credentials)
      request.log_request
      response = request.discover_accounts_with_mfa
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return parsed_response.accounts
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return parsed_response.questions
      else
        raise_generic_error!(response)
      end
    end

    def get_accounts(customer_id, institution_id)
      request = ::Finicity::V1::Request::GetAccounts.new(token, customer_id, institution_id)
      request.log_request
      response = request.get_accounts
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return parsed_response.accounts
      elsif response.status_code == 404
        return []
      else
        raise_generic_error!(response)
      end
    end

    def get_all_accounts(customer_id)
      request = ::Finicity::V1::Request::GetCustomerAccount.new(token, customer_id, nil)
      request.log_request
      response = request.get_all_accounts
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return {:status => 200, :data => parsed_response.accounts }
      elsif response.status_code == 404
        return {:status => 404, :data => [] }
      else
        raise_generic_error!(response)
      end
    end

    def get_customer_account(customer_id, account_id)
      request = ::Finicity::V1::Request::GetCustomerAccount.new(token, customer_id, account_id)
      request.log_request
      response = request.get_customer_account
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return {:status => 200, :data => parsed_response.accounts }
      elsif response.status_code == 404
        return {:status => 404, :data => [] }
      else
        raise_generic_error!(response)
      end
    end

    def get_customer_by_username(username)
      request = ::Finicity::V1::Request::GetCustomersByUsername.new(token, username, 1, 1)
      request.log_request
      response = request.get_customers_by_username
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Customers.parse(response.body)
        if parsed_response.found && parsed_response.found > 1
          raise ::Finicity::DuplicateCustomerError.new(username)
        else
          return parsed_response.customers.first
        end
      else
        raise_generic_error!(response)
      end
    end

    def get_customers_by_username(username, start, limit)
      request = ::Finicity::V1::Request::GetCustomersByUsername.new(token, username, start, limit)
      request.log_request
      response = request.get_customers_by_username
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Customers.parse(response.body)
        return parsed_response.customers
      else
        raise_generic_error!(response)
      end
    end

    def get_customers
      request = ::Finicity::V1::Request::GetCustomers.new(token)
      start = 1
      limit = 25
      customers = []

      loop do
        response = request.get_customers(start, limit)

        if response.ok?
          parsed_response = ::Finicity::V1::Response::Customers.parse(response.body)
          customers << parsed_response.customers

          if parsed_response.more_available?
            start += limit
          else
            return customers.flatten
          end
        else
          raise_generic_error!(response)
        end
      end
    end

    def get_institution(institution_id)
      request = ::Finicity::V1::Request::GetInstitution.new(token, institution_id)
      response = request.get_institution

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Institution.parse(response.body)
        return parsed_response
      else
        raise_generic_error!(response)
      end
    end

    def get_institutions(institution_name)
      request = ::Finicity::V1::Request::GetInstitutions.new(token, institution_name)
      start = 1
      limit = 25
      institutions = []

      loop do
        response = request.get_institutions(start, limit)

        if response.ok?
          parsed_response = ::Finicity::V1::Response::Institutions.parse(response.body)
          institutions << parsed_response.institutions

          if parsed_response.more_available?
            start += limit
          else
            return institutions.flatten
          end
        else
          raise_generic_error!(response)
        end
      end
    end

    def get_all_institutions
      request = ::Finicity::V1::Request::GetInstitutions.new(token, institution_name = nil)
      response = request.get_institutions(1, 10)
      if response.ok?
        parsed_response = JSON.parse(response.body)
        parsed_response
      else
        raise_generic_error!(response)
      end
    end

    def get_login_form(institution_id)
      request = ::Finicity::V1::Request::GetLoginForm.new(token, institution_id)
      response = request.get_login_form

      if response.ok?
        parsed_response = ::Finicity::V1::Response::LoginForm.parse(response.body)
        return parsed_response.login_fields
      else
        raise_generic_error!(response)
      end
    end

    def get_transactions(customer_id, account_id, from_date, to_date)
      request = ::Finicity::V1::Request::GetTransactions.new(token, customer_id, account_id, from_date, to_date)
      request.log_request
      response = request.get_transactions
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Transactions.parse(response.body)
        return parsed_response.transactions
      else
        raise_generic_error!(response)
      end
    end

    def interactive_refresh_account(customer_id, account_id)
      request = ::Finicity::V1::Request::InteractiveRefreshAccount.new(token, customer_id, account_id)
      request.log_request
      response = request.interactive_refresh_account
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return {:status => 200, :data => parsed_response.accounts}
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return {:status => 203, :mfa_session => response.headers["MFA-Session"] ,:data => parsed_response.questions}
      else
        raise_generic_error!(response)
      end
    end

    # The mfa_credentials parameter is an array of hashes with keys :text, :answer
    def interactive_refresh_account_with_mfa(customer_id, account_id, mfa_session, mfa_credentials)
      request = ::Finicity::V1::Request::InteractiveRefreshAccountWithMfa.new(token, mfa_session, customer_id, account_id, mfa_credentials)
      request.log_request
      response = request.interactive_refresh_account_with_mfa
      log_response(response)

      if response.status_code == 200
        @mfa_session = nil
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return {:status => 200, :data => parsed_response.accounts}
      elsif response.status_code == 203
        @mfa_session = response.headers["MFA-Session"]
        parsed_response = ::Finicity::V1::Response::Mfa.parse(response.body)
        return {:status => 203, :mfa_session => response.headers["MFA-Session"] ,:data => parsed_response.questions}
      else
        raise_generic_error!(response)
      end
    end

    def refresh_accounts(customer_id)
      request = ::Finicity::V1::Request::RefreshAccounts.new(token, customer_id)
      request.log_request
      response = request.refresh_accounts
      log_response(response)

      if response.ok?
        parsed_response = ::Finicity::V1::Response::Accounts.parse(response.body)
        return parsed_response.accounts
      else
        raise_generic_error!(response)
      end
    end

    # The login_credentials parameter is an array of hashes with the keys :id, :name, :value
    def update_credentials(customer_id, account_id, login_credentials)
      request = ::Finicity::V1::Request::UpdateCredentials.new(token, customer_id, account_id, login_credentials)
      request.log_request
      response = request.update_credentials
      log_response(response)

      if response.ok?
        # No data to parse, so return a hash for consistent return type
        return {}
      else
        raise_generic_error!(response)
      end
    end

    private

    def log_response(response)
	  ::Finicity.logger.debug do
		log = "RESPONSE"
		log << "\n  STATUS CODE: #{response.status_code}"
		log << "\n  BODY: #{response.body}"
		log
      end
    end

    def raise_generic_error!(response)
      if response.content_type =~ /application\/xml/i
        error = ::Finicity::V1::Response::Error.parse(response.body)
        error_message = error.message
        error_code = error.code
        ::Finicity.logger.debug "xml response parsed...."
      else
        error_message = response.body
        error_code = nil
      end

      fail ::Finicity::GenericError.new(error_message, response.status_code, error_code)
    end

  end
end


text:
package com.github.avarabyeu.restendpoint.http.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author Andrei Varabyeu
 */
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Multipart {
}


text:
import { __decorate, __metadata } from "tslib";
import * as au from "../aurelia";
var MdTooltip = /** @class */ (function () {
    function MdTooltip(element) {
        this.element = element;
        this.position = "bottom";
        this.delay = 50;
        this.html = "";
    }
    MdTooltip.prototype.htmlChanged = function () {
        this.initTooltip();
    };
    MdTooltip.prototype.attached = function () {
        this.initTooltip();
    };
    MdTooltip.prototype.detached = function () {
        if (this.instance) {
            this.instance.destroy();
        }
    };
    MdTooltip.prototype.initTooltip = function () {
        if (this.html) {
            this.instance = new M.Tooltip(this.element, { exitDelay: this.delay, html: this.html, position: this.position });
        }
        else if (this.instance) {
            this.instance.destroy();
        }
    };
    __decorate([
        au.bindable,
        __metadata("design:type", String)
    ], MdTooltip.prototype, "position", void 0);
    __decorate([
        au.bindable,
        __metadata("design:type", Number)
    ], MdTooltip.prototype, "delay", void 0);
    __decorate([
        au.bindable,
        __metadata("design:type", String)
    ], MdTooltip.prototype, "html", void 0);
    MdTooltip = __decorate([
        au.customAttribute("md-tooltip"),
        au.autoinject,
        __metadata("design:paramtypes", [Element])
    ], MdTooltip);
    return MdTooltip;
}());
export { MdTooltip };
//# sourceMappingURL=tooltip.js.map


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.model;

import org.gradle.tooling.model.BuildModel;

import java.util.Collection;

/**
 * {@link Build} is a "lightweight" model represents a Gradle build.
 * It can be used to access "build-level" tooling models built for related Gradle build.
 *
 * This is a replacement for {@link org.gradle.tooling.model.idea.IdeaProject}
 *
 * @see org.jetbrains.plugins.gradle.service.project.ToolingModelsProvider#getBuildModel(Build, Class)
 *
 * @author Vladislav.Soroka
 */
public interface Build extends BuildModel {
  String getName();

  Collection<Project> getProjects();
}


text:
<?php

use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;

require_once __DIR__.'/autoload.php';

class AppKernel extends Kernel
{
    /**
     * @return array
     */
    public function registerBundles()
    {
        return [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),

            new A2lix\TranslationFormBundle\A2lixTranslationFormBundle(),
            new Bazinga\Bundle\JsTranslationBundle\BazingaJsTranslationBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
            new JMS\AopBundle\JMSAopBundle(),
            new JMS\TranslationBundle\JMSTranslationBundle(),
            new JMS\SerializerBundle\JMSSerializerBundle(),
            new JMS\DiExtraBundle\JMSDiExtraBundle($this),
            new Knp\DoctrineBehaviors\Bundle\DoctrineBehaviorsBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Liip\ImagineBundle\LiipImagineBundle(),
            new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(),
            new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(),
            new Snc\RedisBundle\SncRedisBundle(),
            new Troopers\AsseticInjectorBundle\TroopersAsseticInjectorBundle(),
            new Troopers\AlertifyBundle\TroopersAlertifyBundle(),

            //Victoire bundles
            new Victoire\Bundle\AnalyticsBundle\VictoireAnalyticsBundle(),
            new Victoire\Bundle\CoreBundle\VictoireCoreBundle(),
            new Victoire\Bundle\CriteriaBundle\VictoireCriteriaBundle(),
            new Victoire\Bundle\BlogBundle\VictoireBlogBundle(),
            new Victoire\Bundle\BusinessEntityBundle\VictoireBusinessEntityBundle(),
            new Victoire\Bundle\BusinessPageBundle\VictoireBusinessPageBundle(),
            new Victoire\Bundle\FilterBundle\VictoireFilterBundle(),
            new Victoire\Bundle\I18nBundle\VictoireI18nBundle(),
            new Victoire\Bundle\FormBundle\VictoireFormBundle(),
            new Victoire\Bundle\PageBundle\VictoirePageBundle(),
            new Victoire\Bundle\QueryBundle\VictoireQueryBundle(),
            new Victoire\Bundle\MediaBundle\VictoireMediaBundle(),
            new Victoire\Bundle\SeoBundle\VictoireSeoBundle(),
            new Victoire\Bundle\SitemapBundle\VictoireSitemapBundle(),
            new Victoire\Bundle\TemplateBundle\VictoireTemplateBundle(),
            new Victoire\Bundle\TwigBundle\VictoireTwigBundle(),
            new Victoire\Bundle\UserBundle\VictoireUserBundle(),
            new Victoire\Bundle\ViewReferenceBundle\ViewReferenceBundle(),
            new Victoire\Bundle\WidgetBundle\VictoireWidgetBundle(),
            new Victoire\Bundle\WidgetMapBundle\VictoireWidgetMapBundle(),
            //Victoire test bundles
            new Victoire\Widget\ForceBundle\VictoireWidgetForceBundle(),
            new Victoire\Widget\LightSaberBundle\VictoireWidgetLightSaberBundle(),
            new Victoire\Widget\ButtonBundle\VictoireWidgetButtonBundle(),
            new Victoire\Widget\TextBundle\VictoireWidgetTextBundle(),
            new Acme\AppBundle\AcmeAppBundle(),
        ];
    }

    /**
     * @param LoaderInterface $loader
     */
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }

    /**
     * @return string
     */
    public function getCacheDir()
    {
        return sys_get_temp_dir().'/Victoire/cache/'.$this->environment;
    }

    /**
     * @return string
     */
    public function getLogDir()
    {
        return sys_get_temp_dir().'/Victoire/logs/'.$this->environment;
    }

    /**
     * {@inheritdoc}
     */
    public function shutdown()
    {
        if ($this->environment === 'ci') {
            if (false === $this->booted) {
                return;
            }

            $container = $this->container;
            parent::shutdown();
            $this->cleanupContainer($container);
        } else {
            parent::shutdown();
        }
    }

    /**
     * Remove all container references from all loaded services.
     */
    protected function cleanupContainer($container)
    {
        $object = new \ReflectionObject($container);
        $property = $object->getProperty('services');
        $property->setAccessible(true);
        $services = $property->getValue($container) ?: [];
        foreach ($services as $id => $service) {
            if ('kernel' === $id) {
                continue;
            }
            $serviceObject = new \ReflectionObject($service);
            foreach ($serviceObject->getProperties() as $prop) {
                $prop->setAccessible(true);
                if ($prop->isStatic()) {
                    continue;
                }
                $prop->setValue($service, null);
            }
        }
        $property->setValue($container, null);
    }
}


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#ifndef QAUDIORECORDERSLOTS_H
#define QAUDIORECORDERSLOTS_H

#include <QtCore/QObject>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>

#include <QtMultimedia/QAudioRecorder>

#include "qt5xhb_common.h"
#include "qt5xhb_macros.h"
#include "qt5xhb_utils.h"
#include "qt5xhb_signals.h"

class QAudioRecorderSlots: public QObject
{
  Q_OBJECT
  public:
  QAudioRecorderSlots( QObject *parent = 0 );
  ~QAudioRecorderSlots();
  public slots:
  void audioInputChanged( const QString & name );
  void availableAudioInputsChanged();
};

#endif /* QAUDIORECORDERSLOTS_H */


text:
package org.javacs.debug.proto;

/** Optional properties of a variable that can be used to determine how to render the variable in the UI. */
public class VariablePresentationHint {
    /**
     * The kind of variable. Before introducing additional values, try to use the listed values. Values: 'property':
     * public * Indicates that the object is a property. 'method': Indicates that the object is a method. 'class':
     * Indicates that public * the object is a class. 'data': Indicates that the object is data. 'event': Indicates that
     * the object is an event. public * 'baseClass': Indicates that the object is a base class. 'innerClass': Indicates
     * that the object is an inner public * class. 'interface': Indicates that the object is an interface.
     * 'mostDerivedClass': Indicates that the object is public * the most derived class. 'virtual': Indicates that the
     * object is virtual, that means it is a synthetic object introduced by the adapter for rendering purposes, e.g. an
     * index range for large arrays. 'dataBreakpoint': Indicates that a data breakpoint is registered for the object.
     * etc.
     */
    public String kind;
    /**
     * Set of attributes represented as an array of strings. Before introducing additional values, try to use the listed
     * values. Values: 'static': Indicates that the object is static. 'constant': Indicates that the object is a
     * constant. 'readOnly': Indicates that the object is read only. 'rawString': Indicates that the object is a raw
     * string. 'hasObjectId': Indicates that the object can have an Object ID created for it. 'canHaveObjectId':
     * Indicates that the object has an Object ID associated with it. 'hasSideEffects': Indicates that the evaluation
     * had side effects. etc.
     */
    public String[] attributes;
    /**
     * Visibility of variable. Before introducing additional values, try to use the listed values. Values: 'public',
     * 'private', 'protected', 'internal', 'final', etc.
     */
    public String visibility;
}


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Andrey Abramov
/// @author Vasiliy Nabatchikov
////////////////////////////////////////////////////////////////////////////////

#include <rapidjson/rapidjson/document.h> // for rapidjson::Document, rapidjson::Value
#include <rapidjson/rapidjson/writer.h> // for rapidjson::Writer
#include <rapidjson/rapidjson/stringbuffer.h> // for rapidjson::StringBuffer

#include "delimited_token_stream.hpp"

NS_LOCAL

irs::bytes_ref eval_term(irs::bstring& buf, const irs::bytes_ref& data) {
  if (!data.size() || '"' != data[0]) {
    return data; // not a quoted term (even if quotes inside
  }

  buf.clear();

  bool escaped = false;
  size_t start = 1;

  for(size_t i = 1, count = data.size(); i < count; ++i) {
    if ('"' == data[i]) {
      if (escaped && start == i) { // an escaped quote
        escaped = false;

        continue;
      }

      if (escaped) {
        escaped = false;

        break; // mismatched quote
      }

      buf.append(&data[start], i - start);
      escaped = true;
      start = i + 1;
    }
  }

  return start != 1 && start == data.size() ? irs::bytes_ref(buf) : data; // return identity for mismatched quotes
}

size_t find_delimiter(const irs::bytes_ref& data, const irs::bytes_ref& delim) {
  if (delim.null()) {
    return data.size();
  }

  bool quoted = false;

  for (size_t i = 0, count = data.size(); i < count; ++i) {
    if (quoted) {
      if ('"' == data[i]) {
        quoted = false;
      }

      continue;
    }

    if (data.size() - i < delim.size()) {
      break; // no more delimiters in data
    }

    if (0 == memcmp(data.c_str() + i, delim.c_str(), delim.size())
        && (i || delim.size())) { // do not match empty delim at data start
      return i; // delimiter match takes precedence over '"' match
    }

    if ('"' == data[i]) {
      quoted = true;
    }
  }

  return data.size();
}

static const irs::string_ref DELIMITER_PARAM_NAME = "delimiter";

bool parse_json_config(const irs::string_ref& args, std::string& delimiter) {
  rapidjson::Document json;

  if (json.Parse(args.c_str(), args.size()).HasParseError()) {
    IR_FRMT_ERROR(
        "Invalid jSON arguments passed while constructing "
        "delimited_token_stream, arguments: %s",
        args.c_str());

    return false;
  }

  switch (json.GetType()) {
    case rapidjson::kStringType:
      delimiter = json.GetString();
      return true;
    case rapidjson::kObjectType:
      if (json.HasMember(DELIMITER_PARAM_NAME.c_str()) &&
          json[DELIMITER_PARAM_NAME.c_str()].IsString()) {
        delimiter = json[DELIMITER_PARAM_NAME.c_str()].GetString();
        return true;
      }
    default: {}  // fall through
  }

  IR_FRMT_ERROR(
      "Missing '%s' while constructing delimited_token_stream from jSON "
      "arguments: %s",
      DELIMITER_PARAM_NAME.c_str(), args.c_str());

  return false;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief args is a jSON encoded object with the following attributes:
///        "delimiter"(string): the delimiter to use for tokenization <required>
////////////////////////////////////////////////////////////////////////////////
irs::analysis::analyzer::ptr make_json(const irs::string_ref& args) {
  std::string delimiter;
  if (parse_json_config(args, delimiter)) {
    return irs::analysis::delimited_token_stream::make(delimiter);
  } else {
    return nullptr;
  }
}

///////////////////////////////////////////////////////////////////////////////
/// @brief builds analyzer config from internal options in json format
/// @param delimiter reference to analyzer options storage
/// @param definition string for storing json document with config
///////////////////////////////////////////////////////////////////////////////
bool make_json_config(const std::string& delimiter, std::string& definition) {
  rapidjson::Document json;
  json.SetObject();

  rapidjson::Document::AllocatorType& allocator = json.GetAllocator();
  // delimiter
  json.AddMember(
    rapidjson::StringRef(DELIMITER_PARAM_NAME.c_str(), DELIMITER_PARAM_NAME.size()),
    rapidjson::Value(rapidjson::StringRef(delimiter.c_str(), delimiter.length())),
    allocator
  );

  //output json to string
  rapidjson::StringBuffer buffer;
  rapidjson::Writer< rapidjson::StringBuffer> writer(buffer);
  json.Accept(writer);
  definition = buffer.GetString();
  return true;
}

bool normalize_json_config(const irs::string_ref& args,
                           std::string& definition){
  std::string delimiter;
  if (parse_json_config(args, delimiter)) {
    return make_json_config(delimiter, definition);
  } else {
    return false;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief args is a delimiter to use for tokenization
////////////////////////////////////////////////////////////////////////////////
irs::analysis::analyzer::ptr make_text(const irs::string_ref& args) {
  return irs::memory::make_shared<irs::analysis::delimited_token_stream>(
    args
  );
}

bool normalize_text_config(const irs::string_ref& delimiter, std::string& definition) {
  definition = delimiter;
  return true;
}

REGISTER_ANALYZER_JSON(irs::analysis::delimited_token_stream, make_json, normalize_json_config);
REGISTER_ANALYZER_TEXT(irs::analysis::delimited_token_stream, make_text, normalize_text_config);

NS_END

NS_ROOT
NS_BEGIN(analysis)

DEFINE_ANALYZER_TYPE_NAMED(delimited_token_stream, "delimiter")

delimited_token_stream::delimited_token_stream(const string_ref& delimiter)
  : analyzer(delimited_token_stream::type()),
    attrs_(4), // increment + offset + payload + term
    delim_(ref_cast<byte_type>(delimiter)) {
  attrs_.emplace(inc_);
  attrs_.emplace(offset_);
  attrs_.emplace(payload_);
  attrs_.emplace(term_);

  if (!delim_.null()) {
    delim_buf_ = delim_; // keep a local copy of the delimiter
    delim_ = delim_buf_; // update the delimter to point at the local copy
  }
}

/*static*/ analyzer::ptr delimited_token_stream::make(
    const string_ref& delimiter
) {
  return make_text(delimiter);
}

/*static*/ void delimited_token_stream::init() {
  REGISTER_ANALYZER_JSON(delimited_token_stream, make_json, normalize_json_config); // match registration above
  REGISTER_ANALYZER_TEXT(delimited_token_stream, make_text, normalize_text_config); // match registration above
}

bool delimited_token_stream::next() {
  if (data_.null()) {
    return false;
  }

  auto size = find_delimiter(data_, delim_);
  auto next = std::max(size_t(1), size + delim_.size());
  auto start = offset_.end + uint32_t(delim_.size()); // value is allowed to overflow, will only produce invalid result
  auto end = start + size;

  if (irs::integer_traits<uint32_t>::const_max < end) {
    return false; // cannot fit the next token into offset calculation
  }

  offset_.start = start;
  offset_.end = uint32_t(end);
  payload_.value = bytes_ref(data_.c_str(), size);
  term_.value(
    delim_.null()
    ? payload_.value // identity
    : eval_term(term_buf_, payload_.value)
  );
  data_ = size >= data_.size()
        ? bytes_ref::NIL
        : bytes_ref(data_.c_str() + next, data_.size() - next)
        ;

  return true;
}

bool delimited_token_stream::reset(const string_ref& data) {
  data_ = ref_cast<byte_type>(data);
  offset_.start = 0;
  offset_.end = 0 - uint32_t(delim_.size()); // counterpart to computation in next() above

  return true;
}

NS_END // analysis
NS_END // ROOT

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------


text:
  <META NAME="Author" CONTENT="B-Toolkit Release 5.1.0">
  <META NAME="Description" CONTENT="Hypertext version of Rename_SharedSocketServer">
  <TITLE>The Rename_SharedSocketServer machine</TITLE>

MACHINE               Rename_SharedSocketServer(TOK,insize,outsize)

  /*** stateless version of Rename_SocketServer, allowing sharing ***/

SEES                  String_TYPE, Bool_TYPE

OPERATIONS

  /*** operation to initialise the socket ***/

  rep <-- Rename_INIT(lockfile : STRING & port : NAT & bufsavefile : STRING) =
  PRE size(lockfile) < 256 & size(bufsavefile) < 256 THEN rep :: BOOL END;

   /*** operations on the socket ***/

  rep <-- Rename_ACCEPT = BEGIN rep :: BOOL END;

  rep,pp <-- Rename_READ  = BEGIN rep :: BOOL || pp :: NAT END;

  rep <-- Rename_WRITE = BEGIN rep :: BOOL END;

  rep <-- Rename_CLOSE = BEGIN rep :: BOOL END;

  /*** operations to read from the input buffer ***/

  tok <-- Rename_GET_TOK(toksize : 1..4 ) = BEGIN tok :: TOK END;

  ss <-- Rename_GET_STR = BEGIN ss :: STRING END;

  /*** operations to to write the output buffer ***/

  Rename_PUT_TOK(tok : TOK & toksize : 1..4 ) = skip;

  Rename_PUT_STR(ss:STRING) = skip;

  /*** operations to get and set the input buffer pointer ***/

  Rename_SET_IN_PTR(ptr : NAT) = skip;

  ptr <-- Rename_GET_IN_PTR = BEGIN ptr :: NAT END;

  /*** operations to get and set the output buffer pointer ***/

  Rename_SET_OUT_PTR(ptr : NAT) =  skip;

  ptr <-- Rename_GET_OUT_PTR = BEGIN ptr :: NAT END;

  sz <-- Rename_GET_OUT_SIZE = BEGIN sz :: NAT END;

  /*** Client initialisation ***/

  /* opens file, and appends its data until EOF to out_buf;
     then appends a null; gives FALSE if this fails.
  */
  rep <-- Rename_PUT_FILE(filename: STRING) = BEGIN rep :: BOOL END;

  /*** Buffer saving and restoring ***/

  /* appends in_buf to bufsavefile of saved in buffers
  */
  rep, num_saves <-- Rename_SAV_BUF = BEGIN rep :: BOOL || num_saves:: NAT END;

  /* Empty bufsavefile
  */
  Rename_SAV_RMV = skip;

  /* returns TRUE if bufsavefile not empty, else returns FALSE
  */
  rep <-- Rename_RST_BUF = BEGIN rep :: BOOL END;

  /* restores next saved buffer in inbuf; returns FALSE if finished
  */
  rep <-- Rename_NXT_BUF = BEGIN rep :: BOOL END;

  /* available when compiled with flag SERVER_STATS_FLAG, else returns FALSE,""
  */
  rep,filename <-- Rename_PrintStats = BEGIN rep :: BOOL || filename :: STRING END

END

Analysed Constructs

<MENU>

Hypertext Constructs Page

</MENU>

On-line Help

<MENU>

Help Contents Page

Index

</MENU>

Document Last Updated: Thu Dec  6 14:00:03 2001

B-Toolkit Release 5.1.0


text:
package org.springframework.cloud.sleuth.instrument.session;

import org.junit.jupiter.api.Test;

import org.springframework.cloud.sleuth.tracer.SimpleSpan;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.SessionRepository;

import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

class TraceFindByIndexNameSessionRepositoryTests extends TraceSessionRepositoryTests {

	FindByIndexNameSessionRepository delegate = mock(FindByIndexNameSessionRepository.class);

	TraceFindByIndexNameSessionRepository traceSessionRepository = new TraceFindByIndexNameSessionRepository(
			this.simpleTracer, this.delegate);

	@Test
	void should_trace_session_find_by_principle_name() {
		this.traceSessionRepository.findByPrincipalName("foo");

		verify(this.delegate).findByPrincipalName(any());
		SimpleSpan lastSpan = this.simpleTracer.getLastSpan();
		then(lastSpan.name).isEqualTo(SleuthSessionSpan.SESSION_FIND_SPAN.getName());
	}

	@Test
	void should_trace_session_find_by_index_name_value() {
		this.traceSessionRepository.findByIndexNameAndIndexValue("indexName1", "indexValue1");

		verify(this.delegate).findByIndexNameAndIndexValue(any(), any());
		SimpleSpan lastSpan = this.simpleTracer.getLastSpan();
		then(lastSpan.name).isEqualTo(SleuthSessionSpan.SESSION_FIND_SPAN.getName());
		then(lastSpan.tags).containsEntry(SleuthSessionSpan.Tags.INDEX_NAME.getKey(), "indexName1");
	}

	@Override
	SessionRepository sessionRepositoryDelegate() {
		return this.delegate;
	}

	@Override
	SessionRepository sessionRepository() {
		return this.traceSessionRepository;
	}

}


text:
import * as express from 'express'

import { createThriftServer } from '@creditkarma/thrift-server-express'

import { Int64 } from '@creditkarma/thrift-server-core'

import { createHttpClient, IRequest } from '@creditkarma/thrift-client'

import { ThriftClientZipkinFilter } from '@creditkarma/thrift-client-zipkin-filter'

import { ThriftClientTimingFilter } from '@creditkarma/thrift-client-timing-filter'

import { IMappedStruct, ISharedStruct, ISharedUnion } from './generated/shared'

import {
    Calculator,
    IChoice,
    ICommonStruct,
    Operation,
    Work,
} from './generated/calculator-service'

import { AddService } from './generated/add-service'

import { ADD_SERVER_CONFIG, EXPRESS_CALC_SERVER_CONFIG } from './config'
import { ICommonUnion } from './generated/common'

export function createServer(sampleRate: number = 0): express.Application {
    // Create thrift client
    const addServiceClient: AddService.Client<IRequest> = createHttpClient(
        AddService.Client,
        {
            hostName: ADD_SERVER_CONFIG.hostName,
            port: ADD_SERVER_CONFIG.port,
            register:
                sampleRate > 0
                    ? [
                          ThriftClientZipkinFilter({
                              localServiceName: 'calculator-service',
                              remoteServiceName: 'add-service',
                              tracerConfig: {
                                  endpoint: process.env.ZIPKIN_ENDPOINT,
                                  zipkinVersion:
                                      process.env.ZIPKIN_VERSION === 'v2'
                                          ? 'v2'
                                          : 'v1',
                                  httpInterval: 0,
                              },
                          }),
                          ThriftClientTimingFilter({
                              remoteServiceName: 'add-service',
                          }),
                      ]
                    : [
                          ThriftClientTimingFilter({
                              remoteServiceName: 'add-service',
                          }),
                      ],
        },
    )

    const serviceHandlers: Calculator.IHandler<express.Request> = {
        ping(): void {
            return
        },
        add(a: number, b: number, context: express.Request): Promise<number> {
            return addServiceClient.add(a, b, { headers: context.headers })
        },
        addInt64(a: Int64, b: Int64, context: express.Request): Promise<Int64> {
            return addServiceClient.addInt64(a, b, context)
        },
        addWithContext(a: number, b: number, context: express.Request): number {
            if (
                context !== undefined &&
                context.headers['x-fake-token'] === 'fake-token'
            ) {
                return a + b
            } else {
                throw new Error('Unauthorized')
            }
        },
        calculate(
            logId: number,
            work: Work,
            context: express.Request,
        ): number | Promise<number> {
            switch (work.op) {
                case Operation.ADD:
                    return addServiceClient.add(work.num1, work.num2, {
                        headers: context.headers,
                    })
                case Operation.SUBTRACT:
                    return work.num1 - work.num2
                case Operation.DIVIDE:
                    return work.num1 / work.num2
                case Operation.MULTIPLY:
                    return work.num1 * work.num2
            }
        },
        zip(): void {
            return
        },
        getStruct(): ISharedStruct {
            return {
                code: {
                    status: new Int64(0),
                },
                value: 'test',
            }
        },
        getUnion(index: number): ISharedUnion {
            if (index === 1) {
                return { option1: 'foo' }
            } else {
                return { option2: 'bar' }
            }
        },
        getMappedStruct(index: number): IMappedStruct {
            const map = new Map()
            map.set('one', {
                code: {
                    status: 5,
                },
                value: 'test',
            })

            return {
                data: map,
            }
        },
        echoBinary(word: Buffer): string {
            return word.toString('utf-8')
        },
        echoString(word: string): string {
            return word
        },
        checkName(choice: IChoice): string {
            if (choice.firstName !== undefined) {
                return `FirstName: ${choice.firstName.name}`
            } else if (choice.lastName !== undefined) {
                return `LastName: ${choice.lastName.name}`
            } else {
                throw new Error(`Unknown choice`)
            }
        },
        checkOptional(type?: string): string {
            if (type === undefined) {
                return 'undefined'
            } else {
                return type
            }
        },
        mapOneList(list: Array<number>): Array<number> {
            return list.map((next: number) => next + 1)
        },
        mapValues(map: Map<string, number>): Array<number> {
            return Array.from(map.values())
        },
        listToMap(list: Array<Array<string>>): Map<string, string> {
            return list.reduce(
                (acc: Map<string, string>, next: Array<string>) => {
                    acc.set(next[0], next[1])
                    return acc
                },
                new Map(),
            )
        },
        fetchThing(): ICommonStruct {
            return {
                code: {
                    status: new Int64(0),
                },
                value: 'test',
            }
        },
        fetchUnion(): ICommonUnion {
            return { option1: 'test' }
        },
        broken(): void {
            throw new Error(`Yeah, this didn't work`)
        },
    }

    const app: express.Application = createThriftServer({
        path: EXPRESS_CALC_SERVER_CONFIG.path,
        thriftOptions: {
            serviceName: 'calculator-service',
            handler: new Calculator.Processor(serviceHandlers),
        },
    })

    app.get('/control', (req: express.Request, res: express.Response) => {
        res.send('PASS')
    })

    return app
}


text:
namespace ash {
namespace {
// |kEpsilon| is used to check that AngleOfPointInNewCoordinates produces to
// expected angles. This function is only used after points are projected in
// opposite directions along the normal, so they should never be to close to
// each other, checking for equality up to 5 significant figures is more than
// enough.
const float kEpsilon = 0.0001f;
}

// Helper function to check if a given |point| has the |expected_angle_degree|
// in the coordinate system formed by |origin| and |direction|.
void CheckAngleOfPointInNewCoordinates(const gfx::PointF& origin,
                                       const gfx::Vector2dF& direction,
                                       const gfx::PointF& point,
                                       float expected_angle_degree) {
  float result = AngleOfPointInNewCoordinates(origin, direction, point);
  EXPECT_NEAR(expected_angle_degree * M_PI / 180.0f, result, kEpsilon);
}

// Helper function to check if the computed variables match the expected ones.
void CheckNormalLineVariables(const gfx::PointF& start_point,
                              const gfx::PointF& end_point,
                              float expected_slope,
                              float expected_start_intercept,
                              float expected_end_intercept) {
  float calculated_slope;
  float calculated_start_y_intercept;
  float calculated_end_y_intercept;

  ComputeNormalLineVariables(start_point, end_point, &calculated_slope,
                             &calculated_start_y_intercept,
                             &calculated_end_y_intercept);
  EXPECT_NEAR(expected_slope, calculated_slope, kEpsilon);
  EXPECT_NEAR(expected_start_intercept, calculated_start_y_intercept, kEpsilon);
  EXPECT_NEAR(expected_end_intercept, calculated_end_y_intercept, kEpsilon);
}

// Helper function to check if the a given line segment has an expected
// undefined normal line.
void CheckUndefinedNormalLine(const gfx::PointF& start_point,
                              const gfx::PointF& end_point) {
  float calculated_slope;
  float calculated_start_y_intercept;
  float calculated_end_y_intercept;

  ComputeNormalLineVariables(start_point, end_point, &calculated_slope,
                             &calculated_start_y_intercept,
                             &calculated_end_y_intercept);
  EXPECT_TRUE(isnan(calculated_slope));
  EXPECT_TRUE(isnan(calculated_start_y_intercept));
  EXPECT_TRUE(isnan(calculated_end_y_intercept));
}

// Helper function to check that the projections from the given line variables
// and |distance| match those expected in |expected_projections|.
void CheckProjectedPoints(const gfx::PointF& start_point,
                          float slope,
                          float y_intercept,
                          float distance,
                          std::vector<gfx::PointF>& expected_projections) {
  // There can only be two projections.
  EXPECT_EQ(2u, expected_projections.size());

  gfx::PointF calculated_first_projection;
  gfx::PointF calculated_second_projection;

  ComputeProjectedPoints(start_point, slope, y_intercept, distance,
                         &calculated_first_projection,
                         &calculated_second_projection);

  std::vector<gfx::PointF> calculated_projections = {
      calculated_first_projection, calculated_second_projection};

  // Sort the points, so that we do not have to enter the projections in the
  // right order.
  std::sort(calculated_projections.begin(), calculated_projections.end());
  std::sort(expected_projections.begin(), expected_projections.end());

  EXPECT_EQ(expected_projections[0], calculated_projections[0]);
  EXPECT_EQ(expected_projections[1], calculated_projections[1]);
}

// Helper function that checks that an IsFirstPointSmallerAngle will return
// false if |larger_angle_point| is the first point argument and return true if
// |larger_angle_point| is the second point argument.
void CheckFirstPointSmaller(const gfx::PointF& start_point,
                            const gfx::PointF& end_point,
                            const gfx::PointF& larger_angle_point,
                            const gfx::PointF& smaller_angle_point) {
  EXPECT_FALSE(IsFirstPointSmallerAngle(
      start_point, end_point, larger_angle_point, smaller_angle_point));
  EXPECT_TRUE(IsFirstPointSmallerAngle(
      start_point, end_point, smaller_angle_point, larger_angle_point));
}

using LaserSegmentUtilsTest = testing::Test;

TEST_F(LaserSegmentUtilsTest, AngleOfPointInNewCoordinates) {
  {
    // Verify angles remain the same if the origin is at (0, 0) and the
    // direction remains the same (1, 0).
    const gfx::PointF origin(0.0f, 0.0f);
    const gfx::Vector2dF direction(1.0f, 0.0f);

    // The functions range is (-180.0, 180.0).
    for (float angle = -179.0f; angle < 180.0f; angle += 10.0f) {
      float rad = angle * M_PI / 180.0f;
      gfx::PointF new_point(cos(rad), sin(rad));
      CheckAngleOfPointInNewCoordinates(origin, direction, new_point, angle);
    }
  }
  {
    // Verify angles are shifted by 45 degrees if the origin is at (0, 0) and
    // the direction is (1, 1).
    const gfx::PointF origin(0.0f, 0.0f);
    const gfx::Vector2dF direction(1.0f, 1.0f);

    // The functions range is (-180.0, 180.0).
    for (float angle = -179.0f; angle < 180.0f; angle += 10.0f) {
      float rad = (angle + 45.0f) * M_PI / 180.0f;
      gfx::PointF new_point(cos(rad), sin(rad));
      CheckAngleOfPointInNewCoordinates(origin, direction, new_point, angle);
    }
  }
  {
    // Verify angles remain the same if the points are translated by (1, 1),
    // if the origin is at (1, 1) and the direction remains the same (1, 0).
    const gfx::PointF origin(1.0f, 1.0f);
    const gfx::Vector2dF direction(1.0f, 0.0f);

    // The functions range is (-180.0f, 180.0f).
    for (float angle = -179.0f; angle < 180.0f; angle += 10.0f) {
      float rad = angle * M_PI / 180.0f;
      gfx::PointF new_point(cos(rad) + origin.x(), sin(rad) + origin.y());
      CheckAngleOfPointInNewCoordinates(origin, direction, new_point, angle);
    }
  }
  {
    // Verify angles are shifted by 45 degress if the points are translated by
    // (1, 1), if the origin is at (1, 1) and the direction remains the same
    // (1, 0).
    const gfx::PointF origin(1.0f, 1.0f);
    const gfx::Vector2dF direction(1.0f, 1.0f);

    // The functions range is (-180.0, 180.0).
    for (float angle = -179.0f; angle < 180.0f; angle += 10.0f) {
      float rad = (angle + 45.0f) * M_PI / 180.0f;
      gfx::PointF new_point(cos(rad) + origin.x(), sin(rad) + origin.y());
      CheckAngleOfPointInNewCoordinates(origin, direction, new_point, angle);
    }
  }
}

TEST_F(LaserSegmentUtilsTest, ComputeNormalLineVariables) {
  {
    // Verify a line y=x should have a normal line y=-x+b. At point (0,0), b
    // should equal y+x = 0. At point (1,1), b shoudl equal y+x = 2.
    const gfx::PointF start(0.0f, 0.0f);
    const gfx::PointF end(1.0f, 1.0f);
    float slope = -1.0f;
    float start_intercept = 0.0f;
    float end_intercept = 2.0f;
    CheckNormalLineVariables(start, end, slope, start_intercept, end_intercept);
  }
  {
    // Verify a line y=-x should have a normal line y=x+b. At point 0.0f), b
    // should equal y-x =.0f. At point (1,-1), b should equal y-x = -2.
    const gfx::PointF start(0.0f, 0.0f);
    const gfx::PointF end(1.0f, -1.0f);
    float slope = 1.0f;
    float start_intercept = 0.0f;
    float end_intercept = -2.0f;
    CheckNormalLineVariables(start, end, slope, start_intercept, end_intercept);
  }
  {
    // Verify a line x=5 should have a normal line y.0f with intercepts at the
    // previous y point.
    const gfx::PointF start(5.0f, 0.0f);
    const gfx::PointF end(5.0f, 5.0f);
    float slope = 0.0f;
    float start_intercept = 0.0f;
    float end_intercept = 5.0f;
    CheckNormalLineVariables(start, end, slope, start_intercept, end_intercept);
  }
  {
    // Verify a line parallel to the x-axis should be undefined. The line values
    // should not matter.
    const gfx::PointF start(0.0f, 5.0f);
    const gfx::PointF end(5.0f, 5.0f);
    CheckUndefinedNormalLine(start, end);
  }
}

TEST_F(LaserSegmentUtilsTest, ComputeProjectedPoints) {
  {
    // Verify projecting along y=x from (0, 0) by distance sqrt(2) shoudl result
    // in two projections: (1, 1) and (-1, -1). We start from (0, 0) and
    // translate by (1, 1) and (-1, -1) (vectors with slope 1) to get to (1, 1)
    // and (-1, -1). The length of the distance from (1, 1) is sqrt(1*1 + 1*1) =
    // sqrt(2).
    const gfx::PointF start(0.0f, 0.0f);
    const float slope = 1.0f;
    const float y_intercept = 0.0f;
    const float distance = sqrt(2.0f);
    std::vector<gfx::PointF> expected_projections = {gfx::PointF(1.0f, 1.0f),
                                                     gfx::PointF(-1.0f, -1.0f)};
    CheckProjectedPoints(start, slope, y_intercept, distance,
                         expected_projections);
  }
  {
    // Verify projecting along y=-2x+2 from (2, -2) by distance 2*sqrt(5) should
    // result in two projections: (0, 2) and (4, -6). We start from (2, -2) and
    // translate by (-2, 4) and (2, -4) (vectors with slope -2) to get (0, 2)
    // and (4, -6). The length of the distance from (2, -2) is sqrt(2*2 + 4*4) =
    // sqrt(20) = 2*sqrt(5).
    const gfx::PointF start(2.0f, -2.0f);
    const float slope = -2.0f;
    const float y_intercept = 2.0f;
    const float distance = 2.0f * sqrt(5.0f);
    std::vector<gfx::PointF> expected_projections = {gfx::PointF(0.0f, 2.0f),
                                                     gfx::PointF(4.0f, -6.0f)};
    CheckProjectedPoints(start, slope, y_intercept, distance,
                         expected_projections);
  }
  {
    // Verify projecting along y=5 from (5,5) by distance 2 should
    // result in two projections: (5,7) and (5,3).
    const gfx::PointF start(5.0f, 5.0f);
    const float slope = 0.0f;
    const float y_intercept = 5.0f;
    const float distance = 2.0f;
    std::vector<gfx::PointF> expected_projections = {gfx::PointF(7.0f, 5.0f),
                                                     gfx::PointF(3.0f, 5.0f)};
    CheckProjectedPoints(start, slope, y_intercept, distance,
                         expected_projections);
  }
}

TEST_F(LaserSegmentUtilsTest, IsFirstPointSmallerAngle) {
  {
    // Verify this function works in the case direction is unchanged.
    const gfx::PointF start_point(0.0f, 0.0f);
    const gfx::PointF end_point(1.0f, 0.0f);
    const gfx::PointF positive_angle(1.0f, 1.0f);
    const gfx::PointF negative_angle(-1.0f, -1.0f);
    CheckFirstPointSmaller(start_point, end_point, positive_angle,
                           negative_angle);
  }
  {
    // Verify this function works in the case direction is 90 degrees.
    const gfx::PointF start_point(0.0f, 0.0f);
    const gfx::PointF end_point(0.0f, 1.0f);
    const gfx::PointF positive_angle(-1.0f, 0.0f);
    const gfx::PointF negative_angle(1.0f, 0.0f);
    CheckFirstPointSmaller(start_point, end_point, positive_angle,
                           negative_angle);
  }
  {
    // Verify this function works in the case direction is 45 degrees.
    const gfx::PointF start_point(0.0f, 0.0f);
    const gfx::PointF end_point(1.0f, 1.0f);
    const gfx::PointF positive_angle(0.0f, 1.0f);
    const gfx::PointF negative_angle(1.0f, 0.0f);
    CheckFirstPointSmaller(start_point, end_point, positive_angle,
                           negative_angle);
  }
  {
    // Verify this function works in the case direction is -135 degrees.
    const gfx::PointF start_point(0.0f, 0.0f);
    const gfx::PointF end_point(-1.0f, -1.0f);
    const gfx::PointF positive_angle(0.0f, -1.0f);
    const gfx::PointF negative_angle(-1.0f, 0.0f);
    CheckFirstPointSmaller(start_point, end_point, positive_angle,
                           negative_angle);
  }
}

}  // namespace ash


text:
import { BLOG_CATEGORIES } from '../actions/index.js';
const BlogCategoriesReducer = (state = null, action) =>
	(action.type === BLOG_CATEGORIES && action.payload.data) ? action.payload.data : state;
export default BlogCategoriesReducer;


text:
namespace blink {

class ExecutionContext;

// Derived by wrappable objects which need to remain alive due to ongoing
// asynchronous activity, even if they are not referenced in the JavaScript or
// Blink heap.
//
// This is useful for ScriptWrappable objects that are not held alive by regular
// references from the object graph. E.g., XMLHttpRequest may have a pending
// activity that may be visible (e.g. firing event listeners or resolving
// promises) and should thus not be collected.
//
// Such objects should derive from ActiveScriptWrappable<T>, and override
// ScriptWrappable::HasPendingActivity:
//   bool HasPendingActivity() const final;
// which returns true if there may be pending activity which requires the
// wrappable remain alive.
//
// To avoid leaking objects after the context is destroyed, users of
// ActiveScriptWrappable<T> also have to provide a GetExecutionContext() method
// that returns the ExecutionContext or nullptr. A nullptr or already destroyed
// context results in ignoring HasPendingActivity().
template <typename T>
class ActiveScriptWrappable : public ActiveScriptWrappableBase {
 public:
  ActiveScriptWrappable(const ActiveScriptWrappable&) = delete;
  ActiveScriptWrappable& operator=(const ActiveScriptWrappable&) = delete;

  ~ActiveScriptWrappable() override = default;

 protected:
  ActiveScriptWrappable() = default;

  bool IsContextDestroyed() const final {
    return IsContextDestroyedForActiveScriptWrappable(
        static_cast<const T*>(this)->GetExecutionContext());
  }

  bool DispatchHasPendingActivity() const final {
    return static_cast<const T*>(this)->HasPendingActivity();
  }
};

// Helper for ActiveScriptWrappable<T>::IsContextDestroyed();
CORE_EXPORT bool IsContextDestroyedForActiveScriptWrappable(
    const ExecutionContext* execution_context);

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_ACTIVE_SCRIPT_WRAPPABLE_H_


text:
package source

import (
	"fmt"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"github.com/sirupsen/logrus"

	"github.com/skygeario/skygear-server/migrate/pkg/migrate/logging"
)

type Github struct {
	CacheDir string
}

type config struct {
	Owner string
	Repo  string
	Path  string
	Ref   string
}

func (g *Github) Download(sourceURL string) (string, error) {
	c, err := g.parse(sourceURL)
	if err != nil {
		return "", fmt.Errorf("invalid github source url: %s", err.Error())
	}

	return g.downloadFromClone(c)
}

func (g *Github) parse(sourceURL string) (*config, error) {
	c := &config{}
	u, err := url.Parse(sourceURL)
	if err != nil {
		return nil, fmt.Errorf("invalid source url: %s", err.Error())
	}

	c.Owner = u.Host
	p := strings.Split(strings.Trim(u.Path, "/"), "/")
	if len(p) < 1 {
		return nil, fmt.Errorf("invalid source url: missing host")
	}
	c.Repo = p[0]
	c.Path = strings.Join(p[1:], "/")
	c.Ref = u.Fragment

	return c, nil
}

func (g *Github) downloadFromClone(c *config) (string, error) {
	sourceCodeDirPath := g.getSourceCodeDirPath(g.CacheDir, c, "clone")
	cloneSource := fmt.Sprintf(
		"https://github.com/%s/%s.git",
		c.Owner,
		c.Repo,
	)

	logger := logrus.New()
	logwriter := logging.NewLogWriter(logger, logrus.InfoLevel)
	if _, e := os.Stat(sourceCodeDirPath); os.IsNotExist(e) {
		cmd := exec.Command("git", "clone", cloneSource, sourceCodeDirPath)
		logger.WithFields(logrus.Fields{
			"command": cmd.String(),
		}).Info("execute command")
		// git clone pipe its progress message to stderr, but it is not error
		// so we use same writer with info level to both stdout and stderror
		cmd.Stdout = logwriter
		cmd.Stderr = logwriter
		err := cmd.Run()
		if err != nil {
			return "", fmt.Errorf("failed to git clone source: %v", err.Error())
		}

		// check out references
		cmd = exec.Command("git", "-C", sourceCodeDirPath, "checkout", c.Ref)
		logger.WithFields(logrus.Fields{
			"command": cmd.String(),
		}).Info("execute command")
		cmd.Stdout = logwriter
		cmd.Stderr = logwriter
		err = cmd.Run()
		if err != nil {
			return "", fmt.Errorf("failed to git checkout source: %v", err.Error())
		}
	}

	migrateSrcDirPath := filepath.Join(sourceCodeDirPath, c.Path)
	return fmt.Sprintf("file://%s", migrateSrcDirPath), nil
}

func (g *Github) getSourceCodeDirPath(tmpDir string, c *config, subfix string) string {
	return filepath.Join(
		tmpDir,
		fmt.Sprintf("%s-%s-%s-%s", c.Owner, c.Repo, c.Ref, subfix),
	)
}


text:
GOAL
====

* deploy a platform made of 2 frontend servers with NGINX and 2 backend servers with PostgreSQL
* also generates the hosts file to be used by the Ansible inventory

INSTALL
=======

* get the "terraform" repo from Github: https://github.com/arocha7/terraform.git

DEPENDENCIES
============

This configuration uses Ansible roles to deploy NGINX and pgSQL

* get the "ansible" repo from Github: https://github.com/arocha7/ansible.git

USAGE
=====

cd terraform/two-layers-platf
terraform plan    -var-file='os_2layers-trusty.tfvars'
terraform apply   -var-file='os_2layers-trusty.tfvars'
terraform destroy -var-file='os_2layers-trusty.tfvars'

FEEDBACK
========

* arocha@ptinovacao.pt


text:
#ifndef OPENSSL_HEADER_POOL_INTERNAL_H
#define OPENSSL_HEADER_POOL_INTERNAL_H

#include <openssl/lhash.h>
#include <openssl/thread.h>

#include "../lhash/internal.h"

#if defined(__cplusplus)
extern "C" {
#endif

DEFINE_LHASH_OF(CRYPTO_BUFFER)

struct crypto_buffer_st {
  CRYPTO_BUFFER_POOL *pool;
  uint8_t *data;
  size_t len;
  CRYPTO_refcount_t references;
  int data_is_static;
};

struct crypto_buffer_pool_st {
  LHASH_OF(CRYPTO_BUFFER) *bufs;
  CRYPTO_MUTEX lock;
};

#if defined(__cplusplus)
}  // extern C
#endif

#endif  // OPENSSL_HEADER_POOL_INTERNAL_H


text:
layout: event
categories:
  - events
links:
title: Open Hack Session
date: 2014-07-22T18:00:00-05:00
event_id: 115
sponsor: GitHub
tags:
 - openhack
published: true
---

No presentations this week - just come to build, share, and learn about civic tech!

---

#### Leadership Council Meeting #3

Will have our third open leadership discussion at 8pm after the group breakouts get started. This meeting is for anyone who is interested in being involved in running the hack night, taking on new projects, or doing training sessions. If you'd like to bring up a topic, [add it to the agenda](https://docs.google.com/document/d/1WOeq0hAPd23SWuzjOScxvTA-ptt3UuVFDQyDsCSWRHs/edit#).


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

namespace Simulation.Shared {
  public enum PositionSide {
    Short, Long
  }
}


text:
import { Server as HapiServer } from 'hapi';
import * as Hapi from 'hapi';
import { Container } from 'inversify';
import * as winston from 'winston';
import { Config } from './Config';
import { configureContainer } from './configureContainer';
import { configureRouting } from './configureRouting';
import { BaseController } from './controllers/base/BaseController';
import { IConfig } from './IConfig';
import { loadConfig } from './loadConfig';
import { Log } from './Log';

export class Server {
    public async init() {
        const config = this.initializeConfig();
        const log = this.initializeLogging();

        log.debug('Initializing container');
        const container = this.initializeContainer(log, config);

        try {
            log.debug('Intializing hapi server instance');
            const hapiServer = await this.intializeHapiServer(config.get());

            log.debug('Initializing hapi server instance');
            await hapiServer.initialize();

            log.debug('Initializing routes');
            this.initializeRoutes(hapiServer, container);

            log.debug('Starting hapi server instance');
            await hapiServer.start();

            log.info(`Server running at: ${hapiServer.info.uri}`);
        } catch (error) {
            log.error(`Failed to start server: ${error.message}`);
            process.exit(1);
        }
    }

    private initializeConfig(): Config {
        const config = loadConfig();
        return new Config(config);
    }

    private initializeLogging(): Log {
        const { combine, colorize, padLevels, simple } = winston.format;

        const logger = winston.createLogger({
            level: 'info',
            transports: [
                new winston.transports.Console({
                    format: combine(padLevels(), simple(), colorize())
                })
            ]
        });

        return new Log(logger);
    }

    private initializeContainer(log: Log, config: Config): Container {
        const container = new Container();
        configureContainer(container, log, config);

        return container;
    }

    private async intializeHapiServer(config: IConfig): Promise<HapiServer> {
        const hapiServer = new Hapi.Server({
            address: config.server.address,
            port: config.server.port
        });

        await hapiServer.register([/*require('hapi-async-handler'), */ require('inert')]);

        return hapiServer;
    }

    private initializeRoutes(hapiServer: HapiServer, container: Container) {
        const controllers = container.getAll<BaseController>(BaseController);
        configureRouting(hapiServer, controllers);
    }
}


text:
Date: Thu, 07 Nov 1996 19:15:35 GMT
Server: NCSA/1.5
Content-type: text/html
Last-modified: Thu, 05 Sep 1996 17:05:42 GMT
Content-length: 2742

<title>John Watrous' Home Page</title>

John Watrous
(<!WA0>watrous@cs.wisc.edu )

<address>
<!WA1>Computer Sciences Department

University of Wisconsin - Madison

1210 W. Dayton Street

Madison, WI 53706

Telephone: (608) 262-6628

</address>

 Publications

 John Watrous,
<!WA2>
On One-Dimensional Quantum Cellular Automata,
Proc. 36th Ann. Symp. Foundations of Computer Science
(1995), 528-537.

 John Watrous,
A Polynomial-Time Algorithm for the Artin-Whaples Approximation Theorem,
Number Theory: Fourth Conference of the Canadian
Number Theory Association (1995), 397-407.

 Assorted Links

 Quantum Computation Links

<!WA3>
Quantum Computation Archive (Stanford)

<!WA4>
Quantum Information Home Page (Oxford)

<!WA5>
Particle Beam Physics Laboratory Quantum Information Page (UCLA)

<!WA6>
Laboratory for Theoretical & Quantum Computing (Montreal)

<!WA7>
LANL Preprints

 Bibliographies

<!WA8>
Computer Science Bibliographies

<!WA9>
Hypertext Bibliography Project

<!WA10>
Hypatia

 General Reference

<!WA11>
Elements of Style

<!WA12>
Hypertext Webster Interface

<!WA13>
Roget's Thesaurus

 Random Links

<!WA14>
Parasol Records

<!WA15>
PlayStation Links

<!WA16>
Weather Forecast for Madison

<!WA17>
The Isthmus Daily Page

<!WA18>
Mathematical Quotation Server

<!WA19>
Mathematician Biographies

<!WA20>
Geek Site of the Day


text:
package com.alachisoft.tayzgrid.management.clientconfiguration.dom;

import com.alachisoft.tayzgrid.common.configuration.ConfigurationAttributeAnnotation;
import com.alachisoft.tayzgrid.common.Common;
import com.alachisoft.tayzgrid.serialization.core.io.InternalCompactSerializable;
import com.alachisoft.tayzgrid.serialization.standard.io.CompactReader;
import com.alachisoft.tayzgrid.serialization.standard.io.CompactWriter;
import java.io.IOException;

public class CacheServer implements Cloneable, InternalCompactSerializable
{

    private String _serverName;
    private int _priority;
    @ConfigurationAttributeAnnotation(value = "name", appendText = "")
    public final String getServerName()
    {
        return _serverName;
    }

    @ConfigurationAttributeAnnotation(value = "name", appendText = "")
    public final void setServerName(String value)
    {
        _serverName = value;
    }

    public final int getPriority()
    {
        return _priority;
    }

    public final void setPriority(int value)
    {
        _priority = value;
    }

    @Override
    public String toString()
    {
        return _serverName;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (obj instanceof CacheServer)
        {
            CacheServer server = (CacheServer) ((obj instanceof CacheServer) ? obj : null);
            return server.getServerName().toLowerCase().equals(_serverName.toLowerCase());
        }

        return false;
    }

    @Override
    public int hashCode()
    {
        return _serverName.toLowerCase().hashCode();
    }

    public final Object clone()
    {
        CacheServer server = new CacheServer();
        server._serverName = _serverName;
        server._priority = _priority;

        return server;
    }
    //<editor-fold defaultstate="collapsed" desc="CompactS">
    public void Deserialize(CompactReader reader) throws IOException, ClassNotFoundException
    {
        _serverName = (String) Common.readAs(reader.ReadObject(),String.class);
        _priority = reader.ReadInt32();
    }

    public void Serialize(CompactWriter writer) throws IOException
    {
        writer.WriteObject(_serverName);
        writer.Write(_priority);
    }
    //</editor-fold>
}


text:
import Ember from 'ember';

export default Ember.Mixin.create({
  classNameBindings: ['wavesClass', 'wavesClass:waves-effect'],
  wavesClass: 'waves-light'
});