text:
"""DataFrameToMatrix: Convert a DataFrame to a Numpy Matrix (ndarray) Class"""
from __future__ import print_function

# Third Party
import pandas as pd
import numpy as np

# Local imports
from brothon.analysis import dummy_encoder

class DataFrameToMatrix(object):
    """DataFrameToMatrix: Convert a DataFrame to a Numpy Matrix (ndarray) Class
        Notes:
            fit_transform: Does a fit on the transform and returns a transformed matrix
            transform: Based on previous fit parameters returns a transformed matrix
    """
    def __init__(self):
        """Initialize the DataFrameToMatrix class"""
        self.column_names = None
        self.cat_columns = None
        self.normalize = True
        self.norm_map = {}
        self.dummy_encoder = dummy_encoder.DummyEncoder()

    def fit_transform(self, input_df, normalize=True):
        """Convert the dataframe to a matrix (numpy ndarray)
        Args:
            input_df (dataframe): The dataframe to convert
            normalize (bool): Boolean flag to normalize numeric columns (default=True)
        """
        # Shallow copy the dataframe (we'll be making changes to some columns)
        _df = input_df.copy(deep=False)

        # Set class variables that will be used both now and later for transform
        self.normalize = normalize

        # Convert columns that are probably categorical
        self.convert_to_categorical(_df)

        # First check for columns that are explicitly categorical
        self.cat_columns = _df.select_dtypes(include=['category']).columns.tolist()

        # Remove any columns that aren't bool/int/float/category
        _df = _df.select_dtypes(include=['bool', 'int', 'float', 'category'])

        # Normalize any numeric columns if normalize specified
        if self.normalize:
            for column in list(_df.select_dtypes(include=[np.number]).columns.values):
                print('Normalizing column {:s}...'.format(column))
                _df[column], _min, _max = self._normalize_series(_df[column])
                self.norm_map[column] = (_min, _max)

        # Now that categorical columns are setup call the dummy_encoder
        return self.dummy_encoder.fit_transform(_df)

    def transform(self, input_df):
        """Convert the dataframe to a matrix (numpy ndarray)
        Args:
            input_df (dataframe): The dataframe to convert
        """

        # Shallow copy the dataframe (we'll be making changes to some columns)
        _df = input_df.copy(deep=False)

        # Convert all columns that are/should be categorical
        for column in self.cat_columns:

            # Sanity check
            if column not in _df:
                raise RuntimeError('Required column {:s} not found'.format(column))

            # If the column isn't already a category then change it
            if _df[column].dtype == 'object':
                print('Changing column {:s} to category'.format(column))
                _df[column] = pd.Categorical(_df[column])

        # Remove any columns that aren't bool/int/float/category
        _df = _df.select_dtypes(include=['bool', 'int', 'float', 'category'])

        # Normalize any numeric columns if normalize specified
        if self.normalize:
            for column in list(_df.select_dtypes(include=[np.number]).columns.values):
                print('Normalizing column {:s}...'.format(column))
                smin, smax = self.norm_map[column]
                _df[column] = (_df[column] - smin) / (smax - smin)

        # Now that categorical columns are setup call the dummy_encoder
        return self.dummy_encoder.transform(_df)

    @staticmethod
    def convert_to_categorical(df):
        """Run a heuristic on the columns of the dataframe to determine whether it contains categorical values
           if the heuristic decides it's categorical then the type of the column is changed
        Args:
            df (dataframe): The dataframe to check for categorical data
        """
        might_be_categorical = df.select_dtypes(include=[object]).columns.tolist()
        for column in might_be_categorical:
            if df[column].nunique() < 20:

                # Convert the column
                print('Changing column {:s} to category...'.format(column))
                df[column] = pd.Categorical(df[column])

    @staticmethod
    def _normalize_series(series):
        smin = series.min()
        smax = series.max()
        if smax - smin == 0:
            print('Cannot normalize series (div by 0) so not normalizing...')
            smin = 0
            smax = 1
        return (series - smin) / (smax - smin), smin, smax

# Simple test of the functionality
def test():
    """Test for DataFrameToMatrix Class"""
    import os
    import pickle
    from tempfile import NamedTemporaryFile
    import numpy.testing as np_test_utils

    test_df = pd.DataFrame(
        {'A': pd.Categorical(['a', 'b', 'c', 'a'], ordered=True),
         'B': pd.Categorical(['a', 'b', 'c', 'a'], ordered=False),
         'C': pd.Categorical(['a', 'b', 'z', 'a'], categories=['a', 'b', 'z', 'd']),
         'D': [1, 2, 3, 4],
         'E': ['w', 'x', 'y', 'z'],
         'F': [1.1, 2.2, 3.3, 4.4],
         'G': pd.to_datetime([0, 1, 2, 3]),
         'H': [True, False, False, True]
         }
    )
    test_df2 = pd.DataFrame(
        {'A': pd.Categorical(['a', 'b', 'b', 'a'], ordered=True),
         'B': pd.Categorical(['a', 'b', 'd', 'a'], ordered=False),
         'C': pd.Categorical(['a', 'b', 'z', 'y'], categories=['a', 'b', 'z', 'd']),
         'D': [1, 2, 3, 7],
         'E': ['w', 'x', 'z', 'foo'],
         'F': [1.1, 2.2, 3.3, 4.4],
         'H': [True, False, False, False]
         }
    )

    # Copy the test_df for testing later
    copy_test_df = test_df.copy()

    # Test the transformation from dataframe to numpy ndarray and back again
    to_matrix = DataFrameToMatrix()
    matrix = to_matrix.fit_transform(test_df)
    matrix_test = to_matrix.transform(test_df)

    # These two matrices should be the same
    np_test_utils.assert_equal(matrix, matrix_test)

    # Assert that the dataframe we passed in didn't change
    copy_test_df.equals(test_df)

    # Test that the conversion gives us the same columns on a df with different category values
    matrix2 = to_matrix.transform(test_df2)
    assert matrix.shape == matrix2.shape

    # First two ROWS should be the same
    np_test_utils.assert_equal(matrix[0], matrix2[0])
    np_test_utils.assert_equal(matrix[1], matrix2[1])

    # Test normalize
    to_matrix_norm = DataFrameToMatrix()
    norm_matrix = to_matrix_norm.fit_transform(test_df)
    print(norm_matrix)
    assert(norm_matrix[:, 0].min() == 0)
    assert(norm_matrix[:, 0].max() == 1)

    # Make sure normalize 'does the right thing' when doing transform
    norm_matrix2 = to_matrix_norm.transform(test_df2)
    assert(norm_matrix2[:, 0].min() == 0)
    assert(norm_matrix2[:, 0].max() == 2)    # Normalization is based on FIT range

    # Test div by zero in normalize
    test_df3 = test_df2.copy()
    test_df3['D'] = [1, 1, 1, 1]
    norm_matrix3 = to_matrix_norm.fit_transform(test_df3)
    assert(norm_matrix3[:, 0].min() == 1)
    assert(norm_matrix3[:, 0].max() == 1)

    # Test serialization
    temp = NamedTemporaryFile(delete=False)
    pickle.dump(to_matrix, temp)
    temp.close()

    # Deserialize and test
    to_matrix_from_disk = pickle.load(open(temp.name, 'rb'))
    matrix3 = to_matrix_from_disk.transform(test_df)
    matrix4 = to_matrix_from_disk.transform(test_df2)
    np_test_utils.assert_equal(matrix, matrix3)
    np_test_utils.assert_equal(matrix2, matrix4)

    # Remove the temporary file
    os.unlink(temp.name)

if __name__ == "__main__":
    test()


text:
.class public Landroid/app/Notification;
.super Ljava/lang/Object;
.source "Notification.java"

# interfaces
.implements Landroid/os/Parcelable;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/app/Notification$NotificationInjector;,
        Landroid/app/Notification$InboxStyle;,
        Landroid/app/Notification$BigTextStyle;,
        Landroid/app/Notification$BigPictureStyle;,
        Landroid/app/Notification$Style;,
        Landroid/app/Notification$Builder;,
        Landroid/app/Notification$Action;
    }
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/app/Notification;",
            ">;"
        }
    .end annotation
.end field

.field public static final DEFAULT_ALL:I = -0x1

.field public static final DEFAULT_LIGHTS:I = 0x4

.field public static final DEFAULT_SOUND:I = 0x1

.field public static final DEFAULT_VIBRATE:I = 0x2

.field public static final EXTRA_AS_HEADS_UP:Ljava/lang/String; = "headsup"

.field public static final EXTRA_INFO_TEXT:Ljava/lang/String; = "android.infoText"

.field public static final EXTRA_LARGE_ICON:Ljava/lang/String; = "android.largeIcon"

.field public static final EXTRA_LARGE_ICON_BIG:Ljava/lang/String; = "android.largeIcon.big"

.field public static final EXTRA_PEOPLE:Ljava/lang/String; = "android.people"

.field public static final EXTRA_PICTURE:Ljava/lang/String; = "android.picture"

.field public static final EXTRA_PROGRESS:Ljava/lang/String; = "android.progress"

.field public static final EXTRA_PROGRESS_INDETERMINATE:Ljava/lang/String; = "android.progressIndeterminate"

.field public static final EXTRA_PROGRESS_MAX:Ljava/lang/String; = "android.progressMax"

.field public static final EXTRA_SCORE_MODIFIED:Ljava/lang/String; = "android.scoreModified"

.field public static final EXTRA_SHOW_CHRONOMETER:Ljava/lang/String; = "android.showChronometer"

.field public static final EXTRA_SHOW_WHEN:Ljava/lang/String; = "android.showWhen"

.field public static final EXTRA_SMALL_ICON:Ljava/lang/String; = "android.icon"

.field public static final EXTRA_SUB_TEXT:Ljava/lang/String; = "android.subText"

.field public static final EXTRA_SUMMARY_TEXT:Ljava/lang/String; = "android.summaryText"

.field public static final EXTRA_TEXT:Ljava/lang/String; = "android.text"

.field public static final EXTRA_TEXT_LINES:Ljava/lang/String; = "android.textLines"

.field public static final EXTRA_TITLE:Ljava/lang/String; = "android.title"

.field public static final EXTRA_TITLE_BIG:Ljava/lang/String; = "android.title.big"

.field public static final FLAG_AUTO_CANCEL:I = 0x10

.field public static final FLAG_FOREGROUND_SERVICE:I = 0x40

.field public static final FLAG_HIDE_NOTIFICATION:I = 0x10000000

.field public static final FLAG_HIGH_PRIORITY:I = 0x80

.field public static final FLAG_INSISTENT:I = 0x4

.field public static final FLAG_NO_CLEAR:I = 0x20

.field public static final FLAG_ONGOING_EVENT:I = 0x2

.field public static final FLAG_ONLY_ALERT_ONCE:I = 0x8

.field public static final FLAG_SHOW_LIGHTS:I = 0x1

.field public static final HEADS_UP_ALLOWED:I = 0x1

.field public static final HEADS_UP_NEVER:I = 0x0

.field public static final HEADS_UP_REQUESTED:I = 0x2

.field public static final KIND_CALL:Ljava/lang/String; = "android.call"

.field public static final KIND_EMAIL:Ljava/lang/String; = "android.email"

.field public static final KIND_EVENT:Ljava/lang/String; = "android.event"

.field public static final KIND_MESSAGE:Ljava/lang/String; = "android.message"

.field public static final KIND_PROMO:Ljava/lang/String; = "android.promo"

.field public static final PRIORITY_DEFAULT:I = 0x0

.field public static final PRIORITY_HIGH:I = 0x1

.field public static final PRIORITY_LOW:I = -0x1

.field public static final PRIORITY_MAX:I = 0x2

.field public static final PRIORITY_MIN:I = -0x2

.field public static final STREAM_DEFAULT:I = -0x1

.field private static final TAG:Ljava/lang/String; = "Notification"

# instance fields
.field public actions:[Landroid/app/Notification$Action;

.field public audioStreamType:I

.field public bigContentView:Landroid/widget/RemoteViews;

.field public contentIntent:Landroid/app/PendingIntent;

.field public contentView:Landroid/widget/RemoteViews;

.field public defaults:I

.field public deleteIntent:Landroid/app/PendingIntent;

.field public extras:Landroid/os/Bundle;

.field public flags:I

.field public fullScreenIntent:Landroid/app/PendingIntent;

.field public icon:I

.field public iconLevel:I

.field public kind:[Ljava/lang/String;

.field public largeIcon:Landroid/graphics/Bitmap;

.field public ledARGB:I

.field public ledOffMS:I

.field public ledOnMS:I

.field public mFlymeNotification:Landroid/app/NotificationExt;

.field public number:I

.field public priority:I

.field public simId:J

.field public simInfoType:I

.field public sound:Landroid/net/Uri;

.field public tickerText:Ljava/lang/CharSequence;

.field public tickerView:Landroid/widget/RemoteViews;

.field public vibrate:[J

.field public when:J

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

    .prologue
    .line 1046
    new-instance v0, Landroid/app/Notification$1;

    invoke-direct {v0}, Landroid/app/Notification$1;-><init>()V

    sput-object v0, Landroid/app/Notification;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

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

    .prologue
    const/4 v2, 0x0

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

    .line 230
    const/4 v0, -0x1

    iput v0, p0, Landroid/app/Notification;->audioStreamType:I

    .line 468
    new-instance v0, Landroid/os/Bundle;

    invoke-direct {v0}, Landroid/os/Bundle;-><init>()V

    iput-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    .line 2552
    new-instance v0, Landroid/app/NotificationExt;

    invoke-direct {v0}, Landroid/app/NotificationExt;-><init>()V

    iput-object v0, p0, Landroid/app/Notification;->mFlymeNotification:Landroid/app/NotificationExt;

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

    move-result-wide v0

    iput-wide v0, p0, Landroid/app/Notification;->when:J

    .line 697
    iput v2, p0, Landroid/app/Notification;->priority:I

    .line 699
    iput v2, p0, Landroid/app/Notification;->simInfoType:I

    .line 700
    const-wide/16 v0, -0x1

    iput-wide v0, p0, Landroid/app/Notification;->simId:J

    .line 701
    return-void
.end method

.method public constructor <init>(ILjava/lang/CharSequence;J)V
    .locals 1
    .param p1, "icon"    # I
    .param p2, "tickerText"    # Ljava/lang/CharSequence;
    .param p3, "when"    # J
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation

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

    .line 230
    const/4 v0, -0x1

    iput v0, p0, Landroid/app/Notification;->audioStreamType:I

    .line 468
    new-instance v0, Landroid/os/Bundle;

    invoke-direct {v0}, Landroid/os/Bundle;-><init>()V

    iput-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    .line 2552
    new-instance v0, Landroid/app/NotificationExt;

    invoke-direct {v0}, Landroid/app/NotificationExt;-><init>()V

    iput-object v0, p0, Landroid/app/Notification;->mFlymeNotification:Landroid/app/NotificationExt;

    .line 734
    iput p1, p0, Landroid/app/Notification;->icon:I

    .line 735
    iput-object p2, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    .line 736
    iput-wide p3, p0, Landroid/app/Notification;->when:J

    .line 737
    return-void
.end method

.method public constructor <init>(Landroid/content/Context;ILjava/lang/CharSequence;JLjava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/content/Intent;)V
    .locals 2
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "icon"    # I
    .param p3, "tickerText"    # Ljava/lang/CharSequence;
    .param p4, "when"    # J
    .param p6, "contentTitle"    # Ljava/lang/CharSequence;
    .param p7, "contentText"    # Ljava/lang/CharSequence;
    .param p8, "contentIntent"    # Landroid/content/Intent;

    .prologue
    const/4 v1, 0x0

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

    .line 230
    const/4 v0, -0x1

    iput v0, p0, Landroid/app/Notification;->audioStreamType:I

    .line 468
    new-instance v0, Landroid/os/Bundle;

    invoke-direct {v0}, Landroid/os/Bundle;-><init>()V

    iput-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    .line 2552
    new-instance v0, Landroid/app/NotificationExt;

    invoke-direct {v0}, Landroid/app/NotificationExt;-><init>()V

    iput-object v0, p0, Landroid/app/Notification;->mFlymeNotification:Landroid/app/NotificationExt;

    .line 709
    iput-wide p4, p0, Landroid/app/Notification;->when:J

    .line 710
    iput p2, p0, Landroid/app/Notification;->icon:I

    .line 711
    iput-object p3, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    .line 712
    invoke-static {p1, v1, p8, v1}, Landroid/app/PendingIntent;->getActivity(Landroid/content/Context;ILandroid/content/Intent;I)Landroid/app/PendingIntent;

    move-result-object v0

    invoke-virtual {p0, p1, p6, p7, v0}, Landroid/app/Notification;->setLatestEventInfo(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/app/PendingIntent;)V

    .line 715
    iput v1, p0, Landroid/app/Notification;->simInfoType:I

    .line 716
    const-wide/16 v0, -0x1

    iput-wide v0, p0, Landroid/app/Notification;->simId:J

    .line 717
    return-void
.end method

.method public constructor <init>(Landroid/os/Parcel;)V
    .locals 3
    .param p1, "parcel"    # Landroid/os/Parcel;

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

    .line 230
    const/4 v1, -0x1

    iput v1, p0, Landroid/app/Notification;->audioStreamType:I

    .line 468
    new-instance v1, Landroid/os/Bundle;

    invoke-direct {v1}, Landroid/os/Bundle;-><init>()V

    iput-object v1, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    .line 2552
    new-instance v1, Landroid/app/NotificationExt;

    invoke-direct {v1}, Landroid/app/NotificationExt;-><init>()V

    iput-object v1, p0, Landroid/app/Notification;->mFlymeNotification:Landroid/app/NotificationExt;

    .line 744
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    .line 746
    .local v0, "version":I
    invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J

    move-result-wide v1

    iput-wide v1, p0, Landroid/app/Notification;->when:J

    .line 747
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->icon:I

    .line 748
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->number:I

    .line 749
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_0

    .line 750
    sget-object v1, Landroid/app/PendingIntent;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/app/PendingIntent;

    iput-object v1, p0, Landroid/app/Notification;->contentIntent:Landroid/app/PendingIntent;

    .line 752
    :cond_0
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_1

    .line 753
    sget-object v1, Landroid/app/PendingIntent;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/app/PendingIntent;

    iput-object v1, p0, Landroid/app/Notification;->deleteIntent:Landroid/app/PendingIntent;

    .line 755
    :cond_1
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_2

    .line 756
    sget-object v1, Landroid/text/TextUtils;->CHAR_SEQUENCE_CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Ljava/lang/CharSequence;

    iput-object v1, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    .line 758
    :cond_2
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_3

    .line 759
    sget-object v1, Landroid/widget/RemoteViews;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/widget/RemoteViews;

    iput-object v1, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    .line 761
    :cond_3
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_4

    .line 762
    sget-object v1, Landroid/widget/RemoteViews;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/widget/RemoteViews;

    iput-object v1, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    .line 764
    :cond_4
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_5

    .line 765
    sget-object v1, Landroid/graphics/Bitmap;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/graphics/Bitmap;

    iput-object v1, p0, Landroid/app/Notification;->largeIcon:Landroid/graphics/Bitmap;

    .line 769
    :cond_5
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->simInfoType:I

    .line 770
    invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J

    move-result-wide v1

    iput-wide v1, p0, Landroid/app/Notification;->simId:J

    .line 772
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->defaults:I

    .line 773
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->flags:I

    .line 774
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_6

    .line 775
    sget-object v1, Landroid/net/Uri;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/net/Uri;

    iput-object v1, p0, Landroid/app/Notification;->sound:Landroid/net/Uri;

    .line 778
    :cond_6
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->audioStreamType:I

    .line 779
    invoke-virtual {p1}, Landroid/os/Parcel;->createLongArray()[J

    move-result-object v1

    iput-object v1, p0, Landroid/app/Notification;->vibrate:[J

    .line 780
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->ledARGB:I

    .line 781
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->ledOnMS:I

    .line 782
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->ledOffMS:I

    .line 783
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->iconLevel:I

    .line 785
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_7

    .line 786
    sget-object v1, Landroid/app/PendingIntent;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/app/PendingIntent;

    iput-object v1, p0, Landroid/app/Notification;->fullScreenIntent:Landroid/app/PendingIntent;

    .line 789
    :cond_7
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, p0, Landroid/app/Notification;->priority:I

    .line 791
    invoke-virtual {p1}, Landroid/os/Parcel;->createStringArray()[Ljava/lang/String;

    move-result-object v1

    iput-object v1, p0, Landroid/app/Notification;->kind:[Ljava/lang/String;

    .line 793
    invoke-virtual {p1}, Landroid/os/Parcel;->readBundle()Landroid/os/Bundle;

    move-result-object v1

    iput-object v1, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    .line 795
    sget-object v1, Landroid/app/Notification$Action;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->createTypedArray(Landroid/os/Parcelable$Creator;)[Ljava/lang/Object;

    move-result-object v1

    check-cast v1, [Landroid/app/Notification$Action;

    iput-object v1, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    .line 797
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    if-eqz v1, :cond_8

    .line 798
    sget-object v1, Landroid/widget/RemoteViews;->CREATOR:Landroid/os/Parcelable$Creator;

    invoke-interface {v1, p1}, Landroid/os/Parcelable$Creator;->createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Landroid/widget/RemoteViews;

    iput-object v1, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    .line 803
    :cond_8
    invoke-static {p0, p1}, Landroid/app/Notification$NotificationInjector;->readFromParcel(Landroid/app/Notification;Landroid/os/Parcel;)V

    .line 806
    return-void
.end method

.method public static safeCharSequence(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;
    .locals 3
    .param p0, "cs"    # Ljava/lang/CharSequence;

    .prologue
    .line 934
    instance-of v0, p0, Landroid/os/Parcelable;

    if-eqz v0, :cond_0

    .line 935
    const-string v0, "Notification"

    new-instance v1, Ljava/lang/StringBuilder;

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

    const-string/jumbo v2, "warning: "

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

    move-result-object v1

    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/Class;->getCanonicalName()Ljava/lang/String;

    move-result-object v2

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

    move-result-object v1

    const-string v2, " instance is a custom Parcelable and not allowed in Notification"

    invoke-virtual {v1, v2}, 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-static {v0, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 937
    invoke-virtual {p0}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object p0

    .line 940
    .end local p0    # "cs":Ljava/lang/CharSequence;
    :cond_0
    return-object p0
.end method

# virtual methods
.method public clone()Landroid/app/Notification;
    .locals 2

    .prologue
    .line 810
    new-instance v0, Landroid/app/Notification;

    invoke-direct {v0}, Landroid/app/Notification;-><init>()V

    .line 811
    .local v0, "that":Landroid/app/Notification;
    const/4 v1, 0x1

    invoke-virtual {p0, v0, v1}, Landroid/app/Notification;->cloneInto(Landroid/app/Notification;Z)V

    .line 812
    return-object v0
.end method

.method public bridge synthetic clone()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/CloneNotSupportedException;
        }
    .end annotation

    .prologue
    .line 57
    invoke-virtual {p0}, Landroid/app/Notification;->clone()Landroid/app/Notification;

    move-result-object v0

    return-object v0
.end method

.method public cloneInto(Landroid/app/Notification;Z)V
    .locals 12
    .param p1, "that"    # Landroid/app/Notification;
    .param p2, "heavy"    # Z

    .prologue
    const/4 v11, 0x0

    .line 821
    iget-wide v7, p0, Landroid/app/Notification;->when:J

    iput-wide v7, p1, Landroid/app/Notification;->when:J

    .line 822
    iget v7, p0, Landroid/app/Notification;->icon:I

    iput v7, p1, Landroid/app/Notification;->icon:I

    .line 826
    invoke-static {p1, p0}, Landroid/app/Notification$NotificationInjector;->cloneInto(Landroid/app/Notification;Landroid/app/Notification;)V

    .line 829
    iget v7, p0, Landroid/app/Notification;->number:I

    iput v7, p1, Landroid/app/Notification;->number:I

    .line 832
    iget-object v7, p0, Landroid/app/Notification;->contentIntent:Landroid/app/PendingIntent;

    iput-object v7, p1, Landroid/app/Notification;->contentIntent:Landroid/app/PendingIntent;

    .line 833
    iget-object v7, p0, Landroid/app/Notification;->deleteIntent:Landroid/app/PendingIntent;

    iput-object v7, p1, Landroid/app/Notification;->deleteIntent:Landroid/app/PendingIntent;

    .line 834
    iget-object v7, p0, Landroid/app/Notification;->fullScreenIntent:Landroid/app/PendingIntent;

    iput-object v7, p1, Landroid/app/Notification;->fullScreenIntent:Landroid/app/PendingIntent;

    .line 836
    iget-object v7, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    if-eqz v7, :cond_0

    .line 837
    iget-object v7, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    invoke-virtual {v7}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v7

    iput-object v7, p1, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

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

    iget-object v7, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    if-eqz v7, :cond_1

    .line 840
    iget-object v7, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    invoke-virtual {v7}, Landroid/widget/RemoteViews;->clone()Landroid/widget/RemoteViews;

    move-result-object v7

    iput-object v7, p1, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    .line 842
    :cond_1
    if-eqz p2, :cond_2

    iget-object v7, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    if-eqz v7, :cond_2

    .line 843
    iget-object v7, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    invoke-virtual {v7}, Landroid/widget/RemoteViews;->clone()Landroid/widget/RemoteViews;

    move-result-object v7

    iput-object v7, p1, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    .line 845
    :cond_2
    if-eqz p2, :cond_3

    iget-object v7, p0, Landroid/app/Notification;->largeIcon:Landroid/graphics/Bitmap;

    if-eqz v7, :cond_3

    .line 846
    iget-object v7, p0, Landroid/app/Notification;->largeIcon:Landroid/graphics/Bitmap;

    invoke-static {v7}, Landroid/graphics/Bitmap;->createBitmap(Landroid/graphics/Bitmap;)Landroid/graphics/Bitmap;

    move-result-object v7

    iput-object v7, p1, Landroid/app/Notification;->largeIcon:Landroid/graphics/Bitmap;

    .line 850
    :cond_3
    iget v7, p1, Landroid/app/Notification;->simInfoType:I

    if-nez v7, :cond_4

    .line 851
    iget v7, p0, Landroid/app/Notification;->simInfoType:I

    iput v7, p1, Landroid/app/Notification;->simInfoType:I

    .line 853
    :cond_4
    iget-wide v7, p1, Landroid/app/Notification;->simId:J

    const-wide/16 v9, -0x1

    cmp-long v7, v7, v9

    if-nez v7, :cond_5

    .line 854
    iget-wide v7, p0, Landroid/app/Notification;->simId:J

    iput-wide v7, p1, Landroid/app/Notification;->simId:J

    .line 857
    :cond_5
    iget v7, p0, Landroid/app/Notification;->iconLevel:I

    iput v7, p1, Landroid/app/Notification;->iconLevel:I

    .line 858
    iget-object v7, p0, Landroid/app/Notification;->sound:Landroid/net/Uri;

    iput-object v7, p1, Landroid/app/Notification;->sound:Landroid/net/Uri;

    .line 859
    iget v7, p0, Landroid/app/Notification;->audioStreamType:I

    iput v7, p1, Landroid/app/Notification;->audioStreamType:I

    .line 861
    iget-object v6, p0, Landroid/app/Notification;->vibrate:[J

    .line 862
    .local v6, "vibrate":[J
    if-eqz v6, :cond_6

    .line 863
    array-length v0, v6

    .line 864
    .local v0, "N":I
    new-array v5, v0, [J

    iput-object v5, p1, Landroid/app/Notification;->vibrate:[J

    .line 865
    .local v5, "vib":[J
    invoke-static {v6, v11, v5, v11, v0}, Ljava/lang/System;->arraycopy(Ljava/lang/Object;ILjava/lang/Object;II)V

    .line 868
    .end local v0    # "N":I
    .end local v5    # "vib":[J
    :cond_6
    iget v7, p0, Landroid/app/Notification;->ledARGB:I

    iput v7, p1, Landroid/app/Notification;->ledARGB:I

    .line 869
    iget v7, p0, Landroid/app/Notification;->ledOnMS:I

    iput v7, p1, Landroid/app/Notification;->ledOnMS:I

    .line 870
    iget v7, p0, Landroid/app/Notification;->ledOffMS:I

    iput v7, p1, Landroid/app/Notification;->ledOffMS:I

    .line 871
    iget v7, p0, Landroid/app/Notification;->defaults:I

    iput v7, p1, Landroid/app/Notification;->defaults:I

    .line 873
    iget v7, p0, Landroid/app/Notification;->flags:I

    iput v7, p1, Landroid/app/Notification;->flags:I

    .line 875
    iget v7, p0, Landroid/app/Notification;->priority:I

    iput v7, p1, Landroid/app/Notification;->priority:I

    .line 877
    iget-object v4, p0, Landroid/app/Notification;->kind:[Ljava/lang/String;

    .line 878
    .local v4, "thiskind":[Ljava/lang/String;
    if-eqz v4, :cond_7

    .line 879
    array-length v0, v4

    .line 880
    .restart local v0    # "N":I
    new-array v3, v0, [Ljava/lang/String;

    iput-object v3, p1, Landroid/app/Notification;->kind:[Ljava/lang/String;

    .line 881
    .local v3, "thatkind":[Ljava/lang/String;
    invoke-static {v4, v11, v3, v11, v0}, Ljava/lang/System;->arraycopy(Ljava/lang/Object;ILjava/lang/Object;II)V

    .line 884
    .end local v0    # "N":I
    .end local v3    # "thatkind":[Ljava/lang/String;
    :cond_7
    iget-object v7, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    if-eqz v7, :cond_8

    .line 886
    :try_start_0
    new-instance v7, Landroid/os/Bundle;

    iget-object v8, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    invoke-direct {v7, v8}, Landroid/os/Bundle;-><init>(Landroid/os/Bundle;)V

    iput-object v7, p1, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    .line 888
    iget-object v7, p1, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    invoke-virtual {v7}, Landroid/os/Bundle;->size()I
    :try_end_0
    .catch Landroid/os/BadParcelableException; {:try_start_0 .. :try_end_0} :catch_0

    .line 895
    :cond_8
    :goto_0
    iget-object v7, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    if-eqz v7, :cond_9

    .line 896
    iget-object v7, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    array-length v7, v7

    new-array v7, v7, [Landroid/app/Notification$Action;

    iput-object v7, p1, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    .line 897
    const/4 v2, 0x0

    .local v2, "i":I
    :goto_1
    iget-object v7, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    array-length v7, v7

    if-ge v2, v7, :cond_9

    .line 898
    iget-object v7, p1, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    iget-object v8, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    aget-object v8, v8, v2

    invoke-virtual {v8}, Landroid/app/Notification$Action;->clone()Landroid/app/Notification$Action;

    move-result-object v8

    aput-object v8, v7, v2

    .line 897
    add-int/lit8 v2, v2, 0x1

    goto :goto_1

    .line 889
    .end local v2    # "i":I
    :catch_0
    move-exception v1

    .line 890
    .local v1, "e":Landroid/os/BadParcelableException;
    const-string v7, "Notification"

    new-instance v8, Ljava/lang/StringBuilder;

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

    const-string v9, "could not unparcel extras from notification: "

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

    move-result-object v8

    invoke-virtual {v8, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v8

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

    move-result-object v8

    invoke-static {v7, v8, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    .line 891
    const/4 v7, 0x0

    iput-object v7, p1, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    goto :goto_0

    .line 902
    .end local v1    # "e":Landroid/os/BadParcelableException;
    :cond_9
    if-eqz p2, :cond_a

    iget-object v7, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    if-eqz v7, :cond_a

    .line 903
    iget-object v7, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    invoke-virtual {v7}, Landroid/widget/RemoteViews;->clone()Landroid/widget/RemoteViews;

    move-result-object v7

    iput-object v7, p1, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    .line 906
    :cond_a
    if-nez p2, :cond_b

    .line 907
    invoke-virtual {p1}, Landroid/app/Notification;->lightenPayload()V

    .line 909
    :cond_b
    return-void
.end method

.method public describeContents()I
    .locals 1

    .prologue
    .line 944
    const/4 v0, 0x0

    return v0
.end method

.method public final lightenPayload()V
    .locals 2

    .prologue
    const/4 v0, 0x0

    .line 917
    iput-object v0, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    .line 918
    iput-object v0, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    .line 919
    iput-object v0, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    .line 920
    iput-object v0, p0, Landroid/app/Notification;->largeIcon:Landroid/graphics/Bitmap;

    .line 921
    iget-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    if-eqz v0, :cond_0

    .line 922
    iget-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    const-string v1, "android.largeIcon"

    invoke-virtual {v0, v1}, Landroid/os/Bundle;->remove(Ljava/lang/String;)V

    .line 923
    iget-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    const-string v1, "android.largeIcon.big"

    invoke-virtual {v0, v1}, Landroid/os/Bundle;->remove(Ljava/lang/String;)V

    .line 924
    iget-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    const-string v1, "android.picture"

    invoke-virtual {v0, v1}, Landroid/os/Bundle;->remove(Ljava/lang/String;)V

    .line 926
    :cond_0
    return-void
.end method

.method public setLatestEventInfo(Landroid/content/Context;Ljava/lang/CharSequence;Ljava/lang/CharSequence;Landroid/app/PendingIntent;)V
    .locals 3
    .param p1, "context"    # Landroid/content/Context;
    .param p2, "contentTitle"    # Ljava/lang/CharSequence;
    .param p3, "contentText"    # Ljava/lang/CharSequence;
    .param p4, "contentIntent"    # Landroid/app/PendingIntent;
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation

    .prologue
    .line 1081
    new-instance v0, Landroid/app/Notification$Builder;

    invoke-direct {v0, p1}, Landroid/app/Notification$Builder;-><init>(Landroid/content/Context;)V

    .line 1085
    .local v0, "builder":Landroid/app/Notification$Builder;
    iget-wide v1, p0, Landroid/app/Notification;->when:J

    invoke-virtual {v0, v1, v2}, Landroid/app/Notification$Builder;->setWhen(J)Landroid/app/Notification$Builder;

    .line 1086
    iget v1, p0, Landroid/app/Notification;->icon:I

    invoke-virtual {v0, v1}, Landroid/app/Notification$Builder;->setSmallIcon(I)Landroid/app/Notification$Builder;

    .line 1090
    invoke-static {v0, p0}, Landroid/app/Notification$NotificationInjector;->setLatestEventInfo(Landroid/app/Notification$Builder;Landroid/app/Notification;)V

    .line 1093
    iget v1, p0, Landroid/app/Notification;->priority:I

    invoke-virtual {v0, v1}, Landroid/app/Notification$Builder;->setPriority(I)Landroid/app/Notification$Builder;

    .line 1094
    iget-object v1, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    invoke-virtual {v0, v1}, Landroid/app/Notification$Builder;->setTicker(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;

    .line 1095
    iget v1, p0, Landroid/app/Notification;->number:I

    invoke-virtual {v0, v1}, Landroid/app/Notification$Builder;->setNumber(I)Landroid/app/Notification$Builder;

    .line 1096
    iget v1, p0, Landroid/app/Notification;->flags:I

    # setter for: Landroid/app/Notification$Builder;->mFlags:I
    invoke-static {v0, v1}, Landroid/app/Notification$Builder;->access$102(Landroid/app/Notification$Builder;I)I

    .line 1097
    iget-object v1, p0, Landroid/app/Notification;->sound:Landroid/net/Uri;

    iget v2, p0, Landroid/app/Notification;->audioStreamType:I

    invoke-virtual {v0, v1, v2}, Landroid/app/Notification$Builder;->setSound(Landroid/net/Uri;I)Landroid/app/Notification$Builder;

    .line 1098
    iget v1, p0, Landroid/app/Notification;->defaults:I

    invoke-virtual {v0, v1}, Landroid/app/Notification$Builder;->setDefaults(I)Landroid/app/Notification$Builder;

    .line 1099
    iget-object v1, p0, Landroid/app/Notification;->vibrate:[J

    invoke-virtual {v0, v1}, Landroid/app/Notification$Builder;->setVibrate([J)Landroid/app/Notification$Builder;

    .line 1102
    if-eqz p2, :cond_0

    .line 1103
    invoke-virtual {v0, p2}, Landroid/app/Notification$Builder;->setContentTitle(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;

    .line 1105
    :cond_0
    if-eqz p3, :cond_1

    .line 1106
    invoke-virtual {v0, p3}, Landroid/app/Notification$Builder;->setContentText(Ljava/lang/CharSequence;)Landroid/app/Notification$Builder;

    .line 1108
    :cond_1
    invoke-virtual {v0, p4}, Landroid/app/Notification$Builder;->setContentIntent(Landroid/app/PendingIntent;)Landroid/app/Notification$Builder;

    .line 1109
    invoke-virtual {v0, p0}, Landroid/app/Notification$Builder;->buildInto(Landroid/app/Notification;)Landroid/app/Notification;

    .line 1110
    return-void
.end method

.method public setUser(Landroid/os/UserHandle;)V
    .locals 2
    .param p1, "user"    # Landroid/os/UserHandle;

    .prologue
    .line 1177
    invoke-virtual {p1}, Landroid/os/UserHandle;->getIdentifier()I

    move-result v0

    const/4 v1, -0x1

    if-ne v0, v1, :cond_0

    .line 1178
    sget-object p1, Landroid/os/UserHandle;->OWNER:Landroid/os/UserHandle;

    .line 1180
    :cond_0
    iget-object v0, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    if-eqz v0, :cond_1

    .line 1181
    iget-object v0, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    invoke-virtual {v0, p1}, Landroid/widget/RemoteViews;->setUser(Landroid/os/UserHandle;)V

    .line 1183
    :cond_1
    iget-object v0, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    if-eqz v0, :cond_2

    .line 1184
    iget-object v0, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    invoke-virtual {v0, p1}, Landroid/widget/RemoteViews;->setUser(Landroid/os/UserHandle;)V

    .line 1186
    :cond_2
    iget-object v0, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    if-eqz v0, :cond_3

    .line 1187
    iget-object v0, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    invoke-virtual {v0, p1}, Landroid/widget/RemoteViews;->setUser(Landroid/os/UserHandle;)V

    .line 1189
    :cond_3
    return-void
.end method

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

    .prologue
    .line 1114
    new-instance v2, Ljava/lang/StringBuilder;

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

    .line 1115
    .local v2, "sb":Ljava/lang/StringBuilder;
    const-string v3, "Notification(pri="

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

    .line 1116
    iget v3, p0, Landroid/app/Notification;->priority:I

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

    .line 1117
    const-string v3, " contentView="

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

    .line 1118
    iget-object v3, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    if-eqz v3, :cond_2

    .line 1119
    iget-object v3, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    invoke-virtual {v3}, Landroid/widget/RemoteViews;->getPackage()Ljava/lang/String;

    move-result-object v3

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

    .line 1120
    const-string v3, "/0x"

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

    .line 1121
    iget-object v3, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    invoke-virtual {v3}, Landroid/widget/RemoteViews;->getLayoutId()I

    move-result v3

    invoke-static {v3}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v3

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

    .line 1126
    :goto_0
    const-string v3, " vibrate="

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

    .line 1127
    iget v3, p0, Landroid/app/Notification;->defaults:I

    and-int/lit8 v3, v3, 0x2

    if-eqz v3, :cond_3

    .line 1128
    const-string v3, "default"

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

    .line 1143
    :goto_1
    const-string v3, " sound="

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

    .line 1144
    iget v3, p0, Landroid/app/Notification;->defaults:I

    and-int/lit8 v3, v3, 0x1

    if-eqz v3, :cond_7

    .line 1145
    const-string v3, "default"

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

    .line 1151
    :goto_2
    const-string v3, " defaults=0x"

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

    .line 1152
    iget v3, p0, Landroid/app/Notification;->defaults:I

    invoke-static {v3}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v3

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

    .line 1153
    const-string v3, " flags=0x"

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

    .line 1154
    iget v3, p0, Landroid/app/Notification;->flags:I

    invoke-static {v3}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v3

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

    .line 1155
    const-string v3, " kind=["

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

    .line 1156
    iget-object v3, p0, Landroid/app/Notification;->kind:[Ljava/lang/String;

    if-nez v3, :cond_9

    .line 1157
    const-string/jumbo v3, "null"

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

    .line 1164
    :cond_0
    const-string v3, "]"

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

    .line 1165
    iget-object v3, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    if-eqz v3, :cond_1

    .line 1166
    const-string v3, " "

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

    .line 1167
    iget-object v3, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    array-length v3, v3

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

    .line 1168
    const-string v3, " action"

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

    .line 1169
    iget-object v3, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    array-length v3, v3

    const/4 v4, 0x1

    if-le v3, v4, :cond_1

    const-string/jumbo v3, "s"

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

    .line 1171
    :cond_1
    const-string v3, ")"

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

    .line 1172
    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    return-object v3

    .line 1123
    :cond_2
    const-string/jumbo v3, "null"

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

    goto :goto_0

    .line 1129
    :cond_3
    iget-object v3, p0, Landroid/app/Notification;->vibrate:[J

    if-eqz v3, :cond_6

    .line 1130
    iget-object v3, p0, Landroid/app/Notification;->vibrate:[J

    array-length v3, v3

    add-int/lit8 v0, v3, -0x1

    .line 1131
    .local v0, "N":I
    const-string v3, "["

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

    .line 1132
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_3
    if-ge v1, v0, :cond_4

    .line 1133
    iget-object v3, p0, Landroid/app/Notification;->vibrate:[J

    aget-wide v3, v3, v1

    invoke-virtual {v2, v3, v4}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    .line 1134
    const/16 v3, 0x2c

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    .line 1132
    add-int/lit8 v1, v1, 0x1

    goto :goto_3

    .line 1136
    :cond_4
    const/4 v3, -0x1

    if-eq v0, v3, :cond_5

    .line 1137
    iget-object v3, p0, Landroid/app/Notification;->vibrate:[J

    aget-wide v3, v3, v0

    invoke-virtual {v2, v3, v4}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    .line 1139
    :cond_5
    const-string v3, "]"

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

    goto/16 :goto_1

    .line 1141
    .end local v0    # "N":I
    .end local v1    # "i":I
    :cond_6
    const-string/jumbo v3, "null"

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

    goto/16 :goto_1

    .line 1146
    :cond_7
    iget-object v3, p0, Landroid/app/Notification;->sound:Landroid/net/Uri;

    if-eqz v3, :cond_8

    .line 1147
    iget-object v3, p0, Landroid/app/Notification;->sound:Landroid/net/Uri;

    invoke-virtual {v3}, Landroid/net/Uri;->toString()Ljava/lang/String;

    move-result-object v3

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

    goto/16 :goto_2

    .line 1149
    :cond_8
    const-string/jumbo v3, "null"

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

    goto/16 :goto_2

    .line 1159
    :cond_9
    const/4 v1, 0x0

    .restart local v1    # "i":I
    :goto_4
    iget-object v3, p0, Landroid/app/Notification;->kind:[Ljava/lang/String;

    array-length v3, v3

    if-ge v1, v3, :cond_0

    .line 1160
    if-lez v1, :cond_a

    const-string v3, ","

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

    .line 1161
    :cond_a
    iget-object v3, p0, Landroid/app/Notification;->kind:[Ljava/lang/String;

    aget-object v3, v3, v1

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

    .line 1159
    add-int/lit8 v1, v1, 0x1

    goto :goto_4
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 4
    .param p1, "parcel"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    const/4 v3, 0x1

    const/4 v2, 0x0

    .line 952
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 954
    iget-wide v0, p0, Landroid/app/Notification;->when:J

    invoke-virtual {p1, v0, v1}, Landroid/os/Parcel;->writeLong(J)V

    .line 955
    iget v0, p0, Landroid/app/Notification;->icon:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 956
    iget v0, p0, Landroid/app/Notification;->number:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 957
    iget-object v0, p0, Landroid/app/Notification;->contentIntent:Landroid/app/PendingIntent;

    if-eqz v0, :cond_0

    .line 958
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 959
    iget-object v0, p0, Landroid/app/Notification;->contentIntent:Landroid/app/PendingIntent;

    invoke-virtual {v0, p1, v2}, Landroid/app/PendingIntent;->writeToParcel(Landroid/os/Parcel;I)V

    .line 963
    :goto_0
    iget-object v0, p0, Landroid/app/Notification;->deleteIntent:Landroid/app/PendingIntent;

    if-eqz v0, :cond_1

    .line 964
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 965
    iget-object v0, p0, Landroid/app/Notification;->deleteIntent:Landroid/app/PendingIntent;

    invoke-virtual {v0, p1, v2}, Landroid/app/PendingIntent;->writeToParcel(Landroid/os/Parcel;I)V

    .line 969
    :goto_1
    iget-object v0, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    if-eqz v0, :cond_2

    .line 970
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 971
    iget-object v0, p0, Landroid/app/Notification;->tickerText:Ljava/lang/CharSequence;

    invoke-static {v0, p1, p2}, Landroid/text/TextUtils;->writeToParcel(Ljava/lang/CharSequence;Landroid/os/Parcel;I)V

    .line 975
    :goto_2
    iget-object v0, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    if-eqz v0, :cond_3

    .line 976
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 977
    iget-object v0, p0, Landroid/app/Notification;->tickerView:Landroid/widget/RemoteViews;

    invoke-virtual {v0, p1, v2}, Landroid/widget/RemoteViews;->writeToParcel(Landroid/os/Parcel;I)V

    .line 981
    :goto_3
    iget-object v0, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    if-eqz v0, :cond_4

    .line 982
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 983
    iget-object v0, p0, Landroid/app/Notification;->contentView:Landroid/widget/RemoteViews;

    invoke-virtual {v0, p1, v2}, Landroid/widget/RemoteViews;->writeToParcel(Landroid/os/Parcel;I)V

    .line 987
    :goto_4
    iget-object v0, p0, Landroid/app/Notification;->largeIcon:Landroid/graphics/Bitmap;

    if-eqz v0, :cond_5

    .line 988
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 989
    iget-object v0, p0, Landroid/app/Notification;->largeIcon:Landroid/graphics/Bitmap;

    invoke-virtual {v0, p1, v2}, Landroid/graphics/Bitmap;->writeToParcel(Landroid/os/Parcel;I)V

    .line 996
    :goto_5
    iget v0, p0, Landroid/app/Notification;->simInfoType:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 997
    iget-wide v0, p0, Landroid/app/Notification;->simId:J

    invoke-virtual {p1, v0, v1}, Landroid/os/Parcel;->writeLong(J)V

    .line 999
    iget v0, p0, Landroid/app/Notification;->defaults:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1000
    iget v0, p0, Landroid/app/Notification;->flags:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1002
    iget-object v0, p0, Landroid/app/Notification;->sound:Landroid/net/Uri;

    if-eqz v0, :cond_6

    .line 1003
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 1004
    iget-object v0, p0, Landroid/app/Notification;->sound:Landroid/net/Uri;

    invoke-virtual {v0, p1, v2}, Landroid/net/Uri;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1008
    :goto_6
    iget v0, p0, Landroid/app/Notification;->audioStreamType:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1009
    iget-object v0, p0, Landroid/app/Notification;->vibrate:[J

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeLongArray([J)V

    .line 1010
    iget v0, p0, Landroid/app/Notification;->ledARGB:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1011
    iget v0, p0, Landroid/app/Notification;->ledOnMS:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1012
    iget v0, p0, Landroid/app/Notification;->ledOffMS:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1013
    iget v0, p0, Landroid/app/Notification;->iconLevel:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1015
    iget-object v0, p0, Landroid/app/Notification;->fullScreenIntent:Landroid/app/PendingIntent;

    if-eqz v0, :cond_7

    .line 1016
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 1017
    iget-object v0, p0, Landroid/app/Notification;->fullScreenIntent:Landroid/app/PendingIntent;

    invoke-virtual {v0, p1, v2}, Landroid/app/PendingIntent;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1022
    :goto_7
    iget v0, p0, Landroid/app/Notification;->priority:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 1024
    iget-object v0, p0, Landroid/app/Notification;->kind:[Ljava/lang/String;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeStringArray([Ljava/lang/String;)V

    .line 1026
    iget-object v0, p0, Landroid/app/Notification;->extras:Landroid/os/Bundle;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeBundle(Landroid/os/Bundle;)V

    .line 1028
    iget-object v0, p0, Landroid/app/Notification;->actions:[Landroid/app/Notification$Action;

    invoke-virtual {p1, v0, v2}, Landroid/os/Parcel;->writeTypedArray([Landroid/os/Parcelable;I)V

    .line 1030
    iget-object v0, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    if-eqz v0, :cond_8

    .line 1031
    invoke-virtual {p1, v3}, Landroid/os/Parcel;->writeInt(I)V

    .line 1032
    iget-object v0, p0, Landroid/app/Notification;->bigContentView:Landroid/widget/RemoteViews;

    invoke-virtual {v0, p1, v2}, Landroid/widget/RemoteViews;->writeToParcel(Landroid/os/Parcel;I)V

    .line 1039
    :goto_8
    invoke-static {p0, p1, p2}, Landroid/app/Notification$NotificationInjector;->writeToParcel(Landroid/app/Notification;Landroid/os/Parcel;I)V

    .line 1041
    return-void

    .line 961
    :cond_0
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto/16 :goto_0

    .line 967
    :cond_1
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto/16 :goto_1

    .line 973
    :cond_2
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto/16 :goto_2

    .line 979
    :cond_3
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto/16 :goto_3

    .line 985
    :cond_4
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto/16 :goto_4

    .line 991
    :cond_5
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto/16 :goto_5

    .line 1006
    :cond_6
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_6

    .line 1019
    :cond_7
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_7

    .line 1034
    :cond_8
    invoke-virtual {p1, v2}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_8
.end method

redpajama_set_name: RedPajamaGithub


text:
"""

    arrayTools and bezierTools, originally from fontTools and using Numpy,
    now in a pure python implementation. This should ease the Numpy dependency
    for normal UFO input/output and basic scripting tasks.

    comparison test and speedtest provided.

"""


text:
Headers are useful to put at the top of websites and they usually contain a [Nav bar](navigation) for navigation.
```html
<header class="tn-header">
  <div class="tn-row tn-container">
    <h1 class="tn-col-1-3 tn-website-title">Website Title</h1>
    <nav class="tn-col-2-3">
      <!-- Navigation -->
    </nav>
  </div>
</header>
```

This is how to setup the header, you can also add [colors](colors) to personalise and you can use a [grid](grid) to neatly organise it.


text:
using OpenMetaverse;
using System;
using System.Data.SqlClient;

namespace OpenSim.Data.MSSQL
{
    public class MSSQLXInventoryData : IXInventoryData
    {
        //        private static readonly ILog m_log = LogManager.GetLogger(
        //                MethodBase.GetCurrentMethod().DeclaringType);

        private MSSQLFolderHandler m_Folders;
        private MSSQLItemHandler m_Items;

        public MSSQLXInventoryData(string conn, string realm)
        {
            m_Folders = new MSSQLFolderHandler(
                    conn, "inventoryfolders", "InventoryStore");
            m_Items = new MSSQLItemHandler(
                    conn, "inventoryitems", String.Empty);
        }

        public XInventoryFolder[] GetFolders(string[] fields, string[] vals)
        {
            return m_Folders.Get(fields, vals);
        }

        public XInventoryItem[] GetItems(string[] fields, string[] vals)
        {
            return m_Items.Get(fields, vals);
        }

        public bool StoreFolder(XInventoryFolder folder)
        {
            if (folder.folderName.Length > 64)
                folder.folderName = folder.folderName.Substring(0, 64);
            return m_Folders.Store(folder);
        }

        public bool StoreItem(XInventoryItem item)
        {
            if (item.inventoryName.Length > 64)
                item.inventoryName = item.inventoryName.Substring(0, 64);
            if (item.inventoryDescription.Length > 128)
                item.inventoryDescription = item.inventoryDescription.Substring(0, 128);

            return m_Items.Store(item);
        }

        public bool DeleteFolders(string field, string val)
        {
            return m_Folders.Delete(field, val);
        }

        public bool DeleteFolders(string[] fields, string[] vals)
        {
            return m_Folders.Delete(fields, vals);
        }

        public bool DeleteItems(string field, string val)
        {
            return m_Items.Delete(field, val);
        }

        public bool DeleteItems(string[] fields, string[] vals)
        {
            return m_Items.Delete(fields, vals);
        }

        public bool MoveItem(string id, string newParent)
        {
            return m_Items.MoveItem(id, newParent);
        }

        public bool MoveFolder(string id, string newParent)
        {
            return m_Folders.MoveFolder(id, newParent);
        }

        public XInventoryItem[] GetActiveGestures(UUID principalID)
        {
            return m_Items.GetActiveGestures(principalID);
        }
    }

    public class MSSQLItemHandler : MSSQLInventoryHandler<XInventoryItem>
    {
        public MSSQLItemHandler(string c, string t, string m) :
            base(c, t, m)
        {
        }

        public bool MoveItem(string id, string newParent)
        {
            XInventoryItem[] retrievedItems = Get(new string[] { "inventoryID" }, new string[] { id });
            if (retrievedItems.Length == 0)
                return false;

            UUID oldParent = retrievedItems[0].parentFolderID;

            using (SqlConnection conn = new SqlConnection(m_ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = String.Format("update {0} set parentFolderID = @ParentFolderID where inventoryID = @InventoryID", m_Realm);
                    cmd.Parameters.Add(m_database.CreateParameter("@ParentFolderID", newParent));
                    cmd.Parameters.Add(m_database.CreateParameter("@InventoryID", id));
                    cmd.Connection = conn;
                    conn.Open();

                    if (cmd.ExecuteNonQuery() == 0)
                        return false;
                }
            }

            IncrementFolderVersion(oldParent);
            IncrementFolderVersion(newParent);

            return true;
        }

        public XInventoryItem[] GetActiveGestures(UUID principalID)
        {
            using (SqlConnection conn = new SqlConnection(m_ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = String.Format("select * from inventoryitems where avatarId = @uuid and assetType = @type and flags = 1", m_Realm);

                    cmd.Parameters.Add(m_database.CreateParameter("@uuid", principalID.ToString()));
                    cmd.Parameters.Add(m_database.CreateParameter("@type", (int)AssetType.Gesture));
                    cmd.Connection = conn;
                    conn.Open();
                    return DoQuery(cmd);
                }
            }
        }

        public override bool Store(XInventoryItem item)
        {
            if (!base.Store(item))
                return false;

            IncrementFolderVersion(item.parentFolderID);

            return true;
        }
    }

    public class MSSQLFolderHandler : MSSQLInventoryHandler<XInventoryFolder>
    {
        public MSSQLFolderHandler(string c, string t, string m) :
            base(c, t, m)
        {
        }

        public bool MoveFolder(string id, string newParentFolderID)
        {
            XInventoryFolder[] folders = Get(new string[] { "folderID" }, new string[] { id });

            if (folders.Length == 0)
                return false;

            UUID oldParentFolderUUID = folders[0].parentFolderID;

            using (SqlConnection conn = new SqlConnection(m_ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = String.Format("update {0} set parentFolderID = @ParentFolderID where folderID = @folderID", m_Realm);
                    cmd.Parameters.Add(m_database.CreateParameter("@ParentFolderID", newParentFolderID));
                    cmd.Parameters.Add(m_database.CreateParameter("@folderID", id));
                    cmd.Connection = conn;
                    conn.Open();

                    if (cmd.ExecuteNonQuery() == 0)
                        return false;
                }
            }

            IncrementFolderVersion(oldParentFolderUUID);
            IncrementFolderVersion(newParentFolderID);

            return true;
        }

        public override bool Store(XInventoryFolder folder)
        {
            if (!base.Store(folder))
                return false;

            IncrementFolderVersion(folder.parentFolderID);

            return true;
        }
    }

    public class MSSQLInventoryHandler<T> : MSSQLGenericTableHandler<T> where T : class, new()
    {
        public MSSQLInventoryHandler(string c, string t, string m)
            : base(c, t, m)
        {
        }

        protected bool IncrementFolderVersion(UUID folderID)
        {
            return IncrementFolderVersion(folderID.ToString());
        }

        protected bool IncrementFolderVersion(string folderID)
        {
            //            m_log.DebugFormat("[MYSQL ITEM HANDLER]: Incrementing version on folder {0}", folderID);
            //            Util.PrintCallStack();

            string sql = "update inventoryfolders set version=version+1 where folderID = @folderID";

            using (SqlConnection conn = new SqlConnection(m_ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    conn.Open();

                    cmd.Parameters.AddWithValue("@folderID", folderID);

                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception)
                    {
                        return false;
                    }
                }
            }

            return true;
        }
    }
}


text:
package data

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"math"
	"strings"
	"time"

	"github.com/devork/grava/config"
	"github.com/devork/grava/geo"
	"github.com/devork/grava/vtile"

	"github.com/devork/geom"
	"github.com/devork/geom/ewkb"
	"github.com/jackc/pgx"

	log "github.com/sirupsen/logrus"
)

var (
	// TODO: make this configurable
	tileSize uint32 = 4096

	// vector version:
	mvtVersion = uint32(2)

	point      = vtile.Tile_POINT
	polygon    = vtile.Tile_POLYGON
	linestring = vtile.Tile_LINESTRING
)

// Common errors
var (
	ErrNoSuchSource = errors.New("no such source with given name")
)

// Db holds the Database connection
type Db struct {
	db      pgx.ConnPool
	sources map[string][]*Layer
}

// Sources provides a list of the source data this Db instance is managing.
func (d *Db) Sources() map[string][]*Layer {
	return d.sources
}

// Close will release all resources associated with the database
func (d *Db) Close() {
	d.db.Close()
}

// FetchTile queries the database for those features which intersect the given BBOX and the specified layer(s)
func (d *Db) FetchTile(box *geo.BBox, name string) (*vtile.Tile, error) {

	layers, ok := d.sources[name]

	if !ok {
		return nil, ErrNoSuchSource
	}

	// tile pixel width in ground units
	width := float64(tileSize) / (box.Maxx - box.Minx)
	height := float64(tileSize) / (box.Maxy - box.Miny)

	// next tile instance
	tile := vtile.Tile{}
	tile.Layers = []*vtile.Tile_Layer{}
	var vlayer *vtile.Tile_Layer
	var err error

	log.Debugf("Fetching tile data: bbox = %s, name = %s, width = %f, height = %f", box.GoString(), name, width, height)
	for _, layer := range layers {
		vlayer, err = d.readLayer(layer, box, width, height)

		if err != nil {
			return nil, err
		}
		tile.Layers = append(tile.Layers, vlayer)
	}

	return &tile, nil

}

func (d *Db) readLayer(lyr *Layer, box *geo.BBox, width, height float64) (*vtile.Tile_Layer, error) {
	bx := (box.Maxx - box.Minx) * 0.05
	by := (box.Maxy - box.Miny) * 0.05
	log.Debugf("Reading Layer: bbox = %s, name = %s, bx = %f, by = %f", box.GoString(), lyr.Name, bx, by)
	rows, err := d.db.Query(
		lyr.query,
		box.Minx-bx, box.Miny-by, box.Maxx+bx, box.Maxy+by, box.Srid,
	)

	if err != nil {
		return nil, err
	}

	defer rows.Close()

	desc := rows.FieldDescriptions()

	// key -> index
	skips := []int{}
	keys := make([]string, len(desc))
	for idx, key := range desc {

		if key.Name == "geom" || key.Name == "geometry" {
			skips = append(skips, idx)
		}
		keys[idx] = key.Name
	}

	// value -> key index
	values := map[interface{}]int{}
	vcount := 0

	var ins []interface{}

	var tileLayer = vtile.Tile_Layer{}
	tileLayer.Version = &mvtVersion
	tileLayer.Name = &lyr.Name
	tileLayer.Extent = &tileSize

	var features = make([]*vtile.Tile_Feature, 0)
	var r io.Reader

	for rows.Next() {
		ins, err = rows.Values()
		if err != nil {
			return nil, err
		}

		r = bytes.NewReader(ins[0].([]byte))
		g, err := ewkb.Decode(r)

		if err != nil {
			return nil, err
		}

		var feature *vtile.Tile_Feature

		switch g.(type) {
		case *geom.Point:
			feature = readPoint(g.(*geom.Point), box, width, height)
		case *geom.MultiPoint:
			feature = readMultiPoint(g.(*geom.MultiPoint), box, width, height)
		case *geom.Polygon:
			feature = readPolygon(g.(*geom.Polygon), box, width, height)
		case *geom.MultiPolygon:
			feature = readMultiPolygon(g.(*geom.MultiPolygon), box, width, height)
		case *geom.LineString:
			feature = readLinestring(g.(*geom.LineString), box, width, height)
		case *geom.MultiLineString:
			feature = readMultiLinestring(g.(*geom.MultiLineString), box, width, height)
		default:
			log.Warn("unsupported geometry type", "geometry", g.Type())
			continue
		}

	vloop:
		for idx, value := range ins {

			for _, skip := range skips {
				if idx == skip {
					continue vloop
				}
			}

			if value == nil {
				continue
			}

			if v, ok := value.([]string); ok {
				value = strings.Join(v, ",")
			}

			valuesIdx, ok := values[value]

			if !ok {
				values[value] = vcount
				valuesIdx = vcount
				vcount++
			}

			feature.Tags = append(feature.Tags, uint32(idx), uint32(valuesIdx))
		}

		features = append(features, feature)
	}

	if err := rows.Err(); err != nil {
		return nil, err
	}

	tileLayer.Features = features
	tileLayer.Keys = keys
	tileLayer.Values = make([]*vtile.Tile_Value, len(values))

	// create values
	for v, i := range values {
		switch v.(type) {
		case string:
			var str = v.(string)
			tileLayer.Values[i] = &vtile.Tile_Value{StringValue: &str}
		case float32:
			var f32 = v.(float32)
			tileLayer.Values[i] = &vtile.Tile_Value{FloatValue: &f32}
		case float64:
			var f64 = v.(float64)
			tileLayer.Values[i] = &vtile.Tile_Value{DoubleValue: &f64}
		case int:
			var i32 = int64(v.(int))
			tileLayer.Values[i] = &vtile.Tile_Value{IntValue: &i32}
		case int32:
			var i32 = int64(v.(int32))
			tileLayer.Values[i] = &vtile.Tile_Value{IntValue: &i32}
		case uint, uint32, uint64:
			var u64 = v.(uint64)
			tileLayer.Values[i] = &vtile.Tile_Value{UintValue: &u64}
		case int64:
			var i64 = v.(int64)
			tileLayer.Values[i] = &vtile.Tile_Value{SintValue: &i64}
		case bool:
			var b = v.(bool)
			tileLayer.Values[i] = &vtile.Tile_Value{BoolValue: &b}
		case time.Time:
			str := fmt.Sprint(v)
			tileLayer.Values[i] = &vtile.Tile_Value{StringValue: &str}
		default:
			str := fmt.Sprint(v)
			tileLayer.Values[i] = &vtile.Tile_Value{StringValue: &str}
			log.Warn("unexpected type", "value", v, "type", fmt.Sprintf("%T", v))
		}
	}

	return &tileLayer, nil
}

func readPoint(g *geom.Point, box *geo.BBox, width, height float64) *vtile.Tile_Feature {
	var feature = vtile.Tile_Feature{}
	feature.Type = &point

	// convert to coords
	gx := g.Coordinate[0]
	gy := g.Coordinate[1]

	x := int32(math.Floor((gx - box.Minx) * width))
	y := int32(math.Floor((gy - box.Miny) * height))

	cmd := uint32(1&0x7 | 1<<3)
	px := uint32(x<<1 ^ x>>31)
	py := uint32(y<<1 ^ y>>31)
	feature.Geometry = []uint32{cmd, px, py}

	return &feature
}

func readMultiPoint(mp *geom.MultiPoint, box *geo.BBox, width, height float64) *vtile.Tile_Feature {
	var feature = vtile.Tile_Feature{}
	feature.Type = &point

	for _, g := range mp.Points {

		// convert to coords
		gx := g.Coordinate[0]
		gy := g.Coordinate[1]

		x := int32(math.Floor((gx - box.Minx) * width))
		y := int32(math.Floor((gy - box.Miny) * height))

		cmd := uint32(1&0x7 | 1<<3)
		px := uint32(x<<1 ^ x>>31)
		py := uint32(y<<1 ^ y>>31)
		feature.Geometry = []uint32{cmd, px, py}
	}

	return &feature
}

func readLinestring(g *geom.LineString, box *geo.BBox, width, height float64) *vtile.Tile_Feature {
	var feature = vtile.Tile_Feature{}
	var gx float64
	var gy float64
	var dx int32
	var dy int32
	var cmds = []uint32{}
	var x int32
	var y int32
	var lx int32
	var ly int32

	// moveto
	gx = g.Coordinates[0][0]
	gy = g.Coordinates[0][1]

	x = int32(math.Floor((gx - box.Minx) * width))
	y = int32(math.Floor((gy - box.Miny) * height))

	dx = x - lx
	dy = y - ly

	cmd := uint32(1&0x7 | 1<<3)
	cmds = append(cmds, cmd, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))

	lx = x
	ly = y

	// lineto
	// (-1) as we have consumed the first point
	cmd = uint32(2&0x07 | (len(g.Coordinates)-1)<<3)
	cmds = append(cmds, cmd)

	for idx := 1; idx < len(g.Coordinates); idx++ {
		gx = g.Coordinates[idx][0]
		gy = g.Coordinates[idx][1]

		x = int32(math.Floor((gx - box.Minx) * width))
		y = int32(math.Floor((gy - box.Miny) * height))

		dx = x - lx
		dy = y - ly

		lx = x
		ly = y

		cmds = append(cmds, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))
	}

	feature.Geometry = cmds
	feature.Type = &linestring

	return &feature
}

func readMultiLinestring(mls *geom.MultiLineString, box *geo.BBox, width, height float64) *vtile.Tile_Feature {
	var feature = vtile.Tile_Feature{}
	var gx float64
	var gy float64
	var dx int32
	var dy int32
	var cmds = []uint32{}
	var x int32
	var y int32
	var lx int32
	var ly int32

	for _, g := range mls.LineStrings {

		// moveto
		gx = g.Coordinates[0][0]
		gy = g.Coordinates[0][1]

		x = int32(math.Floor((gx - box.Minx) * width))
		y = int32(math.Floor((gy - box.Miny) * height))

		dx = x - lx
		dy = y - ly

		cmd := uint32(1&0x7 | 1<<3)
		cmds = append(cmds, cmd, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))

		lx = x
		ly = y

		// lineto
		// (-1) as we have consumed the first point
		cmd = uint32(2&0x07 | (len(g.Coordinates)-1)<<3)
		cmds = append(cmds, cmd)

		for idx := 1; idx < len(g.Coordinates); idx++ {
			gx = g.Coordinates[idx][0]
			gy = g.Coordinates[idx][1]

			x = int32(math.Floor((gx - box.Minx) * width))
			y = int32(math.Floor((gy - box.Miny) * height))

			dx = x - lx
			dy = y - ly

			lx = x
			ly = y

			cmds = append(cmds, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))
		}
	}

	feature.Geometry = cmds
	feature.Type = &linestring

	return &feature
}

func readPolygon(g *geom.Polygon, box *geo.BBox, width, height float64) *vtile.Tile_Feature {
	var feature = vtile.Tile_Feature{}
	var gx float64
	var gy float64
	var dx int32
	var dy int32
	var cmds = []uint32{}
	var x int32
	var y int32
	var lx int32
	var ly int32

	for _, ring := range g.Rings {
		// moveto
		gx = ring.Coordinates[0][0]
		gy = ring.Coordinates[0][1]

		x = int32(math.Floor((gx - box.Minx) * width))
		y = int32(math.Floor((gy - box.Miny) * height))

		dx = x - lx
		dy = y - ly

		cmd := uint32(1&0x7 | 1<<3)
		cmds = append(cmds, cmd, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))

		//log.Printf("moveto: %d %d => %d %d", x, y, dx, dy)

		lx = x
		ly = y

		// lineto
		// (-2) as we have consumed the first point and ignoring the final point in the ring
		cmd = uint32(2&0x07 | (len(ring.Coordinates)-2)<<3)
		cmds = append(cmds, cmd)

		// ignore last coord as that is a close path
		for idx := 1; idx < len(ring.Coordinates)-1; idx++ {
			gx = ring.Coordinates[idx][0]
			gy = ring.Coordinates[idx][1]

			x = int32(math.Floor((gx - box.Minx) * width))
			y = int32(math.Floor((gy - box.Miny) * height))

			dx = x - lx
			dy = y - ly

			lx = x
			ly = y

			cmds = append(cmds, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))
		}

		//closepath
		cmd = uint32(7&0x07 | 1<<3)
		cmds = append(cmds, cmd)
	}

	feature.Geometry = cmds
	feature.Type = &polygon

	return &feature
}

func readMultiPolygon(g *geom.MultiPolygon, box *geo.BBox, width, height float64) *vtile.Tile_Feature {
	var feature = vtile.Tile_Feature{}
	var gx float64
	var gy float64
	var dx int32
	var dy int32
	var cmds = []uint32{}
	var x int32
	var y int32
	var lx int32
	var ly int32

	for _, poly := range g.Polygons {

		for _, ring := range poly.Rings {
			// moveto
			gx = ring.Coordinates[0][0]
			gy = ring.Coordinates[0][1]

			x = int32(math.Floor((gx - box.Minx) * width))
			y = int32(math.Floor((gy - box.Miny) * height))

			dx = x - lx
			dy = y - ly

			cmd := uint32(1&0x7 | 1<<3)
			cmds = append(cmds, cmd, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))

			//log.Printf("moveto: %d %d => %d %d", x, y, dx, dy)

			lx = x
			ly = y

			// lineto
			// (-2) as we have consumed the first point and ignoring the final point in the ring
			cmd = uint32(2&0x07 | (len(ring.Coordinates)-2)<<3)
			cmds = append(cmds, cmd)

			// ignore last coord as that is a close path
			for idx := 1; idx < len(ring.Coordinates)-1; idx++ {
				gx = ring.Coordinates[idx][0]
				gy = ring.Coordinates[idx][1]

				x = int32(math.Floor((gx - box.Minx) * width))
				y = int32(math.Floor((gy - box.Miny) * height))

				dx = x - lx
				dy = y - ly

				lx = x
				ly = y

				cmds = append(cmds, uint32(dx<<1^dx>>31), uint32(dy<<1^dy>>31))
			}

			//close path
			cmd = uint32(7&0x07 | 1<<3)
			cmds = append(cmds, cmd)
		}
	}

	feature.Geometry = cmds
	feature.Type = &polygon

	return &feature
}

// NewDb opens the database specified at the given path
func NewDb(cfg *config.Config) (*Db, error) {

	if cfg.Postgres == "" {
		return nil, errors.New("no postgres configuration specified")
	}

	var pcon pgx.ConnConfig
	var err error

	if strings.HasPrefix(cfg.Postgres, "postgres://") || strings.HasPrefix(cfg.Postgres, "postgresql://") {
		pcon, err = pgx.ParseURI(cfg.Postgres)

		if err != nil {
			return nil, fmt.Errorf("failed to parse connection uri: %s", err)
		}
	} else {
		pcon, err = pgx.ParseDSN(cfg.Postgres)

		if err != nil {
			return nil, fmt.Errorf("failed to parse connection DSN: %s", err)
		}
	}

	pcon.Logger = &logger{}
	pcon.LogLevel = pgx.LogLevelError

	db, err := pgx.NewConnPool(
		pgx.ConnPoolConfig{
			ConnConfig:     pcon,
			MaxConnections: 10,
		},
	)

	if err != nil {
		return nil, err
	}

	sources := map[string][]*Layer{}
	for _, source := range cfg.Sources {
		sources[source.Name] = make([]*Layer, len(source.Layers))

		for idx, lyr := range source.Layers {
			sources[source.Name][idx], err = read(db, source.Prefix, lyr, cfg.Schema)

			if err != nil {
				return nil, err
			}
		}
	}

	return &Db{*db, sources}, nil
}

// Queries the specified layer to obtain metadata about the table.
func read(db *pgx.ConnPool, prefix, layer, schema string) (*Layer, error) {
	rows, err := db.Query(`
		select
			column_name, udt_name
		from
			information_schema.columns
		where
			table_schema = $1 and table_name = $2
		order by
			ordinal_position asc
		`, schema, prefix+layer,
	)

	if err != nil {
		return nil, err
	}

	defer rows.Close()
	cols := []string{}
	attrs := []Attribute{}

	var col string
	var udt string
	var geom string
	var columns string

	count := 0
	for rows.Next() {
		err = rows.Scan(&col, &udt)

		if err != nil {
			return nil, err
		}

		count++

		// for the types supported, we stick to those that can be easily represented in JSON/MVT
		// could possibly add further type support which can be converted to strings? e.g. URL, IP etc.
		switch udt {
		case "int2", "int4", "int8":
			attrs = append(attrs, Attribute{col, "integer"})
			cols = append(cols, col)
		case "float4", "float8":
			attrs = append(attrs, Attribute{col, "float"})
			cols = append(cols, col)
		case "bool":
			attrs = append(attrs, Attribute{col, "boolean"})
			cols = append(cols, col)
		case "varchar", "text":
			attrs = append(attrs, Attribute{col, "string"})
			cols = append(cols, col)
		case "geometry":
			geom = col
		}
	}

	if count == 0 {
		return nil, fmt.Errorf("no data found for layer: name = %s", layer)
	}

	err = rows.Err()
	if err != nil {
		return nil, err
	}

	if geom == "" {
		return nil, fmt.Errorf("no geometry data found: layer = %s", layer)
	}

	if len(cols) > 0 {
		columns = ", " + strings.Join(cols, ",")
	}

	// get the geometry type
	var geomType string
	err = db.QueryRow(`
		SELECT
			type
		FROM
			geometry_columns
		WHERE f_table_schema = $1
		AND f_table_name = $2
		and f_geometry_column = $3;
	`, schema, prefix+layer, geom).Scan(&geomType)

	if err != nil {
		return nil, fmt.Errorf("cound not determine geometry data: layer = %s, err = %s", layer, err)
	}

	attrs = append(attrs, Attribute{geom, geomType})

	return &Layer{
		layer,
		attrs,
		fmt.Sprintf(
			`select
				ST_AsBinary(ST_Intersection(%s, st_makeenvelope($1, $2, $3, $4, $5))) as geom %s
			from
				%s.%s%s
			where
				st_intersects(geometry, st_makeenvelope($1, $2, $3, $4, $5))
			limit
				20000`,
			geom, columns, schema, prefix, layer,
		),
	}, nil
}

// Attribute details a field value in a layer.
type Attribute struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

// Layer represents a database table
type Layer struct {
	Name       string      `json:"name"`
	Attributes []Attribute `json:"attributes"`
	query      string
}


text:
'use strict';

var expect = require('expect.js')
  , proxyquire = require('proxyquire')
  ;

describe('SockJS', function() {
  describe('Constructor', function () {

    describe('WebSocket specification step #2', function () {
      var main = proxyquire('../../lib/main', { './location': {
        protocol: 'https'
      }});
      var sjs = proxyquire('../../lib/entry', { './main': main });

      it('should throw SecurityError for an insecure url from a secure page', function () {
        expect(function () {
          sjs('http://localhost');
        }).to.throwException(function (e) {
          expect(e).to.be.a(Error);
          expect(e.message).to.contain('SecurityError');
        });
      });

      it('should throw SyntaxError for an invalid url', function () {
        expect(function () {
          sjs('//localhost');
        }).to.throwException(function (e) {
          expect(e).to.be.a(SyntaxError);
        });
      });

      it('should throw SyntaxError for an empty url - #8', function () {
        expect(function () {
          sjs('');
        }).to.throwException(function (e) {
          expect(e).to.be.a(SyntaxError);
        });
      });
    });

  });
});


text:
"""
Lineup optimizations based on predicted scores for each player
"""

import itertools

import collections
import pandas as pd
import numpy as np
from sqlalchemy.orm.exc import NoResultFound

import db
import features as f
import model as m
from util import Timed, lineup_csv_filename
import fanduel as fd

pd.set_option('display.expand_frame_repr', False)

PlayerList = collections.namedtuple("PlayerList", "pg, sg, sf, pf, c")
Combination = collections.namedtuple("Combination", "players cost")
POSITIONS = ["PG_1", "PG_2", "SG_1", "SG_2", "SF_1", "SF_2", "PF_1", "PF_2", "C_1"]

class Player:
    def __init__(self, **kwargs):
        self.fanduel_id = kwargs["fanduel_id"]
        self.db = kwargs["db"]
        self.name = kwargs["name"]
        self.cost = kwargs["cost"]
        self.position = kwargs["position"]
        self.predicted_score = kwargs["predicted_score"]
        self.actual_score = kwargs["actual_score"]
        self.fppg = kwargs["fppg"]
        self.fp_std = kwargs["fp_std"]
        self.team = kwargs["team"]
        self.opponent = kwargs["opponent"]
        self.last_game_fp = kwargs["last_game_fp"]
        self.last_last_game_fp = kwargs["last_last_game_fp"]
        self.last_last_last_game_fp = kwargs["last_last_last_game_fp"]
        self.cv = self.fp_std / self.fppg

        import console as c
        self.skew = c.ALLP[c.ALLP.Name == self.name].Skew.iloc[0]
        self.kurtosis = c.ALLP[c.ALLP.Name == self.name].Kurtosis.iloc[0]

    def __repr__(self):
        return "<Player {} ({}, {}, {} :: p{}, a{})>".format(
            self.db.id,
            self.name,
            self.position,
            self.cost,
            self.predicted_score,
            self.actual_score,
        )

    @property
    def csv_str(self):
        return "{}:{}".format(self.fanduel_id, self.name)

class Lineup:
    def __init__(self, **kwargs):
        self.pg = kwargs.get("pg")
        self.sg = kwargs.get("sg")
        self.sf = kwargs.get("sf")
        self.pf = kwargs.get("pf")
        self.c = kwargs.get("c")

    @property
    def players(self):
        pgs = self.pg.players if self.pg else ()
        sgs = self.sg.players if self.sg else ()
        sfs = self.sf.players if self.sf else ()
        pfs = self.pf.players if self.pf else ()
        cs = self.c.players if self.c else ()
        return pgs + sgs + sfs + pfs + cs

    @property
    def cost(self):
        return sum([p.cost for p in self.players])

    @property
    def predicted_score(self):
        return sum([p.predicted_score for p in self.players])

    @property
    def actual_score(self):
        return sum([p.actual_score for p in self.players])

    @property
    def fp_std(self):
        return sum([p.fp_std for p in self.players])

    @property
    def cv(self):
        return sum([p.cv for p in self.players])

    @property
    def fppg(self):
        return sum([p.fppg for p in self.players])

def old_filter_players(game_day, db_model):
    f.load_gldb_if_empty(game_day)

    cv_cutoff = 0.4
    score_cutoff = 20.0

    import console as c

    all_players = c.allp(game_day)

    manual_drop = []
    injuries_drop = []
    cv_drop = list(all_players[all_players.CV > cv_cutoff].Name)

    fanduel_csv = fd.FanduelCSV \
        .preprocessed(game_day) \
        .drop_players_not_used_to_train_model() \
        .add_column_cv(c.allp(game_day)) \
        .drop_players(manual_drop, "Manual") \
        .drop_players(injuries_drop, "Injuries") \
        .drop_players(cv_drop, "High CV") \
        # .drop_players_with_low_fppg(26.0)

    players = []
    for (_, row) in fanduel_csv.df.iterrows():
        name = row.Name
        try:
            db_player = db.session.query(db.Player) \
                .filter(db.Player.name == name) \
                .one()
        except NoResultFound as e:
            print("ERROR: couldn't find {}, query went to DB".format(name))
            raise e

        try:
            gl = db.session.query(db.GameLog) \
                .join(db.GameLog.game) \
                .filter(db.Game.date == game_day) \
                .filter(db.GameLog.player_id == db_player.id) \
                .one()
            actual_score = gl.fanduel_score
        except NoResultFound:
            actual_score = 0.0

        gls = f.GLDB["players"][name]
        fps = [gl.fanduel_score for gl in gls if gl.zeroes != True]

        if gls[0].game.date == game_day:
            last_game_fp = gls[1].fanduel_score
            last_last_game_fp = gls[2].fanduel_score
            last_last_last_game_fp = gls[3].fanduel_score
        else:
            last_game_fp = gls[0].fanduel_score
            last_last_game_fp = gls[1].fanduel_score
            last_last_last_game_fp = gls[2].fanduel_score

            players.append(Player(
            fanduel_id=row.Id,
            db=db_player,
            name=name,
            cost=row.Salary,
            position=row.Position,
            predicted_score=m.predict(db_model, name, game_day, row.Game)[0],
            actual_score=actual_score,
            fppg=np.array(fps).mean(),
            fp_std=np.array(fps).std(),
            team=row.Team,
            opponent=row.Opponent,
            last_game_fp=last_game_fp,
            last_last_game_fp=last_last_game_fp,
            last_last_last_game_fp=last_last_last_game_fp,
        ))
    return [player for player in players if player.predicted_score > score_cutoff]

def players_by_position(ps):
    list = PlayerList(
        pg=[],
        sg=[],
        sf=[],
        pf=[],
        c=[])
    for p in ps:
        if p.position == "PG":
            list.pg.append(p)
        elif p.position == "SG":
            list.sg.append(p)
        elif p.position == "SF":
            list.sf.append(p)
        elif p.position == "PF":
            list.pf.append(p)
        elif p.position == "C":
            list.c.append(p)

    return list

def choose(ps, count):
    return [Combination(players=c, cost=sum([p.cost for p in c])) for c in itertools.combinations(ps, count)]

def all_lineups(players):
    player_list = players_by_position(players)
    pg_combos = choose(player_list.pg, 2)
    sg_combos = choose(player_list.sg, 2)
    sf_combos = choose(player_list.sf, 2)
    pf_combos = choose(player_list.pf, 2)
    c_combos = choose(player_list.c, 1)

    n_lineups = len(pg_combos) * len(sg_combos) * len(sg_combos) * len(sf_combos) * len(c_combos)
    print("Expected {} lineups to be created, {} players total".format(n_lineups, len(players)))

    lineups = []

    for pg in pg_combos:
        lu = Lineup(pg=pg)
        if lu.cost > 60000: continue
        for sg in sg_combos:
            lu.sg = sg
            if lu.cost > 60000: continue
            for sf in sf_combos:
                lu.sf = sf
                if lu.cost > 60000: continue
                for pf in pf_combos:
                    lu.pf = pf
                    if lu.cost > 60000: continue
                    for c in c_combos:
                        lu.c = c
                        if lu.cost > 60000: continue
                        lineups.append(lu)
                        lu = Lineup(pg=pg, sg=sg, sf=sf, pf=pf)

    print("{} lineups".format(len(lineups)))
    lineups = sorted(lineups, key=lambda l: l.predicted_score, reverse=True)

    return lineups

def old_filter_lineups(lineups):
    # initially didn't filter
    return lineups

def new_filter_lineups(lineups):
    highest_predicted_score = lineups[0].predicted_score
    score_cutoff = highest_predicted_score - 10 #arbitrary

    top_lineups = []
    for lineup in lineups:
        if lineup.predicted_score >= score_cutoff:
            top_lineups.append(lineup)
        else:
            break

    print("{} lineups within 10 points".format(len(top_lineups)))

    lineups = less_repetitive_lineups(top_lineups)
    return lineups

def less_repetitive_lineups(all_lineups):
    filtered_lineups = []

    for lineup in all_lineups:
        should_add = True
        for filtered_lineup in filtered_lineups:
            if lineups_are_too_similar(filtered_lineup, lineup):
                should_add = False
                break

        if should_add:
            filtered_lineups.append(lineup)

    print("{} lineups passed repetitive filter".format(len(filtered_lineups)))

    return filtered_lineups

def lineups_are_too_similar(lineup1, lineup2):
    money_cutoff = 45000 # If more than this value is the same, we'll consider them too similar

    similar_players = []
    for player in lineup1.players:
        if player in lineup2.players:
            similar_players.append(player)

    if cost_of_players(similar_players) > money_cutoff:
        return True

    return False

def cost_of_players(players):
    cost = 0
    for player in players:
        cost += player.cost

    return cost

def pinned_lineups(ps):
    pass

def money(lineup, payout_cutoffs):
    winnings = 0.0
    for award, cutoff in payout_cutoffs.items():
        if lineup.actual_score >= cutoff and award > winnings:
            winnings = award
    return winnings

# Idea here is you pass in game_day, the model, a method to filter players, and a method to filter lineups.
# Should make it easier to swap out model and filtering methods to see how our lineups would be different.
def create_lineups(game_day, db_model, filter_players, filter_lineups):
    with Timed("#create_lineups -- lineup.py", header=True):
        with Timed("Getting Players"):
            # players = get_players(FDCSV.df, game_day, db_model, player_cutoff)
            players = filter_players(game_day, db_model)
            print("Using {} players to create lineups".format(len(players)))

        with Timed("Collecting all line ups"):
            all_possible_lineups = all_lineups(players)
            lineups = filter_lineups(all_possible_lineups)
            if len(lineups) == 0:
                raise Exception("0 lineups, you probably need to raise the player cutoff from {}".format(player_cutoff))

        with Timed("Loading line ups into data frame"):
            # NOTE: Should probably not import a module like console, into this module
            import console as c
            df = c.ludf(lineups)

        # noinspection PyArgumentList
        draft = db.FanduelDraft(
            drafted_at=game_day,
            player_cutoff=20.0,
            model=db_model,
            ldf=df,
            lineups=lineups,
            players=players,
        )

    return draft