问:
Grid Layout+Card Doesnt show images
please help,

I am making a webview app for my college project, each grid items on click will launch separate webviews.
but I am stuck in the grid layout itself.
I tried many solutions but couldn't figure out the issue..
Please see the screenshot

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'

```<code>defaultConfig {
    applicationId "com.example.ikkantekada"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility = 1.7
    targetCompatibility = 1.7
}
</code>```

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

```<code>implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-auth:19.3.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-invites:16.0.0'
implementation 'com.google.firebase:firebase-crash:16.2.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.gridlayout:gridlayout:1.0.0'
</code>```

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:weightSum="10"
    tools:context=".ProfileActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_weight="2">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="313dp"
            android:layout_height="59dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="64dp"
            android:layout_marginTop="22dp"
            app:srcCompat="@drawable/logopng" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="13dp"
            android:layout_marginBottom="27dp"
            android:gravity="center"
            android:text="സ്വാഗതം, നിങ്ങൾക്കിഷ്ടമുള്ളവ തിരഞ്ഞെടുക്കൂ "
            android:textSize="18dp" />

        <Button
            android:id="@+id/SignOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="13dp"
            android:layout_marginBottom="49dp"
            android:text="Sign Out"
            android:textAllCaps="false"
            android:textSize="15sp"
            app:layout_constraintStart_toStartOf="@+id/textView2"
            app:layout_constraintTop_toBottomOf="@+id/textView2" />

    </RelativeLayout>

    <GridLayout
        android:id="@+id/mainGrid"
        android:rowCount="3"
        android:columnCount="2"
        android:alignmentMode="alignMargins"
        android:columnOrderPreserved="false"
        android:layout_weight="8"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:padding="14dp">

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/bag"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/bag"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text2"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/news"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text3"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/cooking.png"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text4"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/bag"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/cake"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text2"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

    </GridLayout>
</LinearLayout>```

答:
In your gradle file you have imported CardView dependency for androidx, but in your XML file you are using android.support.v7.widget.CardView

Change it to androidx.cardview.widget.CardView and give it a try.

Title: Grid Layout+Card Doesnt show images

Body:
please help,

I am making a webview app for my college project, each grid items on click will launch separate webviews.
but I am stuck in the grid layout itself.
I tried many solutions but couldn't figure out the issue..
Please see the screenshot

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'

defaultConfig {
    applicationId "com.example.ikkantekada"
    minSdkVersion 21
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
compileOptions {
    sourceCompatibility = 1.7
    targetCompatibility = 1.7
}

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-auth:19.3.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.0'
implementation 'com.google.firebase:firebase-invites:16.0.0'
implementation 'com.google.firebase:firebase-crash:16.2.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.gridlayout:gridlayout:1.0.0'

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:weightSum="10"
    tools:context=".ProfileActivity">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_weight="2">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="313dp"
            android:layout_height="59dp"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginStart="64dp"
            android:layout_marginTop="22dp"
            app:srcCompat="@drawable/logopng" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="13dp"
            android:layout_marginBottom="27dp"
            android:gravity="center"
            android:text="സ്വാഗതം, നിങ്ങൾക്കിഷ്ടമുള്ളവ തിരഞ്ഞെടുക്കൂ "
            android:textSize="18dp" />

        <Button
            android:id="@+id/SignOut"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="13dp"
            android:layout_marginBottom="49dp"
            android:text="Sign Out"
            android:textAllCaps="false"
            android:textSize="15sp"
            app:layout_constraintStart_toStartOf="@+id/textView2"
            app:layout_constraintTop_toBottomOf="@+id/textView2" />

    </RelativeLayout>

    <GridLayout
        android:id="@+id/mainGrid"
        android:rowCount="3"
        android:columnCount="2"
        android:alignmentMode="alignMargins"
        android:columnOrderPreserved="false"
        android:layout_weight="8"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:padding="14dp">

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/bag"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/bag"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text2"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/news"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text3"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/cooking.png"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text4"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/bag"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

        <android.support.v7.widget.CardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_columnWeight="1"
            android:layout_marginBottom="16dp"
            android:layout_rowWeight="1"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            app:cardElevation="8dp"
            app:cardCornerRadius="8dp">

            <LinearLayout
                android:layout_gravity="center_horizontal|center_vertical"
                android:layout_margin="16dp"
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <ImageView
                    android:src="@drawable/cake"
                    android:layout_gravity="center_horizontal"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

                <TextView
                    android:textAlignment="center"
                    android:text="Text2"
                    android:textColor="#000"
                    android:textSize="18sp"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

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

    </GridLayout>
</LinearLayout>


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: applying cut() on R dataframe daywise

Body:
I have a datatable in R on which I apply a cut() and table(). I am able to get the frequency table based on the conditions. But I am getting overall frequencies. I want to get it day wise. I have a column named as timestamp which have timestamp. Also I have a section column which has value either A or B. How to cut it based on each day each section.

My current output :

Var1    Freq
0-30    1398
30-60   1051
60-80   1006
80-100  36
100>    2

Expected output:

Date        Sec  Var1    Freq
05-01-2020   A   0-30    1398
05-01-2020   A   30-60   1051
05-01-2020   A   60-80   1006
05-01-2020   A   80-100  36
05-01-2020   A   100>    2
05-01-2020   B   0-30    138
05-01-2020   B   30-60   151
05-01-2020   B   60-80   1056
05-01-2020   B   80-100  3
05-01-2020   B   100>    6
06-01-2020   A   0-30    398
06-01-2020   A   30-60   11
06-01-2020   A   60-80   16
06-01-2020   A   80-100  3666
06-01-2020   A   100>    25
06-01-2020   B   0-30    1948
06-01-2020   B   30-60   233
06-01-2020   B   60-80   33
06-01-2020   B   80-100  433
06-01-2020   B   100>    34
and so on.....

My code :

result = as.data.frame(table(cut(df$temp,breaks=c(0,30,60,80,100,1000),labels=c("0-30","30-60","60-80","80-100","100>"))))

Sample data :

timestamp        section    temp
01-05-2020 00:01:22 A   45
02-05-2020 00:01:22 A   10
03-05-2020 00:01:22 A   98
04-05-2020 00:01:22 A   23
05-05-2020 00:01:22 A   67
06-05-2020 00:01:22 A   89
07-05-2020 00:01:22 A   100
08-05-2020 00:01:22 A   110
09-05-2020 00:01:22 A   123
10-05-2020 00:01:22 A   12
01-05-2020 00:01:22 B   23
02-05-2020 00:01:22 B   44
03-05-2020 00:01:22 B   55
04-05-2020 00:01:22 B   12
05-05-2020 00:01:22 B   98
06-05-2020 00:01:22 B   45
07-05-2020 00:01:22 B   87
08-05-2020 00:01:22 B   65
09-05-2020 00:01:22 B   12
10-05-2020 00:01:22 B   8

Body:
Here is one option.  We do the grouping by 'Date' and the cut on the 'temp' column, then summarise to get the frequency with n()

library(dplyr)
library(lubridate)
df %>%
    group_by(Date = as.Date(dmy_hms(timestamp)), section,
     Var1 = cut(temp, breaks=c(0,30,60,80,100,1000),
           labels=c("0-30","30-60","60-80", "80-100", "100>"))) %>%
    summarise(Freq = n())
# A tibble: 20 x 4
# Groups:   Date, section [20]
#   Date       section Var1    Freq
#   <date>     <chr>   <fct>  <int>
# 1 2020-05-01 A       30-60      1
# 2 2020-05-01 B       0-30       1
# 3 2020-05-02 A       0-30       1
# 4 2020-05-02 B       30-60      1
# 5 2020-05-03 A       80-100     1
# 6 2020-05-03 B       30-60      1
# 7 2020-05-04 A       0-30       1
# 8 2020-05-04 B       0-30       1
# 9 2020-05-05 A       60-80      1
#10 2020-05-05 B       80-100     1
#11 2020-05-06 A       80-100     1
#12 2020-05-06 B       30-60      1
#13 2020-05-07 A       80-100     1
#14 2020-05-07 B       80-100     1
#15 2020-05-08 A       100>       1
#16 2020-05-08 B       60-80      1
#17 2020-05-09 A       100>       1
#18 2020-05-09 B       0-30       1
#19 2020-05-10 A       0-30       1
#20 2020-05-10 B       0-30       1

data

df <- structure(list(timestamp = c("01-05-2020 00:01:22", "02-05-2020 00:01:22",
"03-05-2020 00:01:22", "04-05-2020 00:01:22", "05-05-2020 00:01:22",
"06-05-2020 00:01:22", "07-05-2020 00:01:22", "08-05-2020 00:01:22",
"09-05-2020 00:01:22", "10-05-2020 00:01:22", "01-05-2020 00:01:22",
"02-05-2020 00:01:22", "03-05-2020 00:01:22", "04-05-2020 00:01:22",
"05-05-2020 00:01:22", "06-05-2020 00:01:22", "07-05-2020 00:01:22",
"08-05-2020 00:01:22", "09-05-2020 00:01:22", "10-05-2020 00:01:22"
), section = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A",
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B"), temp = c(45L,
10L, 98L, 23L, 67L, 89L, 100L, 110L, 123L, 12L, 23L, 44L, 55L,
12L, 98L, 45L, 87L, 65L, 12L, 8L)), class = "data.frame", row.names = c(NA,
-20L))


问:
How to snooze prometheus alert for specific time
I have faced some issues with Prometheus memory alert. If I take the backup of Gitlab then memory usage going up to 95%. I want to snooze memory alert for a specific time.

e.g. If I am taking a backup at 2 AM then I need to snooze Prometheus memory alert. Is it possible?

答:
You can compare conditions back in history and therefore alert won't popup if metrics doesn't differ more than 2 times for the past two days at this time.</p>

```<code>      - alert: CPULoadAlert
        # Condition for alerting
        expr: >-
          node_load5 / node_load5 offset 1d > 2 and
          node_load5 / node_load5 offset 2d > 2 and
          node_load5 > 1
        for: 5m
        # Annotation - additional informational labels to store more information
        annotations:
          summary: 'Instance {{ $labels.instance }} got an unusual high load on CPU'
          description: '{{ $labels.instance }} of job {{ $labels.job }} got CPU spike over 2x compared to previous 2 days.'
        # Labels - additional labels to be attached to the alert
        labels:
          severity: 'warning'
</code>```

Body:
You can compare conditions back in history and therefore alert won't popup if metrics doesn't differ more than 2 times for the past two days at this time.

      - alert: CPULoadAlert
        # Condition for alerting
        expr: >-
          node_load5 / node_load5 offset 1d > 2 and
          node_load5 / node_load5 offset 2d > 2 and
          node_load5 > 1
        for: 5m
        # Annotation - additional informational labels to store more information
        annotations:
          summary: 'Instance {{ $labels.instance }} got an unusual high load on CPU'
          description: '{{ $labels.instance }} of job {{ $labels.job }} got CPU spike over 2x compared to previous 2 days.'
        # Labels - additional labels to be attached to the alert
        labels:
          severity: 'warning'


问:
How to find total size of user attachments in active storage
I'm using Rails 6.
How to get the total size of user attachments in active storage?

======

Update:

If I have User A and User B

How to get the total size of  User A attachments?

答:
Here is how I do it based in @Yshmarov and @mechnicov answers

In model

```<code>after_create_commit :add_user

private
def add_user
files.attachments.update(user_id: self.user.id)
end
</code>```

In controller

```<code>    @checksize = ActiveStorage::Blob.where(id: current_user.id).map(&:byte_size).sum
</code>```

In view

```<code>  <%= number_to_human_size(@checksize) %>
</code>```

Body:
Here is how I do it based in @Yshmarov and @mechnicov answers

In model

after_create_commit :add_user

private
def add_user
files.attachments.update(user_id: self.user.id)
end

In controller

    @checksize = ActiveStorage::Blob.where(id: current_user.id).map(&:byte_size).sum

In view

  <%= number_to_human_size(@checksize) %>


问:
Filter query by count associated data CakePHP 3
I want to do a query on “Articles” but I only want the “Articles” which have two or more “Comments”. So I have to count “Comments” and use the count result in the where clause.

I know the next code is wrong but it would be something like:

```<code>$articles = $this->Articles->find();

$articles->matching('Comments', function ($q) {
    $commentsCount = $q->func()->count('Comments.id');
    return $q->where($commentsCount . ' >= ' => 2);
});
</code>```

I can´t find any information about this.

答:
It always helps to first figure out how you'd do it in raw SQL, that will make it way easier to figure how to replicate it with CakePHP's query builder.

For example, you cannot use an aggregate in the WHERE clause, that's forbidden in all supported DBMS. WHERE is evaluated before grouping is applied (ie before anything can be counted), you'd have to check the aggregate in the HAVING clause instead, which is evaluated after grouping.

Usually you'd do something along the lines of this in SQL:

SELECT
    Articles.id, ...
FROM
    articles Articles
LEFT JOIN
    comments Comments ON Comments.article_id = Articles.id
GROUP BY
    Articles.id
HAVING
    COUNT(Comments.id) >= 2
```

<p>This can be easily achieved with the query builder like this:</p>

<pre class="lang-php prettyprint-override"><code>$query = $this->Articles
    ->find()
    ->leftJoinWith('Comments')
    ->group('Articles.id')
    ->having(function (
        \Cake\Database\Expression\QueryExpression $exp,
        \Cake\ORM\Query $query
    ) {
        return $exp->gte(
            $query->func()->count('Comments.id'),
            2,
            'integer'
        );
    });
</code>```

Such a query can be very expensive on large tables, as it cannot use any indices, and thus requires a full table scan, ie it has to check every single row. One way to avoid that is using counter caching, which stores the number of associated records in the source table, that way you can compare against an indexable column in the Articles table, ie you could then simply do:

$query = $this->Articles
    ->find()
    ->where([
        'Articles.comment_count >=' => 2,
    ]);
```

See also

Cookbook > Database Access & ORM > Query Builder > Selecting Data > Aggregates - Group and Having

Cookbook > Database Access & ORM > Query Builder > Advanced Conditions

Cookbook > Database Access & ORM > Query Builder > Behaviors > CounterCache

Body:
I want to do a query on “Articles” but I only want the “Articles” which have two or more “Comments”. So I have to count “Comments” and use the count result in the where clause.

I know the next code is wrong but it would be something like:

$articles = $this->Articles->find();

$articles->matching('Comments', function ($q) {
    $commentsCount = $q->func()->count('Comments.id');
    return $q->where($commentsCount . ' >= ' => 2);
});

I can´t find any information about this.

Body:
It always helps to first figure out how you'd do it in raw SQL, that will make it way easier to figure how to replicate it with CakePHP's query builder.

For example, you cannot use an aggregate in the WHERE clause, that's forbidden in all supported DBMS. WHERE is evaluated before grouping is applied (ie before anything can be counted), you'd have to check the aggregate in the HAVING clause instead, which is evaluated after grouping.

Usually you'd do something along the lines of this in SQL:

SELECT
    Articles.id, ...
FROM
    articles Articles
LEFT JOIN
    comments Comments ON Comments.article_id = Articles.id
GROUP BY
    Articles.id
HAVING
    COUNT(Comments.id) >= 2

This can be easily achieved with the query builder like this:

$query = $this->Articles
    ->find()
    ->leftJoinWith('Comments')
    ->group('Articles.id')
    ->having(function (
        \Cake\Database\Expression\QueryExpression $exp,
        \Cake\ORM\Query $query
    ) {
        return $exp->gte(
            $query->func()->count('Comments.id'),
            2,
            'integer'
        );
    });

Such a query can be very expensive on large tables, as it cannot use any indices, and thus requires a full table scan, ie it has to check every single row. One way to avoid that is using counter caching, which stores the number of associated records in the source table, that way you can compare against an indexable column in the Articles table, ie you could then simply do:

$query = $this->Articles
    ->find()
    ->where([
        'Articles.comment_count >=' => 2,
    ]);

See also

Cookbook > Database Access & ORM > Query Builder > Selecting Data > Aggregates - Group and Having

Cookbook > Database Access & ORM > Query Builder > Advanced Conditions

Cookbook > Database Access & ORM > Query Builder > Behaviors > CounterCache


问:
React Native googleUser.getBasicProfile is not a function
whenever i run the code, the google window pops us and I can select the account. After I select the account i this error:
"googleUser.getBasicProfile is not a function."

Here is my code:

```<code>    isUserEqual=(googleUser, firebaseUser) =>{
        if (firebaseUser) {
          var providerData = firebaseUser.providerData;
          for (var i = 0; i < providerData.length; i++) {
            if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
                providerData[i].uid === googleUser.getBasicProfile().getId()) {
              // We don't need to reauth the Firebase connection.

              return true;
            }
          }
        }
        return false;
      }
</code>```

答:
In Expo Documentation we can see that the return object of function Google.logInAsync is the googleUser of your method (i suppose, because i have the same issue with this function in Firebase Documentation), and note that does not have any method in return of logInAsync to match with him.
So i match the providerData[i].uid with googleUser.user.id.

this is the rewritten code:

```<code>for (var i = 0; i < providerData.length; i++) {
   if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
      providerData[i].uid === googleUser.user.id) {
      return true;
   }
 }
</code>```

Body:
whenever i run the code, the google window pops us and I can select the account. After I select the account i this error:
"googleUser.getBasicProfile is not a function."

Here is my code:

    isUserEqual=(googleUser, firebaseUser) =>{
        if (firebaseUser) {
          var providerData = firebaseUser.providerData;
          for (var i = 0; i < providerData.length; i++) {
            if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
                providerData[i].uid === googleUser.getBasicProfile().getId()) {
              // We don't need to reauth the Firebase connection.

              return true;
            }
          }
        }
        return false;
      }

Body:
In Expo Documentation we can see that the return object of function Google.logInAsync is the googleUser of your method (i suppose, because i have the same issue with this function in Firebase Documentation), and note that does not have any method in return of logInAsync to match with him.
So i match the providerData[i].uid with googleUser.user.id.

this is the rewritten code:

for (var i = 0; i < providerData.length; i++) {
   if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
      providerData[i].uid === googleUser.user.id) {
      return true;
   }
 }


问:
Unordered_set questions
Could anyone explain how an unordered set works? I am also not sure how a set works. My main question is what is the efficiency of its find function.

For example, what is the total big O run time of this?

```<code>    vector<int> theFirst;
    vector<int> theSecond;
    vector<int> theMatch;

    theFirst.push_back( -2147483648 );
    theFirst.push_back(2);
    theFirst.push_back(44);

    theSecond.push_back(2);
    theSecond.push_back( -2147483648 );
    theSecond.push_back( 33 );

    //1) Place the contents into a unordered set that is O(m).
    //2) O(n) look up so thats O(m + n).
    //3) Add them to third structure so that's O(t)
    //4) All together it becomes O(m + n + t)
    unordered_set<int> theUnorderedSet(theFirst.begin(), theFirst.end());

    for(int i = 0; i < theSecond.size(); i++)
    {
        if(theUnorderedSet.find(theSecond[i]) != theUnorderedSet.end())
        {
        theMatch.push_back( theSecond[i] );
        cout << theSecond[i];
        }
   }
</code>```

答:
unordered_set and all the other unordered_ data structures use hashing, as mentioned by @Sean. Hashing involves amortized constant time for insertion, and close to constant time for lookup. A hash function essentially takes some information and produces a number from it. It is a function in the sense that the same input has to produce the same output. However, different inputs can result in the same output, resulting in what is termed a collision. Lookup would be guaranteed to be constant time for an "perfect hash function", that is, one with no collisions. In practice, the input number comes from the element you store in the structure (say it's value, it is a primitive type) and maps it to a location in a data structure. Hence, for a given key, the function takes you to the place where the element is stored without need for any traversals or searches (ignoring collisions here for simplicity), hence constant time. There are different implementations of these structures (open addressing, chaining, etc.) See hash table, hash function. I also recommend section 3.7 of The Algorithm Design Manual by Skiena. Now, concerning big-O complexity, you are right that you have O(n) + O(n) + O(size of overlap). Since the overlap cannot be bigger than the smaller of m and n, the overall complexity can be expressed as O(kN), where N is the largest between m and n. So, O(N). Again, this is "best case", without collisions, and with perfect hashing.

set and multi_set on the other hand use binary trees, so insertions and look-ups are typically O(logN). The actual performance of a hashed structure vs. a binary tree one will depend on N, so it is best to try the two approaches and profile them in a realistic running scenario.

ContentLicense: CC BY-SA 3.0

Title: Unordered_set questions

Body:
Could anyone explain how an unordered set works? I am also not sure how a set works. My main question is what is the efficiency of its find function.

For example, what is the total big O run time of this?

    vector<int> theFirst;
    vector<int> theSecond;
    vector<int> theMatch;

    theFirst.push_back( -2147483648 );
    theFirst.push_back(2);
    theFirst.push_back(44);

    theSecond.push_back(2);
    theSecond.push_back( -2147483648 );
    theSecond.push_back( 33 );

    //1) Place the contents into a unordered set that is O(m).
    //2) O(n) look up so thats O(m + n).
    //3) Add them to third structure so that's O(t)
    //4) All together it becomes O(m + n + t)
    unordered_set<int> theUnorderedSet(theFirst.begin(), theFirst.end());

    for(int i = 0; i < theSecond.size(); i++)
    {
        if(theUnorderedSet.find(theSecond[i]) != theUnorderedSet.end())
        {
        theMatch.push_back( theSecond[i] );
        cout << theSecond[i];
        }
   }


问:
Can we type if statement inside the function an argument
For example

```<code>def person(name,if age == 18:...//some instructions and this parameter will be default parameter):
   print(age)
   print(name)

person('Ratheesh')
</code>```

// I Know it sounds dump and silly, but is there any possibility to do that?

I was trying to confirm the user has entered the exact value in argument as i entered...But fortunately i have done it with default argument but whenever i change the parameter value it overrides so, i want to avoid the override...

答:
Why do you want to use the if condition as a parameter. Whatever you are trying to achieve can be done using the if condition inside the code as below :

```<code>def person(name,age):
   if age == 18:
       #some instructions
   print(age)
   print(name)

person('Ratheesh',10)
</code>```

To answer your question, NO, you cannot pass an if condition as an argument. Maybe you can refer the below code if you are trying to put a default parameter value :

```<code>def person(name,age=18): #this will set the default value of age to 18 in case it isn't mention in the call
   if age == 18:
       #some instructions
   print(age)
   print(name)

person('Ratheesh')
</code>```

Hope this solves your problem !

Body:
For example

def person(name,if age == 18:...//some instructions and this parameter will be default parameter):
   print(age)
   print(name)

person('Ratheesh')

// I Know it sounds dump and silly, but is there any possibility to do that?

I was trying to confirm the user has entered the exact value in argument as i entered...But fortunately i have done it with default argument but whenever i change the parameter value it overrides so, i want to avoid the override...

Body:
Why do you want to use the if condition as a parameter. Whatever you are trying to achieve can be done using the if condition inside the code as below :

def person(name,age):
   if age == 18:
       #some instructions
   print(age)
   print(name)

person('Ratheesh',10)

To answer your question, NO, you cannot pass an if condition as an argument. Maybe you can refer the below code if you are trying to put a default parameter value :

def person(name,age=18): #this will set the default value of age to 18 in case it isn't mention in the call
   if age == 18:
       #some instructions
   print(age)
   print(name)

person('Ratheesh')

Hope this solves your problem !


问:
Transform C# List<KeyValuePair<int,string> to TypeScript Object that can be used in Angular 8 DropDownList using ngFor
I have a simple list of KeyValuePair that is being created in MVC Controller and passed to an Angular component.ts. Within Angular I can manually create a key value pair to use in dropdown list as:

```<code>object: { [key: number]: string } = { 2: 'foo', 1: 'bar' };
</code>```

This is what I have in the component.html:

```<code> <option *ngFor="let program of object | keyvalue " value={{program.key}}>{{program.value}}</option>
</code>```

With this method, I get exactly what I expect -- a drop down list. If I use the KeyValyePair that I received from MVC controller the drop down list displays [ object Object] instead of the value I am looking for.
So my question is, how to I transform my KeyValuePair list into the { [key: number], string} format the TypeScript uses?

This is my first attempt at using Angular in DotNet Core 3.1 MVC App and unfortunately at this point I have only a basic knowledge of TypeScript.

答:
object: {[key: number]: string}[];</p>

```<code><ng-container *ngFor="let program of object">
  <option [value]="program.key|keyvalue">{{program.value | keyvalue}}</option>
</ng-container>
</code>```

Body:
I have a simple list of KeyValuePair that is being created in MVC Controller and passed to an Angular component.ts. Within Angular I can manually create a key value pair to use in dropdown list as:

object: { [key: number]: string } = { 2: 'foo', 1: 'bar' };

This is what I have in the component.html:

 <option *ngFor="let program of object | keyvalue " value={{program.key}}>{{program.value}}</option>

With this method, I get exactly what I expect -- a drop down list. If I use the KeyValyePair that I received from MVC controller the drop down list displays [ object Object] instead of the value I am looking for.
So my question is, how to I transform my KeyValuePair list into the { [key: number], string} format the TypeScript uses?

This is my first attempt at using Angular in DotNet Core 3.1 MVC App and unfortunately at this point I have only a basic knowledge of TypeScript.

Body:
object: {[key: number]: string}[];

<ng-container *ngFor="let program of object">
  <option [value]="program.key|keyvalue">{{program.value | keyvalue}}</option>
</ng-container>


答:
You can technically have an if inside the expression where you define a function's default argument, but note that the expression will be evaluated when the function is defined:

```<code>>>> default = "drinking age"
>>> def person(name: str, age: int = 21 if default == "drinking age" else 18):
...     print(name, age)
...
>>> person("Bob")
Bob 21
>>> default = "voting age"
>>> person("Bob")
Bob 21
</code>```

For practical purposes it's hard to imagine why you'd ever want to do something like this.  It'd make more sense to do that evaluation inside the body of the function:

```<code>>>> def person(name: str, age: Optional[int] = None):
...     if age is None:
...         age = 21 if default == "drinking age" else 18
...     print(name, age)
...
>>> person("Bob")
Bob 18
>>> default = "drinking age"
>>> person("Bob")
Bob 21
</code>```

Title: Can we type if statement inside the function an argument

Body:
You can technically have an if inside the expression where you define a function's default argument, but note that the expression will be evaluated when the function is defined:

>>> default = "drinking age"
>>> def person(name: str, age: int = 21 if default == "drinking age" else 18):
...     print(name, age)
...
>>> person("Bob")
Bob 21
>>> default = "voting age"
>>> person("Bob")
Bob 21

For practical purposes it's hard to imagine why you'd ever want to do something like this.  It'd make more sense to do that evaluation inside the body of the function:

>>> def person(name: str, age: Optional[int] = None):
...     if age is None:
...         age = 21 if default == "drinking age" else 18
...     print(name, age)
...
>>> person("Bob")
Bob 18
>>> default = "drinking age"
>>> person("Bob")
Bob 21


问:
Bad input warning in python
The question for the code is attached below .

Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence:    0.8475

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

```<code>fname = input("Enter file name: ")
fh = open(fname,'r')
count=0
val=0
for line in fh:
    if line.find("X-DSPAM-Confidence:")==-1:
        continue
    else:
        count+=1
        pos=line.find(':')
        val+=float(line[pos+1:]
res=float(val/count)
print('Average spam confidence: ',res)
fh.close()
</code>```

I am getting an error stating "bad input on line 13".
can anyone help me out as to why this is happening? Thank you in advance

答: You're missing a closing parentheses. It should be "val+=float(line[pos+1:])"</p>

Title: Bad input warning in python

Body:
The question for the code is attached below .

Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:

X-DSPAM-Confidence:    0.8475

Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.

You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.

fname = input("Enter file name: ")
fh = open(fname,'r')
count=0
val=0
for line in fh:
    if line.find("X-DSPAM-Confidence:")==-1:
        continue
    else:
        count+=1
        pos=line.find(':')
        val+=float(line[pos+1:]
res=float(val/count)
print('Average spam confidence: ',res)
fh.close()

I am getting an error stating "bad input on line 13".
can anyone help me out as to why this is happening? Thank you in advance


问:
How to order contacts by last message date with Sequelize?
I'm trying to create a chat app in nodejs with Sequelize for my db.

Everything works great but when i try to show all user friends ordered by the last message date i have a bug.

To get the users with there messages it works with associations but ordering doesn't.
Here is my function to get messages:

```<code>const getFriends = (id, limit) => {
return new Promise(async (resolve, reject) => {
    try {
       const user = await Follows.findAll({
            where: {
                [Op.or]: {
                    follower_id: id,
                    followed_id: id
                },
            },
            include: Messages
            order: [[Messages, 'createdAt', 'DESC']],
            limit
        })
        resolve(user)
    } catch (e) {
        reject(e)
    }

})
}
</code>```

So Seqeulize does the query but not in the way that I want to.
Here is the query generated by Sequelize:

```<code>SELECT `follows`.*,
       `messages`.*
FROM (
   SELECT `follows`.* FROM `follows`
   WHERE (
         `follows`.`follower_id` = 3
            OR
         `follows`.`followed_id` = 3
   )
   AND `follows`.`reciprocal` = true
   LIMIT 1
)
LEFT OUTER JOIN `messages` ON `follows`.`id` = `messages`.`pairId`
ORDER BY `messages`.`createdAt` DESC;
</code>```

As you see here the ORDER BY messages.createdAt DESC; happens at the end, but after the FROM you can see he does a query to the table i'm already querying.

Which is not LOGIC !!

I would like to my sql query to look like that:

```<code>SELECT `follows`.*,
       `messages`.*
FROM `follows`
LEFT OUTER JOIN `messages` ON `follows`.`id` = `messages`.`pairId`
WHERE (
      `follows`.`follower_id` = 3
         OR
      `follows`.`followed_id` = 3
)
AND `follows`.`reciprocal` = true
ORDER BY `messages`.`createdAt` DESC
LIMIT 1
</code>```

That means that I want my where and my limit to be in the parent query and not in the FROM query.
I really don't know how to do this with Sequelize and didn't find someone having same issue on the internet.
I would be really happy to have some help!

答:
Actualy I found the answer.
I just needed to add subQuery:false and it worked as I wanted !

Body:
I'm trying to create a chat app in nodejs with Sequelize for my db.

Everything works great but when i try to show all user friends ordered by the last message date i have a bug.

To get the users with there messages it works with associations but ordering doesn't.
Here is my function to get messages:

const getFriends = (id, limit) => {
return new Promise(async (resolve, reject) => {
    try {
       const user = await Follows.findAll({
            where: {
                [Op.or]: {
                    follower_id: id,
                    followed_id: id
                },
            },
            include: Messages
            order: [[Messages, 'createdAt', 'DESC']],
            limit
        })
        resolve(user)
    } catch (e) {
        reject(e)
    }

})
}

So Seqeulize does the query but not in the way that I want to.
Here is the query generated by Sequelize:

SELECT `follows`.*,
       `messages`.*
FROM (
   SELECT `follows`.* FROM `follows`
   WHERE (
         `follows`.`follower_id` = 3
            OR
         `follows`.`followed_id` = 3
   )
   AND `follows`.`reciprocal` = true
   LIMIT 1
)
LEFT OUTER JOIN `messages` ON `follows`.`id` = `messages`.`pairId`
ORDER BY `messages`.`createdAt` DESC;

As you see here the ORDER BY messages.createdAt DESC; happens at the end, but after the FROM you can see he does a query to the table i'm already querying.

Which is not LOGIC !!

I would like to my sql query to look like that:

SELECT `follows`.*,
       `messages`.*
FROM `follows`
LEFT OUTER JOIN `messages` ON `follows`.`id` = `messages`.`pairId`
WHERE (
      `follows`.`follower_id` = 3
         OR
      `follows`.`followed_id` = 3
)
AND `follows`.`reciprocal` = true
ORDER BY `messages`.`createdAt` DESC
LIMIT 1

That means that I want my where and my limit to be in the parent query and not in the FROM query.
I really don't know how to do this with Sequelize and didn't find someone having same issue on the internet.
I would be really happy to have some help!


问:
Simple Banking Application in Visual Basic
I hope that someone can point me in the right direction, as I am new to programming.

I made a basic banking application. It displays a balance for the account, has a textbox for the user to enter the amount, and 2 buttons: one for depositing an amount into the account and one for withdrawing an amount. If the user tries to deposit or withdraw a negative number or "0" then it gives an error that it isn't a valid amount. If the user tries to withdraw more than is in the account, it gives an error that they cannot withdraw more money than is in the account.

My problem is that all the error messages are working for the deposit button, but not for the withdraw button. I used nested If structure, output to a label at the bottom.

I tried using breakpoints to examine my variables, but didn't find any issues.

I don't really want the answer, just some help to understand why the Deposit button will give the error but the Withdraw button won't show either error.

```<code>Public Class Form1
    ' Prologue
    ' This is a simple banking application.
    ' It displays a balance for the account, calculates deposits and withdraws, and gives errors for invalid amounts and overdraws

    ' Modular Declarations
    Dim mdecBalance As Decimal = 1000

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
    End Sub

    Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
        ' Declarations
        Dim decDeposit As Decimal
        Dim strDepProblem As String

        ' Input
        decDeposit = txtAmount.Text

        ' Processing
        If decDeposit > 0 Then
            mdecBalance = mdecBalance + decDeposit
        Else
            If decDeposit <= 0 Then
                strDepProblem = "That is not a valid amount to deposit"
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strDepProblem

    End Sub

    Private Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
        ' Declarations
        Dim decWithdraw As Decimal
        Dim strWithdrawNegative As String
        Dim strWithdrawMoreThan As String

        ' Input
        decWithdraw = txtAmount.Text

        ' Processing
        If decWithdraw > 0 Then
            mdecBalance = mdecBalance - decWithdraw
        Else
            If decWithdraw <= 0 Then
                strWithdrawNegative = "Cannot use 0 or negative numbers"
            Else
                If decWithdraw > mdecBalance Then
                    strWithdrawMoreThan = "Cannot withdraw more than you have"
                End If
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strWithdrawNegative
        lblMessage.Text = strWithdrawMoreThan
    End Sub
End Class
</code>```

答:
Here are some ideas to think on, focusing on Sub btnWithdraw_Click.

The code you have under the comment ' Processing is known as an "If-Else Ladder" (http://www.eng.fsu.edu/~haik/met.dir/hcpp.dir/notes.dir/cppnotes/node41.html). To make that ladder with better clarity, it can be refactored to:

```<code>' Processing
If decWithdraw > 0 Then
    mdecBalance = mdecBalance - decWithdraw
ElseIf decWithdraw <= 0 Then
    strWithdrawNegative = "Cannot use 0 or negative numbers"
ElseIf decWithdraw > mdecBalance Then
    strWithdrawMoreThan = "Cannot withdraw more than you have"
End If
</code>```

Since that above ladder puts particular focus on decWithdraw, it can be refactored to use Select Case:

```<code>' Processing
Select Case decWithdraw
    Case Is > 0
        mdecBalance = mdecBalance - decWithdraw
    Case Is <= 0
        strWithdrawNegative = "Cannot use 0 or negative numbers"
    Case Is < mdecBalance ' I.e. decWithdraw > mdecBalance
        strWithdrawMoreThan = "Cannot withdraw more than you have"
End Select
</code>```

Note that VB.NET has the -= assignment statement; so mdecBalance = mdecBalance - decWithdraw can be refactored to mdecBalance -= decWithdraw.

Note that the code tests decWithdraw > 0 before testing decWithdraw > mdecBalance. That's a logic error - the account can get overdrawn (without the desired error) because the decWithdraw > mdecBalance test will not get done because, after the decWithdraw > 0 test succeeds, the code will flow around it.

In fixing that bug, it's makes better sense to return to "If-Else":

```<code>' Processing
If Not decWithdraw > 0 Then
    strWithdrawNegative = "Cannot use 0 or negative numbers"
ElseIf Not decWithdraw <= mdecBalance Then
    strWithdrawMoreThan = "Cannot withdraw more than you have"
Else
    mdecBalance -= decWithdraw
End If
</code>```

Note how the tests are ordered now. First, we make sure decWithdraw is generally valid (must be > 0), then we make sure decWithdraw is valid for the more specific situation (must be <= mdecBalance).

If your sense of math is good, the above can also be written as:

```<code>' Processing
If decWithdraw <= 0 Then
    strWithdrawNegative = "Cannot use 0 or negative numbers"
ElseIf decWithdraw > mdecBalance Then
    strWithdrawMoreThan = "Cannot withdraw more than you have"
Else
    mdecBalance -= decWithdraw
End If
</code>```

E.g. mathematically speaking decWithdraw <= 0 is the same test as Not decWithdraw > 0. Part of the art of programming is in the style; one needs to find a way to write the code which fosters clarity for the humans who may need to read and understand it someday, balanced with how it affects computer performance. (https://wiki.c2.com/?PrematureOptimization) I'm sticking with Not decWithdraw > 0 because I think it'll be an easier read for an audience of corporate line-of-business programmers and business analysts.

Anyway, the style you went with in the error reporting is awkward. If we were to persist with it, one way one can get the right message to come through is:

```<code>If Not String.IsNullOrEmpty(strWithdrawNegative) Then
    lblMessage.Text = strWithdrawNegative
ElseIf Not String.IsNullOrEmpty(strWithdrawMoreThan) Then
    lblMessage.Text = strWithdrawMoreThan
Else
    lblMessage.Text = Nothing
End If
</code>```

It's ugly, but it will work. I would not do the error reporting like this myself. Another style, which scales better, could be:

```<code>Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click

    Const ValidationError_WithdrawNegative As Integer = 1
    Const ValidationError_WithdrawMoreThan As Integer = 2

    ' Declarations
    Dim decWithdraw As Decimal
    Dim intValidationErrorCode As Integer = 0
    Dim strValidationErrorMessage As String = Nothing

    ' Input
    decWithdraw = txtAmount.Text

    ' Processing
    If Not decWithdraw > 0 Then
        intValidationErrorCode = ValidationError_WithdrawNegative
        strValidationErrorMessage = "Cannot use 0 or negative numbers"
    ElseIf Not decWithdraw <= mdecBalance Then
        intValidationErrorCode = ValidationError_WithdrawMoreThan
        strValidationErrorMessage = "Cannot withdraw more than you have"
    Else
        mdecBalance -= decWithdraw
    End If

    ' Output
    lblBalance.Text = mdecBalance.ToString("c")
    lblMessage.Text = If(intValidationErrorCode > 0,
        strValidationErrorMessage,
        Nothing)

End Sub
</code>```

intValidationErrorCode, when > 0, signals the error; ValidationError_WithdrawNegative and ValidationError_WithdrawMoreThan indicates the specific error. (These constants are defined, because it is best to avoid "magic numbers" - https://en.wikipedia.org/wiki/Magic_number_(programming) ).

Note that decWithdraw = txtAmount.Text can error at run-time if something other than a valid number is in txtAmount.Text. One should check for that too:

```<code>Sub btnWithdraw_Click(sender As Object, e As EventArgs) 'Handles btnWithdraw.Click

    Const ValidationError_NotNumeric As Integer = 1
    Const ValidationError_WithdrawNegative As Integer = 2
    Const ValidationError_WithdrawMoreThan As Integer = 3

    ' Declarations
    Dim decWithdraw As Decimal
    Dim intValidationErrorCode As Integer = 0
    Dim strValidationErrorMessage As String = Nothing

    ' Input
    If Not Decimal.TryParse(txtAmount.Text, decWithdraw) Then
        intValidationErrorCode = ValidationError_NotNumeric
        strValidationErrorMessage = "Entry for withdraw is not a valid number"
    Else

        ' Processing
        If Not decWithdraw > 0 Then
            intValidationErrorCode = ValidationError_WithdrawNegative
            strValidationErrorMessage = "Cannot use 0 or negative numbers"
        ElseIf Not decWithdraw <= mdecBalance Then
            intValidationErrorCode = ValidationError_WithdrawMoreThan
            strValidationErrorMessage = "Cannot withdraw more than you have"
        Else
            mdecBalance -= decWithdraw
        End If

    End If

    ' Output
    lblBalance.Text = mdecBalance.ToString("c")
    lblMessage.Text = If(intValidationErrorCode > 0,
        strValidationErrorMessage,
        Nothing)

End Sub
</code>```

The above is not the only way to go about it, and perhaps not the very best way, but hopefully it's a start. Perhaps you can try https://codereview.stackexchange.com/, using tag "beginner" for further advice.

Body:
I hope that someone can point me in the right direction, as I am new to programming.

I made a basic banking application. It displays a balance for the account, has a textbox for the user to enter the amount, and 2 buttons: one for depositing an amount into the account and one for withdrawing an amount. If the user tries to deposit or withdraw a negative number or "0" then it gives an error that it isn't a valid amount. If the user tries to withdraw more than is in the account, it gives an error that they cannot withdraw more money than is in the account.

My problem is that all the error messages are working for the deposit button, but not for the withdraw button. I used nested If structure, output to a label at the bottom.

I tried using breakpoints to examine my variables, but didn't find any issues.

I don't really want the answer, just some help to understand why the Deposit button will give the error but the Withdraw button won't show either error.

Public Class Form1
    ' Prologue
    ' This is a simple banking application.
    ' It displays a balance for the account, calculates deposits and withdraws, and gives errors for invalid amounts and overdraws

    ' Modular Declarations
    Dim mdecBalance As Decimal = 1000

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
    End Sub

    Private Sub btnDeposit_Click(sender As Object, e As EventArgs) Handles btnDeposit.Click
        ' Declarations
        Dim decDeposit As Decimal
        Dim strDepProblem As String

        ' Input
        decDeposit = txtAmount.Text

        ' Processing
        If decDeposit > 0 Then
            mdecBalance = mdecBalance + decDeposit
        Else
            If decDeposit <= 0 Then
                strDepProblem = "That is not a valid amount to deposit"
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strDepProblem

    End Sub

    Private Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click
        ' Declarations
        Dim decWithdraw As Decimal
        Dim strWithdrawNegative As String
        Dim strWithdrawMoreThan As String

        ' Input
        decWithdraw = txtAmount.Text

        ' Processing
        If decWithdraw > 0 Then
            mdecBalance = mdecBalance - decWithdraw
        Else
            If decWithdraw <= 0 Then
                strWithdrawNegative = "Cannot use 0 or negative numbers"
            Else
                If decWithdraw > mdecBalance Then
                    strWithdrawMoreThan = "Cannot withdraw more than you have"
                End If
            End If
        End If

        ' Output
        lblBalance.Text = mdecBalance.ToString("c")
        lblMessage.Text = strWithdrawNegative
        lblMessage.Text = strWithdrawMoreThan
    End Sub
End Class

Body:
Here are some ideas to think on, focusing on Sub btnWithdraw_Click.

The code you have under the comment ' Processing is known as an "If-Else Ladder" (http://www.eng.fsu.edu/~haik/met.dir/hcpp.dir/notes.dir/cppnotes/node41.html). To make that ladder with better clarity, it can be refactored to:

' Processing
If decWithdraw > 0 Then
    mdecBalance = mdecBalance - decWithdraw
ElseIf decWithdraw <= 0 Then
    strWithdrawNegative = "Cannot use 0 or negative numbers"
ElseIf decWithdraw > mdecBalance Then
    strWithdrawMoreThan = "Cannot withdraw more than you have"
End If

Since that above ladder puts particular focus on decWithdraw, it can be refactored to use Select Case:

' Processing
Select Case decWithdraw
    Case Is > 0
        mdecBalance = mdecBalance - decWithdraw
    Case Is <= 0
        strWithdrawNegative = "Cannot use 0 or negative numbers"
    Case Is < mdecBalance ' I.e. decWithdraw > mdecBalance
        strWithdrawMoreThan = "Cannot withdraw more than you have"
End Select

Note that VB.NET has the -= assignment statement; so mdecBalance = mdecBalance - decWithdraw can be refactored to mdecBalance -= decWithdraw.

Note that the code tests decWithdraw > 0 before testing decWithdraw > mdecBalance. That's a logic error - the account can get overdrawn (without the desired error) because the decWithdraw > mdecBalance test will not get done because, after the decWithdraw > 0 test succeeds, the code will flow around it.

In fixing that bug, it's makes better sense to return to "If-Else":

' Processing
If Not decWithdraw > 0 Then
    strWithdrawNegative = "Cannot use 0 or negative numbers"
ElseIf Not decWithdraw <= mdecBalance Then
    strWithdrawMoreThan = "Cannot withdraw more than you have"
Else
    mdecBalance -= decWithdraw
End If

Note how the tests are ordered now. First, we make sure decWithdraw is generally valid (must be > 0), then we make sure decWithdraw is valid for the more specific situation (must be <= mdecBalance).

If your sense of math is good, the above can also be written as:

' Processing
If decWithdraw <= 0 Then
    strWithdrawNegative = "Cannot use 0 or negative numbers"
ElseIf decWithdraw > mdecBalance Then
    strWithdrawMoreThan = "Cannot withdraw more than you have"
Else
    mdecBalance -= decWithdraw
End If

E.g. mathematically speaking decWithdraw <= 0 is the same test as Not decWithdraw > 0. Part of the art of programming is in the style; one needs to find a way to write the code which fosters clarity for the humans who may need to read and understand it someday, balanced with how it affects computer performance. (https://wiki.c2.com/?PrematureOptimization) I'm sticking with Not decWithdraw > 0 because I think it'll be an easier read for an audience of corporate line-of-business programmers and business analysts.

Anyway, the style you went with in the error reporting is awkward. If we were to persist with it, one way one can get the right message to come through is:

If Not String.IsNullOrEmpty(strWithdrawNegative) Then
    lblMessage.Text = strWithdrawNegative
ElseIf Not String.IsNullOrEmpty(strWithdrawMoreThan) Then
    lblMessage.Text = strWithdrawMoreThan
Else
    lblMessage.Text = Nothing
End If

It's ugly, but it will work. I would not do the error reporting like this myself. Another style, which scales better, could be:

Sub btnWithdraw_Click(sender As Object, e As EventArgs) Handles btnWithdraw.Click

    Const ValidationError_WithdrawNegative As Integer = 1
    Const ValidationError_WithdrawMoreThan As Integer = 2

    ' Declarations
    Dim decWithdraw As Decimal
    Dim intValidationErrorCode As Integer = 0
    Dim strValidationErrorMessage As String = Nothing

    ' Input
    decWithdraw = txtAmount.Text

    ' Processing
    If Not decWithdraw > 0 Then
        intValidationErrorCode = ValidationError_WithdrawNegative
        strValidationErrorMessage = "Cannot use 0 or negative numbers"
    ElseIf Not decWithdraw <= mdecBalance Then
        intValidationErrorCode = ValidationError_WithdrawMoreThan
        strValidationErrorMessage = "Cannot withdraw more than you have"
    Else
        mdecBalance -= decWithdraw
    End If

    ' Output
    lblBalance.Text = mdecBalance.ToString("c")
    lblMessage.Text = If(intValidationErrorCode > 0,
        strValidationErrorMessage,
        Nothing)

End Sub

intValidationErrorCode, when > 0, signals the error; ValidationError_WithdrawNegative and ValidationError_WithdrawMoreThan indicates the specific error. (These constants are defined, because it is best to avoid "magic numbers" - https://en.wikipedia.org/wiki/Magic_number_(programming) ).

Note that decWithdraw = txtAmount.Text can error at run-time if something other than a valid number is in txtAmount.Text. One should check for that too:

Sub btnWithdraw_Click(sender As Object, e As EventArgs) 'Handles btnWithdraw.Click

    Const ValidationError_NotNumeric As Integer = 1
    Const ValidationError_WithdrawNegative As Integer = 2
    Const ValidationError_WithdrawMoreThan As Integer = 3

    ' Declarations
    Dim decWithdraw As Decimal
    Dim intValidationErrorCode As Integer = 0
    Dim strValidationErrorMessage As String = Nothing

    ' Input
    If Not Decimal.TryParse(txtAmount.Text, decWithdraw) Then
        intValidationErrorCode = ValidationError_NotNumeric
        strValidationErrorMessage = "Entry for withdraw is not a valid number"
    Else

        ' Processing
        If Not decWithdraw > 0 Then
            intValidationErrorCode = ValidationError_WithdrawNegative
            strValidationErrorMessage = "Cannot use 0 or negative numbers"
        ElseIf Not decWithdraw <= mdecBalance Then
            intValidationErrorCode = ValidationError_WithdrawMoreThan
            strValidationErrorMessage = "Cannot withdraw more than you have"
        Else
            mdecBalance -= decWithdraw
        End If

    End If

    ' Output
    lblBalance.Text = mdecBalance.ToString("c")
    lblMessage.Text = If(intValidationErrorCode > 0,
        strValidationErrorMessage,
        Nothing)

End Sub

The above is not the only way to go about it, and perhaps not the very best way, but hopefully it's a start. Perhaps you can try https://codereview.stackexchange.com/, using tag "beginner" for further advice.


问:
AWS Elastic Beanstalk error: Failed to deploy application
I spent many hours to solve my problem. I use CodePipeline : CodeSource, CodeBuild that produces docker container (code from Bitbucket) and stores the image in ECR.

In CodeDeploy I want to deploy that image from ECR to Elastic Beanstalk:

Errors in Elastic Beanstalk:

```<code>Environment health has transitioned from Info to Degraded. Command failed on all instances. Incorrect application version found on all instances. Expected version "Sample Application" (deployment 6). Application update failed 15 seconds ago and took 59 seconds.

During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version.

Failed to deploy application.

Unsuccessful command execution on instance id(s) 'i-04df549361597208a'. Aborting the operation.
</code>```

Another error from EB:

```<code>Incorrect application version "code-pipeline-1586854202535-MyflashcardsBuildOutput-ce0d6cd7-8290-40ad-a95e-9c57162b9ff1"
(deployment 9). Expected version "Sample Application" (deployment 8).
</code>```

Error in CodeDeploy:

```<code>Action execution failed
Deployment completed, but with errors: During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version. Failed to deploy application. Unsuccessful command execution on instance id(s) 'i-04df539061522208a'. Aborting the operation. [Instance: i-04df549333582208a] Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001].
</code>```

Does anyone know what happens here?

I use Dockerfile:

```<code>### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
EXPOSE 80
COPY --from=build /usr/src/app/dist /usr/share/nginx/html
</code>```

and buildspec.yml:

```<code>version: 0.2
phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - $(aws ecr get-login --region eu-west-1 --no-include-email)
      - REPOSITORY_URI=176901363719.dkr.ecr.eu-west-1.amazonaws.com/myflashcards
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=myflashcards
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image
      - docker build --tag $REPOSITORY_URI:latest .
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - echo Writing image definitions file...
      - printf '[{"name":"eagle","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
#      - echo Deleting old artifacts
#      - aws s3 sync dist/ s3://$BUCKET_NAME --delete
artifacts:
  files: imagedefinitions.json
</code>```

The third step (CodeDeploy) fails:(

答:
Ran into the same issue. The first fix worked for me. Listing down all possible fixes which can resolve this issue:

Reason: some bug with elasticbeanstalk, which is making the multi-stage builder step to fail. AWS logs would show you a message like docker pull requires exactly one argument

Solution: Use unnamed builder. By default, the stages are not named, and you refer to them by their integer number, starting with 0 for the first FROM instruction. Make changes in your docker file as below:

```<code>### STAGE 1: Build ###
FROM node:12.7-alpine
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
EXPOSE 80
COPY --from=0 /usr/src/app/dist /usr/share/nginx/html
</code>```

Reason: Incase using t2.micro as instance type. npm install command sometimes times out on the t2.micro instance.

Solution: Change the instance type that Elastic Beanstalk is using something other than t2.micro(say t2.small)

If none of the above two fixes work, try changing the COPY line of your Dockerfile as below:

COPY package*.json ./

As AWS sometimes prefer ./ over '.'

Body:
I spent many hours to solve my problem. I use CodePipeline : CodeSource, CodeBuild that produces docker container (code from Bitbucket) and stores the image in ECR.

In CodeDeploy I want to deploy that image from ECR to Elastic Beanstalk:

Errors in Elastic Beanstalk:

Environment health has transitioned from Info to Degraded. Command failed on all instances. Incorrect application version found on all instances. Expected version "Sample Application" (deployment 6). Application update failed 15 seconds ago and took 59 seconds.

During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version.

Failed to deploy application.

Unsuccessful command execution on instance id(s) 'i-04df549361597208a'. Aborting the operation.

Another error from EB:

Incorrect application version "code-pipeline-1586854202535-MyflashcardsBuildOutput-ce0d6cd7-8290-40ad-a95e-9c57162b9ff1"
(deployment 9). Expected version "Sample Application" (deployment 8).

Error in CodeDeploy:

Action execution failed
Deployment completed, but with errors: During an aborted deployment, some instances may have deployed the new application version. To ensure all instances are running the same version, re-deploy the appropriate application version. Failed to deploy application. Unsuccessful command execution on instance id(s) 'i-04df539061522208a'. Aborting the operation. [Instance: i-04df549333582208a] Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001].

Does anyone know what happens here?

I use Dockerfile:

### STAGE 1: Build ###
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
EXPOSE 80
COPY --from=build /usr/src/app/dist /usr/share/nginx/html

and buildspec.yml:

version: 0.2
phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - $(aws ecr get-login --region eu-west-1 --no-include-email)
      - REPOSITORY_URI=176901363719.dkr.ecr.eu-west-1.amazonaws.com/myflashcards
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=myflashcards
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image
      - docker build --tag $REPOSITORY_URI:latest .
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - echo Writing image definitions file...
      - printf '[{"name":"eagle","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
#      - echo Deleting old artifacts
#      - aws s3 sync dist/ s3://$BUCKET_NAME --delete
artifacts:
  files: imagedefinitions.json

The third step (CodeDeploy) fails:(

Body:
Ran into the same issue. The first fix worked for me. Listing down all possible fixes which can resolve this issue:

Reason: some bug with elasticbeanstalk, which is making the multi-stage builder step to fail. AWS logs would show you a message like docker pull requires exactly one argument

Solution: Use unnamed builder. By default, the stages are not named, and you refer to them by their integer number, starting with 0 for the first FROM instruction. Make changes in your docker file as below:

### STAGE 1: Build ###
FROM node:12.7-alpine
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
EXPOSE 80
COPY --from=0 /usr/src/app/dist /usr/share/nginx/html

Reason: Incase using t2.micro as instance type. npm install command sometimes times out on the t2.micro instance.

Solution: Change the instance type that Elastic Beanstalk is using something other than t2.micro(say t2.small)

If none of the above two fixes work, try changing the COPY line of your Dockerfile as below:

COPY package*.json ./

As AWS sometimes prefer ./ over '.'


问:
Can I insert a node before current node in singly linked list using C?
Is this even possible, because singly linked list does not have pointer to previous, only next? I have a task to do where I have to write a function that inserts a node before current node, and I just can't seem to do it.

EDIT: I made this

```<code>    void before(List* list, int value) {
        Node * temp = new_node(value);
        temp->data = value;
        temp->next = NULL;
    if(list->size == 0){
        temp->next = list->current;
        list->current = temp;
        return;
    }else{
    for(Node * p = list->head->next; p == list->current; p = p->next){
        list->head = list->current;
        list->current =  list->current->next;
    }
 temp->next = list->head->next;
 list->head->next = temp;
    }
}
</code>```

But for input

```<code>    insert_after_current(list, 1);
    insert_after_current(list, 2);
    insert_after_current(list, 3);
    insert_after_current(list, 4);
    before(list, 5);
</code>```

I receive output

```<code>1 5 2 3 4
</code>```

Can someone explain why?

答:
As you traverse the list, you need to keep track of the previous node you visited.

Once you find the node you want to insert before, have the previous node point to the new node and have the new node point to the current node.

Body:
Is this even possible, because singly linked list does not have pointer to previous, only next? I have a task to do where I have to write a function that inserts a node before current node, and I just can't seem to do it.

EDIT: I made this

    void before(List* list, int value) {
        Node * temp = new_node(value);
        temp->data = value;
        temp->next = NULL;
    if(list->size == 0){
        temp->next = list->current;
        list->current = temp;
        return;
    }else{
    for(Node * p = list->head->next; p == list->current; p = p->next){
        list->head = list->current;
        list->current =  list->current->next;
    }
 temp->next = list->head->next;
 list->head->next = temp;
    }
}

But for input

    insert_after_current(list, 1);
    insert_after_current(list, 2);
    insert_after_current(list, 3);
    insert_after_current(list, 4);
    before(list, 5);

I receive output

1 5 2 3 4

Can someone explain why?


问:
How can you get the clipboard contents with a Windows command?
For example, I can copy a file to the clipboard like this:

```<code>clip < file.txt
</code>```

(Now the contents of file.txt is in the clipboard.)

How can I do the opposite:

```<code>???? > file.txt
</code>```

So that the contents of the clipboard will be in file.txt?

答:
To get contents of clipboard

From win cmd:

```<code>powershell get-clipboard
</code>```

or (via a temp file from HTML parser) on cmd:

```<code>echo x = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text") > temp.vbs
echo WScript.Echo x >> temp.vbs
cscript //nologo temp.vbs
</code>```

Output may be redirected to file.

Body:
For example, I can copy a file to the clipboard like this:

clip < file.txt

(Now the contents of file.txt is in the clipboard.)

How can I do the opposite:

???? > file.txt

So that the contents of the clipboard will be in file.txt?

Body:
To get contents of clipboard

From win cmd:

powershell get-clipboard

or (via a temp file from HTML parser) on cmd:

echo x = CreateObject("htmlfile").ParentWindow.ClipboardData.GetData("text") > temp.vbs
echo WScript.Echo x >> temp.vbs
cscript //nologo temp.vbs

Output may be redirected to file.


问:
geom_col is assigning the wrong independent variable
I have a simple two variable data frame with a third variable acting as a factor

```<code>DF <- data.frame(Depth = c(8.6, 19.6, 42.6, 60.6, 79.4, 101.4, 121.4, 137.6, 163, 180),
       Rb = c(103, 59, 99, 53, 107, 87, 52, 33, 105, 49),
       Litho = as.factor(c(1,2,1,2,1,1,2,2,1,2)))
</code>```

I want to create a bar graph of the absolute values so I am using geom_col(). I want to plot Rb as a function of Depth therefore Depth should be the discrete variable. However, when I plot using

```<code>ggplot (DF, aes(x=Depth, y=Rb))+
geom_col()
</code>```

the graph has horizontal bars that show how much Depth there is at each discrete Rb reading. I want to see the value of Rb at each discrete Depth.

Reversing the x and y gives the same problem, just with vertical bars

```<code>ggplot (DF, aes(x=Rb, y=Depth))+
geom_col()
</code>```

I have also tried the same with geom_bar(stat = 'identity'), but it's still the same problem.

EDIT - THIS WORKS IF ANYONE CAN EXPLAIN WHY

```<code>ggplot (DF, aes(x=Depth, y=Rb/10, fill=Litho)) +
geom_bar(stat='identity') +
labs(x="Depth", y="Rb") +
scale_x_continuous (trans = "reverse") +
scale_y_continuous (position = "right") +
coord_flip()
</code>```

For some reason, dividing the Rb values by 10 sorts the problem out?? Dividing by any number greater than 2 works but if you divide by 1 or 2 (Rb, Rb/1, or Rb/2) it groups the data like in the above graphs and the bars are vertical, not horizontal??

Thanks,
Jeremy

答:
You may force the orientation in geom_col() with the "orientation" argument.

From ?geom_col:

orientation  The orientation of the layer. The default (NA) automatically determines the orientation from the aesthetic mapping. In the rare event that this fails it can be given explicitly by setting orientation to either "x" or "y".

[geom_col] treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using the orientation parameter, which can be either "x" or "y". The value gives the axis that the geom should run along, "x" being the default orientation you would expect for the geom.

See also discussion in the issue Unexpected (?) orientation with geom_col.

```<code>ggplot (DF, aes(x = Depth, y = Rb)) +
  geom_col(orientation = "x")
</code>```

Body:
I have a simple two variable data frame with a third variable acting as a factor

DF <- data.frame(Depth = c(8.6, 19.6, 42.6, 60.6, 79.4, 101.4, 121.4, 137.6, 163, 180),
       Rb = c(103, 59, 99, 53, 107, 87, 52, 33, 105, 49),
       Litho = as.factor(c(1,2,1,2,1,1,2,2,1,2)))

I want to create a bar graph of the absolute values so I am using geom_col(). I want to plot Rb as a function of Depth therefore Depth should be the discrete variable. However, when I plot using

ggplot (DF, aes(x=Depth, y=Rb))+
geom_col()

the graph has horizontal bars that show how much Depth there is at each discrete Rb reading. I want to see the value of Rb at each discrete Depth.

Reversing the x and y gives the same problem, just with vertical bars

ggplot (DF, aes(x=Rb, y=Depth))+
geom_col()

I have also tried the same with geom_bar(stat = 'identity'), but it's still the same problem.

EDIT - THIS WORKS IF ANYONE CAN EXPLAIN WHY

ggplot (DF, aes(x=Depth, y=Rb/10, fill=Litho)) +
geom_bar(stat='identity') +
labs(x="Depth", y="Rb") +
scale_x_continuous (trans = "reverse") +
scale_y_continuous (position = "right") +
coord_flip()

For some reason, dividing the Rb values by 10 sorts the problem out?? Dividing by any number greater than 2 works but if you divide by 1 or 2 (Rb, Rb/1, or Rb/2) it groups the data like in the above graphs and the bars are vertical, not horizontal??

Thanks,
Jeremy

Body:
You may force the orientation in geom_col() with the "orientation" argument.

From ?geom_col:

orientation  The orientation of the layer. The default (NA) automatically determines the orientation from the aesthetic mapping. In the rare event that this fails it can be given explicitly by setting orientation to either "x" or "y".

[geom_col] treats each axis differently and, thus, can thus have two orientations. Often the orientation is easy to deduce from a combination of the given mappings and the types of positional scales in use. Thus, ggplot2 will by default try to guess which orientation the layer should have. Under rare circumstances, the orientation is ambiguous and guessing may fail. In that case the orientation can be specified directly using the orientation parameter, which can be either "x" or "y". The value gives the axis that the geom should run along, "x" being the default orientation you would expect for the geom.

See also discussion in the issue Unexpected (?) orientation with geom_col.

ggplot (DF, aes(x = Depth, y = Rb)) +
  geom_col(orientation = "x")


问:
Xcode Not Immediately Recognizing New Classes (iOS)
I've been working with Xcode for about 5 months now and I just recently ran across a problem when I add a new class. If I add a new class, say for example "CustomCell" and I try to import '#import CustomCell.h' into a different .m file it will give me an error saying 'CustomCell.h file not found' even though it's right there on the list. I've had no problem with this in the past and I know what I'm doing when it comes to importing (at least I haven't changed the way I previously went about it when it worked).

I've had this problem more than once recently and sometimes if I just close out XCode and restart it it will recognize the class. Has anyone else had this problem? Is there a quick way to just refresh the project to see if Xcode can recognize the new class?

答: Fixed, in my case when creating new methods for my class, the other class called test did not see these methods because the target was missing. Thank you</p>


问:
Download flutter app and code back to laptoo
I was almost finished building my first app with Flutter with VScode when my laptops hard drive crashed. All my code gone... I know I should have made a back up and really learnt my lesson now.. I have the app installed on my phone. Is there a way to get it back on my laptop with the full code?</p>

答:
If you have the debug APK you might have a shot. Have a look at this: Flutter debug Apk decompile to get source code

If you don't have the debug APK you are probably in trouble. The code on your phone is compiled and deliberately obfuscated, since usually you want to prevent someone with your app from getting the source code.

Really hope you can get it back. Good luck


问:
How to delete dynamically allocated array in destructor in C++?
enter image description here

As you can see, the destructor complains "Use of undeclared identifier 'a'

Is my array out of scope? How can i delete it, when i call the destructor?

答: a has to be a member variable of the class. As you  have it now its a local