text:
.class public Lcom/mixpanel/android/mpmetrics/MixpanelAPI;
.super Ljava/lang/Object;
.source ""

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/mixpanel/android/mpmetrics/MixpanelAPI$ExpiringLock;,
        Lcom/mixpanel/android/mpmetrics/MixpanelAPI$PeopleImpl;,
        Lcom/mixpanel/android/mpmetrics/MixpanelAPI$InstanceProcessor;,
        Lcom/mixpanel/android/mpmetrics/MixpanelAPI$People;
    }
.end annotation

# static fields
.field private static final ENGAGE_DATE_FORMAT_STRING:Ljava/lang/String; = "yyyy-MM-dd\'T\'HH:mm:ss"

.field private static final LOGTAG:Ljava/lang/String; = "MixpanelAPI"

.field public static final VERSION:Ljava/lang/String; = "4.0.0"

.field private static final sInstanceMap:Ljava/util/Map; = null
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/Map<Ljava/lang/String;Ljava/util/Map<Landroid/content/Context;Lcom/mixpanel/android/mpmetrics/MixpanelAPI;>;>;"
        }
    .end annotation
.end field

.field private static final sPrefsLoader:Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader; = null

.field private static sReferrerPrefs:Ljava/util/concurrent/Future; = null
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/concurrent/Future<Landroid/content/SharedPreferences;>;"
        }
    .end annotation
.end field

# instance fields
.field private final checkForSurveysLock:Lcom/mixpanel/android/mpmetrics/MixpanelAPI$ExpiringLock;

.field private mCachedSurveyActivityHashcode:I

.field private final mCachedSurveyAssetsLock:Ljava/lang/Object;

.field private mCachedSurveyBitmap:Landroid/graphics/Bitmap;

.field private mCachedSurveyHighlightColor:I

.field private final mContext:Landroid/content/Context;

.field private final mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

.field private final mPeople:Lcom/mixpanel/android/mpmetrics/MixpanelAPI$PeopleImpl;

.field private final mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

.field private final mToken:Ljava/lang/String;

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

    .line 1248
    new-instance v0, Ljava/util/HashMap;

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

    sput-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sInstanceMap:Ljava/util/Map;

    .line 1249
    new-instance v0, Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader;

    invoke-direct {v0}, Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader;-><init>()V

    sput-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sPrefsLoader:Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader;

    return-void
.end method

.method constructor <init>(Landroid/content/Context;Ljava/util/concurrent/Future;Ljava/lang/String;)V
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Landroid/content/Context;Ljava/util/concurrent/Future<Landroid/content/SharedPreferences;>;Ljava/lang/String;)V"
        }
    .end annotation

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

    .line 1239
    new-instance v0, Ljava/lang/Object;

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

    iput-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyAssetsLock:Ljava/lang/Object;

    .line 1240
    const/4 v0, -0x1

    iput v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyActivityHashcode:I

    .line 1245
    new-instance v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI$ExpiringLock;

    const-wide/16 v1, 0x2710

    const/4 v3, 0x0

    invoke-direct {v0, v1, v2, v3}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI$ExpiringLock;-><init>(JLcom/mixpanel/android/mpmetrics/MixpanelAPI$1;)V

    iput-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->checkForSurveysLock:Lcom/mixpanel/android/mpmetrics/MixpanelAPI$ExpiringLock;

    .line 103
    iput-object p1, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mContext:Landroid/content/Context;

    .line 104
    iput-object p3, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mToken:Ljava/lang/String;

    .line 105
    new-instance v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI$PeopleImpl;

    const/4 v1, 0x0

    invoke-direct {v0, p0, v1}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI$PeopleImpl;-><init>(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;Lcom/mixpanel/android/mpmetrics/MixpanelAPI$1;)V

    iput-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPeople:Lcom/mixpanel/android/mpmetrics/MixpanelAPI$PeopleImpl;

    .line 106
    invoke-virtual {p0}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->getAnalyticsMessages()Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    move-result-object v0

    iput-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    .line 108
    new-instance v4, Lcom/mixpanel/android/mpmetrics/MixpanelAPI$1;

    invoke-direct {v4, p0}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI$1;-><init>(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)V

    .line 118
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sPrefsLoader:Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader;

    new-instance v1, Ljava/lang/StringBuilder;

    const-string v2, "com.mixpanel.android.mpmetrics.MixpanelAPI_"

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

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

    move-result-object v1

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

    move-result-object v1

    invoke-virtual {v0, p1, v1, v4}, Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader;->loadPreferences(Landroid/content/Context;Ljava/lang/String;Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader$OnPrefsLoadedListener;)Ljava/util/concurrent/Future;

    move-result-object p1

    .line 119
    new-instance v0, Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-direct {v0, p2, p1}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;-><init>(Ljava/util/concurrent/Future;Ljava/util/concurrent/Future;)V

    iput-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    .line 120
    invoke-virtual {p0}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->registerMixpanelActivityLifecycleCallbacks()V

    .line 121
    return-void
.end method

.method static synthetic access$100(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;Lorg/json/JSONArray;)V
    .locals 0

    .line 91
    invoke-direct {p0, p1}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sendAllPeopleRecords(Lorg/json/JSONArray;)V

    return-void
.end method

.method static synthetic access$1000(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)I
    .locals 1

    .line 91
    iget v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyHighlightColor:I

    return v0
.end method

.method static synthetic access$1002(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;I)I
    .locals 0

    .line 91
    iput p1, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyHighlightColor:I

    return p1
.end method

.method static synthetic access$1100(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)I
    .locals 1

    .line 91
    iget v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyActivityHashcode:I

    return v0
.end method

.method static synthetic access$1102(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;I)I
    .locals 0

    .line 91
    iput p1, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyActivityHashcode:I

    return p1
.end method

.method static synthetic access$1200(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)Landroid/content/Context;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mContext:Landroid/content/Context;

    return-object v0
.end method

.method static synthetic access$200(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)Lcom/mixpanel/android/mpmetrics/PersistentProperties;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    return-object v0
.end method

.method static synthetic access$300(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)V
    .locals 0

    .line 91
    invoke-direct {p0}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->pushWaitingPeopleRecord()V

    return-void
.end method

.method static synthetic access$400(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;Lorg/json/JSONObject;)V
    .locals 0

    .line 91
    invoke-direct {p0, p1}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->recordPeopleMessage(Lorg/json/JSONObject;)V

    return-void
.end method

.method static synthetic access$500(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)Lcom/mixpanel/android/mpmetrics/MixpanelAPI$ExpiringLock;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->checkForSurveysLock:Lcom/mixpanel/android/mpmetrics/MixpanelAPI$ExpiringLock;

    return-object v0
.end method

.method static synthetic access$600(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)Ljava/lang/String;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mToken:Ljava/lang/String;

    return-object v0
.end method

.method static synthetic access$700(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    return-object v0
.end method

.method static synthetic access$800(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)Ljava/lang/Object;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyAssetsLock:Ljava/lang/Object;

    return-object v0
.end method

.method static synthetic access$900(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)Landroid/graphics/Bitmap;
    .locals 1

    .line 91
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyBitmap:Landroid/graphics/Bitmap;

    return-object v0
.end method

.method static synthetic access$902(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;Landroid/graphics/Bitmap;)Landroid/graphics/Bitmap;
    .locals 0

    .line 91
    iput-object p1, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mCachedSurveyBitmap:Landroid/graphics/Bitmap;

    return-object p1
.end method

.method static allInstances(Lcom/mixpanel/android/mpmetrics/MixpanelAPI$InstanceProcessor;)V
    .locals 5

    .line 787
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sInstanceMap:Ljava/util/Map;

    move-object v1, v0

    monitor-enter v0

    .line 788
    :try_start_0
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sInstanceMap:Ljava/util/Map;

    invoke-interface {v0}, Ljava/util/Map;->values()Ljava/util/Collection;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v2

    :goto_0
    invoke-interface {v2}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_1

    invoke-interface {v2}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/util/Map;

    .line 789
    invoke-interface {v0}, Ljava/util/Map;->values()Ljava/util/Collection;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v3

    :goto_1
    invoke-interface {v3}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_0

    invoke-interface {v3}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;

    move-object v4, v0

    .line 790
    invoke-interface {p0, v4}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI$InstanceProcessor;->process(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)V

    .line 791
    goto :goto_1

    .line 792
    :cond_0
    goto :goto_0

    .line 793
    :cond_1
    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    return-void

    :catchall_0
    :try_start_1
    move-exception p0

    monitor-exit v1
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    throw p0
.end method

.method public static enableFallbackServer(Landroid/content/Context;Z)V
    .locals 2
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation

    .line 218
    invoke-static {p0}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->getInstance(Landroid/content/Context;)Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    move-result-object v0

    .line 226
    if-nez p1, :cond_0

    const/4 v1, 0x1

    goto :goto_0

    :cond_0
    const/4 v1, 0x0

    :goto_0
    invoke-virtual {v0, v1}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->setDisableFallback(Z)V

    .line 227
    return-void
.end method

.method public static getInstance(Landroid/content/Context;Ljava/lang/String;)Lcom/mixpanel/android/mpmetrics/MixpanelAPI;
    .locals 6

    .line 150
    if-eqz p1, :cond_0

    if-nez p0, :cond_1

    .line 151
    :cond_0
    const/4 v0, 0x0

    return-object v0

    .line 153
    :cond_1
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sInstanceMap:Ljava/util/Map;

    move-object v3, v0

    monitor-enter v0

    .line 154
    :try_start_0
    invoke-virtual {p0}, Landroid/content/Context;->getApplicationContext()Landroid/content/Context;

    move-result-object v4

    .line 156
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sReferrerPrefs:Ljava/util/concurrent/Future;

    if-nez v0, :cond_2

    .line 157
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sPrefsLoader:Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader;

    const-string v1, "com.mixpanel.android.mpmetrics.ReferralInfo"

    const/4 v2, 0x0

    invoke-virtual {v0, p0, v1, v2}, Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader;->loadPreferences(Landroid/content/Context;Ljava/lang/String;Lcom/mixpanel/android/mpmetrics/SharedPreferencesLoader$OnPrefsLoadedListener;)Ljava/util/concurrent/Future;

    move-result-object v0

    sput-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sReferrerPrefs:Ljava/util/concurrent/Future;

    .line 160
    :cond_2
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sInstanceMap:Ljava/util/Map;

    invoke-interface {v0, p1}, Ljava/util/Map;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/util/Map;

    .line 161
    move-object p0, v0

    if-nez v0, :cond_3

    .line 162
    new-instance p0, Ljava/util/HashMap;

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

    .line 163
    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sInstanceMap:Ljava/util/Map;

    invoke-interface {v0, p1, p0}, Ljava/util/Map;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 166
    :cond_3
    invoke-interface {p0, v4}, Ljava/util/Map;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;

    .line 167
    move-object v5, v0

    if-nez v0, :cond_4

    .line 168
    new-instance v5, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;

    sget-object v0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sReferrerPrefs:Ljava/util/concurrent/Future;

    invoke-direct {v5, v4, v0, p1}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;-><init>(Landroid/content/Context;Ljava/util/concurrent/Future;Ljava/lang/String;)V

    .line 169
    invoke-interface {p0, v4, v5}, Ljava/util/Map;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 171
    :cond_4
    monitor-exit v3
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    return-object v5

    .line 172
    :catchall_0
    :try_start_1
    move-exception p0

    monitor-exit v3
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    throw p0
.end method

.method private pushWaitingPeopleRecord()V
    .locals 2

    .line 1164
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->waitingPeopleRecordsForSending()Lorg/json/JSONArray;

    move-result-object v0

    .line 1165
    move-object v1, v0

    if-eqz v0, :cond_0

    .line 1166
    invoke-direct {p0, v1}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->sendAllPeopleRecords(Lorg/json/JSONArray;)V

    .line 1168
    :cond_0
    return-void
.end method

.method private recordPeopleMessage(Lorg/json/JSONObject;)V
    .locals 1

    .line 1156
    const-string v0, "$distinct_id"

    invoke-virtual {p1, v0}, Lorg/json/JSONObject;->has(Ljava/lang/String;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 1157
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    invoke-virtual {v0, p1}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->peopleMessage(Lorg/json/JSONObject;)V

    return-void

    .line 1159
    :cond_0
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0, p1}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->storeWaitingPeopleRecord(Lorg/json/JSONObject;)V

    .line 1161
    return-void
.end method

.method private sendAllPeopleRecords(Lorg/json/JSONArray;)V
    .locals 3

    .line 1173
    const/4 v1, 0x0

    :goto_0
    invoke-virtual {p1}, Lorg/json/JSONArray;->length()I

    move-result v0

    if-ge v1, v0, :cond_0

    .line 1175
    :try_start_0
    invoke-virtual {p1, v1}, Lorg/json/JSONArray;->getJSONObject(I)Lorg/json/JSONObject;

    move-result-object v2

    .line 1176
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    invoke-virtual {v0, v2}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->peopleMessage(Lorg/json/JSONObject;)V
    :try_end_0
    .catch Lorg/json/JSONException; {:try_start_0 .. :try_end_0} :catch_0

    .line 1179
    nop

    .line 1177
    .line 1178
    :catch_0
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 1181
    :cond_0
    return-void
.end method

.method public static setFlushInterval(Landroid/content/Context;J)V
    .locals 1
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation

    .line 195
    invoke-static {p0}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->getInstance(Landroid/content/Context;)Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    move-result-object v0

    .line 203
    invoke-virtual {v0, p1, p2}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->setFlushInterval(J)V

    .line 204
    return-void
.end method

# virtual methods
.method clearPreferences()V
    .locals 1

    .line 808
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->clearPreferences()V

    .line 809
    return-void
.end method

.method public clearSuperProperties()V
    .locals 1

    .line 407
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->clearSuperProperties()V

    .line 408
    return-void
.end method

.method public flush()V
    .locals 1

    .line 325
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->postToServer()V

    .line 326
    return-void
.end method

.method getAnalyticsMessages()Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;
    .locals 1

    .line 801
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mContext:Landroid/content/Context;

    invoke-static {v0}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->getInstance(Landroid/content/Context;)Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    move-result-object v0

    return-object v0
.end method

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

    .line 343
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->getEventsDistinctId()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public getPeople()Lcom/mixpanel/android/mpmetrics/MixpanelAPI$People;
    .locals 1

    .line 418
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPeople:Lcom/mixpanel/android/mpmetrics/MixpanelAPI$PeopleImpl;

    return-object v0
.end method

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

    .line 255
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0, p1}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->setEventsDistinctId(Ljava/lang/String;)V

    .line 256
    return-void
.end method

.method public logPosts()V
    .locals 1

    .line 754
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->logPosts()V

    .line 755
    return-void
.end method

.method registerMixpanelActivityLifecycleCallbacks()V
    .locals 2
    .annotation build Landroid/annotation/TargetApi;
        value = 0xe
    .end annotation

    .line 766
    sget v0, Landroid/os/Build$VERSION;->SDK_INT:I

    const/16 v1, 0xe

    if-lt v0, v1, :cond_0

    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mContext:Landroid/content/Context;

    invoke-static {v0}, Lcom/mixpanel/android/mpmetrics/MPConfig;->readConfig(Landroid/content/Context;)Lcom/mixpanel/android/mpmetrics/MPConfig;

    move-result-object v0

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/MPConfig;->getAutoCheckForSurveys()Z

    move-result v0

    if-eqz v0, :cond_0

    .line 768
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mContext:Landroid/content/Context;

    invoke-virtual {v0}, Landroid/content/Context;->getApplicationContext()Landroid/content/Context;

    move-result-object v0

    instance-of v0, v0, Landroid/app/Application;

    if-eqz v0, :cond_0

    .line 770
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mContext:Landroid/content/Context;

    invoke-virtual {v0}, Landroid/content/Context;->getApplicationContext()Landroid/content/Context;

    move-result-object v0

    check-cast v0, Landroid/app/Application;

    .line 771
    new-instance v1, Lcom/mixpanel/android/mpmetrics/MixpanelActivityLifecycleCallbacks;

    invoke-direct {v1, p0}, Lcom/mixpanel/android/mpmetrics/MixpanelActivityLifecycleCallbacks;-><init>(Lcom/mixpanel/android/mpmetrics/MixpanelAPI;)V

    invoke-virtual {v0, v1}, Landroid/app/Application;->registerActivityLifecycleCallbacks(Landroid/app/Application$ActivityLifecycleCallbacks;)V

    .line 778
    :cond_0
    return-void
.end method

.method public registerSuperProperties(Lorg/json/JSONObject;)V
    .locals 1

    .line 365
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0, p1}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->registerSuperProperties(Lorg/json/JSONObject;)V

    .line 366
    return-void
.end method

.method public registerSuperPropertiesOnce(Lorg/json/JSONObject;)V
    .locals 1

    .line 392
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0, p1}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->registerSuperPropertiesOnce(Lorg/json/JSONObject;)V

    .line 393
    return-void
.end method

.method public track(Ljava/lang/String;Lorg/json/JSONObject;)V
    .locals 9

    .line 274
    :try_start_0
    new-instance v4, Lorg/json/JSONObject;

    invoke-direct {v4}, Lorg/json/JSONObject;-><init>()V

    .line 276
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->getReferrerProperties()Ljava/util/Map;

    move-result-object v0

    .line 277
    invoke-interface {v0}, Ljava/util/Map;->entrySet()Ljava/util/Set;

    move-result-object v0

    invoke-interface {v0}, Ljava/util/Set;->iterator()Ljava/util/Iterator;

    move-result-object v5

    :goto_0
    invoke-interface {v5}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_0

    invoke-interface {v5}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/util/Map$Entry;

    .line 278
    move-object v6, v0

    invoke-interface {v0}, Ljava/util/Map$Entry;->getKey()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    move-object v7, v0

    .line 279
    invoke-interface {v6}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    move-object v8, v0

    .line 280
    invoke-virtual {v4, v7, v8}, Lorg/json/JSONObject;->put(Ljava/lang/String;Ljava/lang/Object;)Lorg/json/JSONObject;

    .line 281
    goto :goto_0

    .line 283
    :cond_0
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->getSuperProperties()Lorg/json/JSONObject;

    move-result-object v0

    .line 284
    move-object v5, v0

    invoke-virtual {v0}, Lorg/json/JSONObject;->keys()Ljava/util/Iterator;

    move-result-object v6

    .line 285
    :goto_1
    invoke-interface {v6}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_1

    .line 286
    invoke-interface {v6}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    move-object v7, v0

    .line 287
    invoke-virtual {v5, v7}, Lorg/json/JSONObject;->get(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    invoke-virtual {v4, v7, v0}, Lorg/json/JSONObject;->put(Ljava/lang/String;Ljava/lang/Object;)Lorg/json/JSONObject;

    .line 288
    goto :goto_1

    .line 292
    :cond_1
    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v0

    const-wide/16 v2, 0x3e8

    div-long v7, v0, v2

    .line 293
    const-string v0, "time"

    invoke-virtual {v4, v0, v7, v8}, Lorg/json/JSONObject;->put(Ljava/lang/String;J)Lorg/json/JSONObject;

    .line 294
    const-string v0, "distinct_id"

    invoke-virtual {p0}, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->getDistinctId()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v4, v0, v1}, Lorg/json/JSONObject;->put(Ljava/lang/String;Ljava/lang/Object;)Lorg/json/JSONObject;

    .line 296
    if-eqz p2, :cond_2

    .line 297
    invoke-virtual {p2}, Lorg/json/JSONObject;->keys()Ljava/util/Iterator;

    move-result-object v5

    .line 298
    :goto_2
    invoke-interface {v5}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_2

    .line 299
    invoke-interface {v5}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    move-object v6, v0

    .line 300
    invoke-virtual {p2, v6}, Lorg/json/JSONObject;->get(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    invoke-virtual {v4, v6, v0}, Lorg/json/JSONObject;->put(Ljava/lang/String;Ljava/lang/Object;)Lorg/json/JSONObject;

    .line 301
    goto :goto_2

    .line 304
    :cond_2
    new-instance v5, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages$EventDescription;

    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mToken:Ljava/lang/String;

    invoke-direct {v5, p1, v4, v0}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages$EventDescription;-><init>(Ljava/lang/String;Lorg/json/JSONObject;Ljava/lang/String;)V

    .line 305
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mMessages:Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;

    invoke-virtual {v0, v5}, Lcom/mixpanel/android/mpmetrics/AnalyticsMessages;->eventsMessage(Lcom/mixpanel/android/mpmetrics/AnalyticsMessages$EventDescription;)V
    :try_end_0
    .catch Lorg/json/JSONException; {:try_start_0 .. :try_end_0} :catch_0

    .line 308
    return-void

    .line 306
    .line 307
    :catch_0
    return-void
.end method

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

    .line 379
    iget-object v0, p0, Lcom/mixpanel/android/mpmetrics/MixpanelAPI;->mPersistentProperties:Lcom/mixpanel/android/mpmetrics/PersistentProperties;

    invoke-virtual {v0, p1}, Lcom/mixpanel/android/mpmetrics/PersistentProperties;->unregisterSuperProperty(Ljava/lang/String;)V

    .line 380
    return-void
.end method


text:
using std::bind;
using std::chrono::system_clock;
using std::default_random_engine;
using std::deque;
using std::list;
using std::move;
using std::uniform_int_distribution;
using std::vector;

namespace ads {

TEST(QueueTest, DefaultConstructor) {
  Queue<int> target;
  ASSERT_EQ(target.Size(), 0);
  ASSERT_TRUE(target.IsEmpty());
}

unsigned seed = system_clock::now().time_since_epoch().count();
default_random_engine generator(seed);
uniform_int_distribution<int> distribution;
auto random_number = bind(distribution, generator);

TEST(QueueTest, ConstructorFromContainer) {
  constexpr auto kContainerSizes = {1 , 5, 10, 1000};
  for (auto kContainerSize : kContainerSizes) {
    list<int> initial_container(kContainerSize);
    for (auto& x : initial_container) {
      x = random_number();
    }
    Queue<int, list<int>> target(initial_container);
    ASSERT_EQ(target.Size(), initial_container.size());
    while (!target.IsEmpty() && !initial_container.empty()) {
      ASSERT_EQ(target.Head(), initial_container.front());
      target.Pop();
      initial_container.pop_front();
    }
  }
}

TEST(QueueTest, MoveConstructorFromContainer) {
  constexpr auto kContainerSizes = {1 , 5, 10, 1000};
  for (auto kContainerSize : kContainerSizes) {
    list<int> initial_container(kContainerSize);
    for (auto& x : initial_container) {
      x = random_number();
    }
    list<int> reference_container(initial_container);
    Queue<int, list<int>> target(move(initial_container));
    ASSERT_EQ(target.Size(), initial_container.size());
    while (!target.IsEmpty() && !reference_container.empty()) {
      ASSERT_EQ(target.Head(), reference_container.front());
      target.Pop();
      reference_container.pop_front();
    }
  }
}

TEST(QueueTest, CopyConstructor) {
  constexpr auto kQueueSizes = {1, 5, 10, 1000};
  for (auto kQueueSize : kQueueSizes) {
    Queue<int> initial_queue;
    for (int i = 0; i < kQueueSize; ++i) {
      initial_queue.Push(random_number());
    }
    Queue<int> target_queue(initial_queue);
    ASSERT_EQ(target_queue.Size(), initial_queue.Size());
    while (!target_queue.IsEmpty() && !initial_queue.IsEmpty()) {
      ASSERT_EQ(target_queue.Head(), initial_queue.Head());
      target_queue.Pop();
      initial_queue.Pop();
    }
  }
}

TEST(QueueTest, MoveConstructor) {
  constexpr auto kQueueSizes = {1, 5, 10, 1000};
  for (auto kQueueSize : kQueueSizes) {
    Queue<int> initial_queue;
    for (int i = 0; i < kQueueSize; ++i) {
      initial_queue.Push(random_number());
    }
    Queue<int> reference_queue(initial_queue);
    Queue<int> target_queue(move(initial_queue));
    ASSERT_EQ(target_queue.Size(), reference_queue.Size());
    while (!target_queue.IsEmpty() && !reference_queue.IsEmpty()) {
      ASSERT_EQ(target_queue.Head(), reference_queue.Head());
      target_queue.Pop();
      reference_queue.Pop();
    }
  }
}

TEST(QueueTest, CopyAssignment) {
  constexpr auto kQueueSizes = {1, 5, 10, 1000};
  for (auto kQueueSize : kQueueSizes) {
    Queue<int> initial_queue;
    for (int i = 0; i < kQueueSize; ++i) {
      initial_queue.Push(random_number());
    }
    Queue<int> target_queue = initial_queue;
    ASSERT_EQ(target_queue.Size(), initial_queue.Size());
    while (!target_queue.IsEmpty() && !initial_queue.IsEmpty()) {
      ASSERT_EQ(target_queue.Head(), initial_queue.Head());
      target_queue.Pop();
      initial_queue.Pop();
    }
  }
}

TEST(QueueTest, MoveAssignment) {
  constexpr auto kQueueSizes = {1, 5, 10, 1000};
  for (auto kQueueSize : kQueueSizes) {
    Queue<int> initial_queue;
    for (int i = 0; i < kQueueSize; ++i) {
      initial_queue.Push(random_number());
    }
    Queue<int> reference_queue(initial_queue);
    Queue<int> target_queue = move(initial_queue);
    ASSERT_EQ(target_queue.Size(), reference_queue.Size());
    while (!target_queue.IsEmpty() && !reference_queue.IsEmpty()) {
      ASSERT_EQ(target_queue.Head(), reference_queue.Head());
      target_queue.Pop();
      reference_queue.Pop();
    }
  }
}

TEST(QueueTest, SwapMemeber) {
  constexpr auto kRightQueueSizes = {1, 5, 10, 1000};
  constexpr auto kLeftQueueSizes = {1, 5, 10, 1000};
  for (auto kRightQueueSize : kRightQueueSizes) {
  for (auto kLeftQueueSize : kLeftQueueSizes) {
      Queue<int> rhs;
      for (int i = 0; i < kRightQueueSize; ++i) {
        rhs.Push(random_number());
      }
      Queue<int> lhs;
      for (int i = 0; i < kLeftQueueSize; ++i) {
        lhs.Push(random_number());
      }
      Queue<int> reference_rhs = rhs;
      Queue<int> reference_lhs = lhs;
      lhs.swap(rhs);
      ASSERT_EQ(lhs, reference_rhs);
      ASSERT_EQ(rhs, reference_lhs);
    }
  }
}

TEST(QueueTest, FreeSwap) {
  constexpr auto kRightQueueSizes = {1, 5, 10, 1000};
  constexpr auto kLeftQueueSizes = {1, 5, 10, 1000};
  for (auto kRightQueueSize : kRightQueueSizes) {
  for (auto kLeftQueueSize : kLeftQueueSizes) {
      Queue<int> rhs;
      for (int i = 0; i < kRightQueueSize; ++i) {
        rhs.Push(random_number());
      }
      Queue<int> lhs;
      for (int i = 0; i < kLeftQueueSize; ++i) {
        lhs.Push(random_number());
      }
      Queue<int> reference_rhs = rhs;
      Queue<int> reference_lhs = lhs;
      swap(lhs, rhs);
      ASSERT_EQ(lhs, reference_rhs);
      ASSERT_EQ(rhs, reference_lhs);
    }
  }
}

TEST(QueueTest, HeadTailPushPopSize) {
  Queue<int> target;
  target.Push(1);
  ASSERT_EQ(target.Size(), 1);
  ASSERT_EQ(target.Head(), 1);
  ASSERT_EQ(target.Tail(), 1);
  target.Push(2);
  ASSERT_EQ(target.Size(), 2);
  ASSERT_EQ(target.Head(), 1);
  ASSERT_EQ(target.Tail(), 2);
  target.Push(3);
  ASSERT_EQ(target.Size(), 3);
  ASSERT_EQ(target.Head(), 1);
  ASSERT_EQ(target.Tail(), 3);
  target.Pop();
  ASSERT_EQ(target.Size(), 2);
  ASSERT_EQ(target.Head(), 2);
  ASSERT_EQ(target.Tail(), 3);
  target.Pop();
  ASSERT_EQ(target.Size(), 1);
  ASSERT_EQ(target.Head(), 3);
  ASSERT_EQ(target.Tail(), 3);
}

TEST(QueueTest, HeadThrowsException) {
  Queue<int> target;
  ASSERT_THROW(target.Head(), HeadOnEmptyQueue);
}

TEST(QueueTest, ConstHead) {
  const Queue<int, deque<int>> target(deque<int>{123});
  ASSERT_EQ(target.Head(), 123);
  const Queue<int> empty_target;
  ASSERT_THROW(empty_target.Head(), HeadOnEmptyQueue);
}

TEST(QueueTest, ConstHeadThrowsException) {
  const Queue<int> target;
  ASSERT_THROW(target.Head(), HeadOnEmptyQueue);
}

TEST(QueueTest, TailThrowsException) {
  Queue<int> target;
  ASSERT_THROW(target.Tail(), TailOnEmptyQueue);
}

TEST(QueueTest, ConstTail) {
  const Queue<int, deque<int>> target(deque<int>{123});
  ASSERT_EQ(target.Tail(), 123);
  const Queue<int> empty_target;
  ASSERT_THROW(empty_target.Tail(), TailOnEmptyQueue);
}

TEST(QueueTest, ConstTailThrowsException) {
  const Queue<int> target;
  ASSERT_THROW(target.Tail(), TailOnEmptyQueue);
}

TEST(QueueTest, PopThrowsException) {
  Queue<int> target;
  ASSERT_THROW(target.Pop(), PopOnEmptyQueue);
}

TEST(QueueTest, MovePush) {
  Queue<double, deque<double>> target;
  double number = 123.456;
  target.Push(move(number));
  ASSERT_EQ(target.Head(), 123.456);
  ASSERT_EQ(target.Size(), 1);
}

TEST(QueueTest, IsEmpty) {
  Queue<int> target;
  ASSERT_TRUE(target.IsEmpty());
  target.Push(1);
  ASSERT_FALSE(target.IsEmpty());
  target.Pop();
  ASSERT_TRUE(target.IsEmpty());
}

TEST(QueueTest, Equality) {
  constexpr auto kQueueSizes = {1, 5, 10, 1000};
  for (auto kQueueSize : kQueueSizes) {
    Queue<int> lhs_queue;
    Queue<int> rhs_queue;
    for (int i = 0; i < kQueueSize; ++i) {
      auto x = random_number();
      rhs_queue.Push(x);
      ASSERT_FALSE(rhs_queue == lhs_queue);
      lhs_queue.Push(x);
      ASSERT_TRUE(rhs_queue == lhs_queue);
    }
  }
}

TEST(QueueTest, NonEquality) {
  constexpr auto kQueueSizes = {1, 5, 10, 1000};
  for (auto kQueueSize : kQueueSizes) {
    Queue<int> lhs_queue;
    Queue<int> rhs_queue;
    for (int i = 0; i < kQueueSize; ++i) {
      auto x = random_number();
      rhs_queue.Push(x);
      ASSERT_TRUE(rhs_queue != lhs_queue);
      lhs_queue.Push(x);
      ASSERT_FALSE(rhs_queue != lhs_queue);
    }
  }
}

}  // namespace ads

redpajama_set_name: RedPajamaGithub


text:
<?php

use Intercom\IntercomNotes;

class IntercomNotesTest extends PHPUnit_Framework_TestCase {
  public function testNoteCreate()
  {
    $stub = $this->getMockBuilder('Intercom\IntercomClient')->disableOriginalConstructor()->getMock();
    $stub->method('post')->willReturn('foo');

    $notes = new IntercomNotes($stub);
    $this->assertEquals('foo', $notes->create([]));
  }

  public function testNotesList()
  {
    $stub = $this->getMockBuilder('Intercom\IntercomClient')->disableOriginalConstructor()->getMock();
    $stub->method('get')->willReturn('foo');

    $notes = new IntercomNotes($stub);
    $this->assertEquals('foo', $notes->getNotes([]));
  }

  public function testNotesGet()
  {
    $stub = $this->getMockBuilder('Intercom\IntercomClient')->disableOriginalConstructor()->getMock();
    $stub->method('get')->will($this->returnArgument(0));

    $notes = new IntercomNotes($stub);
    $this->assertEquals('notes/foo', $notes->getNote("foo"));
  }
}


text:
namespace ApplicationGateway.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Connection draining allows open connections to a backend server to be
    /// active for a specified time after the backend server got removed from
    /// the configuration.
    /// </summary>
    public partial class ApplicationGatewayConnectionDraining
    {
        /// <summary>
        /// Initializes a new instance of the
        /// ApplicationGatewayConnectionDraining class.
        /// </summary>
        public ApplicationGatewayConnectionDraining()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// ApplicationGatewayConnectionDraining class.
        /// </summary>
        /// <param name="enabled">Whether connection draining is enabled or
        /// not.</param>
        /// <param name="drainTimeoutInSec">The number of seconds connection
        /// draining is active. Acceptable values are from 1 second to 3600
        /// seconds.</param>
        public ApplicationGatewayConnectionDraining(bool enabled, int drainTimeoutInSec)
        {
            Enabled = enabled;
            DrainTimeoutInSec = drainTimeoutInSec;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets whether connection draining is enabled or not.
        /// </summary>
        [JsonProperty(PropertyName = "enabled")]
        public bool Enabled { get; set; }

        /// <summary>
        /// Gets or sets the number of seconds connection draining is active.
        /// Acceptable values are from 1 second to 3600 seconds.
        /// </summary>
        [JsonProperty(PropertyName = "drainTimeoutInSec")]
        public int DrainTimeoutInSec { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (DrainTimeoutInSec > 3600)
            {
                throw new ValidationException(ValidationRules.InclusiveMaximum, "DrainTimeoutInSec", 3600);
            }
            if (DrainTimeoutInSec < 1)
            {
                throw new ValidationException(ValidationRules.InclusiveMinimum, "DrainTimeoutInSec", 1);
            }
        }
    }
}


text:
package net.formicary.remoterun.examples;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executors;

import com.google.protobuf.ByteString;
import net.formicary.remoterun.common.RemoteRunException;
import net.formicary.remoterun.common.proto.RemoteRun;
import net.formicary.remoterun.embed.IAgentConnection;
import net.formicary.remoterun.embed.RemoteRunMaster;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.text.StrTokenizer;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A dummy server to illustrate the usage of NettyServer.  To run the examples you first need to generate certificates
 * by running ssl/certs.sh.

 * The commands available are:
 *

 *
l - list connections

 *
r <cmd> [arg [arg [...]]] - run a remote command

 *
i <requestId> <stdin text> - send input to stdin of process

 *
c <requestId> - close stdin of process

 *

 *

 * 21:56:09.607 [main] INFO  c.formicary.remoterun.server.NettyServer - Listening for connections on 0.0.0.0/0.0.0.0:1081
 * 21:56:17.525 [New I/O worker #1] INFO  c.formicary.remoterun.server.NettyServer - Client connected from /127.0.0.1:50495 (1 open connections)
 * 21:56:17.742 [New I/O worker #1] INFO  c.formicary.remoterun.server.NettyServer - Client connection complete from /127.0.0.1:50495 (CN=client1, O=Formicary Ltd, L=London, ST=Greater London, C=GB)
 * l
 * 21:56:23.800 [main] INFO  com.formicary.remoterun.server.Server - 1: CONNECTED /127.0.0.1:50495
 * 21:56:23.800 [main] INFO  com.formicary.remoterun.server.Server - Finished listing 1 agent connections
 * r cat
 * 21:56:27.768 [main] DEBUG n.f.r.common.NettyLoggingHandler - [id: 0x01977fc5, /127.0.0.1:50495 => /127.0.0.1:1081] WRITE: messageType: RUN_COMMAND requestId: 1 runCommand {   cmd: "cat" }
 * 21:56:27.899 [New I/O worker #1] DEBUG n.f.r.common.NettyLoggingHandler - [id: 0x01977fc5, /127.0.0.1:50495 => /127.0.0.1:1081] RECEIVED: messageType: STARTED requestId: 1
 * i 1 hello\n
 * 21:56:40.697 [main] DEBUG n.f.r.common.NettyLoggingHandler - [id: 0x01977fc5, /127.0.0.1:50495 => /127.0.0.1:1081] WRITE: messageType: STDIN_FRAGMENT requestId: 1 stdinFragment: "hello\n"
 * 21:56:40.701 [New I/O worker #1] DEBUG n.f.r.common.NettyLoggingHandler - [id: 0x01977fc5, /127.0.0.1:50495 => /127.0.0.1:1081] RECEIVED: messageType: STDOUT_FRAGMENT requestId: 1 fragment: "hello\n"
 * c 1
 * 21:56:46.610 [main] DEBUG n.f.r.common.NettyLoggingHandler - [id: 0x01977fc5, /127.0.0.1:50495 => /127.0.0.1:1081] WRITE: messageType: CLOSE_STDIN requestId: 1
 * 21:56:46.614 [New I/O worker #1] DEBUG n.f.r.common.NettyLoggingHandler - [id: 0x01977fc5, /127.0.0.1:50495 => /127.0.0.1:1081] RECEIVED: messageType: EXITED requestId: 1 exitCode: 0
 *

 *
 * @author Chris Pearson
 */
public class Server {
  private static final Logger log = LoggerFactory.getLogger(Server.class);
  private RemoteRunMaster remoteRunMaster;

  public static void main(String[] args) {
    new Server().run();
  }

  public void run() {
    remoteRunMaster = new RemoteRunMaster(Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), null);
    InetSocketAddress bindAddress = new InetSocketAddress(1081);
    remoteRunMaster.bind(bindAddress);

    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, CharsetUtil.UTF_8));
      String line;
      while((line = reader.readLine()) != null) {
        try {
          if(line.startsWith("l")) {
            listClientConnections();
          } else if(line.startsWith("r")) {
            runCommand(line);
          } else if(line.startsWith("i")) {
            sendInput(line);
          } else if(line.startsWith("c")) {
            closeInput(line);
          } else {
            log.warn("Unhandled command: " + line);
          }
        } catch(Exception e) {
          log.error("Failed to process command: " + line, e);
        }
      }
    } catch(Exception e) {
      throw new RemoteRunException("Failed whilst processing user input, shutting down", e);
    } finally {
      remoteRunMaster.shutdown();
    }
  }

  private void listClientConnections() {
    Set<IAgentConnection> agentConnections = remoteRunMaster.getAgentConnections();
    int count = 0;
    for(IAgentConnection agentConnection : agentConnections) {
      log.info((++count) + ": " + agentConnection.getConnectionState().name() + " " + agentConnection.getAgentInfo().getHostname());
    }
    log.info("Finished listing " + agentConnections.size() + " agent connections");
  }

  private void runCommand(String line) {
    StrTokenizer tokenizer = new StrTokenizer(line, ' ', '"');
    @SuppressWarnings("unchecked")
    List<String> tokens = tokenizer.getTokenList();
    tokens.remove(0); // first token is the run command
    String command = tokens.remove(0);

    Collection<IAgentConnection> connectedClients = remoteRunMaster.getConnectedClients();
    if(connectedClients.isEmpty()) {
      log.error("Unable to send command: no agent connections");
    } else {
      IAgentConnection connection = connectedClients.iterator().next();

      RemoteRun.MasterToAgent.Builder builder = RemoteRun.MasterToAgent.newBuilder()
        .setMessageType(RemoteRun.MasterToAgent.MessageType.RUN_COMMAND)
        .setRequestId(RemoteRunMaster.getNextRequestId());
      builder.getRunCommandBuilder().setCmd(command).addAllArgs(tokens);
      connection.write(builder.build());
    }
  }

  private void sendInput(String line) {
    StrTokenizer tokenizer = new StrTokenizer(line, ' ', '"');
    @SuppressWarnings("unchecked")
    List<String> tokens = tokenizer.getTokenList();
    tokens.remove(0); // first token is the run command
    long id = Long.parseLong(tokens.remove(0));
    String input = StringUtils.join(tokens, ' ').replaceAll("\\\\n", "\n");

    Collection<IAgentConnection> connectedClients = remoteRunMaster.getConnectedClients();
    if(connectedClients.isEmpty()) {
      log.error("Unable to send command: no agent connections");
    } else {
      IAgentConnection connection = connectedClients.iterator().next();
      RemoteRun.MasterToAgent.Builder builder = RemoteRun.MasterToAgent.newBuilder()
        .setMessageType(RemoteRun.MasterToAgent.MessageType.STDIN_FRAGMENT)
        .setRequestId(id)
        .setFragment(ByteString.copyFromUtf8(input));
      connection.write(builder.build());
    }
  }

  private void closeInput(String line) {
    StrTokenizer tokenizer = new StrTokenizer(line, ' ', '"');
    @SuppressWarnings("unchecked")
    List<String> tokens = tokenizer.getTokenList();
    tokens.remove(0); // first token is the run command
    long id = Long.parseLong(tokens.remove(0));

    Collection<IAgentConnection> connectedClients = remoteRunMaster.getConnectedClients();
    if(connectedClients.isEmpty()) {
      log.error("Unable to send command: no agent connections");
    } else {
      IAgentConnection connection = connectedClients.iterator().next();
      RemoteRun.MasterToAgent.Builder builder = RemoteRun.MasterToAgent.newBuilder().setMessageType(RemoteRun.MasterToAgent.MessageType.CLOSE_STDIN).setRequestId(id);
      connection.write(builder.build());
    }
  }
}


text:
module Inverses (
	det_two,         -- :: Matrix -> Float
    determinant,     -- :: Matrix -> Float
    cofactor_matrix, -- :: Matrix -> Matrix
    adjoint_matrix,  -- :: Matrix -> Matrix
    inverse_matrix,  -- :: Matrix -> Matrix
) where

import Matrices
import Algebra

remove_at :: Int -> [a] -> [a]
remove_at k list = case list of
    []              -> error "List not that long"
    x:xs
        | k == 1    -> xs
        | otherwise -> x:remove_at (k-1) xs

find_cofactor :: Int -> Int -> Matrix -> Matrix
find_cofactor n m matrix = map (remove_at m)  (remove_at n matrix)

det_two :: Matrix -> Float
det_two matrix = (head top)*(last bottom) - (head bottom)*(last top)
                    where
                        top    = head matrix
                        bottom = last matrix

element_at :: Int -> Row -> Float
element_at k row = case row of
    []   -> error "Nope"
    x:xs
        | k == 1    -> x
        | otherwise -> element_at (k-1) xs

determinant :: Matrix -> Float
determinant matrix
    | length matrix == 2  = det_two matrix
    | is_singleton matrix = head (head matrix)
    | otherwise           = find_det (length matrix) matrix
                            where
                                det_element :: Int -> Matrix -> Float
                                det_element m matrix
                                    | m`mod`2 == 0 = (-element_at m (head matrix)) * determinant (find_cofactor 1 m matrix)
                                    | otherwise    = (element_at m (head matrix)) * determinant (find_cofactor 1 m matrix)

                                find_det :: Int -> Matrix -> Float
                                find_det m matrix
                                    | m == 0    = 0
                                    | otherwise = (det_element m matrix) + find_det (m-1) matrix

cofactor_matrix :: Matrix -> Matrix
cofactor_matrix matrix = cofactor_aux (length matrix) (length (head matrix))
                            where
                                cofactor_row :: Int -> Int -> Row
                                cofactor_row n m
                                    | m == 0             = []
                                    | (m+n) `mod` 2 == 1 = cofactor_row n (m-1) ++ [-determinant (find_cofactor n m matrix)]
                                    | otherwise          = cofactor_row n (m-1) ++ [determinant (find_cofactor n m matrix)]

                                cofactor_aux :: Int -> Int -> Matrix
                                cofactor_aux n m
                                    | n == 0    = []
                                    | otherwise = cofactor_aux (n-1) m ++ [cofactor_row n m]

adjoint_matrix :: Matrix -> Matrix
adjoint_matrix matrix = transpose_matrix (cofactor_matrix matrix)

inverse_matrix :: Matrix -> Matrix
inverse_matrix matrix
	| is_singleton matrix = [[(1/head (head matrix))]]
	| otherwise           = scale_matrix (1/(determinant matrix)) (adjoint_matrix matrix)


text:
using UnityEngine;
using System.Collections;

namespace WingroveAudio
{

    public class Audio3DSetting : ScriptableObject
    {
        [SerializeField]
        private AudioRolloffMode m_rolloffMode = AudioRolloffMode.Linear;
        [SerializeField]
        private float m_maxDistance = 100.0f;
        [SerializeField]
        private float m_minDistance = 1.0f;
        [SerializeField]
        private AnimationCurve m_customRolloffCurve = new AnimationCurve(new Keyframe[] {new Keyframe(0,1.0f), new Keyframe(1,0.0f)});
        [SerializeField]
        private bool m_useMaxToNormalizeCustomCurve = true;

        public float GetMaxDistance()
        {
            return m_maxDistance;
        }
        public float GetMinDistance()
        {
            return m_minDistance;
        }
        public AudioRolloffMode GetRolloffMode()
        {
            return m_rolloffMode;
        }
        public float EvaluateCustom(float distance)
        {
            return m_customRolloffCurve.Evaluate(m_useMaxToNormalizeCustomCurve ? distance / m_maxDistance : distance);
        }
    }

}


text:
        <form class="form-horizontal" name="registerForm">
            <fieldset>
                <legend>Register</legend>

                    Email

                        <input type="text" class="form-control" id="inputEmail" ng-model="user.email" required="required" name="Email" placeholder="Email">

                    Password

                        <input type="password" class="form-control" id="inputPassword" ng-model="user.password" required="required" name="Password" placeholder="Password">

                    Confirm Password

                        <input type="password" class="form-control" id="inputConfirm" ng-model="user.confirmPassword" required="required" name="ConfirmPassword" placeholder="ConfirmPassword">

                        <button class="btn btn-default" id="btn-cancel">Cancel</button>
                        <button class="btn btn-primary" id="btn-register" ng-disabled="registeForm.$invalid" ng-click="signup(user)">Register</button>

            </fieldset>
        </form>


text:
package exercise.pizzastore.pizzas;

/**
 * Created by Alberto on 2014-12-27.
 */
public class ChicagoStyleCheesePizza extends Pizza {

    public ChicagoStyleCheesePizza(){
        name = "Chicago Style Deep Dish Cheese Pizza";
        dough = "Extra Thick Crust Dough";
        sauce = "Plum Tomato Sauce";

        toppings.add("Shredded Mozzarella Cheese");
    }
    @Override
    public void cut(){
        System.out.println("Cutting the pizza into square slices");
    }
}


text:
Resource for Concourse CI to send messages to Telegram. You can pass your message from tasks with text file, or send a static message.

![Telegram Botfather](https://core.telegram.org/file/811140763/1/PihKNbjT8UE/03b57814e13713da37)

It allows you to send (put) a messages to Telegram from your pipeline.

## Prepare your bot

Before using this resource, you should create a bot for yourself. Please, [follow the instruction](https://core.telegram.org/bots#6-botfather) to create a bot and to get its **token**. Pass this value to the _bot_token_ parameter.

Then, [find out the chat ID](http://stackoverflow.com/a/32572159/622833) you want to send notifications to. Now you are ready to use it.

### Private channel
It is a good idea to create a private channel for your team where bot will print all the messages from Concourse.
In this case you need to follow this steps:

1) create a _public_ channel, give it a name, say, _@MyChannel_
2) add your bot as an administrator
3) then, send some testing message to this channel, use this command: `curl -X POST "https://api.telegram.org/bot<botApi>/sendMessage?chat_id=@MyChannel&text=123"`. You should see a new message from your bot in your channel. Check the JSON output from this command, you will find an `chat_id`. The output could look like this:
`{ "ok" : true, "result" : { "chat" : { "id" : -1001005582487, "title" : "Test Private Channel", "type" : "channel" }, "date" : 1448245538, "message_id" : 7, "text" : "123" } }`
, where `chat_id` is `-1001005582487`
4) optionally, now you can make your channel private, generate link and send it to your collegues

## Use the resource

The simplest example:

```yml
---
# declare custom resource type:
resource_types:
- name: telegram-notification
  type: docker-image
  source:
    repository: w32blaster/concourse-telegram-notifier
    tag: latest

# declare resource
resources:
- name: telegram-notification
  type: telegram-notification
  source:
    bot_token: "<bot token>"

# use it in your job
jobs:
- name: "Job Send Message To Telegram"
  public: true
  plan:
    - put: telegram-notification
      params:
         chat_id: "<your chat ID>"
         # you need to specify one of text or text_file properties, with text_file you can generate message text in your previous task
         text: "Build ok. [Build $BUILD_NAME](http://localhost:8080/pipelines/$BUILD_PIPELINE_NAME/jobs/$BUILD_JOB_NAME/builds/$BUILD_NAME)"
         text_file: './task_output/file_with_message'
         # optional parameter, Telegram API parse mode, may be HTML or Markdown, Markdown is default value
         parse_mode: HTML
```

Have fun.


text:
using namespace clang;
using namespace csabase;

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

static std::string const check_name("member-definition-in-class-definition");

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

namespace
{
    struct member_definition
    {
        std::map<void const*, bool> reported_;
    };
}

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

static void
member_definition_in_class_definition(Analyser& analyser,
                                      CXXMethodDecl const* decl)
{
    member_definition& data = analyser.attachment<member_definition>();

    if (decl->isTemplateInstantiation()) {
        if (CXXMethodDecl const* tplt = llvm::dyn_cast<CXXMethodDecl>(
                decl->getTemplateInstantiationPattern())) {
            decl = tplt;
        }
    }

    if (decl->getLexicalDeclContext() == decl->getDeclContext()
        && decl->hasInlineBody()
        && !decl->getParent()->isLocalClass()
        && !decl->isImplicit()
        && !data.reported_[decl->getCanonicalDecl()]
        && !analyser.is_test_driver()
        && !decl->getBeginLoc().isMacroID())
    {
        analyser.report(decl, check_name, "CD01",
                "Member function '%0' is defined in the class definition.")
            << decl->getQualifiedNameAsString();
        data.reported_[decl->getCanonicalDecl()] = true;
    }
}

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

static RegisterCheck check(check_name, &member_definition_in_class_definition);

// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
<?php

namespace PHPMD\Rule;

use PDepend\Source\AST\ASTArguments;
use PDepend\Source\AST\ASTArrayIndexExpression;
use PDepend\Source\AST\ASTFieldDeclaration;
use PDepend\Source\AST\ASTMemberPrimaryPrefix;
use PDepend\Source\AST\ASTPropertyPostfix;
use PDepend\Source\AST\ASTVariable;
use PDepend\Source\AST\ASTVariableDeclarator;
use PHPMD\AbstractNode;
use PHPMD\AbstractRule;
use PHPMD\Node\ASTNode;
use ReflectionException;
use ReflectionFunction;

/**
 * Base class for rules that rely on local variables.
 *
 * @since 0.2.6
 */
abstract class AbstractLocalVariable extends AbstractRule
{
    /**
     * @var array Self reference class names.
     */
    protected $selfReferences = array('self', 'static');

    /**
     * PHP super globals that are available in all php scopes, so that they
     * can never be unused local variables.
     *
     * @var array(string=>boolean)
     * @link http://php.net/manual/en/reserved.variables.php
     */
    protected static $superGlobals = array(
        '$argc' => true,
        '$argv' => true,
        '$_COOKIE' => true,
        '$_ENV' => true,
        '$_FILES' => true,
        '$_GET' => true,
        '$_POST' => true,
        '$_REQUEST' => true,
        '$_SERVER' => true,
        '$_SESSION' => true,
        '$GLOBALS' => true,
        '$HTTP_RAW_POST_DATA' => true,
        '$php_errormsg' => true,
        '$http_response_header' => true,
    );

    /**
     * Tests if the given variable node represents a local variable or if it is
     * a static object property or something similar.
     *
     * @param \PHPMD\Node\ASTNode $variable The variable to check.
     * @return boolean
     */
    protected function isLocal(ASTNode $variable)
    {
        return (false === $variable->isThis()
            && $this->isNotSuperGlobal($variable)
            && $this->isRegularVariable($variable)
        );
    }

    /**
     * Tests if the given variable represents one of the PHP super globals
     * that are available in scopes.
     *
     * @param \PHPMD\AbstractNode $variable
     * @return boolean
     */
    protected function isSuperGlobal(AbstractNode $variable)
    {
        return isset(self::$superGlobals[$variable->getImage()]);
    }

    /**
     * Tests if the given variable does not represent one of the PHP super globals
     * that are available in scopes.
     *
     * @param \PHPMD\AbstractNode $variable
     * @return boolean
     */
    protected function isNotSuperGlobal(AbstractNode $variable)
    {
        return !$this->isSuperGlobal($variable);
    }

    /**
     * Tests if the given variable node is a regular variable an not property
     * or method postfix.
     *
     * @param \PHPMD\Node\ASTNode $variable
     * @return boolean
     */
    protected function isRegularVariable(ASTNode $variable)
    {
        $node = $this->stripWrappedIndexExpression($variable);
        $parent = $node->getParent();

        if ($parent->isInstanceOf('PropertyPostfix')) {
            $primaryPrefix = $parent->getParent();
            if ($primaryPrefix->getParent()->isInstanceOf('MemberPrimaryPrefix')) {
                return !$primaryPrefix->getParent()->isStatic();
            }

            return ($parent->getChild(0)->getNode() !== $node->getNode()
                || !$primaryPrefix->isStatic()
            );
        }

        return true;
    }

    /**
     * Removes all index expressions that are wrapped around the given node
     * instance.
     *
     * @param \PHPMD\Node\ASTNode $node
     * @return \PHPMD\Node\ASTNode
     */
    protected function stripWrappedIndexExpression(ASTNode $node)
    {
        if (false === $this->isWrappedByIndexExpression($node)) {
            return $node;
        }

        $parent = $node->getParent();
        if ($parent->getChild(0)->getNode() === $node->getNode()) {
            return $this->stripWrappedIndexExpression($parent);
        }

        return $node;
    }

    /**
     * Tests if the given variable node os part of an index expression.
     *
     * @param \PHPMD\Node\ASTNode $node
     * @return boolean
     */
    protected function isWrappedByIndexExpression(ASTNode $node)
    {
        return ($node->getParent()->isInstanceOf('ArrayIndexExpression')
            || $node->getParent()->isInstanceOf('StringIndexExpression')
        );
    }

    /**
     * PHP is case insensitive so we should compare function names case
     * insensitive.
     *
     * @param \PHPMD\AbstractNode $node
     * @param string $name
     * @return boolean
     */
    protected function isFunctionNameEqual(AbstractNode $node, $name)
    {
        return (0 === strcasecmp(trim($node->getImage(), '\\'), $name));
    }

    /**
     * AST puts namespace prefix to global functions called from a namespace.
     * This method checks if the last part of function fully qualified name is equal to $name
     *
     * @param \PHPMD\AbstractNode $node
     * @param string $name
     * @return boolean
     */
    protected function isFunctionNameEndingWith(AbstractNode $node, $name)
    {
        $parts = explode('\\', trim($node->getImage(), '\\'));

        return (0 === strcasecmp(array_pop($parts), $name));
    }

    /**
     * Get the image of the given variable node.
     *
     * Prefix self:: and static:: properties with "::".
     *
     * @param ASTVariable|ASTPropertyPostfix|ASTVariableDeclarator $variable
     * @return string
     */
    protected function getVariableImage($variable)
    {
        $image = $variable->getImage();

        if ($this->isFieldDeclaration($variable, $image)) {
            $image = "::$image";
        }

        // If variable name is not in the node, it's in the second child
        if ($image === '::') {
            return $image.$variable->getChild(1)->getImage();
        }

        return $this->prependMemberPrimaryPrefix($image, $variable);
    }

    protected function getParentMemberPrimaryPrefixImage($image, ASTPropertyPostfix $postfix)
    {
        do {
            $postfix = $postfix->getParent();
        } while ($postfix && $postfix->getChild(0) && $postfix->getChild(0)->getImage() === $image);

        $previousChildImage = $postfix->getChild(0)->getImage();

        if ($postfix instanceof ASTMemberPrimaryPrefix &&
            in_array($previousChildImage, $this->selfReferences)
        ) {
            return $previousChildImage;
        }

        return null;
    }

    /**
     * Return the PDepend node of ASTNode PHPMD node.
     *
     * Or return the input as is if it's not an ASTNode PHPMD node.
     *
     * @param mixed $node
     * @return \PDepend\Source\AST\ASTArtifact|\PDepend\Source\AST\ASTNode
     */
    protected function getNode($node)
    {
        if ($node instanceof ASTNode) {
            return $node->getNode();
        }

        return $node;
    }

    /**
     * Reflect function trying as namespaced function first, then global function.
     *
     * @SuppressWarnings(PHPMD.EmptyCatchBlock)
     * @param string $functionName
     * @return ReflectionFunction|null
     */
    private function getReflectionFunctionByName($functionName)
    {
        try {
            return new ReflectionFunction($functionName);
        } catch (ReflectionException $exception) {
            $chunks = explode('\\', $functionName);

            if (count($chunks) > 1) {
                try {
                    return new ReflectionFunction(end($chunks));
                } catch (ReflectionException $exception) {
                }
                // @TODO: Find a way to handle user-land functions
                // @TODO: Find a way to handle methods
            }
        }

        return null;
    }

    /**
     * Return true if the given variable is passed by reference in a native PHP function.
     *
     * @param ASTVariable|ASTPropertyPostfix|ASTVariableDeclarator $variable
     * @return bool
     */
    protected function isPassedByReference($variable)
    {
        $parent = $this->getNode($variable->getParent());

        if (!($parent && $parent instanceof ASTArguments)) {
            return false;
        }

        $argumentPosition = array_search($this->getNode($variable), $parent->getChildren());
        $function = $this->getNode($parent->getParent());
        $functionParent = $this->getNode($function->getParent());
        $functionName = $function->getImage();

        if ($functionParent instanceof ASTMemberPrimaryPrefix) {
            // @TODO: Find a way to handle methods
            return false;
        }

        $reflectionFunction = $this->getReflectionFunctionByName($functionName);

        if (!$reflectionFunction) {
            return false;
        }

        $parameters = $reflectionFunction->getParameters();

        return isset($parameters[$argumentPosition]) && $parameters[$argumentPosition]->isPassedByReference();
    }

    /**
     * Prepend "::" if the variable has a ASTMemberPrimaryPrefix.
     *
     * So we can distinguish members from local variable, identify quickly the scope
     * by the image and mostly avoid conflict between a local variable and a property
     * having the same name such as in:
     *
     * ```
     * public function bar()
     * {
     *     self::$foo = 9;
     *     return $foo; // Undefined variable
     * }
     * ```
     *
     * We'll raise the violation because `$foo` and `self::$foo` are not referring the
     * same variable and won't overlap in a storage keyed by image as first one
     * image is "$foo", second one is "::$foo".
     *
     * @param ASTVariable|ASTPropertyPostfix|ASTVariableDeclarator $variable
     * @return string
     */
    private function prependMemberPrimaryPrefix($image, $variable)
    {
        $base = $this->getNode($variable);
        $parent = $this->getNode($base->getParent());

        while ($parent && $parent instanceof ASTArrayIndexExpression && $parent->getChild(0) === $base) {
            $base = $parent;
            $parent = $this->getNode($base->getParent());
        }

        if ($parent instanceof ASTPropertyPostfix) {
            $previousChildImage = $this->getParentMemberPrimaryPrefixImage($image, $parent);

            if (in_array($previousChildImage, $this->selfReferences, true)) {
                return "::$image";
            }
        }

        return $image;
    }

    /**
     * Return true if given node (+ optional image) represent en field declaration:
     *
     * ```
     * class Foo
     * {
     *   public static $field = 9;
     * }
     * ```
     *
     * @param ASTVariable|ASTPropertyPostfix|ASTVariableDeclarator $variable
     * @param string $image
     * @return bool
     */
    private function isFieldDeclaration($variable, $image = '$')
    {
        return substr($image, 0, 1) === '$' &&
            $this->getNode($variable->getParent()) instanceof ASTFieldDeclaration;
    }
}


text:
WORKSPACE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# install python dependencies
pip install -r $WORKSPACE/requirements.txt

# install client's code
cd $WORKSPACE/geography
npm install --python=/usr/bin/python2.7
$WORKSPACE/geography/node_modules/grunt-cli/bin/grunt -v --force
$WORKSPACE/manage.py collectstatic --noinput

$WORKSPACE/manage.py migrate

$WORKSPACE/manage.py compilemessages

$WORKSPACE/manage.py load_flashcards --skip-language-check $WORKSPACE/data/geography-flashcards.json

$WORKSPACE/manage.py load_configab_experiments $WORKSPACE/ab_experiments.json

$WORKSPACE/manage.py generate_concepts
$WORKSPACE/manage.py load_concepts $WORKSPACE/data/concepts.json


text:
require 'spec_helper'

describe TwitterAds::Creative::PromotedTweet do

  before(:each) do
    stub_fixture(:get, :accounts_all, "#{ADS_API}/accounts")
    stub_fixture(:get, :accounts_load, "#{ADS_API}/accounts/2iqph")
  end

  let(:client) do
    Client.new(
      Faker::Lorem.characters(15),
      Faker::Lorem.characters(40),
      "123456-#{Faker::Lorem.characters(40)}",
      Faker::Lorem.characters(40)
    )
  end

  let(:account) { client.accounts.first }

  # check model properties
  subject { described_class.new(account) }
  read  = %w(id approval_status created_at updated_at deleted entity_status)
  write = %w(line_item_id tweet_id)
  include_examples 'object property check', read, write

  describe '#save' do

    it 'raises a client error when missing tweet_id' do
      expect(subject).to receive(:validate).and_call_original
      subject.line_item_id = '12345'
      expect { subject.save }.to raise_error(TwitterAds::ClientError)
    end

    it 'raises a client error when missing line_item_id' do
      expect(subject).to receive(:validate).and_call_original
      subject.tweet_id = 99999999999999999999
      expect { subject.save }.to raise_error(TwitterAds::ClientError)
    end

    it 'sets params[:tweet_ids] from params[:tweet_id]' do
      request = double('request')
      response = double('response')
      allow(response).to receive(:body).and_return({ data: [{}] })
      allow(request).to receive(:perform).and_return(response)
      expected_params = { params: { line_item_id: '12345', tweet_ids: 99999999999999999999 } }

      expect(Request).to receive(:new).with(
        client,
        :post,
        "/#{TwitterAds::API_VERSION}/accounts/#{account.id}/promoted_tweets",
        expected_params
      ).and_return(request)

      subject.line_item_id = '12345'
      subject.tweet_id = 99999999999999999999
      subject.save
    end
  end

end


text:
from __future__ import absolute_import, division, print_function, unicode_literals

ELLIPSIS = '...'

def truncate(s, length, ellipsis=ELLIPSIS):
    if length < len(s):
        if length < len(ellipsis):
            s = ellipsis
        else:
            s = s[0:length - len(ellipsis)] + ellipsis

    return s[0:length]

def truncate_suffix(s, suffix, length, ellipsis=ELLIPSIS):
    suffix = suffix[0:length]
    return truncate(s, length - len(suffix), ellipsis) + suffix


text:
package com.janrain.android.engage.ui;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * @brief The abstract superclass of classes which define custom View hierarchies
 *
 * Extend this class and implement onCreateView to return a custom View hierarchy.
 *
 * This class also supplies several utility methods for controlling the behavior of the UI of the Engage
 * library.
 */
public abstract class JRCustomInterfaceView extends JRCustomInterface {
    private static final String TAG = JRCustomInterfaceView.class.getSimpleName();
    private View mView;
    private JRUiFragment mUiFragment;
    private Context mContext;

    /*package*/ boolean mViewCreated = false;

    /**
     * Implement this method to return your custom view hierarchy for embedding in the Engage library UI.
     *
     * This method should have no side effects as it may be called more than once per activity.
     * @param context The Context
     * @param inflater A LayoutInflater which can be used to inflate your layout file
     * @param container The ViewGroup to which your view will be attached
     * @param savedInstanceState Any state saved
     * @return Your custom sign-in view
     */
    public abstract View onCreateView(Context context,
                             LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState);

    /**
     * Retrieves the Activity object this custom view is a member of
     * @return
     *  The Activity this custom view is a member of
     */
    public Activity getActivity() {
        return mUiFragment.getActivity();
    }

    /**
     * A utility method to retrieve a Resources reference from the Application Context
     * @return
     *  A resources reference from the Application Context
     */
    public Resources getResources() {
        return mContext.getResources();
    }

    /**
     * A utility method to fetch a resource string by id
     * @param id
     *  The id of the string to fetch
     * @return
     *  The fetched string
     */
    public final String getString(int id) {
        return getResources().getString(id);
    }

    /**
     * A utility method to fetch a resource string by id, formatted with arguments
     * @param id
     *  The id of the string to fetch
     * @param formatArgs
     *  The arguments used to format the string with
     * @return
     *  The fetched and formatted string
     */
    public final String getString(int id, Object... formatArgs) {
        return getResources().getString(id, formatArgs);
    }

    /**
     * Gets the created View hierarchy
     * @return the created View hierarchy
     */
    public final View getView() {
        return mView;
    }

    /**
     * Called when the activity displaying the custom view is resuming
     */
    public void onResume() {}

    /**
     * Called when the activity displaying the custom view is pausing
     */
    public void onPause() {}

    /**
     * Called when the activity displaying the custom view is saving its instance state
     * @param outState
     *  The Bundle to write this custom views saved state to
     */
    public void onSaveInstanceState(Bundle outState) {}

    /**
     * Called when the activity displaying the custom view is destroyed
     */
    public void onDestroy() {}

    /**
     * Invoke this utility method to close the provider list
     */
    public final void finishJrSignin() {
        if (mUiFragment instanceof JRProviderListFragment) {
            ((JRProviderListFragment) mUiFragment).finishJrSignin();
        } else {
            Log.e(TAG, "Can't call finishJrSignin from JRCustomUiViews not displayed in JRProviderList");
        }
    }

    /**
     * Utility method to show a progress indicator, convenient for usage during custom username/password
     * authentication. This is not the only way to display a progress dialog, it is also possible to
     * use getActivity to have the Activity object to use with the Android Dialog classes.
     *
     * @param cancelable
     *  Whether the progress dialog is cancelable by the user, for example by pressing the back button
     *
     * @param cancelListener
     *  The listener notified when the dialog is canceled (e.g. by the back button). Null for no listener
     */
    public void showProgressIndicator(boolean cancelable, DialogInterface.OnCancelListener cancelListener) {
        mUiFragment.showProgressDialogForCustomView(cancelable, cancelListener);
    }

    /**
     * Dismiss the progress dialog displayed by showProgressIndicator
     */
    public void dismissProgressIndicator() {
        mUiFragment.dismissProgressDialogForCustomView();
    }

    /**
     * @internal
     * @hide
     */
    /*package*/ final View doOnCreateView(JRUiFragment fragment,
                                          Context context,
                                          LayoutInflater inflater,
                                          ViewGroup container,
                                          Bundle savedInstanceState) {
        mContext = context;
        mUiFragment = fragment;
        mViewCreated = true;
        mView = onCreateView(context, inflater, container, savedInstanceState);
        return mView;
    }
}


text: public class A implements Iface { }


text:
<?php

namespace Incenteev\TranslationCheckerBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

final class ExtractorPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $extractors = array();

        foreach ($container->findTaggedServiceIds('incenteev_translation_checker.extractor') as $id => $tags) {
            $extractors[] = new Reference($id);
        }

        // If there is only one configured extractor, skip the chain one
        if (1 === count($extractors)) {
            $container->setAlias('incenteev_translation_checker.extractor', new Alias((string) $extractors[0], $container->getAlias('incenteev_translation_checker.extractor')->isPublic()));

            return;
        }

        $container->getDefinition('incenteev_translation_checker.extractor.chain')->replaceArgument(0, $extractors);
    }
}


text:
{{ header }}

.. _api.arrays:

======================================
pandas arrays, scalars, and data types
======================================

*******
Objects
*******

.. currentmodule:: pandas

For most data types, pandas uses NumPy arrays as the concrete
objects contained with a :class:`Index`, :class:`Series`, or
:class:`DataFrame`.

For some data types, pandas extends NumPy's type system. String aliases for these types
can be found at :ref:`basics.dtypes`.

=================== ========================== ============================= =============================
Kind of Data        pandas Data Type           Scalar                        Array
=================== ========================== ============================= =============================
TZ-aware datetime   :class:`DatetimeTZDtype`   :class:`Timestamp`            :ref:`api.arrays.datetime`
Timedeltas          (none)                     :class:`Timedelta`            :ref:`api.arrays.timedelta`
Period (time spans) :class:`PeriodDtype`       :class:`Period`               :ref:`api.arrays.period`
Intervals           :class:`IntervalDtype`     :class:`Interval`             :ref:`api.arrays.interval`
Nullable Integer    :class:`Int64Dtype`, ...   (none)                        :ref:`api.arrays.integer_na`
Nullable Float      :class:`Float64Dtype`, ... (none)                        :ref:`api.arrays.float_na`
Categorical         :class:`CategoricalDtype`  (none)                        :ref:`api.arrays.categorical`
Sparse              :class:`SparseDtype`       (none)                        :ref:`api.arrays.sparse`
Strings             :class:`StringDtype`       :class:`str`                  :ref:`api.arrays.string`
Nullable Boolean    :class:`BooleanDtype`      :class:`bool`                 :ref:`api.arrays.bool`
PyArrow             :class:`ArrowDtype`        Python Scalars or :class:`NA` :ref:`api.arrays.arrow`
=================== ========================== ============================= =============================

pandas and third-party libraries can extend NumPy's type system (see :ref:`extending.extension-types`).
The top-level :meth:`array` method can be used to create a new array, which may be
stored in a :class:`Series`, :class:`Index`, or as a column in a :class:`DataFrame`.

.. autosummary::
   :toctree: api/

   array

.. _api.arrays.arrow:

PyArrow
-------

.. warning::

    This feature is experimental, and the API can change in a future release without warning.

The :class:`arrays.ArrowExtensionArray` is backed by a :external+pyarrow:py:class:`pyarrow.ChunkedArray` with a
:external+pyarrow:py:class:`pyarrow.DataType` instead of a NumPy array and data type. The ``.dtype`` of a :class:`arrays.ArrowExtensionArray`
is an :class:`ArrowDtype`.

`Pyarrow <https://arrow.apache.org/docs/python/index.html>`__ provides similar array and `data type <https://arrow.apache.org/docs/python/api/datatypes.html>`__
support as NumPy including first-class nullability support for all data types, immutability and more.

.. note::

    For string types (``pyarrow.string()``, ``string[pyarrow]``), PyArrow support is still facilitated
    by :class:`arrays.ArrowStringArray` and ``StringDtype("pyarrow")``. See the :ref:`string section <api.arrays.string>`
    below.

While individual values in an :class:`arrays.ArrowExtensionArray` are stored as a PyArrow objects, scalars are **returned**
as Python scalars corresponding to the data type, e.g. a PyArrow int64 will be returned as Python int, or :class:`NA` for missing
values.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.ArrowExtensionArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   ArrowDtype

.. _api.arrays.datetime:

Datetimes
---------

NumPy cannot natively represent timezone-aware datetimes. pandas supports this
with the :class:`arrays.DatetimeArray` extension array, which can hold timezone-naive
or timezone-aware values.

:class:`Timestamp`, a subclass of :class:`datetime.datetime`, is pandas'
scalar type for timezone-naive or timezone-aware datetime data. :class:`NaT`
is the missing value for datetime data.

.. autosummary::
   :toctree: api/

   Timestamp

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   NaT

Properties
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Timestamp.asm8
   Timestamp.day
   Timestamp.dayofweek
   Timestamp.day_of_week
   Timestamp.dayofyear
   Timestamp.day_of_year
   Timestamp.days_in_month
   Timestamp.daysinmonth
   Timestamp.fold
   Timestamp.hour
   Timestamp.is_leap_year
   Timestamp.is_month_end
   Timestamp.is_month_start
   Timestamp.is_quarter_end
   Timestamp.is_quarter_start
   Timestamp.is_year_end
   Timestamp.is_year_start
   Timestamp.max
   Timestamp.microsecond
   Timestamp.min
   Timestamp.minute
   Timestamp.month
   Timestamp.nanosecond
   Timestamp.quarter
   Timestamp.resolution
   Timestamp.second
   Timestamp.tz
   Timestamp.tzinfo
   Timestamp.unit
   Timestamp.value
   Timestamp.week
   Timestamp.weekofyear
   Timestamp.year

Methods
~~~~~~~
.. autosummary::
   :toctree: api/

   Timestamp.as_unit
   Timestamp.astimezone
   Timestamp.ceil
   Timestamp.combine
   Timestamp.ctime
   Timestamp.date
   Timestamp.day_name
   Timestamp.dst
   Timestamp.floor
   Timestamp.fromordinal
   Timestamp.fromtimestamp
   Timestamp.isocalendar
   Timestamp.isoformat
   Timestamp.isoweekday
   Timestamp.month_name
   Timestamp.normalize
   Timestamp.now
   Timestamp.replace
   Timestamp.round
   Timestamp.strftime
   Timestamp.strptime
   Timestamp.time
   Timestamp.timestamp
   Timestamp.timetuple
   Timestamp.timetz
   Timestamp.to_datetime64
   Timestamp.to_numpy
   Timestamp.to_julian_date
   Timestamp.to_period
   Timestamp.to_pydatetime
   Timestamp.today
   Timestamp.toordinal
   Timestamp.tz_convert
   Timestamp.tz_localize
   Timestamp.tzname
   Timestamp.utcfromtimestamp
   Timestamp.utcnow
   Timestamp.utcoffset
   Timestamp.utctimetuple
   Timestamp.weekday

A collection of timestamps may be stored in a :class:`arrays.DatetimeArray`.
For timezone-aware data, the ``.dtype`` of a :class:`arrays.DatetimeArray` is a
:class:`DatetimeTZDtype`. For timezone-naive data, ``np.dtype("datetime64[ns]")``
is used.

If the data are timezone-aware, then every value in the array must have the same timezone.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.DatetimeArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   DatetimeTZDtype

.. _api.arrays.timedelta:

Timedeltas
----------

NumPy can natively represent timedeltas. pandas provides :class:`Timedelta`
for symmetry with :class:`Timestamp`. :class:`NaT`
is the missing value for timedelta data.

.. autosummary::
   :toctree: api/

   Timedelta

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   NaT

Properties
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Timedelta.asm8
   Timedelta.components
   Timedelta.days
   Timedelta.max
   Timedelta.microseconds
   Timedelta.min
   Timedelta.nanoseconds
   Timedelta.resolution
   Timedelta.seconds
   Timedelta.unit
   Timedelta.value
   Timedelta.view

Methods
~~~~~~~
.. autosummary::
   :toctree: api/

   Timedelta.as_unit
   Timedelta.ceil
   Timedelta.floor
   Timedelta.isoformat
   Timedelta.round
   Timedelta.to_pytimedelta
   Timedelta.to_timedelta64
   Timedelta.to_numpy
   Timedelta.total_seconds

A collection of :class:`Timedelta` may be stored in a :class:`TimedeltaArray`.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.TimedeltaArray

.. _api.arrays.period:

Periods
-------

pandas represents spans of times as :class:`Period` objects.

Period
------
.. autosummary::
   :toctree: api/

   Period

Properties
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Period.day
   Period.dayofweek
   Period.day_of_week
   Period.dayofyear
   Period.day_of_year
   Period.days_in_month
   Period.daysinmonth
   Period.end_time
   Period.freq
   Period.freqstr
   Period.hour
   Period.is_leap_year
   Period.minute
   Period.month
   Period.ordinal
   Period.quarter
   Period.qyear
   Period.second
   Period.start_time
   Period.week
   Period.weekday
   Period.weekofyear
   Period.year

Methods
~~~~~~~
.. autosummary::
   :toctree: api/

   Period.asfreq
   Period.now
   Period.strftime
   Period.to_timestamp

A collection of :class:`Period` may be stored in a :class:`arrays.PeriodArray`.
Every period in a :class:`arrays.PeriodArray` must have the same ``freq``.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.PeriodArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   PeriodDtype

.. _api.arrays.interval:

Intervals
---------

Arbitrary intervals can be represented as :class:`Interval` objects.

.. autosummary::
   :toctree: api/

    Interval

Properties
~~~~~~~~~~
.. autosummary::
   :toctree: api/

   Interval.closed
   Interval.closed_left
   Interval.closed_right
   Interval.is_empty
   Interval.left
   Interval.length
   Interval.mid
   Interval.open_left
   Interval.open_right
   Interval.overlaps
   Interval.right

A collection of intervals may be stored in an :class:`arrays.IntervalArray`.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.IntervalArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   IntervalDtype

.. Those attributes and methods are included in the API because the docstrings
.. of IntervalIndex and IntervalArray are shared. Including it here to make
.. sure a docstring page is built for them to avoid warnings

..
    .. autosummary::
      :toctree: api/

      arrays.IntervalArray.left
      arrays.IntervalArray.right
      arrays.IntervalArray.closed
      arrays.IntervalArray.mid
      arrays.IntervalArray.length
      arrays.IntervalArray.is_empty
      arrays.IntervalArray.is_non_overlapping_monotonic
      arrays.IntervalArray.from_arrays
      arrays.IntervalArray.from_tuples
      arrays.IntervalArray.from_breaks
      arrays.IntervalArray.contains
      arrays.IntervalArray.overlaps
      arrays.IntervalArray.set_closed
      arrays.IntervalArray.to_tuples

.. _api.arrays.integer_na:

Nullable integer
----------------

:class:`numpy.ndarray` cannot natively represent integer-data with missing values.
pandas provides this through :class:`arrays.IntegerArray`.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.IntegerArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   Int8Dtype
   Int16Dtype
   Int32Dtype
   Int64Dtype
   UInt8Dtype
   UInt16Dtype
   UInt32Dtype
   UInt64Dtype
   NA

.. _api.arrays.float_na:

Nullable float
--------------

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.FloatingArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   Float32Dtype
   Float64Dtype
   NA

.. _api.arrays.categorical:

Categoricals
------------

pandas defines a custom data type for representing data that can take only a
limited, fixed set of values. The dtype of a :class:`Categorical` can be described by
a :class:`CategoricalDtype`.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   CategoricalDtype

.. autosummary::
   :toctree: api/

   CategoricalDtype.categories
   CategoricalDtype.ordered

Categorical data can be stored in a :class:`pandas.Categorical`

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   Categorical

The alternative :meth:`Categorical.from_codes` constructor can be used when you
have the categories and integer codes already:

.. autosummary::
   :toctree: api/

   Categorical.from_codes

The dtype information is available on the :class:`Categorical`

.. autosummary::
   :toctree: api/

   Categorical.dtype
   Categorical.categories
   Categorical.ordered
   Categorical.codes

``np.asarray(categorical)`` works by implementing the array interface. Be aware, that this converts
the :class:`Categorical` back to a NumPy array, so categories and order information is not preserved!

.. autosummary::
   :toctree: api/

   Categorical.__array__

A :class:`Categorical` can be stored in a :class:`Series` or :class:`DataFrame`.
To create a Series of dtype ``category``, use ``cat = s.astype(dtype)`` or
``Series(..., dtype=dtype)`` where ``dtype`` is either

* the string ``'category'``
* an instance of :class:`CategoricalDtype`.

If the :class:`Series` is of dtype :class:`CategoricalDtype`, ``Series.cat`` can be used to change the categorical
data. See :ref:`api.series.cat` for more.

.. _api.arrays.sparse:

Sparse
------

Data where a single value is repeated many times (e.g. ``0`` or ``NaN``) may
be stored efficiently as a :class:`arrays.SparseArray`.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.SparseArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   SparseDtype

The ``Series.sparse`` accessor may be used to access sparse-specific attributes
and methods if the :class:`Series` contains sparse values. See
:ref:`api.series.sparse` and :ref:`the user guide <sparse>` for more.

.. _api.arrays.string:

Strings
-------

When working with text data, where each valid element is a string or missing,
we recommend using :class:`StringDtype` (with the alias ``"string"``).

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.StringArray
   arrays.ArrowStringArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   StringDtype

The ``Series.str`` accessor is available for :class:`Series` backed by a :class:`arrays.StringArray`.
See :ref:`api.series.str` for more.

.. _api.arrays.bool:

Nullable Boolean
----------------

The boolean dtype (with the alias ``"boolean"``) provides support for storing
boolean data (``True``, ``False``) with missing values, which is not possible
with a bool :class:`numpy.ndarray`.

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   arrays.BooleanArray

.. autosummary::
   :toctree: api/
   :template: autosummary/class_without_autosummary.rst

   BooleanDtype
   NA

.. Dtype attributes which are manually listed in their docstrings: including
.. it here to make sure a docstring page is built for them

..
    .. autosummary::
      :toctree: api/

      DatetimeTZDtype.unit
      DatetimeTZDtype.tz
      PeriodDtype.freq
      IntervalDtype.subtype

*********
Utilities
*********

Constructors
------------
.. autosummary::
   :toctree: api/

   api.types.union_categoricals
   api.types.infer_dtype
   api.types.pandas_dtype

Data type introspection
~~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

    api.types.is_bool_dtype
    api.types.is_categorical_dtype
    api.types.is_complex_dtype
    api.types.is_datetime64_any_dtype
    api.types.is_datetime64_dtype
    api.types.is_datetime64_ns_dtype
    api.types.is_datetime64tz_dtype
    api.types.is_extension_array_dtype
    api.types.is_float_dtype
    api.types.is_int64_dtype
    api.types.is_integer_dtype
    api.types.is_interval_dtype
    api.types.is_numeric_dtype
    api.types.is_object_dtype
    api.types.is_period_dtype
    api.types.is_signed_integer_dtype
    api.types.is_string_dtype
    api.types.is_timedelta64_dtype
    api.types.is_timedelta64_ns_dtype
    api.types.is_unsigned_integer_dtype
    api.types.is_sparse

Iterable introspection
~~~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

    api.types.is_dict_like
    api.types.is_file_like
    api.types.is_list_like
    api.types.is_named_tuple
    api.types.is_iterator

Scalar introspection
~~~~~~~~~~~~~~~~~~~~
.. autosummary::
   :toctree: api/

    api.types.is_bool
    api.types.is_complex
    api.types.is_float
    api.types.is_hashable
    api.types.is_integer
    api.types.is_interval
    api.types.is_number
    api.types.is_re
    api.types.is_re_compilable
    api.types.is_scalar


text:
import cv2
import numpy

from logger import logger

class Sentence(object):

    def __init__(self):
        self.x = -1
        self.y = -1
        self.words = []
        self.mask = None

    def compute(self, grayed, contour, all_words):
        (self.x, self.y), (_, _), _ = cv2.minAreaRect(contour)
        for word in all_words:
            if cv2.pointPolygonTest(contour, word.pt, False) >= 0:
                if word.noise:
                    logger.warn('Skipping noisy word: {word}'.format(
                        word=word
                    ))
                else:
                    self.words.append(word)
        mask8 = numpy.zeros(grayed.shape, numpy.uint8)
        cv2.drawContours(mask8, [contour], -1, (255, 0, 0), -1)
        mask32 = numpy.int32(mask8)
        self.mask = cv2.convertScaleAbs(mask32)
        self.words = sorted(self.words, key=lambda x: (x.pt[0], x.pt[1]))
        logger.debug('Compute sentence with {count} words: {words}'.format(
            count=len(self.words),
            words=self.export()
        ))

    def __repr__(self):
        return '%s(%d, %r, %r)' % (
            self.__class__,
            len(self.words),
            self.x, self.y
        )

    def export(self):
        return [word.export() for word in self.words]


text:
package com.areabe.easyaccess.platform;

import com.areabe.easyaccess.EasyAccess;
import java.net.Socket;
import java.io.IOException;

public interface NativeHelper {
public static String ns = "127.0.0.1";
  public boolean restored=true;
  public void addNameServer() throws Exception;
  public void restoreNameServer();
  public void init(EasyAccess parent, String osName, String osVersion) throws Exception;
  public void addProvider() throws Exception;
  public Socket getSecureSocket(String host, int port) throws IOException;
}


text:
@interface NSDateComponents (supp)

@property(nonatomic, readonly) NSDate *zc_toDate;

@end