text:
.class public abstract Lcom/android/internal/http/multipart/Part;
.super Ljava/lang/Object;
.source "Part.java"

# static fields
.field protected static final BOUNDARY:Ljava/lang/String; = "----------------314159265358979323846"

.field protected static final BOUNDARY_BYTES:[B = null

.field protected static final CHARSET:Ljava/lang/String; = "; charset="

.field protected static final CHARSET_BYTES:[B = null

.field protected static final CONTENT_DISPOSITION:Ljava/lang/String; = "Content-Disposition: form-data; name="

.field protected static final CONTENT_DISPOSITION_BYTES:[B = null

.field protected static final CONTENT_TRANSFER_ENCODING:Ljava/lang/String; = "Content-Transfer-Encoding: "

.field protected static final CONTENT_TRANSFER_ENCODING_BYTES:[B = null

.field protected static final CONTENT_TYPE:Ljava/lang/String; = "Content-Type: "

.field protected static final CONTENT_TYPE_BYTES:[B = null

.field protected static final CRLF:Ljava/lang/String; = "\r\n"

.field protected static final CRLF_BYTES:[B = null

.field private static final DEFAULT_BOUNDARY_BYTES:[B = null

.field protected static final EXTRA:Ljava/lang/String; = "--"

.field protected static final EXTRA_BYTES:[B = null

.field private static final LOG:Lorg/apache/commons/logging/Log; = null

.field protected static final QUOTE:Ljava/lang/String; = "\""

.field protected static final QUOTE_BYTES:[B

# instance fields
.field private boundaryBytes:[B

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 55
    const-class v0, Lcom/android/internal/http/multipart/Part;

    invoke-static {v0}, Lorg/apache/commons/logging/LogFactory;->getLog(Ljava/lang/Class;)Lorg/apache/commons/logging/Log;

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    .line 67
    const-string v0, "----------------314159265358979323846"

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->BOUNDARY_BYTES:[B

    .line 73
    sget-object v0, Lcom/android/internal/http/multipart/Part;->BOUNDARY_BYTES:[B

    sput-object v0, Lcom/android/internal/http/multipart/Part;->DEFAULT_BOUNDARY_BYTES:[B

    .line 79
    const-string v0, "\r\n"

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    .line 85
    const-string v0, "\""

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->QUOTE_BYTES:[B

    .line 92
    const-string v0, "--"

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->EXTRA_BYTES:[B

    .line 99
    const-string v0, "Content-Disposition: form-data; name="

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->CONTENT_DISPOSITION_BYTES:[B

    .line 106
    const-string v0, "Content-Type: "

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->CONTENT_TYPE_BYTES:[B

    .line 113
    const-string v0, "; charset="

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->CHARSET_BYTES:[B

    .line 120
    const-string v0, "Content-Transfer-Encoding: "

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    sput-object v0, Lcom/android/internal/http/multipart/Part;->CONTENT_TRANSFER_ENCODING_BYTES:[B

    return-void
.end method

.method public constructor <init>()V
    .locals 0

    .prologue
    .line 52
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static getBoundary()Ljava/lang/String;
    .locals 1

    .prologue
    .line 129
    const-string v0, "----------------314159265358979323846"

    return-object v0
.end method

.method public static getLengthOfParts([Lcom/android/internal/http/multipart/Part;)J
    .locals 2
    .parameter "parts"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 404
    sget-object v0, Lcom/android/internal/http/multipart/Part;->DEFAULT_BOUNDARY_BYTES:[B

    invoke-static {p0, v0}, Lcom/android/internal/http/multipart/Part;->getLengthOfParts([Lcom/android/internal/http/multipart/Part;[B)J

    move-result-wide v0

    return-wide v0
.end method

.method public static getLengthOfParts([Lcom/android/internal/http/multipart/Part;[B)J
    .locals 7
    .parameter "parts"
    .parameter "partBoundary"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 419
    sget-object v5, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v6, "getLengthOfParts(Parts[])"

    invoke-interface {v5, v6}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 420
    if-nez p0, :cond_0

    .line 421
    new-instance v5, Ljava/lang/IllegalArgumentException;

    const-string v6, "Parts may not be null"

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

    throw v5

    .line 423
    :cond_0
    const-wide/16 v3, 0x0

    .line 424
    .local v3, total:J
    const/4 v0, 0x0

    .local v0, i:I
    :goto_0
    array-length v5, p0

    if-ge v0, v5, :cond_2

    .line 426
    aget-object v5, p0, v0

    invoke-virtual {v5, p1}, Lcom/android/internal/http/multipart/Part;->setPartBoundary([B)V

    .line 427
    aget-object v5, p0, v0

    invoke-virtual {v5}, Lcom/android/internal/http/multipart/Part;->length()J

    move-result-wide v1

    .line 428
    .local v1, l:J
    const-wide/16 v5, 0x0

    cmp-long v5, v1, v5

    if-gez v5, :cond_1

    .line 429
    const-wide/16 v5, -0x1

    .line 437
    .end local v1           #l:J
    :goto_1
    return-wide v5

    .line 431
    .restart local v1       #l:J
    :cond_1
    add-long/2addr v3, v1

    .line 424
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 433
    .end local v1           #l:J
    :cond_2
    sget-object v5, Lcom/android/internal/http/multipart/Part;->EXTRA_BYTES:[B

    array-length v5, v5

    int-to-long v5, v5

    add-long/2addr v3, v5

    .line 434
    array-length v5, p1

    int-to-long v5, v5

    add-long/2addr v3, v5

    .line 435
    sget-object v5, Lcom/android/internal/http/multipart/Part;->EXTRA_BYTES:[B

    array-length v5, v5

    int-to-long v5, v5

    add-long/2addr v3, v5

    .line 436
    sget-object v5, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    array-length v5, v5

    int-to-long v5, v5

    add-long/2addr v3, v5

    move-wide v5, v3

    .line 437
    goto :goto_1
.end method

.method public static sendParts(Ljava/io/OutputStream;[Lcom/android/internal/http/multipart/Part;)V
    .locals 1
    .parameter "out"
    .parameter "parts"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 360
    sget-object v0, Lcom/android/internal/http/multipart/Part;->DEFAULT_BOUNDARY_BYTES:[B

    invoke-static {p0, p1, v0}, Lcom/android/internal/http/multipart/Part;->sendParts(Ljava/io/OutputStream;[Lcom/android/internal/http/multipart/Part;[B)V

    .line 361
    return-void
.end method

.method public static sendParts(Ljava/io/OutputStream;[Lcom/android/internal/http/multipart/Part;[B)V
    .locals 3
    .parameter "out"
    .parameter "parts"
    .parameter "partBoundary"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 377
    if-nez p1, :cond_0

    .line 378
    new-instance v1, Ljava/lang/IllegalArgumentException;

    const-string v2, "Parts may not be null"

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 380
    :cond_0
    if-eqz p2, :cond_1

    array-length v1, p2

    if-nez v1, :cond_2

    .line 381
    :cond_1
    new-instance v1, Ljava/lang/IllegalArgumentException;

    const-string/jumbo v2, "partBoundary may not be empty"

    invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v1

    .line 383
    :cond_2
    const/4 v0, 0x0

    .local v0, i:I
    :goto_0
    array-length v1, p1

    if-ge v0, v1, :cond_3

    .line 385
    aget-object v1, p1, v0

    invoke-virtual {v1, p2}, Lcom/android/internal/http/multipart/Part;->setPartBoundary([B)V

    .line 386
    aget-object v1, p1, v0

    invoke-virtual {v1, p0}, Lcom/android/internal/http/multipart/Part;->send(Ljava/io/OutputStream;)V

    .line 383
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 388
    :cond_3
    sget-object v1, Lcom/android/internal/http/multipart/Part;->EXTRA_BYTES:[B

    invoke-virtual {p0, v1}, Ljava/io/OutputStream;->write([B)V

    .line 389
    invoke-virtual {p0, p2}, Ljava/io/OutputStream;->write([B)V

    .line 390
    sget-object v1, Lcom/android/internal/http/multipart/Part;->EXTRA_BYTES:[B

    invoke-virtual {p0, v1}, Ljava/io/OutputStream;->write([B)V

    .line 391
    sget-object v1, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    invoke-virtual {p0, v1}, Ljava/io/OutputStream;->write([B)V

    .line 392
    return-void
.end method

# virtual methods
.method public abstract getCharSet()Ljava/lang/String;
.end method

.method public abstract getContentType()Ljava/lang/String;
.end method

.method public abstract getName()Ljava/lang/String;
.end method

.method protected getPartBoundary()[B
    .locals 1

    .prologue
    .line 169
    iget-object v0, p0, Lcom/android/internal/http/multipart/Part;->boundaryBytes:[B

    if-nez v0, :cond_0

    .line 171
    sget-object v0, Lcom/android/internal/http/multipart/Part;->DEFAULT_BOUNDARY_BYTES:[B

    .line 173
    :goto_0
    return-object v0

    :cond_0
    iget-object v0, p0, Lcom/android/internal/http/multipart/Part;->boundaryBytes:[B

    goto :goto_0
.end method

.method public abstract getTransferEncoding()Ljava/lang/String;
.end method

.method public isRepeatable()Z
    .locals 1

    .prologue
    .line 195
    const/4 v0, 0x1

    return v0
.end method

.method public length()J
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 326
    sget-object v1, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v2, "enter length()"

    invoke-interface {v1, v2}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 327
    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->lengthOfData()J

    move-result-wide v1

    const-wide/16 v3, 0x0

    cmp-long v1, v1, v3

    if-gez v1, :cond_0

    .line 328
    const-wide/16 v1, -0x1

    .line 337
    :goto_0
    return-wide v1

    .line 330
    :cond_0
    new-instance v0, Ljava/io/ByteArrayOutputStream;

    invoke-direct {v0}, Ljava/io/ByteArrayOutputStream;-><init>()V

    .line 331
    .local v0, overhead:Ljava/io/ByteArrayOutputStream;
    invoke-virtual {p0, v0}, Lcom/android/internal/http/multipart/Part;->sendStart(Ljava/io/OutputStream;)V

    .line 332
    invoke-virtual {p0, v0}, Lcom/android/internal/http/multipart/Part;->sendDispositionHeader(Ljava/io/OutputStream;)V

    .line 333
    invoke-virtual {p0, v0}, Lcom/android/internal/http/multipart/Part;->sendContentTypeHeader(Ljava/io/OutputStream;)V

    .line 334
    invoke-virtual {p0, v0}, Lcom/android/internal/http/multipart/Part;->sendTransferEncodingHeader(Ljava/io/OutputStream;)V

    .line 335
    invoke-virtual {p0, v0}, Lcom/android/internal/http/multipart/Part;->sendEndOfHeader(Ljava/io/OutputStream;)V

    .line 336
    invoke-virtual {p0, v0}, Lcom/android/internal/http/multipart/Part;->sendEnd(Ljava/io/OutputStream;)V

    .line 337
    invoke-virtual {v0}, Ljava/io/ByteArrayOutputStream;->size()I

    move-result v1

    int-to-long v1, v1

    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->lengthOfData()J

    move-result-wide v3

    add-long/2addr v1, v3

    goto :goto_0
.end method

.method protected abstract lengthOfData()J
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method public send(Ljava/io/OutputStream;)V
    .locals 2
    .parameter "out"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 306
    sget-object v0, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v1, "enter send(OutputStream out)"

    invoke-interface {v0, v1}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 307
    invoke-virtual {p0, p1}, Lcom/android/internal/http/multipart/Part;->sendStart(Ljava/io/OutputStream;)V

    .line 308
    invoke-virtual {p0, p1}, Lcom/android/internal/http/multipart/Part;->sendDispositionHeader(Ljava/io/OutputStream;)V

    .line 309
    invoke-virtual {p0, p1}, Lcom/android/internal/http/multipart/Part;->sendContentTypeHeader(Ljava/io/OutputStream;)V

    .line 310
    invoke-virtual {p0, p1}, Lcom/android/internal/http/multipart/Part;->sendTransferEncodingHeader(Ljava/io/OutputStream;)V

    .line 311
    invoke-virtual {p0, p1}, Lcom/android/internal/http/multipart/Part;->sendEndOfHeader(Ljava/io/OutputStream;)V

    .line 312
    invoke-virtual {p0, p1}, Lcom/android/internal/http/multipart/Part;->sendData(Ljava/io/OutputStream;)V

    .line 313
    invoke-virtual {p0, p1}, Lcom/android/internal/http/multipart/Part;->sendEnd(Ljava/io/OutputStream;)V

    .line 314
    return-void
.end method

.method protected sendContentTypeHeader(Ljava/io/OutputStream;)V
    .locals 4
    .parameter "out"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 230
    sget-object v2, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v3, "enter sendContentTypeHeader(OutputStream out)"

    invoke-interface {v2, v3}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 231
    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->getContentType()Ljava/lang/String;

    move-result-object v1

    .line 232
    .local v1, contentType:Ljava/lang/String;
    if-eqz v1, :cond_0

    .line 233
    sget-object v2, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    invoke-virtual {p1, v2}, Ljava/io/OutputStream;->write([B)V

    .line 234
    sget-object v2, Lcom/android/internal/http/multipart/Part;->CONTENT_TYPE_BYTES:[B

    invoke-virtual {p1, v2}, Ljava/io/OutputStream;->write([B)V

    .line 235
    invoke-static {v1}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v2

    invoke-virtual {p1, v2}, Ljava/io/OutputStream;->write([B)V

    .line 236
    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->getCharSet()Ljava/lang/String;

    move-result-object v0

    .line 237
    .local v0, charSet:Ljava/lang/String;
    if-eqz v0, :cond_0

    .line 238
    sget-object v2, Lcom/android/internal/http/multipart/Part;->CHARSET_BYTES:[B

    invoke-virtual {p1, v2}, Ljava/io/OutputStream;->write([B)V

    .line 239
    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v2

    invoke-virtual {p1, v2}, Ljava/io/OutputStream;->write([B)V

    .line 242
    .end local v0           #charSet:Ljava/lang/String;
    :cond_0
    return-void
.end method

.method protected abstract sendData(Ljava/io/OutputStream;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method protected sendDispositionHeader(Ljava/io/OutputStream;)V
    .locals 2
    .parameter "out"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 217
    sget-object v0, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v1, "enter sendDispositionHeader(OutputStream out)"

    invoke-interface {v0, v1}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 218
    sget-object v0, Lcom/android/internal/http/multipart/Part;->CONTENT_DISPOSITION_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 219
    sget-object v0, Lcom/android/internal/http/multipart/Part;->QUOTE_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 220
    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->getName()Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v0

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 221
    sget-object v0, Lcom/android/internal/http/multipart/Part;->QUOTE_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 222
    return-void
.end method

.method protected sendEnd(Ljava/io/OutputStream;)V
    .locals 2
    .parameter "out"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 293
    sget-object v0, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v1, "enter sendEnd(OutputStream out)"

    invoke-interface {v0, v1}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 294
    sget-object v0, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 295
    return-void
.end method

.method protected sendEndOfHeader(Ljava/io/OutputStream;)V
    .locals 2
    .parameter "out"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 267
    sget-object v0, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v1, "enter sendEndOfHeader(OutputStream out)"

    invoke-interface {v0, v1}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 268
    sget-object v0, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 269
    sget-object v0, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 270
    return-void
.end method

.method protected sendStart(Ljava/io/OutputStream;)V
    .locals 2
    .parameter "out"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 204
    sget-object v0, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v1, "enter sendStart(OutputStream out)"

    invoke-interface {v0, v1}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 205
    sget-object v0, Lcom/android/internal/http/multipart/Part;->EXTRA_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 206
    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->getPartBoundary()[B

    move-result-object v0

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 207
    sget-object v0, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    invoke-virtual {p1, v0}, Ljava/io/OutputStream;->write([B)V

    .line 208
    return-void
.end method

.method protected sendTransferEncodingHeader(Ljava/io/OutputStream;)V
    .locals 3
    .parameter "out"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    .line 252
    sget-object v1, Lcom/android/internal/http/multipart/Part;->LOG:Lorg/apache/commons/logging/Log;

    const-string v2, "enter sendTransferEncodingHeader(OutputStream out)"

    invoke-interface {v1, v2}, Lorg/apache/commons/logging/Log;->trace(Ljava/lang/Object;)V

    .line 253
    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->getTransferEncoding()Ljava/lang/String;

    move-result-object v0

    .line 254
    .local v0, transferEncoding:Ljava/lang/String;
    if-eqz v0, :cond_0

    .line 255
    sget-object v1, Lcom/android/internal/http/multipart/Part;->CRLF_BYTES:[B

    invoke-virtual {p1, v1}, Ljava/io/OutputStream;->write([B)V

    .line 256
    sget-object v1, Lcom/android/internal/http/multipart/Part;->CONTENT_TRANSFER_ENCODING_BYTES:[B

    invoke-virtual {p1, v1}, Ljava/io/OutputStream;->write([B)V

    .line 257
    invoke-static {v0}, Lorg/apache/http/util/EncodingUtils;->getAsciiBytes(Ljava/lang/String;)[B

    move-result-object v1

    invoke-virtual {p1, v1}, Ljava/io/OutputStream;->write([B)V

    .line 259
    :cond_0
    return-void
.end method

.method setPartBoundary([B)V
    .locals 0
    .parameter "boundaryBytes"

    .prologue
    .line 185
    iput-object p1, p0, Lcom/android/internal/http/multipart/Part;->boundaryBytes:[B

    .line 186
    return-void
.end method

.method public toString()Ljava/lang/String;
    .locals 1

    .prologue
    .line 347
    invoke-virtual {p0}, Lcom/android/internal/http/multipart/Part;->getName()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method


text:
import { ChangeDetectionStrategy, Component } from '@angular/core';

@Component({
    selector: 'app-input-dropdown',
    templateUrl: './input-dropdown.testpage.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InputDropdownTestPageComponent {

    optionList: ReadonlyArray<string> = [
        'One', 'Two', 'Three', 'Four'
    ];

    filteredOptionList: ReadonlyArray<string> = this.optionList;
    get filter(): string {
        return this._filter;
    }

    set filter(value: string) {
        this._filter = value;
        this.filteredOptionList =
            value && (value.length > 0) ?
                this.optionList.filter(option => (option.toLowerCase().indexOf(value.toLowerCase()) > -1)) :
                this.optionList;
    }

    private _filter: string = '';

    disabled: boolean = false;
    placeholder: string = 'Type to search...';
    selected: string;

    selectOption(event: KeyboardEvent, option: string): void {
        this.selected = option;
        event.preventDefault();
    }

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author Fabricio Pontes Harsich fabriph@gmail.com
 */
package com.fabricioph.piteacher;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.fabricioph.piteacher.adapters.DBAdapter;

import java.util.Date;

public class RaiseHandViewActivity extends Activity {
	private DBAdapter mDbHelper;
	private long rowId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_raise_hand_view);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		mDbHelper = new DBAdapter(this);
		mDbHelper.open();
		fillData();
	}

	private void fillData() {
		Bundle bundle = getIntent().getExtras();
		if (bundle == null) {
			Log.e(getString(R.string.app_tag), "Bundle was null.");
			finish();
			return;
		}
		rowId = bundle.getLong(DBAdapter.RH_KEY_ROWID, DBAdapter.ERROR_VALUE);
		if (rowId == DBAdapter.ERROR_VALUE) {
			Log.e(getString(R.string.app_tag), "Couldn't get Raise Hand id.");
			finish();
			return;
		}
		Cursor c = mDbHelper.fetchRaiseHand(rowId);
		TextView content = (TextView) findViewById(R.id.activity_raise_hand_view_content);
		content.setText(c.getString(c.getColumnIndex(DBAdapter.RH_CONTENT)));

		long dateLong = c.getLong(c.getColumnIndex(DBAdapter.RH_DATE));
		Date date = new Date(dateLong);
		TextView dateTextView = (TextView) findViewById(R.id.activity_raise_hand_view_creation_date);
		dateTextView.setText(DateUtils.format(date));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.raise_hand_view, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			mDbHelper.close();
			finish();
			overridePendingTransition(R.anim.leave_1, R.anim.leave_2);
			return true;
		case R.id.raise_hand_view_mark_as_done:
			mDbHelper.raiseHandChangeStatus(rowId, DBAdapter.RH_STATUS_DONE);
			mDbHelper.close();
			Intent returnIntent = new Intent();
			setResult(RESULT_OK, returnIntent);
			finish();
			overridePendingTransition(R.anim.leave_1, R.anim.leave_2);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		mDbHelper.close();
		finish();
		overridePendingTransition(R.anim.leave_1, R.anim.leave_2);
	}
}


text:
package org.gradoop.utils.sampling.statistics;

import org.apache.flink.api.common.ProgramDescription;
import org.apache.flink.api.java.DataSet;
import org.gradoop.examples.AbstractRunner;
import org.gradoop.flink.model.impl.epgm.LogicalGraph;
import org.gradoop.flink.model.impl.functions.tuple.ObjectTo1;
import org.gradoop.flink.model.impl.operators.sampling.statistics.AverageIncomingDegree;
import org.gradoop.flink.model.impl.operators.sampling.statistics.SamplingEvaluationConstants;
import org.gradoop.flink.model.impl.operators.statistics.writer.StatisticWriter;

/**
 * Calls the average incoming degree computation for a logical graph. Writes the result to a
 * csv-file named {@value SamplingEvaluationConstants#FILE_AVERAGE_INCOMING_DEGREE}
 * in the output directory, containing a single line with the average incoming degree value, e.g.:
 *

 * BOF
 * 4
 * EOF
 *

 */
public class AverageIncomingDegreeRunner extends AbstractRunner implements ProgramDescription {

  /**
   * Calls the average incoming degree computation for the graph.
   *
   *

   * args[0] - path to graph
   * args[1] - format of graph (csv, json, indexed)
   * args[2] - output path
   *

   *
   * @param args command line arguments
   * @throws Exception in case of read/write failure
   */
  public static void main(String[] args) throws Exception {

    LogicalGraph graph = readLogicalGraph(args[0], args[1]);

    DataSet<Long> averageIncomingDegree = graph.callForGraph(new AverageIncomingDegree())
      .getGraphHead()
      .map(gh -> gh.getPropertyValue(
        SamplingEvaluationConstants.PROPERTY_KEY_AVERAGE_INCOMING_DEGREE).getLong());

    StatisticWriter.writeCSV(averageIncomingDegree.map(new ObjectTo1<>()),
      appendSeparator(args[2]) + SamplingEvaluationConstants.FILE_AVERAGE_INCOMING_DEGREE);

    getExecutionEnvironment().execute("Sampling Statistics: Average incoming degree");
  }

  @Override
  public String getDescription() {
    return AverageIncomingDegreeRunner.class.getName();
  }
}


text:
package com.esri.gpt.framework.robots;

import com.esri.gpt.framework.util.Val;

/**
 * Robots.txt file directive.
 */
public enum Directive {
  /** User-Agent directive */
  UserAgent("User-Agent"),
  /** Disallow directive */
  Disallow("Disallow"),
  /** Allow directive */
  Allow("Allow"),
  /** Crawl-Delay directive */
  CrawlDelay("Crawl-Delay"),
  /** Host directive */
  Host("Host"),
  /** Sitemap directive */
  Sitemap("Sitemap")
  ;
  private final String symbol;

  Directive(String symbol) {
    this.symbol = symbol;
  }

  /**
   * Gets symbol.
   * <p>
   * Symbol is a string which could be recognized within robots.txt file
   * @return symbol
   */
  public String symbol() {
    return this.symbol;
  }

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

  public static Directive parseDirective(String nameOrSymbol) {
    nameOrSymbol = Val.chkStr(nameOrSymbol);
    for (Directive d: values()) {
      if (d.name().equalsIgnoreCase(nameOrSymbol) || d.symbol().equalsIgnoreCase(nameOrSymbol)) {
        return d;
      }
    }
    return null;
  }
}


text:
import logging
import math

from PyQt5.QtCore import QLocale, QDateTime, pyqtSignal, QObject, QModelIndex, Qt
from sakia.errors import NoPeerAvailable
from sakia.constants import ROOT_SERVERS
from .table_model import CertifiersTableModel, CertifiersFilterProxyModel
from sakia.data.processors import BlockchainProcessor
from duniterpy.api import errors

class IdentityModel(QObject):
    """
    An component
    """
    localized_data_changed = pyqtSignal(dict)

    def __init__(self, parent, app, connection, blockchain_service, identities_service, sources_service):
        """
        Constructor of an component

        :param sakia.gui.identity.controller.IdentityController parent: the controller
        :param sakia.app.Application app: the app
        :param sakia.data.entities.Connection connection: the user connection of this node
        :param sakia.services.BlockchainService blockchain_service: the service watching the blockchain state
        :param sakia.services.IdentitiesService identities_service: the service watching the identities state
        :param sakia.services.SourcesService sources_service: the service watching the sources states
        """
        super().__init__(parent)
        self.app = app
        self.connection = connection
        self.blockchain_processor = BlockchainProcessor.instanciate(app)
        self.blockchain_service = blockchain_service
        self.identities_service = identities_service
        self.sources_service = sources_service
        self.table_model = None
        self.proxy_model = None
        self._logger = logging.getLogger('sakia')

    def init_table_model(self):
        """
        Instanciate the table model of the view
        """
        certifiers_model = CertifiersTableModel(self, self.connection, self.blockchain_service, self.identities_service)
        proxy = CertifiersFilterProxyModel(self.app)
        proxy.setSourceModel(certifiers_model)

        self.table_model = certifiers_model
        self.proxy_model = proxy
        self.table_model.init_certifiers()
        return self.proxy_model

    async def refresh_identity_data(self):
        identity = self.identities_service.get_identity(self.connection.pubkey, self.connection.uid)
        identity = await self.identities_service.load_requirements(identity)

        # update identities in database from the network
        await self.identities_service.initialize_certifications(identity, None, None)

        # update identities from database
        self.table_model.init_certifiers()

    def table_data(self, index):
        if index.isValid() and index.row() < self.table_model.rowCount(QModelIndex()):
            source_index = self.proxy_model.mapToSource(index)
            identity_col = self.table_model.columns_ids.index('identity')
            identity_index = self.table_model.index(source_index.row(), identity_col)
            identity = self.table_model.data(identity_index, Qt.DisplayRole)
            return True, identity
        return False, None

    def get_localized_data(self):
        localized_data = {}
        #  try to request money parameters
        try:
            params = self.blockchain_service.parameters()
        except NoPeerAvailable as e:
            logging.debug('community parameters error : ' + str(e))
            return None

        localized_data['currency'] = ROOT_SERVERS[self.connection.currency]["display"]
        localized_data['growth'] = params.c
        localized_data['days_per_dividend'] = QLocale().toString(params.dt / 86400, 'f', 2)

        last_ud, last_ud_base = self.blockchain_service.last_ud()
        members_count = self.blockchain_service.last_members_count()
        previous_ud, previous_ud_base = self.blockchain_service.previous_ud()
        previous_ud_time = self.blockchain_service.previous_ud_time()
        previous_monetary_mass = self.blockchain_service.previous_monetary_mass()
        previous_members_count = self.blockchain_service.previous_members_count()

        localized_data['units'] = self.app.current_ref.instance(0,
                                                                self.connection.currency,
                                                                self.app, None).units
        localized_data['diff_units'] = self.app.current_ref.instance(0,
                                                                     self.connection.currency,
                                                                     self.app, None).diff_units

        if last_ud:
            # display float values
            localized_data['ud'] = self.app.current_ref.instance(last_ud * math.pow(10, last_ud_base),
                                              self.connection.currency,
                                              self.app).diff_localized(False, True)

            localized_data['members_count'] = self.blockchain_service.current_members_count()

            computed_dividend = self.blockchain_service.computed_dividend()
            # display float values
            localized_data['ud_plus_1'] = self.app.current_ref.instance(computed_dividend,
                                              self.connection.currency, self.app).diff_localized(False, True)

            localized_data['mass'] = self.app.current_ref.instance(self.blockchain_service.current_mass(),
                                              self.connection.currency, self.app).localized(False, True)

            ud_median_time = self.blockchain_service.last_ud_time()
            ud_median_time = self.blockchain_processor.adjusted_ts(self.app.currency, ud_median_time)

            localized_data['ud_median_time'] = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(ud_median_time),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )

            next_ud_median_time = self.blockchain_service.last_ud_time() + params.dt
            next_ud_median_time = self.blockchain_processor.adjusted_ts(self.app.currency, next_ud_median_time)

            localized_data['next_ud_median_time'] = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(next_ud_median_time),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )

            next_ud_reeval = self.blockchain_service.next_ud_reeval()
            next_ud_reeval = self.blockchain_processor.adjusted_ts(self.app.currency, next_ud_reeval)
            localized_data['next_ud_reeval'] = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(next_ud_reeval),
                QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
            )

            if previous_ud:
                mass_minus_1_per_member = (float(0) if previous_ud == 0 or previous_members_count == 0 else
                                           previous_monetary_mass / previous_members_count)
                localized_data['mass_minus_1_per_member'] = self.app.current_ref.instance(mass_minus_1_per_member,
                                                  self.connection.currency, self.app) \
                                                  .localized(False, True)
                localized_data['mass_minus_1'] = self.app.current_ref.instance(previous_monetary_mass,
                                                  self.connection.currency, self.app) \
                                                  .localized(False, True)
                # avoid divide by zero !
                if members_count == 0 or previous_members_count == 0:
                    localized_data['actual_growth'] = float(0)
                else:
                    localized_data['actual_growth'] = (last_ud * math.pow(10, last_ud_base)) / (
                    previous_monetary_mass / members_count)

                previous_ud_time = self.blockchain_processor.adjusted_ts(self.app.currency, previous_ud_time)
                localized_data['ud_median_time_minus_1'] = QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(previous_ud_time),
                    QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                )
        return localized_data

    def get_identity_data(self):
        amount = self.sources_service.amount(self.connection.pubkey)
        localized_amount = self.app.current_ref.instance(amount,
                                                         self.connection.currency,
                                                         self.app).localized(False, True)
        outdistanced_text = self.tr("Outdistanced")
        is_identity = False
        written = False
        is_member = False
        nb_certs = 0
        mstime_remaining = 0
        identity_expiration = 0
        identity_expired = False
        outdistanced = False
        nb_certs_required = self.blockchain_service.parameters().sig_qty

        if self.connection.uid:
            is_identity = True
            try:
                identity = self.identities_service.get_identity(self.connection.pubkey, self.connection.uid)
                if identity:
                    mstime_remaining = self.identities_service.ms_time_remaining(identity)
                    is_member = identity.member
                    outdistanced = identity.outdistanced
                    written = identity.written
                    if not written:
                        identity_expiration = identity.timestamp + self.parameters().sig_window
                        identity_expired = identity_expiration < self.blockchain_processor.time(self.connection.currency)
                        identity_expiration = self.blockchain_processor.adjusted_ts(self.app.currency,
                                                                                identity_expiration)
                    nb_certs = len(self.identities_service.certifications_received(identity.pubkey))
                    if not identity.outdistanced:
                        outdistanced_text = self.tr("In WoT range")
            except errors.DuniterError as e:
                if e.ucode == errors.NO_MEMBER_MATCHING_PUB_OR_UID:
                    pass
                else:
                    self._logger.error(str(e))

        return {
            'written': written,
            'idty_expired': identity_expired,
            'idty_expiration': identity_expiration,
            'amount': localized_amount,
            'is_outdistanced': outdistanced,
            'outdistanced': outdistanced_text,
            'nb_certs': nb_certs,
            'nb_certs_required': nb_certs_required,
            'mstime': mstime_remaining,
            'membership_state': is_member,
            'is_identity': is_identity
        }

    def parameters(self):
        """
        Get community parameters
        """
        return self.blockchain_service.parameters()

    def notifications(self):
        return self.app.parameters.notifications

    async def send_join(self, secret_key, password):
        return await self.app.documents_service.send_membership(self.connection, secret_key, password, "IN")


text:
#include <stdint.h>

#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/tensor.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"

namespace tflite {
namespace ops {
namespace builtin {
namespace rank {

constexpr int kInputTensor = 0;
constexpr int kOutputTensor = 0;

TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) {
  TF_LITE_ENSURE_EQ(context, NumInputs(node), 1);
  TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1);

  const TfLiteTensor* input = GetInput(context, node, kInputTensor);
  TfLiteTensor* output = GetOutput(context, node, kOutputTensor);
  output->type = kTfLiteInt32;

  // By design, the input shape is always known at the time of Prepare, even
  // if the preceding op that generates |input| is dynamic. Thus, we can
  // always compute the rank immediately, without waiting for Eval.
  SetTensorToPersistentRo(output);

  // Rank produces a 0-D int32 Tensor representing the rank of input.
  TfLiteIntArray* output_size = TfLiteIntArrayCreate(0);
  TF_LITE_ENSURE_STATUS(context->ResizeTensor(context, output, output_size));

  TF_LITE_ENSURE_EQ(context, NumDimensions(output), 0);

  // Immediately propagate the known rank to the output tensor. This allows
  // downstream ops that rely on the value to use it during prepare.
  if (output->type == kTfLiteInt32) {
    int32_t* output_data = GetTensorData<int32_t>(output);
    *output_data = NumDimensions(input);
  } else {
    return kTfLiteError;
  }

  return kTfLiteOk;
}

TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
  return kTfLiteOk;
}

}  // namespace rank

TfLiteRegistration* Register_RANK() {
  static TfLiteRegistration r = {nullptr, nullptr, rank::Prepare, rank::Eval};
  return &r;
}

}  // namespace builtin
}  // namespace ops
}  // namespace tflite


text:
PHP Docker images
=================

This repository contains the source for building various versions of
the PHP application as a reproducible Docker image using
[source-to-image](https://github.com/openshift/source-to-image).
Users can choose between RHEL and CentOS based builder images.
The resulting image can be run using [Docker](http://docker.io).

For more information about using these images with OpenShift, please see the
official [OpenShift Documentation](https://docs.openshift.org/latest/using_images/s2i_images/php.html).

Versions
---------------
PHP versions currently supported are:
* php-5.6
* php-7.0

RHEL versions currently supported are:
* RHEL7

CentOS versions currently supported are:
* CentOS7

Installation
---------------
To build a PHP image, choose either the CentOS or RHEL based image:
*  **RHEL based image**

    To build a RHEL based PHP image, you need to run the build on a properly
    subscribed RHEL machine.

    ```
    $ git clone --recursive https://github.com/sclorg/s2i-php-container.git
    $ cd s2i-php-container
    $ make build TARGET=rhel7 VERSION=7.0
    ```

*  **CentOS based image**
    ```
    $ git clone --recursive https://github.com/sclorg/s2i-php-container.git
    $ cd s2i-php-container
    $ make build TARGET=centos7 VERSION=7.0
    ```

Alternatively, you can pull the CentOS image from Docker Hub via:

    $ docker pull centos/php-70-centos7

**Notice: By omitting the `VERSION` parameter, the build/test action will be performed
on all the supported versions of PHP.**

Usage
---------------------------------

For information about usage of Dockerfile for PHP 7.0,
see [usage documentation](7.0/README.md).

For information about usage of Dockerfile for PHP 5.6,
see [usage documentation](5.6/README.md).

Test
---------------------
This repository also provides a [S2I](https://github.com/openshift/source-to-image) test framework,
which launches tests to check functionality of a simple PHP application built on top of the s2i-php image.

Users can choose between testing a PHP test application based on a RHEL or CentOS image.

*  **RHEL based image**

    This image is not available as a trusted build in [Docker Index](https://index.docker.io).

    To test a RHEL7 based PHP-5.5 image, you need to run the test on a properly
    subscribed RHEL machine.

    ```
    $ cd s2i-php-container
    $ make test TARGET=rhel7 VERSION=7.0
    ```

*  **CentOS based image**

    ```
    $ cd s2i-php-container
    $ make test TARGET=centos7 VERSION=7.0
    ```

**Notice: By omitting the `VERSION` parameter, the build/test action will be performed
on all the supported versions of PHP.**

Repository organization
------------------------
* **`<php-version>`**

    Dockerfile and scripts to build container images from.

* **`hack/`**

    Folder containing scripts which are responsible for the build and test actions performed by the `Makefile`.

Image name structure
------------------------

1. Platform name (lowercase) - php
2. Platform version(without dots) - 70
3. Base builder image - centos7/rhel7

Examples: `php-70-centos7`, `php-70-rhel7`


text:
"use strict";

var hasOwnProperty = Object.prototype.hasOwnProperty;

/**
 * Merges object properties
 */
module.exports = function assign() {
  var into = arguments[0];
  for (var i = 1; i < arguments.length; i++) {
    var source = arguments[i];
    if (source != null) {
      for (var k in source) {
        if (hasOwnProperty.call(source, k)) {
          into[k] = source[k];
        }
      }
    }
  }
  return into;
};


text:
import { t, ChartMetadata, ChartPlugin } from '@superset-ui/core';
import transformProps from './transformProps';
import thumbnail from './images/thumbnail.png';
import controlPanel from './controlPanel';

const metadata = new ChartMetadata({
  category: t('Ranking'),
  credits: ['https://syntagmatic.github.io/parallel-coordinates'],
  description: t(
    'Plots the individual metrics for each row in the data vertically and links them together as a line. This chart is useful for comparing multiple metrics across all of the samples or rows in the data.',
  ),
  name: t('Parallel Coordinates'),
  tags: [t('Coordinates'), t('Directional'), t('Legacy'), t('Relational')],
  thumbnail,
  useLegacyApi: true,
});

export default class ParallelCoordinatesChartPlugin extends ChartPlugin {
  constructor() {
    super({
      loadChart: () => import('./ReactParallelCoordinates'),
      metadata,
      transformProps,
      controlPanel,
    });
  }
}


text:
using System.IO;
using Aspose.Pdf;
using Aspose.Pdf.Text;
using System;

namespace Aspose.Pdf.Examples.CSharp.AsposePDF.Text
{
    public class RenderingReplaceableSymbols
    {
        public static void Run()
        {
            // ExStart:RenderingReplaceableSymbols
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            Aspose.Pdf.Document pdfApplicationDoc = new Aspose.Pdf.Document();
            Aspose.Pdf.Page applicationFirstPage = (Aspose.Pdf.Page)pdfApplicationDoc.Pages.Add();

            // Initialize new TextFragment with text containing required newline markers
            Aspose.Pdf.Text.TextFragment textFragment = new Aspose.Pdf.Text.TextFragment("Applicant Name: " + Environment.NewLine + " Joe Smoe");

            // Set text fragment properties if necessary
            textFragment.TextState.FontSize = 12;
            textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman");
            textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
            textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red;

            // Create TextParagraph object
            TextParagraph par = new TextParagraph();

            // Add new TextFragment to paragraph
            par.AppendLine(textFragment);

            // Set paragraph position
            par.Position = new Aspose.Pdf.Text.Position(100, 600);

            // Create TextBuilder object
            TextBuilder textBuilder = new TextBuilder(applicationFirstPage);
            // Add the TextParagraph using TextBuilder
            textBuilder.AppendParagraph(par);

            dataDir = dataDir + "RenderingReplaceableSymbols_out.pdf";
            pdfApplicationDoc.Save(dataDir);
            // ExEnd:RenderingReplaceableSymbols
            Console.WriteLine("\nReplaceable symbols render successfully duing pdf creation.\nFile saved at " + dataDir);
        }
    }
}


text:
"""
Root URLconf for ``polymorphic_auth.tests`` project.
"""

from django.conf.urls import include, patterns, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^admin/', include(admin.site.urls)),
)


text:
package io.termd.core.tty;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;

import javax.websocket.ClientEndpointConfig;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * @author Julien Viet
 */
  public abstract class WebsocketTtyTestBase extends TtyTestBase {

  private Endpoint endpoint;
  private Session session;
  private PipedReader in;

  @After
  public void after() throws Exception {
    if (session != null) {
      try {
        session.close();
      } finally {
        in = null;
        session = null;
        endpoint = null;
      }
    }
  }

  @Override
  public boolean checkDisconnected() {
    return session == null || !session.isOpen();
  }

  @Override
  protected void assertConnect(String term) throws Exception {
    if (endpoint != null) {
      throw failure("Already a session");
    }
    CountDownLatch latch = new CountDownLatch(1);
    PipedWriter out = new PipedWriter();
    in = new PipedReader(out);
    endpoint = new Endpoint() {
      @Override
      public void onOpen(Session session, EndpointConfig endpointConfig) {
        session.addMessageHandler(new MessageHandler.Whole<String>() {
          @Override
          public void onMessage(String message) {
            try {
              out.write(message);
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        });
        latch.countDown();
      }
      @Override
      public void onClose(Session sess, CloseReason closeReason) {
        session = null;
        endpoint = null;
        in = null;
      }
      @Override
      public void onError(Session session, Throwable thr) {
      }
    };
    ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build();
    WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
    session = webSocketContainer.connectToServer(endpoint, clientEndpointConfig, new URI("http://localhost:8080/ws"));
    latch.await();
  }

  @Override
  protected void assertWrite(String s) throws Exception {
    Map<String, String> msg = new HashMap<>();
    msg.put("action", "read");
    msg.put("data", s);
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(msg);
    session.getBasicRemote().sendText(json);
  }

  @Override
  protected String assertReadString(int len) throws Exception {
    char[] buf = new char[len];
    while (len > 0) {
      int count = in.read(buf, buf.length - len, len);
      if (count == -1) {
        throw failure("Could not read enough");
      }
      len -= count;
    }
    return new String(buf);
  }

  @Override
  protected void assertWriteln(String s) throws Exception {
    assertWrite(s + "\r");
  }

  @Override
  protected void assertDisconnect(boolean clean) throws Exception {
    if (clean) {
      session.close();
    } else {
      // No way ???
      session.close();
    }
  }

  @Override
  protected void resize(int width, int height) throws Exception {
    Map<String, Object> msg = new HashMap<>();
    msg.put("action", "resize");
    msg.put("cols", width);
    msg.put("rows", height);
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(msg);
    session.getBasicRemote().sendText(json);
  }

  @Override
  public void testDifferentCharset() throws Exception {
    // Don't test, charset in this case is always UTF-8 for text frames
  }
}


text:
<?php

namespace Yepsua\LocalityBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Country
 *
 * @ORM\Table(name="country")
 * @ORM\Entity(repositoryClass="Yepsua\LocalityBundle\Entity\Repository\CountryRepository")
 */
class Country extends BaseAttribute
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="Yepsua\LocalityBundle\Entity\Locality", mappedBy="country")
     */
    protected $localities;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->localities = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add localities
     *
     * @param \Yepsua\LocalityBundle\Entity\Locality $localities
     * @return Country
     */
    public function addLocality(\Yepsua\LocalityBundle\Entity\Locality $localities)
    {
        $this->localities[] = $localities;

        return $this;
    }

    /**
     * Remove localities
     *
     * @param \Yepsua\LocalityBundle\Entity\Locality $localities
     */
    public function removeLocality(\Yepsua\LocalityBundle\Entity\Locality $localities)
    {
        $this->localities->removeElement($localities);
    }

    /**
     * Get localities
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getLocalities()
    {
        return $this->localities;
    }
}


text:
package cz.metacentrum.perun.registrar.modules;

import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.Vo;
import cz.metacentrum.perun.core.api.exceptions.AlreadyMemberException;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.bl.PerunBl;
import cz.metacentrum.perun.registrar.model.Application;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * This module sorts new VO members into the groups based on their affiliations from ČVUT/UK IdPs
 *
 * @author Pavel Zlámal <zlamal@cesnet.cz>
 */
public class CvutFbmi extends DefaultRegistrarModule {

	private final static Logger log = LoggerFactory.getLogger(CvutFbmi.class);

	/**
	 * Add approved VO members into specific groups based on their affiliation from ČVUT or UK IdP
	 */
	@Override
	public Application approveApplication(PerunSession session, Application app) throws MemberNotExistsException, WrongAttributeAssignmentException, AttributeNotExistsException, GroupNotExistsException {

		PerunBl perun = (PerunBl)session.getPerun();
		User user = app.getUser();
		Vo vo = app.getVo();

		// For INITIAL VO APPLICATIONS
		if (Application.AppType.INITIAL.equals(app.getType()) && app.getGroup() == null) {

			Attribute a = perun.getAttributesManagerBl().getAttribute(session, user, AttributesManager.NS_USER_ATTR_VIRT + ":eduPersonScopedAffiliations");

			if (a.getValue() != null) {

				Member member = perun.getMembersManagerBl().getMemberByUser(session, vo, user);

				List<String> affiliations = a.valueAsList();

				if (affiliations.contains("employee@cvut.cz")) {
					categorizeMember(session, vo, member, "Osoby:CVUT:Zamestnanec");
				}
				if (affiliations.contains("student@cvut.cz")) {
					categorizeMember(session, vo, member, "Osoby:CVUT:Student");
				}
				if (affiliations.contains("employee@cuni.cz")) {
					categorizeMember(session, vo, member, "Osoby:UK:Zamestnanec");
				}
				if (affiliations.contains("student@cuni.cz")) {
					categorizeMember(session, vo, member, "Osoby:UK:Student");
				}

			}

		}

		return app;

	}

	private void categorizeMember(PerunSession session, Vo vo, Member member, String groupName) {

		PerunBl perun = (PerunBl)session.getPerun();
		Group group = null;
		try {
			group = perun.getGroupsManagerBl().getGroupByName(session, vo, groupName);
			perun.getGroupsManagerBl().addMember(session, group, member);
		} catch (GroupNotExistsException e) {
			log.warn("Destination group {} for ČVUT FBMI and UK members categorisation doesn't exists.", groupName, e);
		} catch (WrongReferenceAttributeValueException | WrongAttributeValueException e) {
			log.error("Member {} couldn't be added to expected group {}.", member, group, e);
		} catch (AlreadyMemberException e) {
			// IGNORE
		}

	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>The GNU Fortran Compiler: MALLOC</title>

<meta name="description" content="The GNU Fortran Compiler: MALLOC">
<meta name="keywords" content="The GNU Fortran Compiler: MALLOC">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Intrinsic-Procedures.html#Intrinsic-Procedures" rel="up" title="Intrinsic Procedures">
<link href="MASKL.html#MASKL" rel="next" title="MASKL">
<link href="LTIME.html#LTIME" rel="prev" title="LTIME">

Next: MASKL, Previous: LTIME, Up: Intrinsic Procedures   [Contents][Index]

8.161 MALLOC — Allocate dynamic memory

Description:

MALLOC(SIZE) allocates <var>SIZE</var> bytes of dynamic memory and
returns the address of the allocated memory. The MALLOC intrinsic
is an extension intended to be used with Cray pointers, and is provided
in GNU Fortran to allow the user to compile legacy code. For new code
using Fortran 95 pointers, the memory allocation intrinsic is
ALLOCATE.

Standard:

GNU extension

Class:

Function

Syntax:

PTR = MALLOC(SIZE)

Arguments:

<var>SIZE</var>	The type shall be INTEGER.

Return value:

The return value is of type INTEGER(K), with <var>K</var> such that
variables of type INTEGER(K) have the same size as
C pointers (sizeof(void *)).

Example:

The following example demonstrates the use of MALLOC and
FREE with Cray pointers.

program test_malloc
  implicit none
  integer i
  real*8 x(*), z
  pointer(ptr_x,x)

  ptr_x = malloc(20*8)
  do i = 1, 20
    x(i) = sqrt(1.0d0 / i)
  end do
  z = 0
  do i = 1, 20
    z = z + x(i)
    print *, z
  end do
  call free(ptr_x)
end program test_malloc

See also:

FREE


text:
#ifndef OGR_XERCES_HEADERS_H
#define OGR_XERCES_HEADERS_H

#if ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2)) && !defined(_MSC_VER))
#pragma GCC system_header
#endif

#include <util/PlatformUtils.hpp>

#ifdef XERCES_CPP_NAMESPACE_USE
XERCES_CPP_NAMESPACE_USE
#endif

#endif /* OGR_XERCES_HEADERS_H */


text:
class Account
  class InsufficentFundException < StandardError;end
  include MongoMapper::Document
  safe

  key :name, String
  key :balance, Integer, :default=>0

  timestamps!

  ensure_index(:name, :unique => true)
  #ensure_index(:match_count)
  #ensure_index(:win_count)
  #ensure_index(:step_count)
  #ensure_index(:guess_hits_count)

  protected :balance=

  def withdraw(amount)
    if self.balance < amount
      raise InsufficentFundException
    end
    self.balance -= amount
  end
  def deposit(amount)
    self.balance += amount
  end
end


text:
#pragma once
#include <aws/workdocs/WorkDocs_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace WorkDocs
{
namespace Model
{
  enum class ResourceType
  {
    NOT_SET,
    FOLDER,
    DOCUMENT
  };

namespace ResourceTypeMapper
{
AWS_WORKDOCS_API ResourceType GetResourceTypeForName(const Aws::String& name);

AWS_WORKDOCS_API Aws::String GetNameForResourceType(ResourceType value);
} // namespace ResourceTypeMapper
} // namespace Model
} // namespace WorkDocs
} // namespace Aws


text:
<?php

namespace MagePal\GmailSmtpApp\Plugin\Mail;

class TransportPlugin extends \Zend_Mail_Transport_Smtp
{
    /** @var \MagePal\GmailSmtpApp\Helper\Data */
    protected $dataHelper;

    /**
     * @param \MagePal\GmailSmtpApp\Helper\Data $dataHelper
     */
    public function __construct(\MagePal\GmailSmtpApp\Helper\Data $dataHelper)
    {
        $this->dataHelper = $dataHelper;
    }

    /**
     * @param \Magento\Framework\Mail\TransportInterface $subject
     * @param \Closure $proceed
     */
    public function aroundSendMessage(\Magento\Framework\Mail\TransportInterface $subject, \Closure $proceed){

        if($this->dataHelper->isActive()){
            $message = $subject->getMessage();
            $this->sendSmtpMessage($message);
        }
        else{
            $proceed();
        }
    }

    /**
     * @param \Magento\Framework\Mail\MessageInterface $message
     * @throws \Magento\Framework\Exception\MailException
     */
    public function sendSmtpMessage(\Magento\Framework\Mail\MessageInterface $message){
        $dataHelper = $this->dataHelper;

        //Set reply-to path
        $setReturnPath = $dataHelper->getConfigSetReturnPath();
        switch ($setReturnPath) {
            case 1:
                $returnPathEmail = $message->getFrom();
                break;
            case 2:
                $returnPathEmail = $dataHelper->getConfigReturnPathEmail();
                break;
            default:
                $returnPathEmail = null;
                break;
        }

        if ($returnPathEmail !== null && $dataHelper->getConfigSetReturnPath()) {
            $message->setReturnPath($returnPathEmail);
        }

        if ($message->getReplyTo() === NULL && $dataHelper->getConfigSetReplyTo()) {
            $message->setReplyTo($returnPathEmail);
        }

        if ($returnPathEmail !== null && $dataHelper->getConfigSetFrom()) {
            $message->clearFrom();
            $message->setFrom($returnPathEmail);
        }

        //set config
        $smtpConf = [
            'name' => $dataHelper->getConfigName(),
            'port' => $dataHelper->getConfigSmtpPort(),
        ];

        $auth = strtolower($dataHelper->getConfigAuth());
        if ($auth != 'none') {
            $smtpConf['auth'] = $auth;
            $smtpConf['username'] = $dataHelper->getConfigUsername();
            $smtpConf['password'] = $dataHelper->getConfigPassword();
        }

        $ssl = $dataHelper->getConfigSsl();
        if ($ssl != 'none') {
            $smtpConf['ssl'] = $ssl;
        }
        $smtpHost = $dataHelper->getConfigSmtpHost();
        $this->initialize($smtpHost, $smtpConf);

        try {
            parent::send($message);
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\MailException(new \Magento\Framework\Phrase($e->getMessage()), $e);
        }
    }

    /**
     * @param string $host
     * @param array $config
     */
    public function initialize($host = '127.0.0.1', Array $config = array())
    {
        if (isset($config['name'])) {
            $this->_name = $config['name'];
        }
        if (isset($config['port'])) {
            $this->_port = $config['port'];
        }
        if (isset($config['auth'])) {
            $this->_auth = $config['auth'];
        }

        $this->_host = $host;
        $this->_config = $config;
    }
}


text:
<?php
namespace Imagery;

use Imagery\Element\Image\Jpeg;
use Imagery\Element\Image\Png;
use Imagery\Element\Image\Gif;

/**
 * Factory class to generate an image response by image.
 *
 * The Factory class does some mime guessing and create an image by mime type (if supported).
 * It is the convinient way to use Imagery but you can also create an Image by explicit type.
 *
 * @package Imagery
 * @author Willi Eßer <contact@troublete.com>
 * @version Jun 2015
 */
class ImageFactory
{
    /**
     * class var that contains the path of the image
     * @var string
     */
    private $path;

    /**
     * class var that contains the image
     * @var \Imagery\Element\Image
     */
    private $image;

    /**
     * basic constructor function to init the process by providing an file path
     * @param string $path
     */
    public function __construct($path)
    {
        try {
            if (empty($path))
            {
                throw new \Exception('The use of the ImageFactory requires an path name to start the whole process. Place provide an image.');
            }

            $this->path = $path;
            $this->setImage();
        }
        catch(\Exception $ex)
        {
            return $ex;
        }
    }

    /**
     * function to guess which mime type / which image type it is
     * @return string
     */
    private function guessType()
    {
        $file_info = \finfo_open(FILEINFO_MIME_TYPE);
        return \finfo_file($file_info, $this->path);
    }

    /**
     * function to set the create the image via mime type
     */
    private function setImage()
    {
        $mime = $this->guessType();

        if (Jpeg::MIME == $mime)
        {
            $this->image = new Jpeg();
        }
        else if (Png::MIME == $mime)
        {
            $this->image = new Png();
        }
        else if (Gif::MIME == $mime)
        {
            $this->image = new Gif();
        }
        else
        {
            $this->image = null;
            return;
        }

        $this->image->setup($this->path);
        $this->image->setImageResource($this->image->createResource($this->path));
        return $this;
    }

    /**
     * function to return the image
     * @return \Imagery\Element\Image
     */
    public function getImage()
    {
        return $this->image;
    }
}


text:
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Article } from "./articles/article";
import { Category } from "./categories/category";

export class InMemoryDataService implements InMemoryDbService {
  createDb () {
    const articles: Article[]= [
      {
        _id: 1,
        title: 'test1',
        author: { name: 'robert', email: 'a@b.c' },
        date: new Date(),
        category: 'test',
        content: 'this is a test article.  This sentence should only display on'
          + ' click. Same goes for this one.',
        sticky: false,
        image: '',
        image_dimensions: { width: 0, height: 0 }
      },
      {
        _id: 2,
        title: 'test2',
        author: { name: 'mitchell', email: 'a@b.c' },
        date: new Date(),
        category: 'test',
        content: 'this is another test article. This sentence should only '
          + 'display on click.',
        sticky: false,
        image: '',
        image_dimensions: { width: 0, height: 0 }
      },
      {
        _id: 3,
        title: 'When Learning a Dead Language, Read, Reread, and Reread Again',
        author: { name: "Robert Mitchell", email: 'robert.mitchell36@gmail.com'},
        date: new Date(),
        category: 'Classics',
        content: '
While many students of foreign language rely heavily on '
          + 'dialogue with native speakers for improvement, those of us '
          + 'learning dead languages such as Latin and ancient Greek tend to '
          + 'think we lack that luxury. It is true that we cannot simply come '
          + 'upon a native speaker in the wild, but we can still dialogue with '
          + 'native speakers in a meaningful and beneficial way: by drinking '
          + 'deeply from the literary traditions they left behind. These texts '
          + 'can be our conversation partners if we would simply allow them to '
          + 'lead the discussion, and test our abilities with a reply in their '
          + 'language. Still, reaching that level of experience where phrasing '
          + 'complex thoughts in the language is possible, is difficult. How '
          + 'does the student of a dead language raise his abilities that high '
          + 'above the dirt?
' +
        '
When I first started learning Latin, I knew from past experience '
          + 'in studying Mandarin that the best way to cement knowledge of '
          + 'grammar and vocabulary was to read as much as I could in the '
          + 'language to see them used properly as much as possible. After a '
          + 'few chapters of Wheelock\'s Latin, I became concerned that I '
          + 'wouldn\'t have that luxury, since most of the reading in the book '
          + 'was one-line sentences which often had grammatical ambiguities '
          + 'arising from lack of context greatly diminishing their utility. '
          + 'Because of this, the language remained foreign, not familiar: I '
          + 'could look at the text and determine what it meant, but the Latin '
          + 'felt uncomfortable.
',
        sticky: true,
        image: '',
        image_dimensions: { width: 0, height: 0 }
      }
    ];
    const categories: Category[] = [
      {
        "_id": "57b5423cf22c6b7d4055fef4",
        "name": "Technology",
        "description": "\"... adding one thing to another to find the scheme "
          + "of things\" Ecclesiastes vii 27b ESV",
        "aboutAuthor": "Technology, and especially Computer Programming, ought "
          + "to be approached with all their underlying structure and beauty "
          + "in mind, not simply as tools to finish a job.",
      },
      {
        "_id": "57b615eb2bbb9de840f4970c",
        "name": "Everything",
        "description": "\"What the heart liketh best, the mind studieth most.\""
          + " - Richard Sibbes",
        "aboutAuthor": "Robert Mitchell is Reformed & Presbyterian (a member "
          + "of the OPC), a reader of Classics, Mathematics, Poetry, "
          + "Philosophy & Theology, and a student of Chinese, Greek & Latin.",
        },
      {
        "_id": "58acbd8e82ed51604029fa01",
        "name": "Mathematics",
        "description": "So teach us to number our days, that we may apply our "
          + "hearts unto wisdom. - Psalm xc 12",
        "aboutAuthor": "If Logic is the greatest tool of the human mind, then "
          + "Mathematics is perhaps the best sandbox in which it can play: "
          + "with endless subjects to explore, innumerable ways to apply even "
          + "the most basic thoughts, and a strange sense of beauty that seems "
          + "unique to some of the most elegant theorems.",
        },
      {
        "_id": "58ae18bb82ed51604029fa04",
        "name": "Classics",
        "description": "\"To read the Latin and Greek authors in their "
          + "original, is a sublime luxury ...\" - Thomas Jefferson",
        "aboutAuthor": "The Classics are those great Greek and Roman works "
          + "that have stood the test of time quite literally, with copies "
          + "being written over the past two to three thousand years, in "
          + "genres ranging from love poetry to dry history, nevertheless "
          + "captivating the imaginations of generations of scholars and "
          + "laymen alike."
      },
      {
        _id: '0',
        name: 'Latest Articles',
        description: '"What the heart liketh best, the mind studieth most." - Richard Sibbes',
        aboutAuthor: 'Robert Mitchell is Reformed & Presbyterian (a member of '
          + 'the OPC), a reader of Classics, Mathematics, Poetry, Philosophy & '
          + 'Theology, and a student of Chinese, Greek & Latin.'
      }
    ];
    return { articles, categories };
  }
}


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

Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions
    Public Class MyBaseKeywordRecommenderTests
        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoneInClassDeclarationTest()
            VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoneInModuleDeclarationTest()
            VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoneInModuleMethodBodyTest()
            VerifyRecommendationsMissing(<ModuleMethodBody>|</ModuleMethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoneInStructureDeclarationTest()
            VerifyRecommendationsMissing(<StructureDeclaration>|</StructureDeclaration>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoneInStructureMethodBodyTest()
            VerifyRecommendationsMissing(<StructureMethodBody>|</StructureMethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseInStatementTest()
            VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterReturnTest()
            VerifyRecommendationsContain(<MethodBody>Return |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterArgument1Test()
            VerifyRecommendationsContain(<MethodBody>Goo(|</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterArgument2Test()
            VerifyRecommendationsContain(<MethodBody>Goo(bar, |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterBinaryExpressionTest()
            VerifyRecommendationsContain(<MethodBody>Goo(bar + |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterNotTest()
            VerifyRecommendationsContain(<MethodBody>Goo(Not |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterTypeOfTest()
            VerifyRecommendationsContain(<MethodBody>If TypeOf |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterDoWhileTest()
            VerifyRecommendationsContain(<MethodBody>Do While |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterDoUntilTest()
            VerifyRecommendationsContain(<MethodBody>Do Until |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterLoopWhileTest()
            VerifyRecommendationsContain(<MethodBody>
Do
Loop While |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterLoopUntilTest()
            VerifyRecommendationsContain(<MethodBody>
Do
Loop Until |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterIfTest()
            VerifyRecommendationsContain(<MethodBody>If |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterElseIfTest()
            VerifyRecommendationsContain(<MethodBody>ElseIf |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterElseSpaceIfTest()
            VerifyRecommendationsContain(<MethodBody>Else If |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterErrorTest()
            VerifyRecommendationsContain(<MethodBody>Error |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterThrowTest()
            VerifyRecommendationsContain(<MethodBody>Throw |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterInitializerTest()
            VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterArrayInitializerSquiggleTest()
            VerifyRecommendationsContain(<MethodBody>Dim x = {|</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseAfterArrayInitializerCommaTest()
            VerifyRecommendationsContain(<MethodBody>Dim x = {0, |</MethodBody>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseNotInModuleTest()
            VerifyRecommendationsMissing(<File>
Module Goo
Sub Goo()
|
End Sub()
End Module</File>, "MyBase")
        End Sub

        <Fact>
        <Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseInStructureTest()
            VerifyRecommendationsMissing(<File>
Module Goo
Sub Goo()
|
End Sub()
End Module</File>, "MyBase")
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseToHandleInheritedMemberTest()
            Dim text = <File>Public Class BaseClass
    Protected Event Event1()
End Class

Public Class Class1
    Inherits BaseClass

        Sub Handler() Handles |
    End Class</File>

            VerifyRecommendationsContain(text, "MyBase")
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoMyBaseToHandleInheritedMemberIfThereIsNotOneTest()
            Dim text = <File>Public Class BaseClass
End Class

Public Class Class1
    Inherits BaseClass

        Sub Handler() Handles |
    End Class |</File>

            VerifyRecommendationsMissing(text, "MyBase")
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub NoMyBaseToHandleInaccessibleInheritedMemberTest()
            Dim text = <File>Public Class Base
    Private Event Click()
    Sub a() Handles MyClass.Click
    End Sub
End Class
Public Class Derived
    Inherits Base
    Sub b() Handles |
End Class
</File>

            VerifyRecommendationsMissing(text, "MyBase")
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseInNameOf1Test()
            VerifyRecommendationsContain(<MethodBody>Dim s = NameOf(|</MethodBody>, "MyBase")
        End Sub

        <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
        Public Sub MyBaseInNameOf2Test()
            VerifyRecommendationsMissing(<MethodBody>Dim s = NameOf(System.|</MethodBody>, "MyBase")
        End Sub
    End Class
End Namespace


text:
"""
libOpenCM3

The libOpenCM3 framework aims to create a free/libre/open-source
firmware library for various ARM Cortex-M0(+)/M3/M4 microcontrollers,
including ST STM32, Ti Tiva and Stellaris, NXP LPC 11xx, 13xx, 15xx,
17xx parts, Atmel SAM3, Energy Micro EFM32 and others.

http://www.libopencm3.org/wiki/Main_Page
"""

from __future__ import absolute_import

import re
from os import listdir, sep, walk
from os.path import isfile, join, normpath

from SCons.Script import DefaultEnvironment

from platformio.util import exec_command

env = DefaultEnvironment()

env.Replace(
    PLATFORMFW_DIR=join("$PIOPACKAGES_DIR", "framework-libopencm3")
)

BOARD_BUILDOPTS = env.get("BOARD_OPTIONS", {}).get("build", {})

def find_ldscript(src_dir):
    ldscript = None
    matches = []
    for item in sorted(listdir(src_dir)):
        _path = join(src_dir, item)
        if not isfile(_path) or not item.endswith(".ld"):
            continue
        matches.append(_path)

    if len(matches) == 1:
        ldscript = matches[0]
    elif isfile(join(src_dir, BOARD_BUILDOPTS['ldscript'])):
        ldscript = join(src_dir, BOARD_BUILDOPTS['ldscript'])

    assert isfile(ldscript)
    return ldscript

def generate_nvic_files():
    fw_dir = env.subst("$PLATFORMFW_DIR")
    for root, _, files in walk(join(fw_dir, "include", "libopencm3")):
        if "irq.json" not in files or isfile(join(root, "nvic.h")):
            continue

        exec_command(
            ["python", join("scripts", "irq2nvic_h"),
             join("." + root.replace(fw_dir, ""),
                  "irq.json").replace("\\", "/")],
            cwd=fw_dir
        )

def parse_makefile_data(makefile):
    data = {"includes": [], "objs": [], "vpath": ["./"]}

    with open(makefile) as f:
        content = f.read()

        # fetch "includes"
        re_include = re.compile(r"^include\s+([^\r\n]+)", re.M)
        for match in re_include.finditer(content):
            data['includes'].append(match.group(1))

        # fetch "vpath"s
        re_vpath = re.compile(r"^VPATH\s+\+?=\s+([^\r\n]+)", re.M)
        for match in re_vpath.finditer(content):
            data['vpath'] += match.group(1).split(":")

        # fetch obj files
        objs_match = re.search(
            r"^OBJS\s+\+?=\s+([^\.]+\.o\s*(?:\s+\\s+)?)+", content, re.M)
        assert objs_match
        data['objs'] = re.sub(
            r"(OBJS|[\+=\\\s]+)", "\n", objs_match.group(0)).split()
    return data

def get_source_files(src_dir):
    mkdata = parse_makefile_data(join(src_dir, "Makefile"))

    for include in mkdata['includes']:
        _mkdata = parse_makefile_data(normpath(join(src_dir, include)))
        for key, value in _mkdata.iteritems():
            for v in value:
                if v not in mkdata[key]:
                    mkdata[key].append(v)

    sources = []
    lib_root = env.subst("$PLATFORMFW_DIR")
    for obj_file in mkdata['objs']:
        src_file = obj_file[:-1] + "c"
        for search_path in mkdata['vpath']:
            src_path = normpath(join(src_dir, search_path, src_file))
            if isfile(src_path):
                sources.append(join("$BUILD_DIR", "FrameworkLibOpenCM3",
                                    src_path.replace(lib_root + sep, "")))
                break
    return sources

def merge_ld_scripts(main_ld_file):

    def _include_callback(match):
        included_ld_file = match.group(1)
        # search included ld file in lib directories
        for root, _, files in walk(env.subst(join("$PLATFORMFW_DIR", "lib"))):
            if included_ld_file not in files:
                continue
            with open(join(root, included_ld_file)) as fp:
                return fp.read()
        return match.group(0)

    content = ""
    with open(main_ld_file) as f:
        content = f.read()

    incre = re.compile(r"^INCLUDE\s+\"?([^\.]+\.ld)\"?", re.M)
    with open(main_ld_file, "w") as f:
        f.write(incre.sub(_include_callback, content))

#
# Processing ...
#

if BOARD_BUILDOPTS.get("core") == "lm4f":
    env.Append(
        CPPDEFINES=["LM4F"]
    )

env.VariantDirWrap(
    join("$BUILD_DIR", "FrameworkLibOpenCM3Variant"),
    join("$PLATFORMFW_DIR", "include")
)

env.Append(
    CPPPATH=[
        join("$BUILD_DIR", "FrameworkLibOpenCM3"),
        join("$BUILD_DIR", "FrameworkLibOpenCM3Variant")
    ]
)

root_dir = env.subst(
    join("$PLATFORMFW_DIR", "lib", BOARD_BUILDOPTS.get("core")))
if BOARD_BUILDOPTS.get("core") == "stm32":
    root_dir = join(root_dir, BOARD_BUILDOPTS.get("variant")[5:7])

ldscript_path = find_ldscript(root_dir)
merge_ld_scripts(ldscript_path)
generate_nvic_files()

# override ldscript by libopencm3
assert "LDSCRIPT_PATH" in env
env.Replace(
    LDSCRIPT_PATH=ldscript_path
)

libs = []
env.VariantDirWrap(
    join("$BUILD_DIR", "FrameworkLibOpenCM3"),
    "$PLATFORMFW_DIR"
)
libs.append(env.Library(
    join("$BUILD_DIR", "FrameworkLibOpenCM3"),
    get_source_files(root_dir)
))

env.Append(LIBS=libs)


text:
import { parse as parseContentTypeHeader } from 'content-type';
import { HttpHeaders } from '../types/http-header';
import { isLocalFile } from './is-local-file';

/** Convenience function to check if a resource is a HTMLDocument. */
export const isHTMLDocument = (targetURL: string, responseHeaders: HttpHeaders): boolean => {

    // If it's a local file, presume it's a HTML document.

    if (isLocalFile(targetURL)) {
        return true;
    }

    // Otherwise, check.

    const contentTypeHeaderValue: string | undefined = responseHeaders['content-type'];
    let mediaType: string;

    try {
        mediaType = parseContentTypeHeader(contentTypeHeaderValue || '').type;
    } catch (e) {
        return false;
    }

    return mediaType === 'text/html';
};


text:
require 'rubygems'
require 'sinatra'
require 'json'
require 'pg'
# require 'octokit'
# require 'coveralls'
# require 'travis'
require "httparty"
require "sinatra/multi_route"
require 'yaml'
require 'active_record'

require_relative 'models/models'
require_relative 'models/methods'
#require_relative "roapi_utils"

$config = YAML::load_file(File.join(__dir__, 'config.yaml'))

ActiveSupport::Deprecation.silenced = true
val = ENV['SSH_CLIENT']
if val.to_s == ''
  ActiveRecord::Base.establish_connection($config['db']['localhost'])
else
  ActiveRecord::Base.establish_connection($config['db']['ec2'])
end

class ROApp < Sinatra::Application
  register Sinatra::MultiRoute

  # before do
  #   # puts '[ENV]'
  #   # p ENV
  #   puts '[Params]'
  #   p params
  #   # puts '[body]'
  #   # p JSON.parse(request.body.read)
  # end

  ## configuration
  configure do
    set :raise_errors, true
    set :show_exceptions, true
    set :protection, :except => [:json_csrf]
  end

  # halt: error helpers
  # error 400 do
  #   halt 400, {'Content-Type' => 'application/json'}, JSON.generate({ 'error' => 'malformed request' })
  # end

  error 401 do
    halt 401, {'Content-Type' => 'application/json'}, JSON.generate({ 'error' => 'unauthorized' })
  end

  not_found do
    halt 404, {'Content-Type' => 'application/json'}, JSON.generate({ 'error' => 'route not found' })
  end

  error 405 do
    halt 405, {'Content-Type' => 'application/json'}, JSON.generate({ 'error' => 'Method Not Allowed' })
  end

  error 500 do
    halt 500, {'Content-Type' => 'application/json'}, JSON.generate({ 'error' => 'server error' })
  end

  # headers and auth helpers
  helpers do
    def headers_get
      headers "Content-Type" => "application/json; charset=utf8"
      headers "Access-Control-Allow-Methods" => "HEAD, GET"
      headers "Access-Control-Allow-Origin" => "*"
      cache_control :public, :must_revalidate, :max_age => 60
    end

    def headers_auth
      headers "Content-Type" => "application/json; charset=utf8"
      headers "Access-Control-Allow-Methods" => "HEAD, GET, POST, PUT, DELETE"
      headers "Access-Control-Allow-Origin" => "*"
      cache_control :public, :must_revalidate, :max_age => 60
    end

    def protected!
      return if authorized?
      headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
      halt 401
    end

    def authorized?
      @auth ||=  Rack::Auth::Basic::Request.new(request.env)
      @auth.provided? and @auth.basic? and @auth.credentials and @auth.credentials == [ENV['ROAPI_USER'], ENV['ROAPI_PWD']]
    end
  end

  # handler - redirects any /foo -> /foo/
  #  - if has any query params, passes to handler as before
  get %r{(/.*[^\/])$} do
    if request.query_string == "" or request.query_string.nil?
      redirect request.script_name + "#{params[:captures].first}/"
    else
      pass
    end
  end

  ## routes
  get '/?' do
    headers_get
    redirect '/heartbeat'
  end

  get '/docs/?' do
    headers_get
    redirect 'https://github.com/ropensci/roapi/wiki', 301
  end

  get "/heartbeat/?" do
    headers_get
    $ip = request.ip
    return JSON.pretty_generate({
      "routes" => [
        "/docs (GET)",
        "/heartbeat (GET)",
        "/repos (GET)",
        "/repos/:repo_name: (GET) (POST, PUT, DELETE [auth])",
        "/repos/:repo_name:/github (GET)",
        "/repos/:repo_name:/travis (GET)",
        "/repos/:repo_name:/appveyor (GET)",
        "/repos/:repo_name:/cranlogs (GET)",
        "/repos/:repo_name:/cran (GET)",
        "/repos/:repo_name:/dependencies (GET)",
        "/repos/:repo_name:/citations (GET)",
        "/repos/:repo_name:/groupings (GET)",
        "/repos/:repo_name:/categories (GET)",
        "/categories (GET)",
        "/groupings (GET)"
      ]
    })
  end

  get '/repos/?' do
    headers_get
    begin
      data = get_repo(params)
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/repos/:name/?' do
    headers_get
    begin
      data = get_repo(params)
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  # routes to get individual tables
  get '/repos/:name/github/?' do
    headers_get
    begin
      data = get_repo_table('github')
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/repos/:name/travis/?' do
    headers_get
    begin
      data = get_repo_table('travis')
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/repos/:name/appveyor/?' do
    headers_get
    begin
      data = get_repo_table('appveyor')
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/repos/:name/cranlogs/?' do
    headers_get
    begin
      data = get_repo_table('cranlogs')
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/repos/:name/cran/?' do
    headers_get
    begin
      data = get_repo_table('cran')
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  # dependencies and reverse dependencies
  get '/repos/:name/dependencies/?' do
    headers_get
    begin
      data = get_repo_deps()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  # citations
  get '/repos/:name/citations/?' do
    headers_get
    begin
      data = get_repo_citations()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  # groupings
  get '/repos/:name/groupings/?' do
    headers_get
    begin
      data = get_repo_groupings()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/groupings/?' do
    headers_get
    begin
      data = get_all_groupings()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/groupings/:grouping/?' do
    headers_get
    begin
      data = get_groupings()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  # categories
  get '/repos/:name/categories/?' do
    headers_get
    begin
      data = get_repo_categories()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/categories/?' do
    headers_get
    begin
      data = get_all_categories()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  get '/categories/:category/?' do
    headers_get
    begin
      data = get_categories()
      raise Exception.new('no results found') if data.length.zero?
      { count: data.length, error: nil, data: data }.to_json
    rescue Exception => e
      halt 400, { count: 0, error: { message: e.message }, data: nil }.to_json
    end
  end

  # prevent some HTTP methods
  route :copy, :patch, :options, :trace, '/*' do
    halt 405
  end

end


text:
package org.nkjmlab.util.twitter;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import twitter4j.Twitter;
import twitter4j.auth.AccessToken;
import twitter4j.auth.NullAuthorization;

public class TwitterFactory {

  public static Twitter create() {
    return create("/twitter4j.properties", "UTF-8");
  }

  public static Twitter create(String name, String charsetName) {
    Twitter twitter = new twitter4j.TwitterFactory().getInstance();
    if (!(twitter.getAuthorization() instanceof NullAuthorization)) {
      return twitter;
    }
    Properties props = readPropertiesFromResource(name, charsetName);
    AccessToken accessToken = new AccessToken(props.getProperty("oauth.accessToken"),
        props.getProperty("oauth.accessTokenSecret"));
    twitter.setOAuthConsumer(props.getProperty("oauth.consumerKey"),
        props.getProperty("oauth.consumerSecret"));
    twitter.setOAuthAccessToken(accessToken);
    return twitter;

  }

  private static Properties readPropertiesFromResource(String name, String charsetName) {
    Properties props = new Properties();
    try (InputStream in = TwitterFactory.class.getResourceAsStream(name);
        InputStreamReader reader = new InputStreamReader(in, charsetName)) {
      props.load(reader);
    } catch (IOException e) {
      throw new RuntimeException();
    }
    return props;
  }
}


text:
'use strict';
var ko = require('knockout');
require('knockout-punches');
var $ = require('jquery');
var $osf = require('osfHelpers');

ko.punches.enableAll();
var language = require('osfLanguage').Addons.dataverse;

function ViewModel(url) {
    var self = this;
    self.connected = ko.observable();
    self.dataverse = ko.observable();
    self.dataverseUrl = ko.observable();
    self.study = ko.observable();
    self.doi = ko.observable();
    self.studyUrl = ko.observable('');
    self.citation = ko.observable('');
    self.loaded = ko.observable(false);

    // Flashed messages
    self.message = ko.observable('');
    self.messageClass = ko.observable('text-info')

    self.init = function() {
        $.ajax({
            url: url, type: 'GET', dataType: 'json',
            success: function(response) {
                var data = response.data;
                self.connected(data.connected);
                self.dataverse(data.dataverse);
                self.dataverseUrl(data.dataverseUrl);
                self.study(data.study);
                self.doi(data.doi);
                self.studyUrl(data.studyUrl);
                self.citation(data.citation);
                self.loaded(true);
            },
            error: function(xhr) {
                self.loaded(true);
                var errorMessage = (xhr.status === 403) ? language.widgetInvalid : language.widgetError;
                self.changeMessage(errorMessage, 'text-danger');
            }
        });
    };

    /** Change the flashed status message */
    self.changeMessage = function(text, css, timeout) {
        self.message(text);
        var cssClass = css || 'text-info';
        self.messageClass(cssClass);
        if (timeout) {
            // Reset message after timeout period
            setTimeout(function() {
                self.message('');
                self.messageClass('text-info');
            }, timeout);
        }
    };
}

// Public API
function DataverseWidget(selector, url) {
    var self = this;
    self.viewModel = new ViewModel(url);
    $osf.applyBindings(self.viewModel, selector);
    self.viewModel.init();
}

module.exports = DataverseWidget;