问:
Move one particular view up when opening a keyboard not the entire layout
I want functionality like Facebook like when we create any post with an image on it only they push one bar on top of the image, not the entire layout. In my case, I am using NestedScrollView as a parent with child ConstraintLayout and the bar is designed in Linear layout.

This is my app:

I want something like this:

This is my XML

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fillViewport="true">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.03" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.97" />

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/select_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/dimen_15dp"
        android:clickable="true"
        android:clipChildren="false"
        android:focusable="true"
        android:foreground="@drawable/ripple"
        android:paddingTop="@dimen/dimen_5dp"
        android:paddingEnd="@dimen/dimen_5dp"
        android:paddingBottom="@dimen/dimen_5dp"
        android:src="@drawable/left_arrow"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.00"
        app:layout_constraintStart_toStartOf="@id/guideline1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00" />

    <androidx.appcompat.widget.AppCompatTextView

        android:id="@+id/back_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="8dp"
        android:layout_marginTop="@dimen/dimen_15dp"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="@font/opensans_bold"
        android:paddingTop="@dimen/dimen_5dp"
        android:paddingEnd="@dimen/dimen_5dp"
        android:paddingBottom="@dimen/dimen_5dp"
        android:text="@string/new_post"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="@dimen/dimen_16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/select_back"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/postTextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/dimen_15dp"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="@font/roboto_regular"
        android:foreground="?android:selectableItemBackground"
        android:paddingStart="@dimen/dimen_5dp"
        android:paddingTop="@dimen/dimen_5dp"
        android:paddingBottom="@dimen/dimen_5dp"
        android:text="@string/post"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="@dimen/dimen_16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/back_title"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00" />

    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginTop="12dp"
        android:background="@color/grey_text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/select_back"
        app:layout_constraintVertical_bias="0.0" />

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_image"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_centerVertical="true"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:src="@drawable/rock"
        app:civ_border_color="@color/white"
        app:civ_border_width="2dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/dimen_10dp"
        android:layout_marginTop="20dp"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="@font/opensans_bold"
        android:text="Dwayne johnson"
        android:textColor="@color/textview_black"
        android:textSize="@dimen/dimen_14sp"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/profile_image"
        app:layout_constraintTop_toBottomOf="@+id/line" />

    <com.skyfishjy.library.RippleBackground
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="44dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line"
        app:rb_color="#29B6F6"
        app:rb_duration="2000"
        app:rb_radius="5dp"
        app:rb_rippleAmount="3"
        app:rb_scale="4">

        <ImageView
            android:id="@+id/world"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="TODO"
            android:padding="10dp"
            android:src="@drawable/world" />

    </com.skyfishjy.library.RippleBackground>

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/down_arrow"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_marginTop="16dp"
        android:foreground="?attr/selectableItemBackground"
        android:padding="10dp"
        android:src="@drawable/ic_arrow_down_sign_to_navigate"
        app:layout_constraintStart_toEndOf="@+id/content"
        app:layout_constraintTop_toBottomOf="@+id/line" />

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="8dp"
        android:layout_below="@+id/rel"
        android:layout_marginTop="8dp"
        android:background="#DCDCDC"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/profile_image" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/category1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:background="@drawable/button_background"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="sans-serif"
        android:foreground="?android:selectableItemBackground"
        android:padding="5dp"
        android:text="@string/personal"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="10sp"
        android:textStyle="normal"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view"
        app:textAllCaps="false" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/category2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:background="@drawable/post_btn_bg"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="sans-serif"
        android:foreground="?android:selectableItemBackground"
        android:padding="5dp"
        android:text="@string/awareness"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimary"
        android:textSize="10sp"
        android:textStyle="normal"
        app:layout_constraintStart_toEndOf="@+id/category1"
        app:layout_constraintTop_toBottomOf="@+id/view"
        app:textAllCaps="false" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/category3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:background="@drawable/post_btn_bg"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="sans-serif"
        android:foreground="?android:selectableItemBackground"
        android:padding="5dp"
        android:text="@string/scheme"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimary"
        android:textSize="10sp"
        android:textStyle="normal"
        app:layout_constraintStart_toEndOf="@+id/category2"
        app:layout_constraintTop_toBottomOf="@+id/view"
        app:textAllCaps="false" />

    <View
        android:id="@+id/line1"
        android:layout_width="match_parent"
        android:layout_height="0.4dp"
        android:layout_marginTop="8dp"
        android:background="@color/grey_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/category3" />

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/write_post"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_100dp"
        android:layout_below="@+id/line1"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/post_edit_text_bg"
        android:fontFamily="@font/roboto_regular"
        android:gravity="start"
        android:hint="What's on your mind..."
        android:inputType="textMultiLine"
        android:textColor="@color/textview_black"
        android:textColorHint="@color/grey2_text"
        android:textCursorDrawable="@drawable/cursor_color"
        android:textSize="@dimen/dimen_16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line1" />

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/timelineImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:visibility="gone"
        android:layout_marginBottom="@dimen/dimen_20dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/write_post">

    </androidx.appcompat.widget.AppCompatImageView>

    <VideoView
        android:id="@+id/timelineVideo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        android:layout_marginBottom="@dimen/dimen_20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/write_post"
        app:layout_constraintVertical_bias="0.072">

    </VideoView>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="8dp"
        android:background="@drawable/item_bg"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/camera"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:foreground="?android:selectableItemBackground"
            android:padding="10dp"
            android:src="@drawable/ic_camera" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/gallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:foreground="?android:selectableItemBackground"
            android:padding="10dp"
            android:src="@drawable/gallery" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>
</code>```

Tried everything in the manifest

```<code>android:windowSoftInputMode="adjustPan"
android:windowSoftInputMode="adjustResize"
android:windowSoftInputMode="adjustNothing"
</code>```

but nothing worked. All are pushing my entire layout up.

答: I think this is because, you are using NestedScrollView as parent check by replacing NestedScrollView with any other layout</p>

Body:
I want functionality like Facebook like when we create any post with an image on it only they push one bar on top of the image, not the entire layout. In my case, I am using NestedScrollView as a parent with child ConstraintLayout and the bar is designed in Linear layout.

This is my app:

I want something like this:

This is my XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fillViewport="true">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.03" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.97" />

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/select_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/dimen_15dp"
        android:clickable="true"
        android:clipChildren="false"
        android:focusable="true"
        android:foreground="@drawable/ripple"
        android:paddingTop="@dimen/dimen_5dp"
        android:paddingEnd="@dimen/dimen_5dp"
        android:paddingBottom="@dimen/dimen_5dp"
        android:src="@drawable/left_arrow"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.00"
        app:layout_constraintStart_toStartOf="@id/guideline1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00" />

    <androidx.appcompat.widget.AppCompatTextView

        android:id="@+id/back_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="8dp"
        android:layout_marginTop="@dimen/dimen_15dp"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="@font/opensans_bold"
        android:paddingTop="@dimen/dimen_5dp"
        android:paddingEnd="@dimen/dimen_5dp"
        android:paddingBottom="@dimen/dimen_5dp"
        android:text="@string/new_post"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="@dimen/dimen_16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/select_back"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/postTextview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/dimen_15dp"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="@font/roboto_regular"
        android:foreground="?android:selectableItemBackground"
        android:paddingStart="@dimen/dimen_5dp"
        android:paddingTop="@dimen/dimen_5dp"
        android:paddingBottom="@dimen/dimen_5dp"
        android:text="@string/post"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="@dimen/dimen_16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/guideline2"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toEndOf="@+id/back_title"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.00" />

    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:layout_marginTop="12dp"
        android:background="@color/grey_text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/select_back"
        app:layout_constraintVertical_bias="0.0" />

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/profile_image"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_centerVertical="true"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:src="@drawable/rock"
        app:civ_border_color="@color/white"
        app:civ_border_width="2dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/dimen_10dp"
        android:layout_marginTop="20dp"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="@font/opensans_bold"
        android:text="Dwayne johnson"
        android:textColor="@color/textview_black"
        android:textSize="@dimen/dimen_14sp"
        android:textStyle="bold"
        app:layout_constraintStart_toEndOf="@+id/profile_image"
        app:layout_constraintTop_toBottomOf="@+id/line" />

    <com.skyfishjy.library.RippleBackground
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="44dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line"
        app:rb_color="#29B6F6"
        app:rb_duration="2000"
        app:rb_radius="5dp"
        app:rb_rippleAmount="3"
        app:rb_scale="4">

        <ImageView
            android:id="@+id/world"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="TODO"
            android:padding="10dp"
            android:src="@drawable/world" />

    </com.skyfishjy.library.RippleBackground>

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/down_arrow"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_centerVertical="true"
        android:layout_marginTop="16dp"
        android:foreground="?attr/selectableItemBackground"
        android:padding="10dp"
        android:src="@drawable/ic_arrow_down_sign_to_navigate"
        app:layout_constraintStart_toEndOf="@+id/content"
        app:layout_constraintTop_toBottomOf="@+id/line" />

    <View
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="8dp"
        android:layout_below="@+id/rel"
        android:layout_marginTop="8dp"
        android:background="#DCDCDC"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/profile_image" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/category1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:background="@drawable/button_background"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="sans-serif"
        android:foreground="?android:selectableItemBackground"
        android:padding="5dp"
        android:text="@string/personal"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="10sp"
        android:textStyle="normal"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view"
        app:textAllCaps="false" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/category2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:background="@drawable/post_btn_bg"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="sans-serif"
        android:foreground="?android:selectableItemBackground"
        android:padding="5dp"
        android:text="@string/awareness"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimary"
        android:textSize="10sp"
        android:textStyle="normal"
        app:layout_constraintStart_toEndOf="@+id/category1"
        app:layout_constraintTop_toBottomOf="@+id/view"
        app:textAllCaps="false" />

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/category3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:background="@drawable/post_btn_bg"
        android:clickable="true"
        android:focusable="true"
        android:fontFamily="sans-serif"
        android:foreground="?android:selectableItemBackground"
        android:padding="5dp"
        android:text="@string/scheme"
        android:textAllCaps="false"
        android:textColor="@color/colorPrimary"
        android:textSize="10sp"
        android:textStyle="normal"
        app:layout_constraintStart_toEndOf="@+id/category2"
        app:layout_constraintTop_toBottomOf="@+id/view"
        app:textAllCaps="false" />

    <View
        android:id="@+id/line1"
        android:layout_width="match_parent"
        android:layout_height="0.4dp"
        android:layout_marginTop="8dp"
        android:background="@color/grey_text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/category3" />

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/write_post"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dimen_100dp"
        android:layout_below="@+id/line1"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@drawable/post_edit_text_bg"
        android:fontFamily="@font/roboto_regular"
        android:gravity="start"
        android:hint="What's on your mind..."
        android:inputType="textMultiLine"
        android:textColor="@color/textview_black"
        android:textColorHint="@color/grey2_text"
        android:textCursorDrawable="@drawable/cursor_color"
        android:textSize="@dimen/dimen_16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/line1" />

    <androidx.appcompat.widget.AppCompatImageView
        android:id="@+id/timelineImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:visibility="gone"
        android:layout_marginBottom="@dimen/dimen_20dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/write_post">

    </androidx.appcompat.widget.AppCompatImageView>

    <VideoView
        android:id="@+id/timelineVideo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        android:layout_marginBottom="@dimen/dimen_20dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/write_post"
        app:layout_constraintVertical_bias="0.072">

    </VideoView>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="8dp"
        android:background="@drawable/item_bg"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/camera"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:foreground="?android:selectableItemBackground"
            android:padding="10dp"
            android:src="@drawable/ic_camera" />

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/gallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:foreground="?android:selectableItemBackground"
            android:padding="10dp"
            android:src="@drawable/gallery" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

Tried everything in the manifest

android:windowSoftInputMode="adjustPan"
android:windowSoftInputMode="adjustResize"
android:windowSoftInputMode="adjustNothing"

but nothing worked. All are pushing my entire layout up.


来源: stackexchange

问:
Get the value of textbox after refreshing the form
I have a continuous form that has the property that has some fields.
When I click a button on the form a Requery is processed on the form which results in updated value of some textboxes (these are not enabled, i.e. read only).

What I'm trying to do is to get the value of one of the textboxes in the form after Requery.
How do I do that?
I've tried using the Current event to get the value after the requery (refresh) but it's not working. Is there any other event that can do the work?

答:
Thanks for your contribution..
The problem was that the value of the field I was trying to get the value of comes from adding 2 values (a + b)

and so the solution was updating the field before saving its value to a different variable...

ContentLicense: CC BY-SA 3.0


问:
How to run bson command access nested items structure by using C# mongodriver client?
How can I run a simple mongodb command by accessing nested mongodb structure by writing ansi mongo script?
But it can not work because it is not correct I am looking for an answer by googling but I couldn't find any best answer . I know using mongodb with C# it is like a torture. Please give me great advise. because I am exhausted making research on the internet. My code is a poseido code. it is a kind of my desire. Also please look at my picture to understand structure of my mongodb json structure.

```<code>  var customerinfos = db_ScaleGrid.RunCommand<BsonDocument>(new BsonDocument("db.getCollection('customers').find({'Items.0.Source.CustomerInfo':{$exists:true}})",""));
            foreach (var customerinfo in customerinfos)
            {
                var customerid = customerinfo["customerid"];
                var customerName = customerinfo["customerName"];
            }
</code>```

答:
i hope i've understood your structure and requirement correctly. if not let me know and i'll ammend my answer accordingly. you can easily access customer info with mongodb c# driver's AsQueryable interface like so:

var collection = new MongoClient("mongodb://localhost")
                    .GetDatabase("test")
                    .GetCollection<Customer>("customers");

var result = collection.AsQueryable()
                .Select(c => c.Items[0].Source.CustomerInfo)
                .ToArray();
```

<p>here's a strongly-typed test program:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>using MongoDB.Entities;
using MongoDB.Entities.Core;
using System;
using System.Linq;

namespace StackOverFlow
{
    public class Customer : Entity
    {
        public Item[] Items { get; set; }
    }

    public class Item
    {
        public Source Source { get; set; }
    }

    public class Source
    {
        public CustomerInfo CustomerInfo { get; set; }
    }

    public class CustomerInfo
    {
        public string CustomerID { get; set; }
        public string CustomerName { get; set; }
    }

    public static class Program
    {
        private static void Main()
        {
            new DB("test");

            var customer = new Customer
            {
                Items = new[]
                {
                    new Item
                    {
                        Source = new Source {
                            CustomerInfo = new CustomerInfo
                            {
                                CustomerID = "xxxxxxx",
                                CustomerName = "customer one"
                            }
                        }
                    }
                }
            };

            customer.Save();

            var result = DB.Queryable<Customer>()
                           .Select(c => c.Items[0].Source.CustomerInfo)
                           .ToArray();

            foreach (var info in result)
            {
                Console.WriteLine($"id: {info.CustomerName} / name: {info.CustomerName}");
            }

            Console.ReadKey();
        }
    }
}</code>```

above test program uses my library MongoDB.Entities for brevity. if you're overwhelmed by the verbosity of the official driver, you might want to check out my library.

ContentLicense: CC BY-SA 4.0

Body:
How can I run a simple mongodb command by accessing nested mongodb structure by writing ansi mongo script?
But it can not work because it is not correct I am looking for an answer by googling but I couldn't find any best answer . I know using mongodb with C# it is like a torture. Please give me great advise. because I am exhausted making research on the internet. My code is a poseido code. it is a kind of my desire. Also please look at my picture to understand structure of my mongodb json structure.

  var customerinfos = db_ScaleGrid.RunCommand<BsonDocument>(new BsonDocument("db.getCollection('customers').find({'Items.0.Source.CustomerInfo':{$exists:true}})",""));
            foreach (var customerinfo in customerinfos)
            {
                var customerid = customerinfo["customerid"];
                var customerName = customerinfo["customerName"];
            }

Body:
i hope i've understood your structure and requirement correctly. if not let me know and i'll ammend my answer accordingly. you can easily access customer info with mongodb c# driver's AsQueryable interface like so:

var collection = new MongoClient("mongodb://localhost")
                    .GetDatabase("test")
                    .GetCollection<Customer>("customers");

var result = collection.AsQueryable()
                .Select(c => c.Items[0].Source.CustomerInfo)
                .ToArray();

here's a strongly-typed test program:

using MongoDB.Entities;
using MongoDB.Entities.Core;
using System;
using System.Linq;

namespace StackOverFlow
{
    public class Customer : Entity
    {
        public Item[] Items { get; set; }
    }

    public class Item
    {
        public Source Source { get; set; }
    }

    public class Source
    {
        public CustomerInfo CustomerInfo { get; set; }
    }

    public class CustomerInfo
    {
        public string CustomerID { get; set; }
        public string CustomerName { get; set; }
    }

    public static class Program
    {
        private static void Main()
        {
            new DB("test");

            var customer = new Customer
            {
                Items = new[]
                {
                    new Item
                    {
                        Source = new Source {
                            CustomerInfo = new CustomerInfo
                            {
                                CustomerID = "xxxxxxx",
                                CustomerName = "customer one"
                            }
                        }
                    }
                }
            };

            customer.Save();

            var result = DB.Queryable<Customer>()
                           .Select(c => c.Items[0].Source.CustomerInfo)
                           .ToArray();

            foreach (var info in result)
            {
                Console.WriteLine($"id: {info.CustomerName} / name: {info.CustomerName}");
            }

            Console.ReadKey();
        }
    }
}

above test program uses my library MongoDB.Entities for brevity. if you're overwhelmed by the verbosity of the official driver, you might want to check out my library.


问:
Manually setting the Google Analytics Client ID
I have a sub-domain that I am unable to put GTM or GA tracking code on.  I have GA on the main domain.

I can retrieve the _ga cookie and get the Client ID but but if a user has not been to the main website they won't have one.

My question is:

Can I set a cookie called _ga (in the same format as GA sets it) and will this get picked up by GA if the user then goes back to the main website?

答:
This article seems to be what you need:

Cookie Settings And Subdomain Tracking In Universal Analytics
https://www.simoahava.com/analytics/cookie-settings-and-subdomain-tracking-in-universal-analytics/


问:
xgboost in Python is not returning importance of features despite what is referred in the documentation
According to the xgboost documentation (https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training) the xgboost returns feature importances:

feature_importances_

Feature importances property

Note

Feature importance is defined only for tree boosters.  Feature importance is only defined when the decision tree model is chosen as base learner
  ((booster=gbtree). It is not defined for other base learner types, such as linear learners (booster=gblinear).

Returns:  feature_importances_

Return type:  array of shape [n_features]

However, this does not seem to case, as the following toy example shows:

```<code>import seaborn as sns
import xgboost as xgb

mpg = sns.load_dataset('mpg')

toy = mpg[['mpg', 'cylinders', 'displacement', 'horsepower', 'weight',
       'acceleration']]

toy = toy.sample(frac=1)

N = toy.shape[0]

N1 = int(N/2)

toy_train = toy.iloc[:N1, :]
toy_test = toy.iloc[N1:, :]

toy_train_x = toy_train.iloc[:, 1:]

toy_train_y = toy_train.iloc[:, 1]

toy_test_x = toy_test.iloc[:, 1:]

toy_test_y = toy_test.iloc[:, 1]

max_depth = 6
eta = 0.3
subsample = 0.8
colsample_bytree = 0.7
alpha = 0.1

params = {"booster" : 'gbtree' , 'objective' : 'reg:linear' , 'max_depth' : max_depth, 'eta' : eta,\
             'subsample' : subsample, 'colsample_bytree' : colsample_bytree, 'alpha' : alpha}

dtrain_toy = xgb.DMatrix(data = toy_train_x , label = toy_train_y)
dtest_toy = xgb.DMatrix(data = toy_test_x, label = toy_test_y)
watchlist = [(dtest_toy, 'eval'), (dtrain_toy, 'train')]

xg_reg_toy = xgb.train(params = params, dtrain = dtrain_toy, num_boost_round = 1000, evals = watchlist, \
                early_stopping_rounds = 20)

xg_reg_toy.feature_importances_
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-378-248f7887e307> in <module>()
----> 1 xg_reg_toy.feature_importances_

AttributeError: 'Booster' object has no attribute 'feature_importances_'
</code>```

答:
For someone who is not using Scikit-Learn API like me, because of obvious reasons.
From here I was able to get the importance of the feature:

```<code>clf.get_score()
</code>```

Also, I was looking into a more intuitive representation here:

```<code>from xgboost import plot_importance
plot_importance(clf, max_num_features=10)
</code>```

This generates the bar chart with specified (optional) max_num_features in the order of their importance.

Body:
According to the xgboost documentation (https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training) the xgboost returns feature importances:

feature_importances_

Feature importances property

Note

Feature importance is defined only for tree boosters.  Feature importance is only defined when the decision tree model is chosen as base learner
  ((booster=gbtree). It is not defined for other base learner types, such as linear learners (booster=gblinear).

Returns:  feature_importances_

Return type:  array of shape [n_features]

However, this does not seem to case, as the following toy example shows:

import seaborn as sns
import xgboost as xgb

mpg = sns.load_dataset('mpg')

toy = mpg[['mpg', 'cylinders', 'displacement', 'horsepower', 'weight',
       'acceleration']]

toy = toy.sample(frac=1)

N = toy.shape[0]

N1 = int(N/2)

toy_train = toy.iloc[:N1, :]
toy_test = toy.iloc[N1:, :]

toy_train_x = toy_train.iloc[:, 1:]

toy_train_y = toy_train.iloc[:, 1]

toy_test_x = toy_test.iloc[:, 1:]

toy_test_y = toy_test.iloc[:, 1]

max_depth = 6
eta = 0.3
subsample = 0.8
colsample_bytree = 0.7
alpha = 0.1

params = {"booster" : 'gbtree' , 'objective' : 'reg:linear' , 'max_depth' : max_depth, 'eta' : eta,\
             'subsample' : subsample, 'colsample_bytree' : colsample_bytree, 'alpha' : alpha}

dtrain_toy = xgb.DMatrix(data = toy_train_x , label = toy_train_y)
dtest_toy = xgb.DMatrix(data = toy_test_x, label = toy_test_y)
watchlist = [(dtest_toy, 'eval'), (dtrain_toy, 'train')]

xg_reg_toy = xgb.train(params = params, dtrain = dtrain_toy, num_boost_round = 1000, evals = watchlist, \
                early_stopping_rounds = 20)

xg_reg_toy.feature_importances_
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-378-248f7887e307> in <module>()
----> 1 xg_reg_toy.feature_importances_

AttributeError: 'Booster' object has no attribute 'feature_importances_'

Body:
For someone who is not using Scikit-Learn API like me, because of obvious reasons.
From here I was able to get the importance of the feature:

clf.get_score()

Also, I was looking into a more intuitive representation here:

from xgboost import plot_importance
plot_importance(clf, max_num_features=10)

This generates the bar chart with specified (optional) max_num_features in the order of their importance.


问:
Unable to update R packages in default library on Windows 7
I'm trying to update packages on RGui (64-bit) using update.packages but I'm getting the following message:

```<code>Warning in install.packages(update[instlib == l, "Package"], l, contriburl = contriburl,  :
  'lib = "C:/PROGRA~1/R/R-212~1.1/library"' is not writable
Error in install.packages(update[instlib == l, "Package"], l, contriburl = contriburl,  :
  unable to install packages
</code>```

I've looked at the library folder in Explorer and it has read only set, so I removed it. However, it reappears when I check the properties again immediately after doing this. Installing new packages is unaffected since they have a separate folder in my user profile.

Is there a trick to getting this to work?

答: Sometimes there may also be a possibility that your Antivirus is blocking the application. Unblock the application if anti virus has blocked it. </p>

Body:
I'm trying to update packages on RGui (64-bit) using update.packages but I'm getting the following message:

Warning in install.packages(update[instlib == l, "Package"], l, contriburl = contriburl,  :
  'lib = "C:/PROGRA~1/R/R-212~1.1/library"' is not writable
Error in install.packages(update[instlib == l, "Package"], l, contriburl = contriburl,  :
  unable to install packages

I've looked at the library folder in Explorer and it has read only set, so I removed it. However, it reappears when I check the properties again immediately after doing this. Installing new packages is unaffected since they have a separate folder in my user profile.

Is there a trick to getting this to work?


答:
add This in your meniFest file beside your activity tag

```<code>android:windowSoftInputMode="adjustResize"
</code>```

and,put scrollView as a parent layout in your xml file

Title: Move one particular view up when opening a keyboard not the entire layout

Body:
add This in your meniFest file beside your activity tag

android:windowSoftInputMode="adjustResize"

and,put scrollView as a parent layout in your xml file


问:
Not matching sample in y axis for knn
Im trying to make my way to a sligthly more flexible knn input script than the tutorials based of the iris dataset but Im having some trouble (I think) to add the matching 2nd dimension to the numpy array in #6 and when I come to #11. the fitting.

File "G:\PROGRAMMERING\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 212, in check_consistent_length
      " samples: %r" % [int(l) for l in lengths]) ValueError: Found input variables with inconsistent numbers of samples: [150, 1]

x is (150,5) and y is (150,1). 150 is the number of samples in both, but they differ in number of fields, is this the problem and if so how do I fix it?

```<code>#1. Loading the Pandas libraries as pd
import pandas as pd
import numpy as np

#2. Read data from the file 'custom.csv' placed in your code directory
data = pd.read_csv("custom.csv")

#3. Preview the first 5 lines of the loaded data
print(data.head())
print(type(data))

#4.Test the shape of the data
print(data.shape)
df = pd.DataFrame(data)
print(df)

#5. Convert non-numericals to numericals
print(df.dtypes)
# Any object should be converted to numerical
df['species'] = pd.Categorical(df['species'])
df['species'] = df.species.cat.codes
print("outcome:")
print(df.dtypes)

#6.Convert df to numpy.ndarray
np = df.to_numpy()
print(type(np)) #this should state <class 'numpy.ndarray'>
print(data.shape)
print(np)
x = np.data
y = [df['species']]
print(y)

#K-nearest neighbor (find closest) - searach for the K nearest observations in the dataset
#The model calculates the distance to all, and selects the K nearest ones.
#8. Import the class you plan to use
from sklearn.neighbors import (KNeighborsClassifier)
#9. Pick a value for K
k = 2
#10. Instantiate the "estimator" (make an instance of the model)
knn  = KNeighborsClassifier(n_neighbors=k)
print(knn)
#11. fit the model with data/model training
knn.fit(x, y)
#12. Predict the response for a new observation
print(knn.predict([[3, 5, 4, 2]]))```
```

答:
This is how I used the scikit-learn KNeighborsClassifier to fit the knn model:

```<code>import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier

df = datasets.load_iris()
X = pd.DataFrame(df.data)
y = df.target
knn = KNeighborsClassifier(n_neighbors = 2)
knn.fit(X,y)
print(knn.predict([[6, 3, 5, 2]]))
#prints output class [2]
print(knn.predict([[3, 5, 4, 2]]))
#prints output class [1]
</code>```

From DataFrame you don't need to convert to numpy array, you can directly fit the model on DataFrame, also while converting the DataFrame to numpy array you have named that as np which is also used to import numpy at the top import numpy as np

Title: Not matching sample in y axis for knn

Body:
Im trying to make my way to a sligthly more flexible knn input script than the tutorials based of the iris dataset but Im having some trouble (I think) to add the matching 2nd dimension to the numpy array in #6 and when I come to #11. the fitting.

File "G:\PROGRAMMERING\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 212, in check_consistent_length
      " samples: %r" % [int(l) for l in lengths]) ValueError: Found input variables with inconsistent numbers of samples: [150, 1]

x is (150,5) and y is (150,1). 150 is the number of samples in both, but they differ in number of fields, is this the problem and if so how do I fix it?

#1. Loading the Pandas libraries as pd
import pandas as pd
import numpy as np

#2. Read data from the file 'custom.csv' placed in your code directory
data = pd.read_csv("custom.csv")

#3. Preview the first 5 lines of the loaded data
print(data.head())
print(type(data))

#4.Test the shape of the data
print(data.shape)
df = pd.DataFrame(data)
print(df)

#5. Convert non-numericals to numericals
print(df.dtypes)
# Any object should be converted to numerical
df['species'] = pd.Categorical(df['species'])
df['species'] = df.species.cat.codes
print("outcome:")
print(df.dtypes)

#6.Convert df to numpy.ndarray
np = df.to_numpy()
print(type(np)) #this should state <class 'numpy.ndarray'>
print(data.shape)
print(np)
x = np.data
y = [df['species']]
print(y)

#K-nearest neighbor (find closest) - searach for the K nearest observations in the dataset
#The model calculates the distance to all, and selects the K nearest ones.
#8. Import the class you plan to use
from sklearn.neighbors import (KNeighborsClassifier)
#9. Pick a value for K
k = 2
#10. Instantiate the "estimator" (make an instance of the model)
knn  = KNeighborsClassifier(n_neighbors=k)
print(knn)
#11. fit the model with data/model training
knn.fit(x, y)
#12. Predict the response for a new observation
print(knn.predict([[3, 5, 4, 2]]))```

Body:
This is how I used the scikit-learn KNeighborsClassifier to fit the knn model:

import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.neighbors import KNeighborsClassifier

df = datasets.load_iris()
X = pd.DataFrame(df.data)
y = df.target
knn = KNeighborsClassifier(n_neighbors = 2)
knn.fit(X,y)
print(knn.predict([[6, 3, 5, 2]]))
#prints output class [2]
print(knn.predict([[3, 5, 4, 2]]))
#prints output class [1]

From DataFrame you don't need to convert to numpy array, you can directly fit the model on DataFrame, also while converting the DataFrame to numpy array you have named that as np which is also used to import numpy at the top import numpy as np


问:
When a variable goes out of scope does that mean it doesn't exist?
I'm not sure I understand scope - does an out-of-scope variable (I'm using Ruby) exist in memory somewhere or does it stop existing (I know you can't access it). Would it be inaccurate to say that an out-of-scope variable does not exist any more?

Maybe this is a philosophical question.

答:
When a variable falls out of scope is anyone around to hear it scream?

This isn't a ruby question so much as a general question about garbage collection. In a garbage collected language such as Ruby or C# when a variable falls out of scope it's marked in some manner that says it's no longer in use. When this happens you can't get at it any more and it sits around twiddling its thumbs - but it does still have memory allocated to it.

At some point the garbage collector will wake up and look for variables marked as not in use. It will dispose of them and at that point they're no longer in memory at all.

It can be more complicated than this, depending on how the garbage collector works, but it's close enough :)

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: blowdart


问:
Force Emacs to use a particular encoding if and only if that causes no trouble
In my .emacs file, I use the line

```<code>'(setq coding-system-for-write 'iso-8859-1-unix)
</code>```

to have Emacs save files in the iso-8859-1-unix encoding. When I
enter characters that cannot be encoded that way ("Łódź" for
example), I get prompted to select a different encoding, but upon
entering `iso-8859-1-unix' into the minibuffer, the file is saved and
the offending characters are lost.

If I just hit enter at the prompt, the file is saved in Unicode, and
when I close and reopen Emacs it is interpreted as a Unicode file
again. If I then remove the offending characters, save the file and
close and reopen Emacs another time, it is still interpreted as a
Unicode file -- from which I deduce that it has still been saved in
Unicode, even though saving in iso-8859-1-unix would have been
possible.

So is there a way to force Emacs to write a file in iso-8859-1
whenever possible, and never save it in that encoding if doing so
would gobble characters?

Many thanks in advance,

Thure Dührsen

答:
Try

```<code>(setq-default buffer-file-coding-system 'iso-8859-1)
</code>```

Edit:

Incorporating AProgrammer's suggestion, we get

```<code>(defun enforce-coding-system-priority ()
  (let ((pref (car (coding-system-priority-list)))
        (list (find-coding-systems-region (point-min) (point-max))))
    (when (or (memq 'undecided list) (memq pref list))
      (setq buffer-file-coding-system pref))))

(add-hook 'before-save-hook 'enforce-coding-system-priority)

(prefer-coding-system 'iso-8859-1)
</code>```

Body:
In my .emacs file, I use the line

'(setq coding-system-for-write 'iso-8859-1-unix)

to have Emacs save files in the iso-8859-1-unix encoding. When I
enter characters that cannot be encoded that way ("Łódź" for
example), I get prompted to select a different encoding, but upon
entering `iso-8859-1-unix' into the minibuffer, the file is saved and
the offending characters are lost.

If I just hit enter at the prompt, the file is saved in Unicode, and
when I close and reopen Emacs it is interpreted as a Unicode file
again. If I then remove the offending characters, save the file and
close and reopen Emacs another time, it is still interpreted as a
Unicode file -- from which I deduce that it has still been saved in
Unicode, even though saving in iso-8859-1-unix would have been
possible.

So is there a way to force Emacs to write a file in iso-8859-1
whenever possible, and never save it in that encoding if doing so
would gobble characters?

Many thanks in advance,

Thure Dührsen

Body:
Try

(setq-default buffer-file-coding-system 'iso-8859-1)

Edit:

Incorporating AProgrammer's suggestion, we get

(defun enforce-coding-system-priority ()
  (let ((pref (car (coding-system-priority-list)))
        (list (find-coding-systems-region (point-min) (point-max))))
    (when (or (memq 'undecided list) (memq pref list))
      (setq buffer-file-coding-system pref))))

(add-hook 'before-save-hook 'enforce-coding-system-priority)

(prefer-coding-system 'iso-8859-1)


问:
How to remove content of JTextField while DocumentListener is running?
for the following Code I get an IllegalStateException (Attempt to mutate in notification):

```<code>private class DocumentHandler implements DocumentListener {
    public void changedUpdate(DocumentEvent ev) {
        // unused
    }
    public void insertUpdate(DocumentEvent ev) {
        if(textInput.getText().equals("...")) {
        JOptionPane.showMessageDialog(null, "...");
        textInput.setText("");
    }
}
</code>```

Why can´t I change a TextField while a DocumentListener is active?

I tried to remove the DocumentListener while the TextField is set to " " but that didn´t help at all.
I know that someone asked a very similar question before, but I don´t get that answer...

Thanks

答:
In general, you don't -- you don't change the state of the Document while listening to it when using a DocumentListener. The two possible solutions that I know of:

From within your Listener, put the code that makes the changes that you wish to make within a Runnable and queue the Runnable onto the Swing event thread by calling SwingUtilities.invokeLater(yourRunnable). This is a shameless kludge

Much better: Don't use a DocumentListener but rather a DocumentFilter since this type of listener was geared towards making changes to the Document before the text is visualized within the component.

Unrelated side issue: your code shows a worrisome degree of coupling in that you try to change the text in a specific text component from within your listener. DocumentListeners should be fully agnostic of the text component whose document that they listen to, and in fact may be added to more than one Document.

A DocumentFilter has 3 methods that need to be overridden and do what you expect them to do:  what you would expect them to do:

insertString: insert a String into the document

remove: removes text from the document

replace: replaces text in the document

What is more, these methods do their actions before the text component renders the changes to the document.

So within my method overrides, I extract the current document's text, and use the parameters to create what the new text will look like, for example for the replace method I did:

```<code>@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
        throws BadLocationException {
    String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
    StringBuilder sb = new StringBuilder(currentText);

    String newText = sb.replace(offset, offset + length, text).toString();
</code>```

I then do a boolean test on the newText to see if it is "good", and if so, call the super's method, here replace(...), passing in all the parameters. If not, if the newText fails the test, then I remove all the text from the document and show a JOptionPane.

So in this example, I use this as my test method:

```<code>private boolean isTextOk(String text) {
    return !BAD_TEXTS.contains(text);
}
</code>```

which tests to see if the text is any of the disallowed Strings, here "...", "   ", "oops", "OOPS", but it could be any Strings that you desire. Again, if the text passes the text, call the super's method, else remove the text:

```<code>if (isTextOk(newText)) {
    super.replace(fb, offset, length, text, attrs);
} else {
    badText(fb);
}
</code>```

Where badText(fb) does:

```<code>private void badText(FilterBypass fb) throws BadLocationException {
    remove(fb, 0, fb.getDocument().getLength());
    JOptionPane.showMessageDialog(null, "Don't do this!", "Bad Text Entered",
            JOptionPane.WARNING_MESSAGE);
}
</code>```

The whole example is:

```<code>import java.util.Arrays;
import java.util.List;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

@SuppressWarnings("serial")
public class ClearThreeDots extends JPanel {
    private JTextField textField = new JTextField(40);

    public ClearThreeDots() {
        ((PlainDocument) textField.getDocument()).setDocumentFilter(new MyDocFilter());
        add(textField);
    }

    private static void createAndShowGui() {
        ClearThreeDots mainPanel = new ClearThreeDots();

        JFrame frame = new JFrame("Clear Three Dots");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
</code>```

```<code>class MyDocFilter extends DocumentFilter {
    private static final List<String> BAD_TEXTS = Arrays.asList("...", "   ", "oops", "OOPS");

    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
            throws BadLocationException {
        String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
        StringBuilder sb = new StringBuilder(currentText);

        String newText = sb.insert(offset, string).toString();

        if (isTextOk(newText)) {
            super.insertString(fb, offset, string, attr);
        } else {
            badText(fb);
        }
    }

    @Override
    public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
        String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
        StringBuilder sb = new StringBuilder(currentText);

        String newText = sb.replace(offset, offset + length, "").toString();

        if (isTextOk(newText)) {
            super.remove(fb, offset, length);
        } else {
            badText(fb);
        }

    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
        String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
        StringBuilder sb = new StringBuilder(currentText);

        String newText = sb.replace(offset, offset + length, text).toString();

        if (isTextOk(newText)) {
            super.replace(fb, offset, length, text, attrs);
        } else {
            badText(fb);
        }

    }

    private boolean isTextOk(String text) {
        return !BAD_TEXTS.contains(text);
    }

    private void badText(FilterBypass fb) throws BadLocationException {
        remove(fb, 0, fb.getDocument().getLength());
        JOptionPane.showMessageDialog(null, "Don't do this!", "Bad Text Entered",
                JOptionPane.WARNING_MESSAGE);
    }

}
</code>```

Body:
for the following Code I get an IllegalStateException (Attempt to mutate in notification):

private class DocumentHandler implements DocumentListener {
    public void changedUpdate(DocumentEvent ev) {
        // unused
    }
    public void insertUpdate(DocumentEvent ev) {
        if(textInput.getText().equals("...")) {
        JOptionPane.showMessageDialog(null, "...");
        textInput.setText("");
    }
}

Why can´t I change a TextField while a DocumentListener is active?

I tried to remove the DocumentListener while the TextField is set to " " but that didn´t help at all.
I know that someone asked a very similar question before, but I don´t get that answer...

Thanks

Body:
In general, you don't -- you don't change the state of the Document while listening to it when using a DocumentListener. The two possible solutions that I know of:

From within your Listener, put the code that makes the changes that you wish to make within a Runnable and queue the Runnable onto the Swing event thread by calling SwingUtilities.invokeLater(yourRunnable). This is a shameless kludge

Much better: Don't use a DocumentListener but rather a DocumentFilter since this type of listener was geared towards making changes to the Document before the text is visualized within the component.

Unrelated side issue: your code shows a worrisome degree of coupling in that you try to change the text in a specific text component from within your listener. DocumentListeners should be fully agnostic of the text component whose document that they listen to, and in fact may be added to more than one Document.

A DocumentFilter has 3 methods that need to be overridden and do what you expect them to do:  what you would expect them to do:

insertString: insert a String into the document

remove: removes text from the document

replace: replaces text in the document

What is more, these methods do their actions before the text component renders the changes to the document.

So within my method overrides, I extract the current document's text, and use the parameters to create what the new text will look like, for example for the replace method I did:

@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
        throws BadLocationException {
    String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
    StringBuilder sb = new StringBuilder(currentText);

    String newText = sb.replace(offset, offset + length, text).toString();

I then do a boolean test on the newText to see if it is "good", and if so, call the super's method, here replace(...), passing in all the parameters. If not, if the newText fails the test, then I remove all the text from the document and show a JOptionPane.

So in this example, I use this as my test method:

private boolean isTextOk(String text) {
    return !BAD_TEXTS.contains(text);
}

which tests to see if the text is any of the disallowed Strings, here "...", "   ", "oops", "OOPS", but it could be any Strings that you desire. Again, if the text passes the text, call the super's method, else remove the text:

if (isTextOk(newText)) {
    super.replace(fb, offset, length, text, attrs);
} else {
    badText(fb);
}

Where badText(fb) does:

private void badText(FilterBypass fb) throws BadLocationException {
    remove(fb, 0, fb.getDocument().getLength());
    JOptionPane.showMessageDialog(null, "Don't do this!", "Bad Text Entered",
            JOptionPane.WARNING_MESSAGE);
}

The whole example is:

import java.util.Arrays;
import java.util.List;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

@SuppressWarnings("serial")
public class ClearThreeDots extends JPanel {
    private JTextField textField = new JTextField(40);

    public ClearThreeDots() {
        ((PlainDocument) textField.getDocument()).setDocumentFilter(new MyDocFilter());
        add(textField);
    }

    private static void createAndShowGui() {
        ClearThreeDots mainPanel = new ClearThreeDots();

        JFrame frame = new JFrame("Clear Three Dots");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class MyDocFilter extends DocumentFilter {
    private static final List<String> BAD_TEXTS = Arrays.asList("...", "   ", "oops", "OOPS");

    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
            throws BadLocationException {
        String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
        StringBuilder sb = new StringBuilder(currentText);

        String newText = sb.insert(offset, string).toString();

        if (isTextOk(newText)) {
            super.insertString(fb, offset, string, attr);
        } else {
            badText(fb);
        }
    }

    @Override
    public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
        String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
        StringBuilder sb = new StringBuilder(currentText);

        String newText = sb.replace(offset, offset + length, "").toString();

        if (isTextOk(newText)) {
            super.remove(fb, offset, length);
        } else {
            badText(fb);
        }

    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
            throws BadLocationException {
        String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
        StringBuilder sb = new StringBuilder(currentText);

        String newText = sb.replace(offset, offset + length, text).toString();

        if (isTextOk(newText)) {
            super.replace(fb, offset, length, text, attrs);
        } else {
            badText(fb);
        }

    }

    private boolean isTextOk(String text) {
        return !BAD_TEXTS.contains(text);
    }

    private void badText(FilterBypass fb) throws BadLocationException {
        remove(fb, 0, fb.getDocument().getLength());
        JOptionPane.showMessageDialog(null, "Don't do this!", "Bad Text Entered",
                JOptionPane.WARNING_MESSAGE);
    }

}


问:
TimePicker with 30 minute interval not working
I am working on a android application and i want to set the timepicker interval to 30 minutes instead of 1 minute by default. This is my code:

```<code>private void setTimePickerIntervalZeroThirtyMinutes(TimePicker timePicker) {
        int TIME_PICKER_INTERVAL = 30;
        NumberPicker minutePicker = timePicker.findViewById(Resources.getSystem().getIdentifier("minute", "id", "android"));
        minutePicker.setMinValue(0);
        minutePicker.setMaxValue((60 / TIME_PICKER_INTERVAL) + 28);
        List<String> displayedValues = new ArrayList<>();
        for(int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }
        minutePicker.setDisplayedValues(displayedValues.toArray(new String[0]));
    }
</code>```

If I run the above function, it displays the following error:

```<code>java.lang.ArrayIndexOutOfBoundsException: length=2; index=30
        at android.widget.NumberPicker.updateInputTextView(NumberPicker.java:1990)
        at android.widget.NumberPicker.setDisplayedValues(NumberPicker.java:1554)
</code>```

I need to mention that I want to set the min value to 0 and the max value to 30, because otherwise the app won't save the data correctly to the database. Bot when I do that, it gives me the error that i have shown to you. What am I doing wrong here? Thank you in advance!

答:
Your problem is found to be in the loop construction.

loop construct : i = 0

first loop: i += 30 (i = 30)

second loop: i += 30 (i = 60)

60 < 60  = false (exit loop)

therefore your array has only 2 indexes and you trying to access something that does not exist. that is why you get the ArrayIndexOutOfBoundsException. Happy coding.

Body:
I am working on a android application and i want to set the timepicker interval to 30 minutes instead of 1 minute by default. This is my code:

private void setTimePickerIntervalZeroThirtyMinutes(TimePicker timePicker) {
        int TIME_PICKER_INTERVAL = 30;
        NumberPicker minutePicker = timePicker.findViewById(Resources.getSystem().getIdentifier("minute", "id", "android"));
        minutePicker.setMinValue(0);
        minutePicker.setMaxValue((60 / TIME_PICKER_INTERVAL) + 28);
        List<String> displayedValues = new ArrayList<>();
        for(int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            displayedValues.add(String.format("%02d", i));
        }
        minutePicker.setDisplayedValues(displayedValues.toArray(new String[0]));
    }

If I run the above function, it displays the following error:

java.lang.ArrayIndexOutOfBoundsException: length=2; index=30
        at android.widget.NumberPicker.updateInputTextView(NumberPicker.java:1990)
        at android.widget.NumberPicker.setDisplayedValues(NumberPicker.java:1554)

I need to mention that I want to set the min value to 0 and the max value to 30, because otherwise the app won't save the data correctly to the database. Bot when I do that, it gives me the error that i have shown to you. What am I doing wrong here? Thank you in advance!


问:
Fetch Error "Promise returned from fetchData is ignored"
I created a component which is fetching data from an api.

import React, {useState, useEffect} from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        console.log(data)
    };
    fetchData()

    return (

    );
};

export default Users;```

I created fetch function, but anyway i can't get the response from server. After passing about 2 minutes, i'm getting in console 503 error. Why the fetch doesn't work?

答:
I am getting response here by just calling fetch or even hitting https://jsonplaceholder.typicode.com/users in browser

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        console.log(data)
    };
    fetchData()

  ```

Body:
I created a component which is fetching data from an api.

import React, {useState, useEffect} from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        console.log(data)
    };
    fetchData()

    return (

    );
};

export default Users;

I created fetch function, but anyway i can't get the response from server. After passing about 2 minutes, i'm getting in console 503 error. Why the fetch doesn't work?


问:
Does errors.deadletterqueue.topic.name work for source connector
Does "errors.deadletterqueue.topic.name" work for source connector? I tested with JDBC sink connector and it works, but I don't find a record which has serialization error goes to dead letter queue.

I use Debezium Connector for MongoDB and apache-kafka-connect version is 2.4.0.

The rest error handling config:

```<code>"errors.tolerance": "all",
"errors.log.enable": "false",
"errors.deadletterqueue.topic.name": "test-dlq",
"errors.deadletterqueue.context.headers.enable": "true"
</code>```

答:
apache-kafka-connect has included error handling options, including the functionality to route messages to a dead letter queue since Apache Kafka 2.0 through KIP-298: Error Handling in Connect. According this KIP, Dead Letter Queue is supported for Sink Connectors only.

Also you can check Kafka Connect docs:

errors.deadletterqueue.topic.name: The name of the topic to be used as the dead letter queue (DLQ) for messages that result in an error when processed by this sink connector, or its transformations or converters. The topic name is blank by default, which means that no messages are to be recorded in the DLQ.

Great article about Error Handling and Dead Letter Queues by Robin Moffatt

Body:
Does "errors.deadletterqueue.topic.name" work for source connector? I tested with JDBC sink connector and it works, but I don't find a record which has serialization error goes to dead letter queue.

I use Debezium Connector for MongoDB and apache-kafka-connect version is 2.4.0.

The rest error handling config:

"errors.tolerance": "all",
"errors.log.enable": "false",
"errors.deadletterqueue.topic.name": "test-dlq",
"errors.deadletterqueue.context.headers.enable": "true"


问:
C++ - Calculating the inverse of a matrix
I've tried to write a program that should be able to calculate the inverse of a matrix:
Here's what I have so far:

```<code>#include <iostream>
#include <vector>
#include <math.h>
#include <iomanip>
#include <stdexcept>

double getDeterminant(const std::vector<std::vector<double>> vect) {
    if(vect.size() != vect[0].size()) {
        throw std::runtime_error("Matrix is not quadratic");
    }
    int dimension = vect.size();

    if(dimension == 0) {
        return 1;
    }

    if(dimension == 1) {
        return vect[0][0];
    }

    //Formula for 2x2-matrix
    if(dimension == 2) {
        return vect[0][0] * vect[1][1] - vect[0][1] * vect[1][0];
    }

    double result = 0;
    int sign = 1;
    for(int i = 0; i < dimension; i++) {

        //Submatrix
        std::vector<std::vector<double>> subVect(dimension - 1, std::vector<double> (dimension - 1));
        for(int m = 1; m < dimension; m++) {
            int z = 0;
            for(int n = 0; n < dimension; n++) {
                if(n != i) {
                    subVect[m-1][z] = vect[m][n];
                    z++;
                }
            }
        }

        //recursive call
        result = result + sign * vect[0][i] * getDeterminant(subVect);
        sign = -sign;
    }

    return result;
}

std::vector<std::vector<double>> getTranspose(const std::vector<std::vector<double>> matrix1) {

    //Transpose-matrix: height = width(matrix), width = height(matrix)
    std::vector<std::vector<double>> solution(matrix1[0].size(), std::vector<double> (matrix1.size()));

    //Filling solution-matrix
    for(size_t i = 0; i < matrix1.size(); i++) {
        for(size_t j = 0; j < matrix1[0].size(); j++) {
            solution[j][i] = matrix1[i][j];
        }
    }
    return solution;
}

std::vector<std::vector<double>> getCofactor(const std::vector<std::vector<double>> vect) {
    if(vect.size() != vect[0].size()) {
        throw std::runtime_error("Matrix is not quadratic");
    }

    std::vector<std::vector<double>> solution(vect.size(), std::vector<double> (vect.size()));
    std::vector<std::vector<double>> subVect(vect.size() - 1, std::vector<double> (vect.size() - 1));

    for(std::size_t i = 0; i < vect.size(); i++) {
        for(std::size_t j = 0; j < vect[0].size(); j++) {

            int p = 0;
            for(size_t x = 0; x < vect.size(); x++) {
                if(x == i) {
                    continue;
                }
                int q = 0;

                for(size_t y = 0; y < vect.size(); y++) {
                    if(y == j) {
                        continue;
                    }

                    subVect[p][q] = vect[x][y];
                    q++;
                }
                p++;
            }
            solution[i][j] = pow(-1, i + j) * getDeterminant(subVect);
        }
    }
    return solution;
}

std::vector<std::vector<double>> getInverse(const std::vector<std::vector<double>> vect) {
    if(getDeterminant(vect) == 0) {
        throw std::runtime_error("Determinant is 0");
    }
    double d = 1.0/getDeterminant(vect);
    std::vector<std::vector<double>> solution(vect.size(), std::vector<double> (vect.size()));

    for(size_t i = 0; i < vect.size(); i++) {
        for(size_t j = 0; j < vect.size(); j++) {
            solution[i][j] = vect[i][j] * d;
        }
    }

    return getTranspose(getCofactor(solution));
}

void printMatrix(const std::vector<std::vector<double>> vect) {
    for(std::size_t i = 0; i < vect.size(); i++) {
        for(std::size_t j = 0; j < vect[0].size(); j++) {
            std::cout << std::setw(8) << vect[i][j] << " ";
        }
        std::cout << "\n";
    }
}

int main() {
    std::vector<std::vector<double>> matrix(3, std::vector<double> (3));
    matrix = {
        {1,2,3},
        {4,5,6},
        {7,8,8}
    };

    printMatrix(getInverse(matrix));
    return 0;
}
</code>```

The functions for calculating the determinant, the transpose- and the cofactor-matrix work correctly (as far as I can see), but the function for calculating the inverse-matrix doesn't.
I searched the internet and found this, which uses the same function for calculating the inverse.

Is this formula incorrect, or do you have any other idea, why it doesnt work?

The matrix I am using is

and the inverse of it should be

答:
First of all, thanks for your comments.

The problem was the order of execution.
The correct solution is:

```<code>std::vector<std::vector<double>> getInverse(const std::vector<std::vector<double>> vect) {
    if(getDeterminant(vect) == 0) {
        throw std::runtime_error("Determinant is 0");
    }

    double d = 1.0/getDeterminant(vect);
    std::vector<std::vector<double>> solution(vect.size(), std::vector<double> (vect.size()));

    for(size_t i = 0; i < vect.size(); i++) {
        for(size_t j = 0; j < vect.size(); j++) {
            solution[i][j] = vect[i][j];
        }
    }

    solution = getTranspose(getCofactor(solution));

    for(size_t i = 0; i < vect.size(); i++) {
        for(size_t j = 0; j < vect.size(); j++) {
            solution[i][j] *= d;
        }
    }

    return solution;
}
</code>```

Body:
I've tried to write a program that should be able to calculate the inverse of a matrix:
Here's what I have so far:

#include <iostream>
#include <vector>
#include <math.h>
#include <iomanip>
#include <stdexcept>

double getDeterminant(const std::vector<std::vector<double>> vect) {
    if(vect.size() != vect[0].size()) {
        throw std::runtime_error("Matrix is not quadratic");
    }
    int dimension = vect.size();

    if(dimension == 0) {
        return 1;
    }

    if(dimension == 1) {
        return vect[0][0];
    }

    //Formula for 2x2-matrix
    if(dimension == 2) {
        return vect[0][0] * vect[1][1] - vect[0][1] * vect[1][0];
    }

    double result = 0;
    int sign = 1;
    for(int i = 0; i < dimension; i++) {

        //Submatrix
        std::vector<std::vector<double>> subVect(dimension - 1, std::vector<double> (dimension - 1));
        for(int m = 1; m < dimension; m++) {
            int z = 0;
            for(int n = 0; n < dimension; n++) {
                if(n != i) {
                    subVect[m-1][z] = vect[m][n];
                    z++;
                }
            }
        }

        //recursive call
        result = result + sign * vect[0][i] * getDeterminant(subVect);
        sign = -sign;
    }

    return result;
}

std::vector<std::vector<double>> getTranspose(const std::vector<std::vector<double>> matrix1) {

    //Transpose-matrix: height = width(matrix), width = height(matrix)
    std::vector<std::vector<double>> solution(matrix1[0].size(), std::vector<double> (matrix1.size()));

    //Filling solution-matrix
    for(size_t i = 0; i < matrix1.size(); i++) {
        for(size_t j = 0; j < matrix1[0].size(); j++) {
            solution[j][i] = matrix1[i][j];
        }
    }
    return solution;
}

std::vector<std::vector<double>> getCofactor(const std::vector<std::vector<double>> vect) {
    if(vect.size() != vect[0].size()) {
        throw std::runtime_error("Matrix is not quadratic");
    }

    std::vector<std::vector<double>> solution(vect.size(), std::vector<double> (vect.size()));
    std::vector<std::vector<double>> subVect(vect.size() - 1, std::vector<double> (vect.size() - 1));

    for(std::size_t i = 0; i < vect.size(); i++) {
        for(std::size_t j = 0; j < vect[0].size(); j++) {

            int p = 0;
            for(size_t x = 0; x < vect.size(); x++) {
                if(x == i) {
                    continue;
                }
                int q = 0;

                for(size_t y = 0; y < vect.size(); y++) {
                    if(y == j) {
                        continue;
                    }

                    subVect[p][q] = vect[x][y];
                    q++;
                }
                p++;
            }
            solution[i][j] = pow(-1, i + j) * getDeterminant(subVect);
        }
    }
    return solution;
}

std::vector<std::vector<double>> getInverse(const std::vector<std::vector<double>> vect) {
    if(getDeterminant(vect) == 0) {
        throw std::runtime_error("Determinant is 0");
    }
    double d = 1.0/getDeterminant(vect);
    std::vector<std::vector<double>> solution(vect.size(), std::vector<double> (vect.size()));

    for(size_t i = 0; i < vect.size(); i++) {
        for(size_t j = 0; j < vect.size(); j++) {
            solution[i][j] = vect[i][j] * d;
        }
    }

    return getTranspose(getCofactor(solution));
}

void printMatrix(const std::vector<std::vector<double>> vect) {
    for(std::size_t i = 0; i < vect.size(); i++) {
        for(std::size_t j = 0; j < vect[0].size(); j++) {
            std::cout << std::setw(8) << vect[i][j] << " ";
        }
        std::cout << "\n";
    }
}

int main() {
    std::vector<std::vector<double>> matrix(3, std::vector<double> (3));
    matrix = {
        {1,2,3},
        {4,5,6},
        {7,8,8}
    };

    printMatrix(getInverse(matrix));
    return 0;
}

The functions for calculating the determinant, the transpose- and the cofactor-matrix work correctly (as far as I can see), but the function for calculating the inverse-matrix doesn't.
I searched the internet and found this, which uses the same function for calculating the inverse.

Is this formula incorrect, or do you have any other idea, why it doesnt work?

The matrix I am using is

and the inverse of it should be

Body:
First of all, thanks for your comments.

The problem was the order of execution.
The correct solution is:

std::vector<std::vector<double>> getInverse(const std::vector<std::vector<double>> vect) {
    if(getDeterminant(vect) == 0) {
        throw std::runtime_error("Determinant is 0");
    }

    double d = 1.0/getDeterminant(vect);
    std::vector<std::vector<double>> solution(vect.size(), std::vector<double> (vect.size()));

    for(size_t i = 0; i < vect.size(); i++) {
        for(size_t j = 0; j < vect.size(); j++) {
            solution[i][j] = vect[i][j];
        }
    }

    solution = getTranspose(getCofactor(solution));

    for(size_t i = 0; i < vect.size(); i++) {
        for(size_t j = 0; j < vect.size(); j++) {
            solution[i][j] *= d;
        }
    }

    return solution;
}


问:
Give different format to output of SQLite
I have a code like this to ouput data from database where first, is the firstname of an user, and birth the birthday year of the user

```<code>name = db.execute(f'SELECT first, birth FROM mydatabase WHERE house = "{house_roster}"')
print(name[0])
</code>```

and my output of my first row (print[0]) is something like this:

```<code>{'first': 'Cedric', 'birth': 1977}
</code>```

How can I make it just something like this?

```<code>Cedric, 1977
</code>```

答:
```<code>print(', '.join(name[0].values()))
</code>```

It is an universal solution, for any number and any names of fields.

Body:
I have a code like this to ouput data from database where first, is the firstname of an user, and birth the birthday year of the user

name = db.execute(f'SELECT first, birth FROM mydatabase WHERE house = "{house_roster}"')
print(name[0])

and my output of my first row (print[0]) is something like this:

{'first': 'Cedric', 'birth': 1977}

How can I make it just something like this?

Cedric, 1977

Body:
print(', '.join(name[0].values()))

It is an universal solution, for any number and any names of fields.


问:
Magento - Moving Cart_sidebar to top.phtml
I'm looking to move the cart_sidebar up into top.phtml, It's a rather simple move that i've done several times, however I am having 0 luck doing it now that I'm running Magento 1.5.1.

did they change something significant?

see code being used below.

checkout.xml

```<code><reference name="mini_cart_top">
    <block type="checkout/cart_sidebar" name="mini_cart_top"  template="checkout/cart/sidebar.phtml"/>
</reference>
</code>```

page.xml

```<code><block type="page/html_header" name="header" as="header">
    <block type="checkout/cart_sidebar" name="mini_cart_top" as="mini_cart_top" template="checkout/cart/sidebar.phtml"/>
other misc code...
</code>```

top.phtml

```<code><?php echo $this->getChildHtml('mini_cart_top'); ?>
</code>```

any help would be greatly appreciated!

catalog.xml

```<code><reference name="top.menu">
            <block type="catalog/navigation" name="catalog.topnav" template="catalog/navigation/top.phtml"/>
            <block type="checkout/cart_sidebar" name="mini_cart_top" as="mini_cart_top" template="checkout/cart/sidebar.phtml"/>

        </reference>
</code>```

答:
I've moved this successfully in 1.5

You've put the cart_sidebar XML block into the header block which would allow you to use it in header.phtml, not in top.phtml.

top.phtml is a similar block to sidebar.phtml - it should only really contain the categories navigation, not the shopping cart.

If you can clarify where you want to put it and why, I'll tell you how to get it working.

Body:
I'm looking to move the cart_sidebar up into top.phtml, It's a rather simple move that i've done several times, however I am having 0 luck doing it now that I'm running Magento 1.5.1.

did they change something significant?

see code being used below.

checkout.xml

<reference name="mini_cart_top">
    <block type="checkout/cart_sidebar" name="mini_cart_top"  template="checkout/cart/sidebar.phtml"/>
</reference>

page.xml

<block type="page/html_header" name="header" as="header">
    <block type="checkout/cart_sidebar" name="mini_cart_top" as="mini_cart_top" template="checkout/cart/sidebar.phtml"/>
other misc code...

top.phtml

<?php echo $this->getChildHtml('mini_cart_top'); ?>

any help would be greatly appreciated!

catalog.xml

<reference name="top.menu">
            <block type="catalog/navigation" name="catalog.topnav" template="catalog/navigation/top.phtml"/>
            <block type="checkout/cart_sidebar" name="mini_cart_top" as="mini_cart_top" template="checkout/cart/sidebar.phtml"/>

        </reference>


问:
Average of a subset in an array which is out of bounds with constant complexity
This is a follow up question to my previous issue to do with 2d array processing techqniques with o(1) complexity.

That is to get the average of a subset of an array but if this subset extends beyond the bounds of an array taking those as zero. This is with a 2D array.

In reality the array can go up to [2000][2000] but lets take a 2D array that is sized [4][4] for simplicity.

```<code>array[4][4] = {0,  1,  2,  3
               4,  5,  6,  7
               8,  9,  10, 11
               12, 13, 14, 15}
</code>```

Now let's say I want to get the sum of the array between [2][2] and [3][3], i.e. adding 10 + 11 + 14 + 15 and dividing by four. This can be made in a o(1) solution by using a 'summed area table' or 'integral image' techniques.

However I am little confused about how to keep this o(1) complexity providing/when:

the array subset extends outside the actual array

the array indices outside the actual array are taken as zero.

The algorithm computation is still o(1)

So for example lets say for this pixel sum I am asked to get the sum of [2][2] to [4][4]. This has a theoretical array of, numbers outside actual are denoted f (for fake) but are taken as zero:

```<code>array_theory[5][5] = {0,  1,  2,  3,  0f
                      4,  5,  6,  7,  0f
                      8,  9,  10, 11, 0f
                      12, 13, 14, 15, 0f
                      0f, 0f, 0f, 0f, 0f}
</code>```

or in an image:

So now the average between [2][2] and [4][4] is (10 + 11 + 0f + 14 + 15 + 0f + 0f + 0f + 0f)/ 9

I think I have to use some sort of filter or image processing technique that I can't seem to a key word to allow me to find/implement it and am flirting with it in my search results.

Any help would be greatly appreciated!

答:
The solution you have been given previously to compute the sum of the elements in a subarray with one corner at array[i0][j0] and another corner at array[i1][j1] in O(1) time after prior preparation is to prepare an array sums in which sums[i][j] is the sum of all elements in the subarray array[0][0] to array[i][j], after which the sum of an arbitrary subarray may be computed as sums[i1][j1] - sums[i1][j0-1] - sums[i0-1][j1] + sums[i0-1][j0-1], except that any of those terms is replaced with 0 if either of its subscripts is less than zero.

To extend this beyond the greater edges of the array, simply clamp the terms to their maximums: If any subscript exceeds the last valid index of the array, replace it with the last valid index of the array.

We might define an auxiliary function to access sums:

```<code>/*  Return sums[i][j] from an array that is physically r rows and c columns
    but is conceptually extended infinitely on all four sides as if
    arrays[i][j] contained zeros for all elements outside the physical
    array.
*/
Type Sums(ssize_t r, ssize_t c, Type sums[r][c], ssize_t i, ssize_t j)
{
    if (i < 0 || j < 0) return 0;
    if (r <= i) i = r-1;
    if (c <= j) j = c-1;
    return sums[i][j];
}
</code>```

Then the sum of the elements in the subarray from array[i0][j0] to array[i1][j1] is simply Sums[i1][j1] - Sums[i1][j0-1] - Sums[i0-1][j1] + Sums[i0-1][j0-1], and the average is of course (Sums[i1][j1] - Sums[i1][j0-1] - Sums[i0-1][j1] + Sums[i0-1][j0-1]) / ((j1-j0+1) * (i1-i0+1)).

Body:
This is a follow up question to my previous issue to do with 2d array processing techqniques with o(1) complexity.

That is to get the average of a subset of an array but if this subset extends beyond the bounds of an array taking those as zero. This is with a 2D array.

In reality the array can go up to [2000][2000] but lets take a 2D array that is sized [4][4] for simplicity.

array[4][4] = {0,  1,  2,  3
               4,  5,  6,  7
               8,  9,  10, 11
               12, 13, 14, 15}

Now let's say I want to get the sum of the array between [2][2] and [3][3], i.e. adding 10 + 11 + 14 + 15 and dividing by four. This can be made in a o(1) solution by using a 'summed area table' or 'integral image' techniques.

However I am little confused about how to keep this o(1) complexity providing/when:

the array subset extends outside the actual array

the array indices outside the actual array are taken as zero.

The algorithm computation is still o(1)

So for example lets say for this pixel sum I am asked to get the sum of [2][2] to [4][4]. This has a theoretical array of, numbers outside actual are denoted f (for fake) but are taken as zero:

array_theory[5][5] = {0,  1,  2,  3,  0f
                      4,  5,  6,  7,  0f
                      8,  9,  10, 11, 0f
                      12, 13, 14, 15, 0f
                      0f, 0f, 0f, 0f, 0f}

or in an image:

So now the average between [2][2] and [4][4] is (10 + 11 + 0f + 14 + 15 + 0f + 0f + 0f + 0f)/ 9

I think I have to use some sort of filter or image processing technique that I can't seem to a key word to allow me to find/implement it and am flirting with it in my search results.

Any help would be greatly appreciated!

Body:
The solution you have been given previously to compute the sum of the elements in a subarray with one corner at array[i0][j0] and another corner at array[i1][j1] in O(1) time after prior preparation is to prepare an array sums in which sums[i][j] is the sum of all elements in the subarray array[0][0] to array[i][j], after which the sum of an arbitrary subarray may be computed as sums[i1][j1] - sums[i1][j0-1] - sums[i0-1][j1] + sums[i0-1][j0-1], except that any of those terms is replaced with 0 if either of its subscripts is less than zero.

To extend this beyond the greater edges of the array, simply clamp the terms to their maximums: If any subscript exceeds the last valid index of the array, replace it with the last valid index of the array.

We might define an auxiliary function to access sums:

/*  Return sums[i][j] from an array that is physically r rows and c columns
    but is conceptually extended infinitely on all four sides as if
    arrays[i][j] contained zeros for all elements outside the physical
    array.
*/
Type Sums(ssize_t r, ssize_t c, Type sums[r][c], ssize_t i, ssize_t j)
{
    if (i < 0 || j < 0) return 0;
    if (r <= i) i = r-1;
    if (c <= j) j = c-1;
    return sums[i][j];
}

Then the sum of the elements in the subarray from array[i0][j0] to array[i1][j1] is simply Sums[i1][j1] - Sums[i1][j0-1] - Sums[i0-1][j1] + Sums[i0-1][j0-1], and the average is of course (Sums[i1][j1] - Sums[i1][j0-1] - Sums[i0-1][j1] + Sums[i0-1][j0-1]) / ((j1-j0+1) * (i1-i0+1)).


问:
|| operator in c++ for vector norm
I'm trying to write a own "library" for vectors where I can define operators such as "*" for scalar multiplication and "+" for vector addition etc. I think I got most of it right, but now I'm trying to define a operator for the l2 norm of a vector using "| |", meaning this:

```<code>Vector v;
// let v be (3, 4)
double a = |v|;
// then a should be 5 (sqrt(16 + 9))
</code>```

but then I get this error:

```<code>main.cpp:11:17: error: no match for 'operator|' (operand types are 'Vector' and 'int')
     double a = v|2|;
               ~^~
main.cpp:11:20: error: expected primary-expression before ';' token
     double a = v|2|;
</code>```

Now here I'm struggling to define the operator ||...

I tried doing something like this:

```<code>double Vector::operator||(int){
//  here I used the scalar product to calculate the norm
    double d = (*this) * (*this);
    return sqrt(d);
}
</code>```

or I tried defining it as friend function with two parameters. I think the main problem is what parameters I have to give the operator because it always requiers two (or one if its a member function). I just cant figure out a way to do it...

Has anyone of you an idea how solve this or is there no solution for this and I have to use a normal function?

Thanks in advance :)

答:
You can't do that, because C++ doesn't support such a syntax. The best you can do is to create a function called something like magnitude and do your calculations in it. Like this:

```<code>template <typename T>
T magnitude(std::vector<T> const& vec) { ... }

double a = magnitude(v);
</code>```

Title: || operator in c++ for vector norm

Body:
I'm trying to write a own "library" for vectors where I can define operators such as "*" for scalar multiplication and "+" for vector addition etc. I think I got most of it right, but now I'm trying to define a operator for the l2 norm of a vector using "| |", meaning this:

Vector v;
// let v be (3, 4)
double a = |v|;
// then a should be 5 (sqrt(16 + 9))

but then I get this error:

main.cpp:11:17: error: no match for 'operator|' (operand types are 'Vector' and 'int')
     double a = v|2|;
               ~^~
main.cpp:11:20: error: expected primary-expression before ';' token
     double a = v|2|;

Now here I'm struggling to define the operator ||...

I tried doing something like this:

double Vector::operator||(int){
//  here I used the scalar product to calculate the norm
    double d = (*this) * (*this);
    return sqrt(d);
}

or I tried defining it as friend function with two parameters. I think the main problem is what parameters I have to give the operator because it always requiers two (or one if its a member function). I just cant figure out a way to do it...

Has anyone of you an idea how solve this or is there no solution for this and I have to use a normal function?

Thanks in advance :)

Body:
You can't do that, because C++ doesn't support such a syntax. The best you can do is to create a function called something like magnitude and do your calculations in it. Like this:

template <typename T>
T magnitude(std::vector<T> const& vec) { ... }

double a = magnitude(v);