text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                xmlns:ads="http://schemas.android.com/apk/res-auto"
                android:background="@color/backgroundColor">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true">
    </com.google.android.gms.ads.AdView>

    <LinearLayout
        android:id="@+id/first_innings_button_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/adView"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">

        <Button
            android:id="@+id/first_innings_calc_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/button_design"
            android:clickable="true"
            android:text="@string/calculate"
            android:textColor="@color/white"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/first_innings_final_total_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/first_innings_button_container"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:orientation="vertical"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingEnd="10dp"
            android:paddingStart="15dp"
            android:weightSum="8">

            <TextView
                android:id="@+id/first_innings_team1_final_total_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="@string/team_1_final_total"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/black"/>

            <EditText
                android:id="@+id/first_innings_team1_final_total_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="6"
                android:digits="0123456789"
                android:gravity="center"
                android:imeOptions="actionNext"
                android:inputType="number"
                android:maxLength="4"
                android:nextFocusForward="@+id/first_innings_team2_overs_et"
                android:textAppearance="?android:attr/textAppearanceSmall"/>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingEnd="10dp"
            android:paddingStart="15dp"
            android:weightSum="8">

            <TextView
                android:id="@+id/first_innings_team2_overs_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="2"
                android:text="@string/team2overs_first_innings"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@color/black"/>

            <EditText
                android:id="@+id/first_innings_team2_overs_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="6"
                android:digits="0123456789."
                android:gravity="center"
                android:imeOptions="actionDone"
                android:inputType="numberDecimal"
                android:maxLength="4"
                android:textAppearance="?android:attr/textAppearanceSmall"/>
        </LinearLayout>
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/first_innings_final_total_container"
        android:fillViewport="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="20dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            tools:context=".Scenario2">

            <LinearLayout
                android:id="@+id/G50_spinner_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:orientation="vertical"
                android:paddingBottom="10dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/g50_expected_average_score"/>

                <Spinner
                    android:id="@+id/g50_spinner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/total_overs_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/G50_spinner_container"
                android:baselineAligned="false"
                android:orientation="horizontal"
                android:weightSum="8">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="2"
                    android:orientation="vertical"
                    android:paddingEnd="0dp"
                    android:paddingStart="10dp">

                    <TextView
                        android:id="@+id/number_overs_text_view"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:paddingBottom="15dp"
                        android:paddingTop="15dp"
                        android:text="@string/start_inning_1_overs"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:textColor="@color/black"/>
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="6"
                    android:orientation="vertical"
                    android:paddingEnd="10dp"
                    android:paddingStart="0dp">

                    <EditText
                        android:id="@+id/first_innings_number_overs_edit_text"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:digits="0123456789."
                        android:gravity="center"
                        android:hint="@string/overs"
                        android:imeOptions="actionNext"
                        android:inputType="numberDecimal"
                        android:maxLength="4"
                        android:nextFocusForward="@+id/first_innings_which_over_interruption_1_et"
                        android:paddingTop="15dp"
                        android:textAppearance="?android:attr/textAppearanceSmall"/>
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:id="@+id/first_innings_interruption_spinner_container"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/total_overs_container"
                android:layout_marginTop="20dp"
                android:orientation="vertical"
                android:paddingBottom="10dp"
                android:paddingLeft="10dp"
                android:paddingRight="10dp">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/number_of_interruptions"/>

                <Spinner
                    android:id="@+id/first_innings_interruptions_spinner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>

            </LinearLayout>

            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view_1_fi"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/first_innings_interruption_spinner_container"
                android:layout_gravity="center"
                android:layout_marginTop="5dp"
                card_view:cardBackgroundColor="@color/white"
                card_view:cardCornerRadius="10dp"
                card_view:cardElevation="4dp"
                card_view:cardUseCompatPadding="true">

                <LinearLayout
                    android:id="@+id/first_innings_interruption_1_container"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/first_innings_interruption_spinner_container"
                    android:orientation="vertical"
                    >

                    <TextView
                        android:id="@+id/first_innings_interruption_1_tv"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="5dp"
                        android:layout_marginTop="5dp"
                        android:paddingLeft="10dp"
                        android:paddingRight="10dp"
                        android:text="@string/interruption_1"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:textColor="@color/black"
                        android:textStyle="bold|italic"/>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:paddingEnd="10dp"
                        android:paddingStart="20dp">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_which_over_interruption_1_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/interruption_1_over"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_which_over_interruption_1_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789."
                                android:gravity="center"
                                android:hint="@string/overs"
                                android:inputType="numberDecimal"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_total_interruption_1_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>

                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_total_interruption_1_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/total_at_interruption"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_total_interruption_1_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789"
                                android:gravity="center"
                                android:hint="@string/total"
                                android:inputType="number"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_wickets_lost_interruption_1_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_wickets_lost_interruption_1_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/interruption_1_wickets"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@+id/first_innings_wickets_lost_interruption_1_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789"
                                android:gravity="center"
                                android:hint="@string/wickets"
                                android:inputType="number"
                                android:maxLength="2"
                                android:nextFocusForward="@+id/first_innings_overs_remaining_interruption_1_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_overs_remaining_interruption_1_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/interruption_1_remaining"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_overs_remaining_interruption_1_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789."
                                android:gravity="center"
                                android:hint="@string/overs"
                                android:inputType="numberDecimal"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_which_over_interruption_2_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>

            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view_2_fi"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/card_view_1_fi"
                android:layout_gravity="center"
                android:layout_marginTop="5dp"
                card_view:cardBackgroundColor="@color/white"
                card_view:cardCornerRadius="10dp"
                card_view:cardElevation="4dp"
                card_view:cardUseCompatPadding="true">

                <LinearLayout
                    android:id="@+id/first_innings_interruption_2_container"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/first_innings_interruption_1_container"
                    android:orientation="vertical"
                    >

                    <TextView
                        android:id="@+id/first_innings_interruption_2_tv"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="5dp"
                        android:layout_marginTop="5dp"
                        android:paddingLeft="10dp"
                        android:paddingRight="10dp"
                        android:text="@string/interruption_2"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:textColor="@color/black"
                        android:textStyle="bold|italic"/>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:paddingEnd="10dp"
                        android:paddingStart="20dp">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_which_over_interruption_2_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/interruption_1_over"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_which_over_interruption_2_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789."
                                android:gravity="center"
                                android:hint="@string/overs"
                                android:inputType="numberDecimal"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_total_interruption_2_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>

                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_total_interruption_2_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:paddingBottom="10dp"
                                android:text="@string/total_at_interruption"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@+id/first_innings_total_interruption_2_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789"
                                android:gravity="center"
                                android:hint="@string/total"
                                android:inputType="number"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_wickets_lost_interruption_2_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_wickets_lost_interruption_2_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:paddingBottom="10dp"
                                android:text="@string/interruption_1_wickets"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_wickets_lost_interruption_2_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789"
                                android:gravity="center"
                                android:hint="@string/wickets"
                                android:inputType="number"
                                android:maxLength="2"
                                android:nextFocusForward="@+id/first_innings_overs_remaining_interruption_2_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_overs_remaining_interruption_2_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/interruption_1_remaining"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_overs_remaining_interruption_2_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789."
                                android:gravity="center"
                                android:hint="@string/overs"
                                android:inputType="numberDecimal"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_which_over_interruption_3_et"
                                android:paddingBottom="15dp"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
            </android.support.v7.widget.CardView>

            <android.support.v7.widget.CardView
                xmlns:card_view="http://schemas.android.com/apk/res-auto"
                android:id="@+id/card_view_3_fi"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/card_view_2_fi"
                android:layout_gravity="center"
                android:layout_marginBottom="10dp"
                android:layout_marginTop="5dp"
                card_view:cardBackgroundColor="@color/white"
                card_view:cardCornerRadius="10dp"
                card_view:cardElevation="4dp"
                card_view:cardUseCompatPadding="true">

                <LinearLayout
                    android:id="@+id/first_innings_interruption_3_container"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/first_innings_interruption_2_container"
                    android:orientation="vertical"
                    >

                    <TextView
                        android:id="@+id/first_innings_interruption_3_tv"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="5dp"
                        android:layout_marginTop="5dp"
                        android:paddingLeft="10dp"
                        android:paddingRight="10dp"
                        android:text="@string/interruption_3"
                        android:textAppearance="?android:attr/textAppearanceSmall"
                        android:textColor="@color/black"
                        android:textStyle="bold|italic"/>

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:paddingEnd="10dp"
                        android:paddingStart="20dp">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_which_over_interruption_3_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/interruption_1_over"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_which_over_interruption_3_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789."
                                android:gravity="center"
                                android:hint="@string/overs"
                                android:inputType="numberDecimal"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_total_interruption_3_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_total_interruption_3_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:paddingBottom="10dp"
                                android:text="@string/total_at_interruption"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_total_interruption_3_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789"
                                android:gravity="center"
                                android:hint="@string/total"
                                android:inputType="number"
                                android:maxLength="4"
                                android:nextFocusForward="@+id/first_innings_wickets_lost_interruption_3_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_wickets_lost_interruption_3_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:paddingBottom="10dp"
                                android:text="@string/interruption_1_wickets"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_wickets_lost_interruption_3_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789"
                                android:gravity="center"
                                android:hint="@string/wickets"
                                android:inputType="number"
                                android:maxLength="2"
                                android:nextFocusForward="@+id/first_innings_overs_remaining_interruption_3_et"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:orientation="horizontal"
                            android:weightSum="8">

                            <TextView
                                android:id="@+id/first_innings_overs_remaining_interruption_3_tv"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="2"
                                android:text="@string/interruption_1_remaining"
                                android:textAppearance="?android:attr/textAppearanceSmall"
                                android:textColor="@color/black"/>

                            <EditText
                                android:id="@id/first_innings_overs_remaining_interruption_3_et"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_marginBottom="5dp"
                                android:layout_marginTop="5dp"
                                android:layout_weight="6"
                                android:digits="0123456789."
                                android:gravity="center"
                                android:hint="@string/overs"
                                android:inputType="numberDecimal"
                                android:maxLength="4"
                                android:paddingBottom="15dp"
                                android:textAppearance="?android:attr/textAppearanceSmall"/>
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
            </android.support.v7.widget.CardView>
        </RelativeLayout>
    </ScrollView>
</RelativeLayout>


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.acme</groupId>
		<artifactId>acme-parent</artifactId>
		<version>1.0.0-SNAPSHOT</version>
		<relativePath>../acme-parent</relativePath>
	</parent>

	<artifactId>acme-application</artifactId>

	<dependencies>
		<dependency>
			<groupId>org.acme</groupId>
			<artifactId>acme-backend-rest-api</artifactId>
		</dependency>
	</dependencies>

</project>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sylius\Bundle\CoreBundle\Form\Type;

use Sylius\Bundle\ProductBundle\Form\Type\VariantType as BaseVariantType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * Product variant type.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class ProductVariantType extends BaseVariantType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $builder
            ->add('sku', 'text', array(
                'label' => 'sylius.form.variant.sku',
            ))
            ->add('price', 'sylius_money', array(
                'label' => 'sylius.form.variant.price',
            ))
            ->add('availableOnDemand', 'checkbox', array(
                'label' => 'sylius.form.variant.available_on_demand',
            ))
            ->add('onHand', 'integer', array(
                'label' => 'sylius.form.variant.on_hand',
            ))
            ->add('images', 'collection', array(
                'type' => 'sylius_image',
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'label' => 'sylius.form.variant.images',
            ))
            ->add('width', 'number', array(
                'required' => false,
                'label' => 'sylius.form.variant.width',
            ))
            ->add('height', 'number', array(
                'required' => false,
                'label' => 'sylius.form.variant.height',
            ))
            ->add('depth', 'number', array(
                'required' => false,
                'label' => 'sylius.form.variant.depth',
            ))
            ->add('weight', 'number', array(
                'required' => false,
                'label' => 'sylius.form.variant.weight',
            ))
        ;
    }
}


text:
```
$ bower install m43nu/angular-auto-height
```

Include it in your angular-app:

```
angular.module('myApp', [
  // ...
  'm43nu.auto-height'
]).
config(function () {
  // ...
```

### npm:

```
$ npm install angular-auto-height
```

Include it in your angular-app:

```
angular.module('myApp', [
  // ...
  require('angular-auto-height')
]).
config(function () {
  // ...
```

### NuGet:

```
$ Install-Package AngularAutoHeight
```

Include it in your angular-app:

```
angular.module('myApp', [
  // ...
  'm43nu.auto-height'
]).
config(function () {
  // ...
```

Use it in your html:

```
<div class="parent">
    <div class="sibling">I need some space too</div>
    <div auto-height>
        I stretch to the available height,
        calculated from the height available from .parent and my siblings.
    </div>
</div>
```

## Community

### Got a question?

Just send me a message and I'll try to get to you as soon as possible.

### Found a bug?

Please submit a new issue.

### Fixed something?

1. Fork angular-auto-height
2. Create a topic branch - `git checkout -b my_branch`
3. Push to your branch - `git push origin my_branch`
4. Send me a pull-request for your topic branch
5. That's it!

### License

Released Under [MIT License](https://github.com/m43nu/angular-auto-height/blob/master/LICENSE).


text:
package org.tourgune.mdp.amazon.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.tourgune.mdp.amazon.bean.Region;
import org.tourgune.mdp.amazon.utils.Constants;
import org.tourgune.mdp.misc.db.QueriesConfig;
import org.tourgune.mdp.misc.db.TablesDB;

public class RegionDao {

	public List<Region> selectRegions(Connection con, String country, String nuts2, String nuts3, String locality) throws Exception {

		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Region> listRegions = new ArrayList<Region>();
		List<String> listParams = new ArrayList<String>();

		try {
			if (con != null) {
				String rowSql = QueriesConfig.getInstance().getProperty(Constants.SELECT_SCRAPPABLE_REGIONS);
				String fullSql = rowSql;

				if (country.equals("all"))
					fullSql = rowSql.replace(Constants.SELECT_SCRAPPABLE_COUNTRY_CONSTRAINT, "");
				else if (country.equals("null"))
					fullSql = rowSql.replace(Constants.SELECT_SCRAPPABLE_COUNTRY_CONSTRAINT, " AND dg.country IS NULL");
				else if (country.equals("notnull"))
					fullSql = rowSql.replace(Constants.SELECT_SCRAPPABLE_COUNTRY_CONSTRAINT, " AND dg.country IS NOT NULL");
				else {
					fullSql = rowSql.replace(Constants.SELECT_SCRAPPABLE_COUNTRY_CONSTRAINT, " AND dg.country = ?");
					listParams.add(country);
				}

				if (nuts2.equals("all"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS2_CONSTRAINT, "");
				else if (nuts2.equals("null"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS2_CONSTRAINT, " AND dg.NUTS2 IS NULL");
				else if (nuts2.equals("notnull"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS2_CONSTRAINT, " AND dg.NUTS2 IS NOT NULL");
				else {
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS2_CONSTRAINT, " AND dg.NUTS2 = ?");
					listParams.add(nuts2);
				}

				if (nuts3.equals("all"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS3_CONSTRAINT, "");
				else if (nuts3.equals("null"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS3_CONSTRAINT, " AND dg.NUTS3 IS NULL");
				else if (nuts3.equals("notnull"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS3_CONSTRAINT, " AND dg.NUTS3 IS NOT NULL");
				else {
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_NUTS3_CONSTRAINT, " AND dg.NUTS3 = ?");
					listParams.add(nuts3);
				}

				if (locality.equals("all"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_LOCALITY_CONSTRAINT, "");
				else if (locality.equals("null"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_LOCALITY_CONSTRAINT, " AND dg.locality IS NULL");
				else if (locality.equals("notnull"))
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_LOCALITY_CONSTRAINT, " AND dg.locality IS NOT NULL");
				else {
					fullSql = fullSql.replace(Constants.SELECT_SCRAPPABLE_LOCALITY_CONSTRAINT, " AND dg.locality = ?");
					listParams.add(locality);
				}

				ps = con.prepareStatement(fullSql);
				for (int i = 0; i < listParams.size(); i++)
					ps.setString(i + 1, listParams.get(i));
				rs = ps.executeQuery();
				while (rs.next()) {
					Region dbRegion = new Region();
					dbRegion.setIdGeography(rs.getInt(TablesDB.DG_ID_GEOGRAPHY));
					dbRegion.setIdGeographyChannel(rs.getInt(TablesDB.DG_ID_GEOGRAPHY_CHANNEL));
					listRegions.add(dbRegion);
				}
				rs.close();
				ps.close();

				return listRegions;
			} else {
				throw new Exception("Database connection NULL");
			}
		} catch (Exception e) {
			throw e;
		}
	}
}


text:
layout: post
title: Toolbox Workshop 2017
categories: special toolbox veranstaltungen
special-title: Toolbox Workshop 2017
special-subtitle: Python, Unix, Make, Git, LaTeX
special-action: Mehr Infos
image: images/toolbox.png
author: Max
---

Auch im Jahr 2017 veranstaltet PeP et al. wieder den Toolbox Workshop.

Dieser richtet sich vor allem an die kommenden Drittsemester
und behandelt die Grundlagen des wissenschaftlichen Arbeitens
und den Umgang mit den nötigen Werkzeugen.

Vom 25. bis zum 29. September werden die Themen
"Grundlagen der Programmiersprache Python", "Versuche auswerten und erste Datenanalyse mit NumPy und SciPy", "Grafiken erstellen mit matplotlib", "Die Unix-Kommandozeile", "Automatisieren mit Gnu Make" und "Versionskontrolle mit Git" besprochen.

Die zweite Woche vom 2. bis zum 6. Oktober steht ganz im Zeichen von LaTeX.

Weitere Informationen und Anmeldung [hier](http://toolbox.pep-dortmund.org).


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-302.js
 * @description Object.defineProperty - 'O' is an Arguments object, 'name' is an index named property of 'O' but not defined in [[ParameterMap]] of 'O', and 'desc' is accessor descriptor, test 'name' is defined in 'O' with all correct attribute values (10.6 [[DefineOwnProperty]] step 3)
 */

function testcase() {
        return (function () {
            delete arguments[0];
            function getFunc() {
                return 10;
            }
            function setFunc(value) {
                this.setVerifyHelpProp = value;
            }
            Object.defineProperty(arguments, "0", {
                get: getFunc,
                set: setFunc,
                enumerable: false,
                configurable: false
            });
            return accessorPropertyAttributesAreCorrect(arguments, "0", getFunc, setFunc, "setVerifyHelpProp", false, false);
        }(0, 1, 2));
    }
runTestCase(testcase);


text:
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.views.generic import TemplateView

urlpatterns = [
    url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
    url(r'^photos/', include('robocoach1.photos.urls', namespace='photos')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


text:
from os import environ
from time import time, sleep

import requests
import requests.auth
from requests_oauthlib import OAuth1

from .exceptions import *

class API:
    def __init__(self, session=None):
        self.log_function = print
        self.retry_rate = 5
        self.num_retries = 5
        self.failed_last = False
        self.force_stop = False
        self.ignore_errors = False
        self.common_errors = (requests.exceptions.ConnectionError,
                              requests.exceptions.Timeout,
                              requests.exceptions.HTTPError)
        self.session = session

    def __str__(self):
        return pformat(vars(self))

    def log_error(self, e):
        """
        Print errors. Stop travis-ci from leaking api keys

        :param e: The error
        :return: None
        """

        if not environ.get('CI'):
            self.log_function(e)
            if hasattr(e, 'response') and hasattr(e.response, 'text'):
                self.log_function(e.response.text)

    def _sleep(self, seconds):
        """
        Sleep between requests, but don't force asynchronous code to wait

        :param seconds: The number of seconds to sleep
        :return: None
        """
        for _ in range(int(seconds)):
            if not self.force_stop:
                sleep(1)

    @staticmethod
    def merge_params(parameters, new):
        if new:
            parameters = {**parameters, **new}
        return parameters

    def get(self, *args, **kwargs):

        """
        An interface for get requests that handles errors more gracefully to
        prevent data loss
        """

        try:
            req_func = self.session.get if self.session else requests.get
            req = req_func(*args, **kwargs)
            req.raise_for_status()
            self.failed_last = False
            return req

        except requests.exceptions.RequestException as e:
            self.log_error(e)
            for i in range(1, self.num_retries):
                sleep_time = self.retry_rate * i
                self.log_function("Retrying in %s seconds" % sleep_time)
                self._sleep(sleep_time)
                try:
                    req = requests.get(*args, **kwargs)
                    req.raise_for_status()
                    self.log_function("New request successful")
                    return req
                except requests.exceptions.RequestException:
                    self.log_function("New request failed")

            # Allows for the api to ignore one potentially bad request
            if not self.failed_last:
                self.failed_last = True
                raise ApiError(e)
            else:
                raise FatalApiError(e)

class Youtube(API):
    def __init__(self, api_key):
        super().__init__()

        self.key = api_key
        self.url = "https://www.googleapis.com/youtube/v3"
        self.request_rate = 5
        self.last_request = time()

    def api_call(self, edge, parameters, return_results=True):
        req = self.get("%s/%s" % (self.url, edge), params=parameters)

        time_diff = time() - self.last_request
        if time_diff < self.request_rate:
            sleep(self.request_rate - time_diff)

        self.last_request = time()

        if not req:
            return None

        if return_results:
            return req.json()

    def search(self, query, count=50, order="relevance", page='',
               result_type="video", channel_id=None, channel_type=None,
               event_type=None, location=None, location_radius=None,
               published_after=None, published_before=None, region_code=None,
               relevance_language=None, safe_search=None, topic_id=None,
               video_caption=None, video_category_id=None,
               video_definition=None, video_dimension=None,
               video_duration=None, video_embeddable=None,
               video_license=None, video_syndicated=None, video_type=None,
               **params):

        count = 50 if count > 50 else count
        parameters = {"part": "snippet",
                      "q": query,
                      "maxResults": count,
                      "order": order,
                      "type": result_type,
                      "channelId": channel_id,
                      "channelType": channel_type,
                      "eventType": event_type,
                      "location": location,
                      "locationRadius": location_radius,
                      "publishedAfter": published_after,
                      "publishedBefore": published_before,
                      "regionCode": region_code,
                      "relevanceLanguage": relevance_language,
                      "safeSearch": safe_search,
                      "topicId": topic_id,
                      "videoCaption": video_caption,
                      "videoCategoryId": video_category_id,
                      "videoDefinition": video_definition,
                      "videoDimension": video_dimension,
                      "videoDuration": video_duration,
                      "videoEmbeddable": video_embeddable,
                      "videoLicense": video_license,
                      "videoSyndicated": video_syndicated,
                      "videoType": video_type,
                      "pageToken": page,
                      "key": self.key}
        parameters = self.merge_params(parameters, params)

        return self.api_call('search', parameters)

    def guess_channel_id(self, username, count=5):
        parameters = {
            "forUsername": username,
            "part": "id",
            "maxResults": count,
            "key": self.key
        }
        return self.api_call('channels', parameters)['items']

    def channel(self, channel_id, count=50, order="date", page='',
                result_type="video", **params):

        count = 50 if count > 50 else count
        parameters = {"part": "snippet,id",
                      "channelId": channel_id,
                      "maxResults": count,
                      "order": order,
                      "type": result_type,
                      "pageToken": page,
                      "key": self.key}
        parameters = self.merge_params(parameters, params)

        return self.api_call('search', parameters)

    def videos(self, video_id, count=50, page='', **params):
        parts = ["contentDetails", "id", "liveStreamingDetails",
                 "localizations", "player", "recordingDetails", "snippet",
                 "statistics", "status", "topicDetails"]
        parameters = {
            "part": ",".join(parts),
            "id": video_id,
            "maxResults": count,
            "pageToken": page,
            "key": self.key
        }
        parameters = self.merge_params(parameters, params)

        return self.api_call('videos', parameters)

    def video_comments(self, video_id, count=100, order="time", page='',
                       search_terms=None, text_format="html", **params):

        count = 50 if count > 50 else count
        if type(search_terms) is list:
            search_terms = ",".join(search_terms)

        parts = ["id", "replies", "snippet"]
        parameters = {
            "part": ",".join(parts),
            "videoId": video_id,
            "maxResults": count,
            "order": order,
            "searchTerms": search_terms,
            "textFormat": text_format,
            "pageToken": page,
            "key": self.key
        }
        parameters = self.merge_params(parameters, params)

        return self.api_call('commentThreads', parameters)

    def comments_list(self, parent_id, max_results=100, page='',
                      text_format='html', **params):
        parts = ["id", "snippet"]
        parameters = {
            "part": ",".join(parts),
            "parentId": parent_id,
            "maxResults": max_results,
            "textFormat": text_format,
            "pageToken": page,
            "key": self.key
        }
        parameters = self.merge_params(parameters, params)

        return self.api_call('comments', parameters)

    def channel_comments(self, channel_id, count=100, order="time", page='',
                         search_term="", text_format="html", **params):

        count = 100 if count > 100 else count
        parts = ["id", "replies", "snippet"]
        parameters = {
            "part": ",".join(parts),
            "allThreadsRelatedToChannelId": channel_id,
            "maxResults": count,
            "order": order,
            "search_term": search_term,
            "text_format": text_format,
            "pageToken": page,
            "key": self.key
        }
        parameters = self.merge_params(parameters, params)

        return self.api_call('commentThreads', parameters)

class Reddit(API):
    def __init__(self, application_id, application_secret):
        super().__init__()
        self.retry_rate /= 2  # Because it will try reauthorise if failure

        self.application_id = application_id
        self.application_secret = application_secret

        self.url = "https://oauth.reddit.com"
        self.request_rate = 5
        self.user_agent = "SocialReaper"
        self.headers = {}
        self.token_expiry = 0
        self.requires_reauth = True

        self.auth()
        self.last_request = time()

    def auth(self):
        client_auth = requests.auth.HTTPBasicAuth('%s' % self.application_id,
                                                  '%s' % self.application_secret)
        post_data = {"grant_type": "client_credentials"}
        headers = {"User-Agent": self.user_agent}

        try:
            response = requests.post(
                "https://www.reddit.com/api/v1/access_token",
                auth=client_auth, data=post_data,
                headers=headers)
        except requests.exceptions.RequestException as e:
            raise ApiError(e)

        rj = response.json()

        self.headers = {"Authorization": "bearer %s" % rj.get('access_token'),
                        "User-Agent": self.user_agent}
        self.token_expiry = time() + rj.get('expires_in', 0)

    def api_call(self, edge, parameters, return_results=True):

        if time() > self.token_expiry + 30:
            self.auth()

        time_diff = time() - self.last_request
        if time_diff < self.request_rate:
            sleep(self.request_rate - time_diff)

        self.last_request = time()

        try:
            req = self.get("%s/%s" % (self.url, edge), params=parameters,
                           headers=self.headers)
        except (ApiError, FatalApiError):
            try:
                self.auth()
            except ApiError:
                pass
            req = self.get("%s/%s" % (self.url, edge), params=parameters,
                           headers=self.headers)

        if return_results:
            return req.json()

    def search(self, query, count=100, order="new", page='',
               result_type="link", time_period="all", **params):

        parameters = {"show": "all",
                      "q": query,
                      "limit": count,
                      "sort": order,
                      "type": result_type,
                      "t": time_period,
                      "after": page}
        parameters = self.merge_params(parameters, params)

        return self.api_call('search.json', parameters)

    def subreddit(self, subreddit, count=100, category="new", page='',
                  time_period='all', **params):

        parameters = {"limit": count,
                      "t": time_period,
                      "after": page}
        parameters = self.merge_params(parameters, params)

        return self.api_call('r/%s/%s.json' % (subreddit, category), parameters)

    def user(self, user, count=100, order="new", page='',
             result_type="overview", time_period='all', **params):

        parameters = {"show": "all",
                      "limit": count,
                      "sort": order,
                      "type": result_type,
                      "t": time_period,
                      "after": page}
        parameters = self.merge_params(parameters, params)

        return self.api_call('user/%s/%s.json' % (user, result_type),
                             parameters)

    def thread_comments(self, thread, subreddit, order="top", sub_thread=None,
                        **params):

        parameters = {"depth": 50,
                      "showmore": True,
                      "sort": order}
        parameters = self.merge_params(parameters, params)

        path = None
        if sub_thread:
            path = 'r/%s/comments/%s/_/%s.json' % (
            subreddit, thread, sub_thread)
        else:
            path = 'r/%s/comments/%s.json' % (subreddit, thread)

        return self.api_call(path, parameters)

    def more_children(self, children, link_id, sort="new",
                      **params):
        parameters = {"api_type": "json",
                      "children": ",".join(children),
                      "link_id": link_id,
                      "sort": sort,
                      "limit_children": False
                      }
        parameters = self.merge_params(parameters, params)

        return self.api_call('api/morechildren', parameters)

class Facebook(API):
    def __init__(self, api_key):
        super().__init__()

        self.key = api_key
        self.url = "https://graph.facebook.com/v"
        self.version = "2.9"
        self.request_rate = 1
        self.last_request = time()

    def api_call(self, edge, parameters, return_results=True):
        req = self.get("%s%s/%s" % (self.url, self.version, edge),
                       params=parameters)

        time_diff = time() - self.last_request
        if time_diff < self.request_rate:
            sleep(self.request_rate - time_diff)

        self.last_request = time()

        if return_results:
            return req.json()

    def node_edge(self, node, edge, fields=None, params=None):

        """

        :param node:
        :param edge:
        :param fields:
        :param params:
        :return:
        """
        if fields:
            fields = ",".join(fields)

        parameters = {"fields": fields,
                      "access_token": self.key}
        parameters = self.merge_params(parameters, params)

        return self.api_call('%s/%s' % (node, edge), parameters)

    def post(self, post_id, fields=None, **params):

        """

        :param post_id:
        :param fields:
        :param params:
        :return:
        """
        if fields:
            fields = ",".join(fields)

        parameters = {"fields": fields,
                      "access_token": self.key}
        parameters = self.merge_params(parameters, params)

        return self.api_call('%s' % post_id, parameters)

    def page_posts(self, page_id, after='', post_type="posts",
                   include_hidden=False, fields=None, **params):

        """

        :param page_id:
        :param after:
        :param post_type: Can be 'posts', 'feed', 'tagged', 'promotable_posts'
        :param include_hidden:
        :param fields:
        :param params:
        :return:
        """
        if fields:
            fields = ",".join(fields)

        parameters = {"access_token": self.key,
                      "after": after,
                      "fields": fields,
                      "include_hidden": include_hidden}
        parameters = self.merge_params(parameters, params)

        return self.api_call('%s/%s' % (page_id, post_type), parameters)

    def post_comments(self, post_id, after='', order="chronological",
                      filter="stream", fields=None, **params):

        """

        :param post_id:
        :param after:
        :param order: Can be 'ranked', 'chronological', 'reverse_chronological'
        :param filter: Can be 'stream', 'toplevel'
        :param fields: Can be 'id', 'application', 'attachment', 'can_comment',
        'can_remove', 'can_hide', 'can_like', 'can_reply_privately', 'comments',
        'comment_count', 'created_time', 'from', 'likes', 'like_count',
        'live_broadcast_timestamp', 'message', 'message_tags', 'object',
        'parent', 'private_reply_conversation', 'user_likes'
        :param params:
        :return:
        """
        if fields:
            fields = ",".join(fields)

        parameters = {"access_token": self.key,
                      "after": after,
                      "order": order,
                      "fields": fields,
                      "filter": filter}
        parameters = self.merge_params(parameters, params)

        return self.api_call('%s/comments' % post_id, parameters)

class Tumblr(API):
    def __init__(self, api_key):
        super().__init__()

        self.api_key = api_key

        self.url = "https://api.tumblr.com/v2"
        self.request_rate = 2
        self.last_request = time()

    def api_call(self, edge, parameters, return_results=True):
        parameters['api_key'] = self.api_key
        req = self.get("%s/%s" % (self.url, edge), params=parameters)

        time_diff = time() - self.last_request
        if time_diff < self.request_rate:
            sleep(self.request_rate - time_diff)

        self.last_request = time()

        if return_results:
            return req.json()

    def blog(self, blog, limit=20, offset=0, **params):
        parameters = {
            "limit": limit,
            "offset": offset
        }
        parameters = self.merge_params(parameters, params)

        return self.api_call("blog/%s/info" % blog, parameters)

    def blog_posts(self, blog, type="text", limit=20, offset=0, filter="text",
                   notes_info=True, reblog_info=True,
                   **params):
        parameters = {
            "limit": limit,
            "offset": offset,
            "filter": filter,
            "notes_info": notes_info,
            "reblog_info": reblog_info
        }
        parameters = self.merge_params(parameters, params)

        return self.api_call("blog/%s/posts/%s" % (blog, type), parameters)

    def tag(self, tag, limit=20, before=None, filter=None, **params):
        parameters = {
            "tag": tag,
            "limit": limit,
            "before": before,
            "filter": filter
        }
        parameters = self.merge_params(parameters, params)

        return self.api_call("tagged", parameters)

class Twitter(API):
    def __init__(self, api_key, api_secret, access_token, access_token_secret):
        super().__init__()

        self.app_key = api_key
        self.app_secret = api_secret
        self.oauth_token = access_token
        self.oauth_token_secret = access_token_secret

        self.url = "https://api.twitter.com/1.1"
        self.request_rate = 5

        self.auth = OAuth1(self.app_key, self.app_secret, self.oauth_token,
                           self.oauth_token_secret)
        self.last_request = time()

    def api_call(self, edge, parameters, return_results=True):
        req = self.get("%s/%s" % (self.url, edge), params=parameters,
                       auth=self.auth)

        time_diff = time() - self.last_request
        if time_diff < self.request_rate:
            sleep(self.request_rate - time_diff)

        self.last_request = time()

        if return_results:
            return req.json()

    def search(self, query, count=100, max_id='',
               result_type="mixed", include_entities=True,
               tweet_mode='extended', **params):

        count = 100 if count < 100 else count
        parameters = {"q": query,
                      "count": count,
                      "max_id": max_id,
                      "result_type": result_type,
                      "include_entities": include_entities,
                      "tweet_mode": tweet_mode}
        parameters = self.merge_params(parameters, params)

        return self.api_call("search/tweets.json", parameters)

    def user(self, username, count=200, max_id=None, exclude_replies=False,
             include_retweets=False, tweet_mode='extended', **params):
        parameters = {"screen_name": username,
                      "count": count,
                      "max_id": max_id,
                      "exclude_replies": exclude_replies,
                      "include_rts": include_retweets,
                      "tweet_mode": tweet_mode}
        parameters = self.merge_params(parameters, params)

        return self.api_call("statuses/user_timeline.json", parameters)

class Pinterest(API):
    def __init__(self, access_token):
        super().__init__()

        self.access_token = access_token
        self.url = "https://api.pinterest.com/v1"
        self.request_rate = 10

        self.last_request = time()

    def api_call(self, edge, parameters, return_results=True):
        parameters['access_token'] = self.access_token
        req = self.get(f"{self.url}/{edge}", params=parameters)

        time_diff = time() - self.last_request
        if time_diff < self.request_rate:
            sleep(self.request_rate - time_diff)

        self.last_request = time()

        if return_results:
            return req.json()

    def read_edge(self, edge, fields, **params):
        parameters = {"fields": ",".join(fields) if fields else None}
        parameters = self.merge_params(parameters, params)

        return self.api_call(edge, parameters)

class Twitch(API):
    def __init__(self, client_id):
        super().__init__()

        self.client_id = client_id
        self.url = "https://api.twitch.tv/helix"
        self.request_rate = 5

        self.last_request = time()

    def api_call(self, edge, parameters, return_results=True):
        headers = {
            'Client-ID': self.client_id
        }
        req = self.get(f"{self.url}/{edge}", params=parameters,
                       headers=headers)

        time_diff = time() - self.last_request
        if time_diff < self.request_rate:
            sleep(self.request_rate - time_diff)

        self.last_request = time()

        if return_results:
            return req.json()

    def videos(self, id=None, user_id=None, game_id=None, after=None,
               before=None, first=100, period='all', sort='time',
               type='all', **kwargs):

        parameters = {
            'id': id,
            'user_id': user_id,
            'game_id': game_id,
            'after': after,
            'before': before,
            'first': first,
            'period': period,
            'sort': sort,
            'type': type
        }

        parameters = self.merge_params(parameters, kwargs)
        return self.api_call('videos', parameters=parameters)

    def user_id(self, username):
        return self.api_call('users', parameters={'login': username})


text:
angular.module('marbleCoreApp').constant('AuthLevels', {
    public: 'public',
    anon: 'anon',
    user: 'user',
    admin: 'admin',
  })
  .controller('LoginCtrl', ['$scope', '$rootScope', '$state', 'Auth', function($scope, $rootScope, $state, Auth) {
    $scope.credentials = {
      username: '',
      password: '',
    };

    var myself = this;
    this.alerts = [];
    this.addAlert = function(msg, type) {
      console.log(msg);
      myself.alerts.push({
        type: type,
        msg: msg
      });
    };
    this.closeAlert = function(index) {
      myself.alerts.splice(index, 1);
    };

    $scope.isAuthenticated = Auth.isAuthenticated();

    $scope.reason = $state.params.reason;

    this.currentUser = Auth.user;
    $scope.logout = function() {
      Auth.logout();
      this.currentUser = {};
      $state.go('dashboard.home', {}, { reload: true });
    }

    $scope.auth = function(credentials) {
      Auth.auth(credentials).then(function(user) {

        if (Auth.isAuthenticated()) {
          if ($rootScope.returnToState) {
            $state.go($rootScope.returnToState.name, $rootScope.returnToStateParams);
          } else {
            $state.go('dashboard.home');
          }
        } else {
          console.log("User is not authenticated.");
        }
      }, function(res) {
        var message = "There was a problem while logging in. The error message is <" + res.statusText + ">";
        if (res.status == "401") {
          message = "The user credentials you provided are not valid, please check your data and try again.";
        }
        myself.addAlert(message, "danger");
      });
      $scope.isAuthenticated = Auth.isAuthenticated();
    };

  }])
  .factory('Session', function() {
    var user = {};
    return {
      user: user,
      setUser: function(u) {
        for (var i in u.authorities) {
          var authority = u.authorities[i].authority;
          if (authority == "ROLE_SERVICE") {
            u.isService = true;
            u.profile = "Service";
            break;
          } else if (authority == "ROLE_ADMIN") {
            u.isAdmin = true;
            u.profile = "Admin";
            break;
          } else if (authority == "ROLE_REGULAR") {
            u.isRegular = true;
            u.profile = "Regular";
            break;
          } else if (authority == "ROLE_VIEWER") {
            u.isViewer = true;
            u.profile = "Viewer";
            break;
          }
        }
        return angular.extend(user, u);
      },
      userSet: function() {
        return (Object.getOwnPropertyNames(user).length > 0);
      },
      clear: function() {
        if (user) {
          for (var k in user) {
            if (user.hasOwnProperty(k)) {
              delete user[k];
            }
          }
        } else {
          user = {};
        }
        return user;
      },
    };
  })
  .factory('Auth', ['$http', '$rootScope', '$state', '$q', 'Session', 'AuthLevels', function($http, $rootScope, $state, $q, Session, AuthLevels) {
    var Auth = {
      auth: function(credentials) {
        // Login operation
        var url = "user";
        var headers = credentials ? {
          authorization: "Basic " + btoa(credentials.username + ":" + credentials.password)
        } : {};
        return $http
          .get('/api/' + url, {
            headers: headers
          })
          .then(function(res) {
              return Session.setUser(res.data);
            }
            /*,
                      function() { return Session.clear(); }*/
          );
      },
      ping: function() {
        return $http
          .get('/api/user')
          .then(function(res) {
              return Session.user = (res.data);
            },
            function() {
              return Session.clear();
            });
      },
      logout: function() {
        return $http
          .post('/logout')
          .then(function(res) {
              return Session.clear();
            },
            function() {
              return Session.clear();
            });

      },

      identity: function(force) {
        var deferred = $q.defer();

        if (Session.userSet() && !force) {
          deferred.resolve(Session.user);
        } else {
          Auth.ping().then(
            function(data) {
              deferred.resolve(Session.user);
            },
            function() {
              deferred.resolve(Session.user);
            });
        }

        return deferred.promise;
      },
      authorize: function(toState, toStateParams) {
        return Auth.identity()
          .then(function() {
            if (toState && toState.data &&
              !Auth.isAuthorized(toState.data.access)) {
              if (Auth.isAuthenticated()) {
                $state.go('403'); // user is signed in but not authorized for desired state
              } else {
                // user is not authenticated. stow the state they wanted before you
                // send them to the signin state, so you can return them when you're done
                $rootScope.returnToState = toState;
                $rootScope.returnToStateParams = toStateParams;

                // now, send them to the signin state so they can log in
                $state.go('login');
              }
            }
          });
      },

      isInitialized: function() {
        return Session.userSet();
      },
      isAuthenticated: function() {
        return Session.userSet() && Session.user.name !== undefined;
      },

      isAuthorized: function(authLevel) {
        if (!Session.userSet()) {
          return false;
        }
        if (authLevel === null || authLevel === undefined) {
          return true;
        } else if (authLevel == AuthLevels.public) {
          return true;
        } else if (authLevel == AuthLevels.anon) {
          return (Session.user.id == 0);
        } else if (authLevel == AuthLevels.user) {
          return (Session.user.id > 0);
        } else if (authLevel == AuthLevels.admin) {
          return (Session.user.id > 0 && Session.user.admin);
        } else {
          return false;
        }
      },

      user: Session.user,

    };
    return Auth;
  }])
  .config(['$stateProvider', function($stateProvider) {
    // Need access to both state representations. Decorate any attribute to access private state object.
    $stateProvider.decorator('path', function(state, parentFn) {
      // Add a default empty resolve
      if (state.self.resolve === undefined) {
        state.self.resolve = {};
        state.resolve = state.self.resolve;
      }
      //Add an auth resolve
      state.resolve.authorize = function(Auth) {
        return Auth.authorize(state, {})
      }
      return parentFn(state);
    });
  }])
  .factory('getInterceptor', ['$q',  '$rootScope', '$location', '$state', '$stateParams', 'Session',
    function($q, $rootScope, $location, $state, $stateParams, Session) {
    // I'd like to use $state instead of $location, but that creates
    // a circular dependency.
    return {
      'responseError': function(response) {
        if (response.status === 401 || response.status === 419) {
          // probably timed out
          if ($state.current.name != "login") {
            $rootScope.returnToState = $state.current;
            var oldParams = {};
            angular.extend(oldParams, $stateParams);
            $rootScope.returnToStateParams = oldParams;
          }
          Session.clear();

          $location.path('/dashboard/login');

          // Another method using Include returnUrl (not implemented as we are using returnToState)
          // http://stackoverflow.com/questions/30125293/angularjs-location-path-not-working-for-returnurl
        }
        if (response.status === 403) {
          $location.path('/dashboard/login');
        }

        return $q.reject(response);
      }
    };
  }])
  .directive('access', ['ngIfDirective', 'Auth', function(ngIfDirective, Auth) {
    var ngIf = ngIfDirective[0];
    return {
      transclude: ngIf.transclude,
      priority: ngIf.priority,
      terminal: ngIf.terminal,
      restrict: ngIf.restrict,
      link: function($scope, $element, $attr) {
        $attr.ngIf = function() {
          return Auth.isAuthorized($attr['access']);
        };
        ngIf.link.apply(ngIf, arguments);
      }
    };
  }])
  .run(['Auth', function(Auth) {
    Auth.auth();
  }]);


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

<title>JField (Java Class Library API)</title>
<meta name="date" content="2015-04-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element

org.jsimpledb.annotation

Annotation Type JField

@Retention(value=RUNTIME)
 @Target(value=METHOD)
 @Documented
public @interface JField

Java annotation for creating simple fields, including reference fields that refer to other Java model object types.

 This annotation is used in two scenarios:

To describe a simple database field by annotating the corresponding abstract Java bean property `getter' method

To describe the sub-field(s) of a complex database field (i.e., set, list, or map),
      that is, the collection element or map key and value

 Note that this annotation can be applied to superclass and interface methods to have the corresponding
 field defined in all sub-types.

 This annotation is not required when auto-generation of properties is enabled; see JSimpleClass.autogenFields().

Non-Reference Fields

 If the field is not a reference field, the property type is inferred from the type of the annotated method or,
 in the case of complex sub-fields, the generic type of the collection class. The name of the property type
 must be registered in the FieldTypeRegistry (perhaps via @JFieldType),
 and the corresponding FieldType is then used to encode/decode field values.
 The type name may also be specified explicitly by name().

 Simple fields may be indexed(); see org.jsimpledb.index for information on querying indexes.

Reference Fields

 If the type of the field is (assignable to) a @JsimpleClass-annotated Java model object type,
 then the field is a reference field.

 Reference fields have configurable behavior when the containing object or the referred-to object is deleted;
 see onDelete() and cascadeDelete().

 Reference fields are always indexed; the value of indexed() is ignored.

Uniqueness Constraints

 Fields that are not complex sub-fields may be marked as unique() to impose a uniqueness constraint on the value.
 Fields with uniqueness constraints must be indexed. Uniqueness constraints are handled at the JSimpleDB layer and function as
 an implicit validation constraint. In other words, the constraint is verified when the validation queue is processed
 and is affected by the transaction's configured ValidationMode.

 Optionally, specific field values may be marked as excluded from the uniqueness constraint via uniqueExclude().
 If so, the specified values may appear in multiple objects without violating the constraint. Because null values
 are not allowed in annotations, uniqueExcludeNull() is provided to exclude the null value.

 In ValidationMode.AUTOMATIC, any upgraded JObjects are automatically
 added to the validation queue, so a uniqueness constraint added in a new schema version will be automatically verified
 when any object is upgraded.
 However, simpley adding, removing, or changing uniqueness constraints on an existing field doesn't force a schema
 version change. Therefore, existing database objects that were previously valid could be in violation of a uniqueness
 constraint that is added without one. To avoid this possibililty, change the schema version number as well.

Optional Element Summary

Optional Elements

Modifier and Type
Optional Element and Description

boolean
cascadeDelete

For reference fields, configure cascading behavior when the containing object is
 deleted.

boolean
indexed

Whether this field is indexed or not.

String
name

The name of this field.

DeleteAction
onDelete

For reference fields, configure the behavior when the referred-to object is
 deleted.

int
storageId

Storage ID for this field.

String
type

Optional override for the type of this field.

boolean
unique

Require this field's value to be unique among all database objects.

String[]
uniqueExclude

Specify field value(s) which are excluded from the uniqueness constraint.

boolean
uniqueExcludeNull

Specify that the null value is excluded from the uniqueness constraint.

Element Detail

name

public abstract String name

The name of this field.

 If equal to the empty string (default value), the name is inferred from the name of the annotated Java bean getter method.

 For sub-fields of complex fields, this property must be left unset.

Returns:

the name of the field

Default:

""

type

public abstract String type

Optional override for the type of this field.

 If set, this must equal the name of a type registered in the FieldTypeRegistry
 associated with the Database instance, and the annotated method's return type must match the
 FieldType's supported Java type.

 If equal to the empty string (default value), then the Java type is inferred from the return type of the getter method
 and the FieldType is found via
 FieldTypeRegistry.getFieldType().

 For reference fields (i.e., methods with return value equal to a @JSimpleClass-annotated class),
 this property must be left unset.

 For sub-fields of complex fields, this property can be used to force a primitive sub-field type instead of a
 primitive wrapper type. In that case, the complex field will disallow null values. For example:

  @JSetField(element = @JField(type = "float")) // nulls will be disallowed
  public abstract List<Float> getScores();

Returns:

the name of the field's type

Default:

""

storageId

public abstract int storageId

Storage ID for this field. Value should be positive and unique within the contained class.
 If zero, the configured StorageIdGenerator will be consulted to auto-generate a value
 unless JSimpleClass.autogenFields() is false (in which case an error occurs).

Returns:

the field's storage ID

See Also:

StorageIdGenerator.generateFieldStorageId(),
StorageIdGenerator.generateSetElementStorageId(),
StorageIdGenerator.generateListElementStorageId(),
StorageIdGenerator.generateMapKeyStorageId(),
StorageIdGenerator.generateMapValueStorageId()

Default:

0

indexed

public abstract boolean indexed

Whether this field is indexed or not.

 Setting this property to true creates a simple index on this field. To have this field participate in
 a composite index on multiple fields, use JSimpleClass.compositeIndexes().

 Note: reference fields are always indexed (for reference fields, this property is ignored).

Returns:

whether the field is indexed

Default:

false

onDelete

public abstract DeleteAction onDelete

For reference fields, configure the behavior when the referred-to object is
 deleted.

 For non-reference fields this property must be equal to its default value.

Returns:

desired behavior when a referenced object is deleted

See Also:

cascadeDelete(),
JObject.delete()

Default:

org.jsimpledb.core.DeleteAction.EXCEPTION

cascadeDelete

public abstract boolean cascadeDelete

For reference fields, configure cascading behavior when the containing object is
 deleted. If set to true, the referred-to object
 is automatically deleted as well.

 For non-reference fields this property must be equal to its default value.

Returns:

whether deletion should cascade to the referred-to object

See Also:

onDelete(),
JObject.delete()

Default:

false

unique

public abstract boolean unique

Require this field's value to be unique among all database objects.

 This property must be false for sub-fields of complex fields.

Returns:

whether the field's value should be unique

See Also:

uniqueExclude(),
uniqueExcludeNull()

Default:

false

uniqueExclude

public abstract String[] uniqueExclude

Specify field value(s) which are excluded from the uniqueness constraint.

 The specified values must be valid String encodings of the associated field. For example:

  @JField(indexed = true, unique = true, uniqueExclude = { "Infinity", "-Infinity" })
  public abstract float getPriority();

 This property must be left empty when unique() is false.

Returns:

values to exclude from the uniqueness constraint

See Also:

unique(),
uniqueExcludeNull()

Default:

{}

uniqueExcludeNull

public abstract boolean uniqueExcludeNull

Specify that the null value is excluded from the uniqueness constraint.

 This property must be left false when unique() is false or the field has primitive type.

Returns:

whether null should be excluded from the uniqueness constraint

See Also:

unique(),
uniqueExclude()

Default:

false

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element


text:
package com.hankcs.hanlp.dictionary;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.collection.trie.DoubleArrayTrie;
import com.hankcs.hanlp.collection.trie.bintrie.BinTrie;
import com.hankcs.hanlp.corpus.io.ByteArray;
import com.hankcs.hanlp.corpus.io.IOUtil;
import com.hankcs.hanlp.utility.Predefine;
import com.hankcs.hanlp.utility.TextUtility;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
import static com.hankcs.hanlp.utility.Predefine.logger;

/**
 * 2元语法词典
 * @author hankcs
 */
public class BiGramDictionary
{
    static DoubleArrayTrie<Integer> trie;

    public final static String path = HanLP.Config.BiGramDictionaryPath;
    public static final int totalFrequency = 37545990;
    // 自动加载词典
    static
    {
        long start = System.currentTimeMillis();
        if (!load(path))
        {
            logger.severe("二元词典加载失败");
            System.exit(-1);
        }
        else
        {
            logger.info(path + "加载成功,耗时" + (System.currentTimeMillis() - start) + "ms");
        }
    }
    public static boolean load(String path)
    {
        logger.info("二元词典开始加载:"+ path);
        trie = new DoubleArrayTrie<Integer>();
        boolean create = !loadDat(path);
        if (!create) return true;
        TreeMap<String, Integer> map = new TreeMap<String, Integer>();
        BufferedReader br;
        try
        {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
            String line;
            while ((line = br.readLine()) != null)
            {
                String[] params = line.split("\\s");
                String twoWord = params[0];
                int freq = Integer.parseInt(params[1]);
                map.put(twoWord, freq);
            }
            br.close();
            logger.info("二元词典读取完毕:" + path + ",开始构建双数组Trie树(DoubleArrayTrie)……");
        } catch (FileNotFoundException e)
        {
            logger.severe("二元词典" + path + "不存在!"+ e);
            return false;
        } catch (IOException e)
        {
            logger.severe("二元词典" + path + "读取错误!"+ e);
            return false;
        }

        int resultCode = trie.build(map);
        logger.info("二元词典DAT构建结果:{}"+ resultCode);
//        reSaveDictionary(map, path);
        logger.info("二元词典加载成功:" + trie.size() + "个词条");
        if (create)
        {
            try
            {
                DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path + Predefine.BIN_EXT)));
                Collection<Integer> freqList = map.values();
                out.writeInt(freqList.size());
                for (int freq : freqList)
                {
                    out.writeInt(freq);
                }
                trie.save(out);
                out.close();
            }
            catch (Exception e)
            {
                logger.warning("在缓存" + path + Predefine.BIN_EXT + "时发生异常" + TextUtility.exceptionToString(e));
                return false;
            }
        }
        return true;
    }

    /**
     * 从dat文件中加载排好的trie
     * @param path
     * @return
     */
    private static boolean loadDat(String path)
    {
        try
        {
            ByteArray byteArray = ByteArray.createByteArray(path + Predefine.BIN_EXT);
            if (byteArray == null) return false;

            int size = byteArray.nextInt();
            Integer[] value = new Integer[size];
            for (int i = 0; i < size; i++)
            {
                value[i] = byteArray.nextInt();
            }
            if (!trie.load(byteArray, value)) return false;
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

    /**
     * 找寻特殊字串,如未##串
     * @deprecated 没事就不要用了
     * @return 一个包含特殊词串的set
     */
    public static Set<String> _findSpecialString()
    {
        Set<String> stringSet = new HashSet<String>();
        BufferedReader br;
        try
        {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));
            String line;
            while ((line = br.readLine()) != null)
            {
                String[] params = line.split("\t");
                String twoWord = params[0];
                params = twoWord.split("@");
                for (String w : params)
                {
                    if (w.contains("##"))
                    {
                        stringSet.add(w);
                    }
                }
            }
            br.close();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return stringSet;
    }

    /**
     * 获取共现频次
     * @param from 第一个词
     * @param to 第二个词
     * @return 第一个词@第二个词出现的频次
     */
    public static int getBiFrequency(String from, String to)
    {
        return getBiFrequency(from + '@' + to);
    }

    /**
     * 获取共现频次
     * @param twoWord 用@隔开的两个词
     * @return 共现频次
     */
    public static int getBiFrequency(String twoWord)
    {
        Integer result = trie.get(twoWord);
        return (result == null ? 0 : result);
    }

    /**
     * 将NGram词典重新写回去
     * @param map
     * @param path
     * @return
     */
    private static boolean reSaveDictionary(TreeMap<String, Integer> map, String path)
    {
        StringBuilder sbOut = new StringBuilder();
        for (Map.Entry<String, Integer> entry : map.entrySet())
        {
            sbOut.append(entry.getKey());
            sbOut.append(' ');
            sbOut.append(entry.getValue());
            sbOut.append('\n');
        }

        return IOUtil.saveTxt(path, sbOut.toString());
    }

    /**
     * 接受键数组与值数组,排序以供建立trie树
     * @param wordList
     * @param freqList
     */
    private static void sortListForBuildTrie(List<String> wordList, List<Integer> freqList, String path)
    {
        BinTrie<Integer> binTrie = new BinTrie<Integer>();
        for (int i = 0; i < wordList.size(); ++i)
        {
            binTrie.put(wordList.get(i), freqList.get(i));
        }
        Collections.sort(wordList);
        try
        {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path)));
//            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "_sort.txt")));
            for (String w : wordList)
            {
                bw.write(w + '\t' + binTrie.get(w));
                bw.newLine();
            }
            bw.close();
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}


text:
import os
import codecs
import json
import glob

dirname = os.path.join(
    os.path.expanduser('~'),
    '.s3sync'
)

def get_config():
    path = os.path.join(dirname, 'config', 'credentials.json')

    with codecs.open(path, encoding='UTF-8', mode='r') as cfile:
        content = cfile.read()
        config = json.loads(content)

        return config

def get_files():
    path = os.path.join(dirname, 'config', 'files.json')

    with codecs.open(path, encoding='UTF-8', mode='r') as cfile:
        content = cfile.read()
        files = json.loads(content)

        return files

def clear_working():
    files = glob.glob(os.path.join(dirname, 'working', '*.txt'))

    for f in files:
        os.remove(f)

    return