问:
how to use item decoration in a recyclerview within a dialog with rounded corners and transparent background
I am using a dialog and in this dialog I am using a recyclerview and I am also setting a custom background drawable with rounded corners for that dialog.
the problem is whenever I try to set an item decoration for the recyclerview it shows some weird lines in bottom cut corners of dialog like here 1 and here 2
 I think that's because I set the dialog background to be transparent.
I want to know how to remove these lines

The item decoration

public ItemDecoration(Context context) {

        mDivider = context.getResources().getDrawable(R.drawable.recycler_horizontal_divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i <= childCount-2; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
```

<p>the background for dialog </p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"></solid>
    <corners android:radius="@dimen/viewsRadius"></corners>
</shape>
</code>```

Layout for dialog

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content"
    android:background="@drawable/rounded_corners_dialog_back"
    >

    <TextView
        android:id="@+id/dialogNameTxt"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:tag="bold"
        android:text=""
        android:textColor="@color/black"
        android:textSize="@dimen/textSize"
        android:textStyle="" />

    <TextView
        android:id="@+id/closeBtn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:tag="icon"
        android:gravity="center"
        android:background="@drawable/yellow_circle"
        android:textColor="@color/white"
        android:textSize="@dimen/textSize"
        android:text="@string/closeIcon" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/dialogList"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/closeBtn"
        android:tag="bold" />

    <Button
        android:id="@+id/addBtn"
        android:layout_width="match_parent"
        android:layout_height="@dimen/viewsHeight"
        android:text="@string/add"
        android:tag="bold"
        android:layout_margin="10dp"
        android:textColor="@color/white"
        android:textAllCaps="false"
        android:background="@drawable/rounded_yellow_button"
        android:layout_below="@id/dialogList"
        />

  <android.support.constraint.ConstraintLayout
      android:visibility="gone"
      android:id="@+id/commentView"
      android:layout_width="match_parent"
      android:layout_below="@id/dialogList"
     android:layout_margin="10dp"
      android:layout_height="wrap_content">

      <EditText
          android:id="@+id/messageEditTxt"
          android:layout_width="0dp"
          android:layout_height="@dimen/viewsHeight"
          android:background="@drawable/edit_text_back"
          android:ems="10"
          android:hint="@string/write_a_comment"
          android:inputType="textPersonName"
          android:paddingStart="10dp"
          android:paddingEnd="10dp"
          android:layout_marginEnd="10dp"
          android:tag="regularFont"
          android:textColor="@color/black"
          android:textCursorDrawable="@null"
          app:layout_constraintEnd_toStartOf="@+id/sendBtn"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintBottom_toBottomOf="parent" />

      <TextView
          android:id="@+id/sendBtn"
          android:layout_width="@dimen/circleButtonDimension"
          android:layout_height="@dimen/circleButtonDimension"
          android:background="@drawable/yellow_circle"
          android:gravity="center"
          android:padding="@dimen/iconTextPadding"
          android:tag="icon"
          android:text="@string/sendIcon"
          android:textColor="@color/white"
          android:textSize="@dimen/iconTextSize"
          app:layout_constraintBottom_toBottomOf="parent"
          app:layout_constraintEnd_toEndOf="parent"/>

  </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/dialogNameTxt"
        android:id="@+id/cancelDialogView"
        android:visibility="gone">

        <TextView
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="10dp"
            android:tag="regularFont"
            android:text="@string/confirm_cancel"
            android:textColor="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            app:layout_constraintBottom_toTopOf="@id/yesBtn"/>

        <Button
            android:id="@+id/yesBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/yes"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/guideline4"
            app:layout_constraintStart_toStartOf="parent" />

        <Button
            android:id="@+id/noBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/no"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/guideline4" />

        <android.support.constraint.Guideline
            android:id="@+id/guideline4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/errorIcon"
            android:textSize="60sp"
            android:textColor="@color/red"
            android:tag="icon"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

</RelativeLayout>
```

<p>and here I set the background transparent for dialog in order to show my background</p>

<pre class="lang-java prettyprint-override"><code>getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
</code>```

答:
The solution could be add bottomPadding for dialog background exactly the same like  radius.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"></solid>
    <corners android:radius="@dimen/viewsRadius"></corners>
    <padding android:bottom="@dimen/viewsRadius"/>
</shape>
</code>```

Body:
I am using a dialog and in this dialog I am using a recyclerview and I am also setting a custom background drawable with rounded corners for that dialog.
the problem is whenever I try to set an item decoration for the recyclerview it shows some weird lines in bottom cut corners of dialog like here 1 and here 2
 I think that's because I set the dialog background to be transparent.
I want to know how to remove these lines

The item decoration

public ItemDecoration(Context context) {

        mDivider = context.getResources().getDrawable(R.drawable.recycler_horizontal_divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i <= childCount-2; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

the background for dialog

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"></solid>
    <corners android:radius="@dimen/viewsRadius"></corners>
</shape>

Layout for dialog

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="wrap_content"
    android:background="@drawable/rounded_corners_dialog_back"
    >

    <TextView
        android:id="@+id/dialogNameTxt"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:tag="bold"
        android:text=""
        android:textColor="@color/black"
        android:textSize="@dimen/textSize"
        android:textStyle="" />

    <TextView
        android:id="@+id/closeBtn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:tag="icon"
        android:gravity="center"
        android:background="@drawable/yellow_circle"
        android:textColor="@color/white"
        android:textSize="@dimen/textSize"
        android:text="@string/closeIcon" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/dialogList"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/closeBtn"
        android:tag="bold" />

    <Button
        android:id="@+id/addBtn"
        android:layout_width="match_parent"
        android:layout_height="@dimen/viewsHeight"
        android:text="@string/add"
        android:tag="bold"
        android:layout_margin="10dp"
        android:textColor="@color/white"
        android:textAllCaps="false"
        android:background="@drawable/rounded_yellow_button"
        android:layout_below="@id/dialogList"
        />

  <android.support.constraint.ConstraintLayout
      android:visibility="gone"
      android:id="@+id/commentView"
      android:layout_width="match_parent"
      android:layout_below="@id/dialogList"
     android:layout_margin="10dp"
      android:layout_height="wrap_content">

      <EditText
          android:id="@+id/messageEditTxt"
          android:layout_width="0dp"
          android:layout_height="@dimen/viewsHeight"
          android:background="@drawable/edit_text_back"
          android:ems="10"
          android:hint="@string/write_a_comment"
          android:inputType="textPersonName"
          android:paddingStart="10dp"
          android:paddingEnd="10dp"
          android:layout_marginEnd="10dp"
          android:tag="regularFont"
          android:textColor="@color/black"
          android:textCursorDrawable="@null"
          app:layout_constraintEnd_toStartOf="@+id/sendBtn"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintBottom_toBottomOf="parent" />

      <TextView
          android:id="@+id/sendBtn"
          android:layout_width="@dimen/circleButtonDimension"
          android:layout_height="@dimen/circleButtonDimension"
          android:background="@drawable/yellow_circle"
          android:gravity="center"
          android:padding="@dimen/iconTextPadding"
          android:tag="icon"
          android:text="@string/sendIcon"
          android:textColor="@color/white"
          android:textSize="@dimen/iconTextSize"
          app:layout_constraintBottom_toBottomOf="parent"
          app:layout_constraintEnd_toEndOf="parent"/>

  </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/dialogNameTxt"
        android:id="@+id/cancelDialogView"
        android:visibility="gone">

        <TextView
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="10dp"
            android:tag="regularFont"
            android:text="@string/confirm_cancel"
            android:textColor="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            app:layout_constraintBottom_toTopOf="@id/yesBtn"/>

        <Button
            android:id="@+id/yesBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/yes"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/guideline4"
            app:layout_constraintStart_toStartOf="parent" />

        <Button
            android:id="@+id/noBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/no"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/guideline4" />

        <android.support.constraint.Guideline
            android:id="@+id/guideline4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/errorIcon"
            android:textSize="60sp"
            android:textColor="@color/red"
            android:tag="icon"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

</RelativeLayout>

and here I set the background transparent for dialog in order to show my background

getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

Body:
The solution could be add bottomPadding for dialog background exactly the same like  radius.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"></solid>
    <corners android:radius="@dimen/viewsRadius"></corners>
    <padding android:bottom="@dimen/viewsRadius"/>
</shape>


来源: stackexchange

问:
Maven: Invalid target release: 10
I'm trying to compile my maven project using Java 10 but I'm having trouble. In my IDE (IntelliJ IDEA) everything compiles and runs just fine under Java 10. I installed the latest maven version 3.5.4 and pointed my JAVA_HOME to the JDK 10:

```<code>$ mvn --version
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T20:33:14+02:00)
Maven home: C:\Maven\bin\..
Java version: 10.0.2, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk-10.0.2
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
</code>```

The maven command I use is:

```<code>mvn package -Dmaven.test.skip
</code>```

In my pom.xml I had the following for Java 8 which worked fine:

```<code><properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <libraries.directory>libraries</libraries.directory>
</properties>
</code>```

For Java 10 I changed it to the following:

```<code><maven.compiler.source>10</maven.compiler.source>
<maven.compiler.target>10</maven.compiler.target>
</code>```

This does not work, just like using 1.10 as the version for the source and target compiler.

The full debug logging output (-X command line switch) is the following:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project My-Project: Fatal error compiling: invalid target release: 1.10 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project My-Project: Fatal error compiling
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Fatal error compiling
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1086)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:168)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.codehaus.plexus.compiler.CompilerException: invalid target release: 1.10
    at org.codehaus.plexus.compiler.javac.JavaxToolsCompiler.compileInProcess (JavaxToolsCompiler.java:173)
    at org.codehaus.plexus.compiler.javac.JavacCompiler.performCompile (JavacCompiler.java:174)
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1075)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:168)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: java.lang.IllegalArgumentException: invalid target release: 1.10
    at com.sun.tools.javac.main.OptionHelper$GrumpyHelper.error (OptionHelper.java:103)
    at com.sun.tools.javac.main.Option$12.process (Option.java:216)
    at com.sun.tools.javac.api.JavacTool.processOptions (JavacTool.java:217)
    at com.sun.tools.javac.api.JavacTool.getTask (JavacTool.java:156)
    at com.sun.tools.javac.api.JavacTool.getTask (JavacTool.java:107)
    at com.sun.tools.javac.api.JavacTool.getTask (JavacTool.java:64)
    at org.codehaus.plexus.compiler.javac.JavaxToolsCompiler.compileInProcess (JavaxToolsCompiler.java:125)
    at org.codehaus.plexus.compiler.javac.JavacCompiler.performCompile (JavacCompiler.java:174)
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1075)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:168)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

Adding the maven-compiler-plugin like suggested in this answer also does not work:

```<code>Fatal error compiling: invalid flag: --release -> [Help 1]
</code>```

Any ideas on how to fix this problem?

答:
Get your java version by running java -version.

You'll get a output like :

```<code>java version "1.8.0_201"
</code>```

Now go to your POM file and update source and target properities of maven-compiler-plugin with your installed java version. In my case it's 1.8

```<code><plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <configuration>
      <source>1.8</source>
      <target>1.8</target>
   </configuration>
</plugin>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Maven: Invalid target release: 10

Body:
I'm trying to compile my maven project using Java 10 but I'm having trouble. In my IDE (IntelliJ IDEA) everything compiles and runs just fine under Java 10. I installed the latest maven version 3.5.4 and pointed my JAVA_HOME to the JDK 10:

$ mvn --version
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T20:33:14+02:00)
Maven home: C:\Maven\bin\..
Java version: 10.0.2, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk-10.0.2
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"

The maven command I use is:

mvn package -Dmaven.test.skip

In my pom.xml I had the following for Java 8 which worked fine:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <libraries.directory>libraries</libraries.directory>
</properties>

For Java 10 I changed it to the following:

<maven.compiler.source>10</maven.compiler.source>
<maven.compiler.target>10</maven.compiler.target>

This does not work, just like using 1.10 as the version for the source and target compiler.

The full debug logging output (-X command line switch) is the following:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project My-Project: Fatal error compiling: invalid target release: 1.10 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project My-Project: Fatal error compiling
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Fatal error compiling
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1086)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:168)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: org.codehaus.plexus.compiler.CompilerException: invalid target release: 1.10
    at org.codehaus.plexus.compiler.javac.JavaxToolsCompiler.compileInProcess (JavaxToolsCompiler.java:173)
    at org.codehaus.plexus.compiler.javac.JavacCompiler.performCompile (JavacCompiler.java:174)
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1075)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:168)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
Caused by: java.lang.IllegalArgumentException: invalid target release: 1.10
    at com.sun.tools.javac.main.OptionHelper$GrumpyHelper.error (OptionHelper.java:103)
    at com.sun.tools.javac.main.Option$12.process (Option.java:216)
    at com.sun.tools.javac.api.JavacTool.processOptions (JavacTool.java:217)
    at com.sun.tools.javac.api.JavacTool.getTask (JavacTool.java:156)
    at com.sun.tools.javac.api.JavacTool.getTask (JavacTool.java:107)
    at com.sun.tools.javac.api.JavacTool.getTask (JavacTool.java:64)
    at org.codehaus.plexus.compiler.javac.JavaxToolsCompiler.compileInProcess (JavaxToolsCompiler.java:125)
    at org.codehaus.plexus.compiler.javac.JavacCompiler.performCompile (JavacCompiler.java:174)
    at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute (AbstractCompilerMojo.java:1075)
    at org.apache.maven.plugin.compiler.CompilerMojo.execute (CompilerMojo.java:168)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
    at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
    at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
    at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954)
    at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
    at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke (Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Adding the maven-compiler-plugin like suggested in this answer also does not work:

Fatal error compiling: invalid flag: --release -> [Help 1]

Any ideas on how to fix this problem?

Body:
Get your java version by running java -version.

You'll get a output like :

java version "1.8.0_201"

Now go to your POM file and update source and target properities of maven-compiler-plugin with your installed java version. In my case it's 1.8

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <configuration>
      <source>1.8</source>
      <target>1.8</target>
   </configuration>
</plugin>


问:
MiniMagick - cannot load such file
I'm trying to use MiniMagick to resize images and I did the following in my controller file:

```<code>require 'rubygems'
require 'mini_magick'
</code>```

and

```<code>img = MiniMagick::Image.open(file)
</code>```

But when I invoke the controller the following

```<code>LoadError (cannot load such file -- mini_magick)
</code>```

I've added gem 'mini_magick' to my Gemfile so I have really no idea what's going on. Can someone help me with this?

BTW, it is available in both irb and rails console, but not when run as a server.

Thx in advance.

答:
Add gem "mini_magick" to your Gemfile

and restart your server.

ContentLicense: CC BY-SA 3.0

Title: MiniMagick - cannot load such file

Body:
I'm trying to use MiniMagick to resize images and I did the following in my controller file:

require 'rubygems'
require 'mini_magick'

and

img = MiniMagick::Image.open(file)

But when I invoke the controller the following

LoadError (cannot load such file -- mini_magick)

I've added gem 'mini_magick' to my Gemfile so I have really no idea what's going on. Can someone help me with this?

BTW, it is available in both irb and rails console, but not when run as a server.

Thx in advance.


问:
unstacking shift data (start and end time) into hourly data
I have a df as follows which shows when a person started a shift, ended a shift, the amount of hours and the date worked.

```<code>Business_Date   Number PayTimeStart PayTimeEnd          Hours
0   2019-05-24  1       2019-05-24 11:00:00 2019-05-24 12:15:00 1.250
1   2019-05-24  2       2019-05-24 12:30:00 2019-05-24 13:30:00 1.00
</code>```

Now what I'm trying to do is break this into an hourly format, so I know how many hours were used between 11:00 - 12:00

so, in my head, for the above, I want to put the 1 hour between 11 - 12 into the bin for 11:00 and the remainder 0.25 into the next bin of 12

so I would end up with something like

```<code>    Business Date   Time Hour
0   2019-05-24  11:00 1
1   2019-05-24  12:00 0.75
2   2019-05-24  13:00 0.5
</code>```

答:
One idea is working with minutes - first use list comprehension with flattening for Series and then grouping by hours with hours for count by GroupBy.size and last divide by 60 for final hours:

```<code>s = pd.Series([z for x, y in zip(df['Pay Time Start'],
                                 df['Pay Time End'] - pd.Timedelta(60, unit='s'))
                 for z in pd.date_range(x, y, freq='Min')])

df = (s.groupby([s.dt.date.rename('Business Date'), s.dt.hour.rename('Time')])
       .size()
       .div(60)
       .reset_index(name='Hour'))
print (df)
  Business Date  Time  Hour
0    2019-05-24    11  1.00
1    2019-05-24    12  0.75
2    2019-05-24    13  0.50
</code>```

If you need to group by a location or ID

```<code> df1 = pd.DataFrame([(z, w) for x, y, w in zip(df['Pay Time Start'],
                                              df['Pay Time End'] - pd.Timedelta(60, unit='s'),
                                              df['Location']) for z in pd.date_range(x, y, freq='Min')],
                   columns=['Date','Location'])

 df = (df1.groupby([df1['Date'].dt.date.rename('Business Date'),
                       df1['Date'].dt.hour.rename('Time'), df1['Location']])
          .size() .div(60) .reset_index(name='Hour'))
</code>```

Body:
I have a df as follows which shows when a person started a shift, ended a shift, the amount of hours and the date worked.

Business_Date   Number PayTimeStart PayTimeEnd          Hours
0   2019-05-24  1       2019-05-24 11:00:00 2019-05-24 12:15:00 1.250
1   2019-05-24  2       2019-05-24 12:30:00 2019-05-24 13:30:00 1.00

Now what I'm trying to do is break this into an hourly format, so I know how many hours were used between 11:00 - 12:00

so, in my head, for the above, I want to put the 1 hour between 11 - 12 into the bin for 11:00 and the remainder 0.25 into the next bin of 12

so I would end up with something like

    Business Date   Time Hour
0   2019-05-24  11:00 1
1   2019-05-24  12:00 0.75
2   2019-05-24  13:00 0.5

Body:
One idea is working with minutes - first use list comprehension with flattening for Series and then grouping by hours with hours for count by GroupBy.size and last divide by 60 for final hours:

s = pd.Series([z for x, y in zip(df['Pay Time Start'],
                                 df['Pay Time End'] - pd.Timedelta(60, unit='s'))
                 for z in pd.date_range(x, y, freq='Min')])

df = (s.groupby([s.dt.date.rename('Business Date'), s.dt.hour.rename('Time')])
       .size()
       .div(60)
       .reset_index(name='Hour'))
print (df)
  Business Date  Time  Hour
0    2019-05-24    11  1.00
1    2019-05-24    12  0.75
2    2019-05-24    13  0.50

If you need to group by a location or ID

 df1 = pd.DataFrame([(z, w) for x, y, w in zip(df['Pay Time Start'],
                                              df['Pay Time End'] - pd.Timedelta(60, unit='s'),
                                              df['Location']) for z in pd.date_range(x, y, freq='Min')],
                   columns=['Date','Location'])

 df = (df1.groupby([df1['Date'].dt.date.rename('Business Date'),
                       df1['Date'].dt.hour.rename('Time'), df1['Location']])
          .size() .div(60) .reset_index(name='Hour'))


问:
Text color is not updating in ListView
I am building an Android application and I need to change the text color of all cells in the ListView.

This is the code I use to populate and connect the ListView with the Activity file:

protected void onCreate(Bundle savedInstanceState) {
        ...

        // Create a temp array.
        ListView lv = (ListView) findViewById(R.id.gamesList);
        displayGames = new ArrayList<String>();

        // Populates ListView
        updateList();

        // Create Array Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,displayGames);
        lv.setAdapter(adapter);
    }
```

<p>My problem is that the text of the TextView in the cells does not have the correct color even though I specifically changed it on the XML file. See this code below: </p>

<p>This is the XML code for the creation of the ListView:</p>

```<ListView
        android:id="@+id/gamesList"
        android:layout_width="396dp"
        android:layout_height="342dp"
        android:layout_marginStart="9dp"
        android:layout_marginEnd="10dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout6"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout5"
        app:layout_constraintVertical_bias="0.854" />
```

<p>I defined the Text cells in a new XML file called <code>simple_list_item_1.xml</code>.</p>

```<TextView
        android:id="@+id/game"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="@color/white"
        android:textColorHint="@color/white"
        tools:ignore="MissingConstraints" />
```

I am running the app on a Pixel 2 emulator using API 22 Android 5,1.

答:
While setting Adapter to ListView you are referring android.R.layout.simple_list_item_1 which is default system resource and not the one you created in your xml. You need to use R.layout.simple_list_item_1

```<code>// Create Array Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1,displayGames);
</code>```

Title: Text color is not updating in ListView

Body:
I am building an Android application and I need to change the text color of all cells in the ListView.

This is the code I use to populate and connect the ListView with the Activity file:

protected void onCreate(Bundle savedInstanceState) {
        ...

        // Create a temp array.
        ListView lv = (ListView) findViewById(R.id.gamesList);
        displayGames = new ArrayList<String>();

        // Populates ListView
        updateList();

        // Create Array Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,displayGames);
        lv.setAdapter(adapter);
    }

My problem is that the text of the TextView in the cells does not have the correct color even though I specifically changed it on the XML file. See this code below:

This is the XML code for the creation of the ListView:

<ListView
        android:id="@+id/gamesList"
        android:layout_width="396dp"
        android:layout_height="342dp"
        android:layout_marginStart="9dp"
        android:layout_marginEnd="10dp"
        app:layout_constraintBottom_toTopOf="@+id/linearLayout6"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout5"
        app:layout_constraintVertical_bias="0.854" />

I defined the Text cells in a new XML file called simple_list_item_1.xml.

<TextView
        android:id="@+id/game"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:paddingStart="?android:attr/listPreferredItemPaddingStart"
        android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="@color/white"
        android:textColorHint="@color/white"
        tools:ignore="MissingConstraints" />

I am running the app on a Pixel 2 emulator using API 22 Android 5,1.

Body:
While setting Adapter to ListView you are referring android.R.layout.simple_list_item_1 which is default system resource and not the one you created in your xml. You need to use R.layout.simple_list_item_1

// Create Array Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1,displayGames);


问:
Wordpress - Create Page with custom CSS and JS only
I am creating a Wordpress plugin that adds a page that embeds a React app.

On plugin activation, a post is inserted with wp_insert_post() function, and then the load_app_template() function is triggered to set the post template.
This template contains wp_head() in the head section and my React app.

The problem is that some other plugins are loading some JS and CSS in the head that are disturbing the React app behavior. I am trying to remove all JS and CSS given by Wordpress & other plugins and add my own.

If I remove wp_head() from the post template, then I cannot register styles and scripts with my plugin through wp_register_script.

How to remove all JS and CSS from Wordpress and plugins and add my own from my plugin ?

There could be two ways :

Remove wp_head() and manually add links to my JS and CSS in the HTML template. I can do that for Jquery and Bootstrap but I don't know how to put links of JS files from my plugin directory.

Keep wp_head(), deregister all CSS and JS and add my own afterwards with Wordpress hooks. I am not able to remove some Javascript from other plugins with this solution. I tried deregistering all following this answer.

Thank you !

答:
You can remove unused CSS/JS from that page. Put this code on your function.php

```<code>function remove_unused_css_js() {
// remove only from that page
if(get_the_ID() == 'Your Page ID'){
    wp_dequeue_style('css-id'); // remove css
    wp_dequeue_script('js-id'); // remove js
}
}
add_action( 'wp_print_styles', 'remove_unused_css_js', 100 );
</code>```

Hope this will help.

Body:
You can remove unused CSS/JS from that page. Put this code on your function.php

function remove_unused_css_js() {
// remove only from that page
if(get_the_ID() == 'Your Page ID'){
    wp_dequeue_style('css-id'); // remove css
    wp_dequeue_script('js-id'); // remove js
}
}
add_action( 'wp_print_styles', 'remove_unused_css_js', 100 );

Hope this will help.


问:
Added events in google calendar not display in Android Pie?
I want to add events in google calendar programmatically and I have the following code to add events on my calendar:

```<code>try {
            ContentResolver cr = getContentResolver();
            ContentValues values = new ContentValues();

            String calendarId = getGmailCalendarId(mContext);

            values.put(CalendarContract.Events.DTSTART, startMillis);
            values.put(CalendarContract.Events.DTEND, endMillis);
            values.put(CalendarContract.Events.TITLE, title);
            //values.put(CalendarContract.Events.DESCRIPTION, description);
            values.put(CalendarContract.Events.EVENT_LOCATION, location);
            values.put(CalendarContract.Events.HAS_ALARM, false);
            values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, Calendar.getInstance()
                    .getTimeZone().getID());

            System.out.println(Calendar.getInstance().getTimeZone().getID());

//            Uri uri;
//            if (Integer.parseInt(Build.VERSION.SDK) >= 8)
//                uri = cr.insert(Uri.parse("content://com.android.calendar/events"), values);
//            else
//                uri = cr.insert(Uri.parse("content://calendar/events"), values);

            Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
            long eventId = java.lang.Long.parseLong(((Uri) uri).getLastPathSegment());
            Log.d("Event_Id", eventId + "");
            syncCalendar(mContext, calendarId);

        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

I got correct gmail id using this method which returns me calendarId.

getGmailCalendarId()

```<code>public String getGmailCalendarId(Context c) {
        String calenderId = "";
        String[] projection = new String[]{"_id", "calendar_displayName"};
        Uri calendars = Uri.parse("content://com.android.calendar/calendars");
        ContentResolver contentResolver = c.getContentResolver();
        Cursor managedCursor = contentResolver.query(calendars,
                projection, null, null, null);

        if (managedCursor != null && managedCursor.moveToFirst()) {
            String calName;
            String calID;
            int nameCol = managedCursor.getColumnIndex(projection[1]);
            int idCol = managedCursor.getColumnIndex(projection[0]);
            do {
                calName = managedCursor.getString(nameCol);
                calID = managedCursor.getString(idCol);
                if (calName.contains("@gmail")) {
                    calenderId = calID;
                    break;
                }

            } while (managedCursor.moveToNext());
            managedCursor.close();
            return calenderId;
        }

        return calenderId;

    }
</code>```

syncCalendar

```<code>public static void syncCalendar(Context context, String calendarId) {
    try {
        ContentResolver cr = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        values.put(CalendarContract.Calendars.VISIBLE, 1);

        Uri updateUri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, Long.parseLong(calendarId));
        cr.update(updateUri, values, null, null);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Everything is perfect, There is no any error. It returns me event id which means the event added successfully. The Issue is, the added events are visible in google calendar in all devices except android pie (9). In android pie, it returns  me event id but events are not displaying in calendar app.

The added events are visible in google calendar for all devices except
  android pie (9)

I followed many SO questions and answers but never get any idea about android pie issue with calendar.

答:
I fought for this issue from many days, but finally I solved it. The issue is with google account in my android pie device.

The steps, I followed are

Logout all google accounts from the device

Then Login with all accounts

Run the app and execute the code.

After that it works fine in my device.

Body:
I want to add events in google calendar programmatically and I have the following code to add events on my calendar:

try {
            ContentResolver cr = getContentResolver();
            ContentValues values = new ContentValues();

            String calendarId = getGmailCalendarId(mContext);

            values.put(CalendarContract.Events.DTSTART, startMillis);
            values.put(CalendarContract.Events.DTEND, endMillis);
            values.put(CalendarContract.Events.TITLE, title);
            //values.put(CalendarContract.Events.DESCRIPTION, description);
            values.put(CalendarContract.Events.EVENT_LOCATION, location);
            values.put(CalendarContract.Events.HAS_ALARM, false);
            values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, Calendar.getInstance()
                    .getTimeZone().getID());

            System.out.println(Calendar.getInstance().getTimeZone().getID());

//            Uri uri;
//            if (Integer.parseInt(Build.VERSION.SDK) >= 8)
//                uri = cr.insert(Uri.parse("content://com.android.calendar/events"), values);
//            else
//                uri = cr.insert(Uri.parse("content://calendar/events"), values);

            Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
            long eventId = java.lang.Long.parseLong(((Uri) uri).getLastPathSegment());
            Log.d("Event_Id", eventId + "");
            syncCalendar(mContext, calendarId);

        } catch (Exception e) {
            e.printStackTrace();
        }

I got correct gmail id using this method which returns me calendarId.

getGmailCalendarId()

public String getGmailCalendarId(Context c) {
        String calenderId = "";
        String[] projection = new String[]{"_id", "calendar_displayName"};
        Uri calendars = Uri.parse("content://com.android.calendar/calendars");
        ContentResolver contentResolver = c.getContentResolver();
        Cursor managedCursor = contentResolver.query(calendars,
                projection, null, null, null);

        if (managedCursor != null && managedCursor.moveToFirst()) {
            String calName;
            String calID;
            int nameCol = managedCursor.getColumnIndex(projection[1]);
            int idCol = managedCursor.getColumnIndex(projection[0]);
            do {
                calName = managedCursor.getString(nameCol);
                calID = managedCursor.getString(idCol);
                if (calName.contains("@gmail")) {
                    calenderId = calID;
                    break;
                }

            } while (managedCursor.moveToNext());
            managedCursor.close();
            return calenderId;
        }

        return calenderId;

    }

syncCalendar

public static void syncCalendar(Context context, String calendarId) {
    try {
        ContentResolver cr = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        values.put(CalendarContract.Calendars.VISIBLE, 1);

        Uri updateUri = ContentUris.withAppendedId(CalendarContract.Calendars.CONTENT_URI, Long.parseLong(calendarId));
        cr.update(updateUri, values, null, null);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Everything is perfect, There is no any error. It returns me event id which means the event added successfully. The Issue is, the added events are visible in google calendar in all devices except android pie (9). In android pie, it returns  me event id but events are not displaying in calendar app.

The added events are visible in google calendar for all devices except
  android pie (9)

I followed many SO questions and answers but never get any idea about android pie issue with calendar.


问:
Getting the GUI of an app that went poof!
Today my Visual Studio disappeared. I can see devenv.exe in the 'Processes' tab in Task Manager but not in the Applications tab. I have unsaved changes. Is there a way to "revive" VS so changes can be saved?</p>

答: Sometimes I find that Windows GUI apps can still be running but not appear in the Taskbar or the Applications pane. First thing to check is whether you can Alt+Tab to it? Problem solved if so, but if not, try Process Explorer. Right-click on devenv and see if Window -> Bring to Front works. Since it lists all processes in a single hierarchical view it might be able to 'resurrect' VS.</p>

OwnerDisplayName: Abdu

ContentLicense: CC BY-SA 2.5


问:
how to use ngIf to show data if the value exist?
I need to show an error messege  to show on page if the data searched is not existing on database.
should I use ngIf or there is a better method to apply this?
right now once I click with the wrong data searched nothing is happening
products.component.html

```<code><fa (click)="backToHome()" class="arrow" name="chevron-left"></fa>
<h1>جستجو</h1>
<br /><br /><br /><br />
  <div class="search">
    <input class="input" [(ngModel)]="item" required placeholder="جستجو میان محصولات و برندها" />
    <fa class="icon" name="search" (click)="fetchProducts()"></fa>
  </div>
<p>تاریخچه جستجو</p>
<span>{{name}}</span>
<br />
<br />
  <ul>
    <li *ngFor="let product of resultSearch">
        <a href="#">{{product.name}}</a>

    </li>
  </ul>
 <ul *ngIf="products.lenght">
      <li>{{products.name}}</li>
  </ul>

<router-outlet></router-outlet>
</code>```

product.component.ts

```<code>import { ProductsService } from './../products.service';
import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-search-page',
  templateUrl:'./search-page.component.html',
  styleUrls: ['./search-page.component.scss']
})
export class SearchPageComponent implements OnInit {
  public products=[];
  resultSearch;
  item='';
constructor(
  private ProductsService:ProductsService,
  private _router:Router,
    ) {
      this.ProductsService.getProducts().
      subscribe(data=> {
        this.products=data
      // this.fetchProducts();
      }
        );
   }

 ngOnInit() {
  }
  fetchProducts()
  {
    this.resultSearch=this.products.filter(product => product.name.includes(this.item));
  }
  backToHome()
  {
    this._router.navigate(['/home']);
  }
  getProduct()
  {
    return this.products.filter(product => product.name.includes(this.item));
  }
  condition(){
    let condition = " not found!";
    if(!this.products.length){
      return condition;
    }
  }
}
</code>```

答:
I solved it like this </p>

```<code>condition(){
    let condition = " not found!";
    if(this.resultSearch && this.resultSearch.length==0){
      return condition;
    }
</code>```

```<code><ul *ngIf="resultSearch && resultSearch.length">
    <li *ngFor="let product of resultSearch">
        <a href="#">{{product.name}}</a>
    </li>
  </ul>
<p *ngIf="condition()">!not found</p>
</code>```

Body:
I need to show an error messege  to show on page if the data searched is not existing on database.
should I use ngIf or there is a better method to apply this?
right now once I click with the wrong data searched nothing is happening
products.component.html

<fa (click)="backToHome()" class="arrow" name="chevron-left"></fa>

جستجو

    <input class="input" [(ngModel)]="item" required placeholder="جستجو میان محصولات و برندها" />
    <fa class="icon" name="search" (click)="fetchProducts()"></fa>

تاریخچه جستجو

{{name}}

        {{product.name}}

{{products.name}}

<router-outlet></router-outlet>

product.component.ts

import { ProductsService } from './../products.service';
import { Component, OnInit} from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-search-page',
  templateUrl:'./search-page.component.html',
  styleUrls: ['./search-page.component.scss']
})
export class SearchPageComponent implements OnInit {
  public products=[];
  resultSearch;
  item='';
constructor(
  private ProductsService:ProductsService,
  private _router:Router,
    ) {
      this.ProductsService.getProducts().
      subscribe(data=> {
        this.products=data
      // this.fetchProducts();
      }
        );
   }

 ngOnInit() {
  }
  fetchProducts()
  {
    this.resultSearch=this.products.filter(product => product.name.includes(this.item));
  }
  backToHome()
  {
    this._router.navigate(['/home']);
  }
  getProduct()
  {
    return this.products.filter(product => product.name.includes(this.item));
  }
  condition(){
    let condition = " not found!";
    if(!this.products.length){
      return condition;
    }
  }
}

Body:
I solved it like this

condition(){
    let condition = " not found!";
    if(this.resultSearch && this.resultSearch.length==0){
      return condition;
    }

<ul *ngIf="resultSearch && resultSearch.length">
    <li *ngFor="let product of resultSearch">
        <a href="#">{{product.name}}</a>
    </li>
  </ul>
<p *ngIf="condition()">!not found</p>


问:
Is handling the `Imbalance` type mandatory after withdraw or deposit?
When using any of the functions which mint/burn the base currency (e.g. Currency::withdraw()), you're given an Imbalance return value. Does Substrate expect me to do something with it?

答:
You get back an Imbalance whenever you perform some "one-sided operation" within the Balances module (deposit, slash, withdraw, etc...).

The both PositiveImbalance and NegativeImbalance implement the Drop trait, which defines a destructor function that gets called when a variable goes out of scope.

In the case of an Imbalance, the drop function simply updates the total issuance of the balances module to ensure that the sum of all current account balances is equal to the total issuance.

So by default, no, you do not need to do anything with the imbalance returned to you. You can just place the result of a "one-sided operation" into an unused variable like so:

let _ = <balances::Module<T> as Currency<_>>::withdraw(...)?;
```

<p>However, if you want to, you are also given a set of tools to manage imbalances returned to you:</p>

<pre class="lang-rust prettyprint-override"><code>impl<T: Trait<I>, I: Instance> Imbalance<T::Balance> for NegativeImbalance<T, I> {
    type Opposite = PositiveImbalance<T, I>;

    fn zero() -> Self {...}

    fn drop_zero(self) -> result::Result<(), Self> {...}

    fn split(self, amount: T::Balance) -> (Self, Self) {...}

    fn merge(mut self, other: Self) -> Self {...}

    fn subsume(&mut self, other: Self) {...}

    fn offset(self, other: Self::Opposite) -> result::Result<Self, Self::Opposite> {...}

    fn peek(&self) -> T::Balance {...}
}
</code>```

Body:
You get back an Imbalance whenever you perform some "one-sided operation" within the Balances module (deposit, slash, withdraw, etc...).

The both PositiveImbalance and NegativeImbalance implement the Drop trait, which defines a destructor function that gets called when a variable goes out of scope.

In the case of an Imbalance, the drop function simply updates the total issuance of the balances module to ensure that the sum of all current account balances is equal to the total issuance.

So by default, no, you do not need to do anything with the imbalance returned to you. You can just place the result of a "one-sided operation" into an unused variable like so:

let _ = <balances::Module<T> as Currency<_>>::withdraw(...)?;

However, if you want to, you are also given a set of tools to manage imbalances returned to you:

impl<T: Trait<I>, I: Instance> Imbalance<T::Balance> for NegativeImbalance<T, I> {
    type Opposite = PositiveImbalance<T, I>;

    fn zero() -> Self {...}

    fn drop_zero(self) -> result::Result<(), Self> {...}

    fn split(self, amount: T::Balance) -> (Self, Self) {...}

    fn merge(mut self, other: Self) -> Self {...}

    fn subsume(&mut self, other: Self) {...}

    fn offset(self, other: Self::Opposite) -> result::Result<Self, Self::Opposite> {...}

    fn peek(&self) -> T::Balance {...}
}


问:
Push Notification - Mobile to Mobile
I want to send message from one mobile to another mobile(Push Notification).
Firebase has a push notification service, but it's not directly between mobile to mobile.

It's either mobile to desktop(Upstream), or desktop to mobile(downstream).

Basically the app is supposed to send alert from one mobile to another.

I am beginner, would really appreciate if there's already a function for this.

答:
I have done this with the help of a web configuration.

You will need a Web database table to save the FCM Token and username for each device.

Username can be any unique thing you can get from any registration process you want or you can hard code that as well for testing purpose but FCM Token Id must be auto Generated you can find the code how to get it form web.

Every Device FCM Token ID is attached with the username and must be unique which will be used to distinguish between all the devices in web.

Now the Process will be--

sender mobile -> Server Having all the FCM token id (and code to send notification) -> Receiver Mobile

From sender device you call the server, sending it the message and the receiver's username.

Now at server side it will search its table and find the particular FCM Token id for the specific username you have sent.

Now it will send the given message to the device of that specific token Id.

Hope this will help you!

Title: Push Notification - Mobile to Mobile


问:
issue sending logs with FileBeat
I am able to get some of my logs sent from FileBeat to Logstash, but I seem to be having an issue with a 2 of them.

Do you guys have any words of wisdom?

I see logs in the folders that FileBeat is suppose to read from, but I am getting no dice on getting them to be sent back.

Part of the Filebeat Yml

```<code># Mailoney
     -
        paths:
        - /data/mailoney/log/commands.log
        input_type: log
        document_type: Mailoney

        fields:
        fields_under_root: true
        json.keys_under_root: false
        json.add_error_key: true

# Conpot
     -
        paths:
        - /data/conpot/log/*.json"
        input_type: log
        document_type: Conpot

        fields:
        fields_under_root: true
        json.keys_under_root: false
        json.add_error_key: true

# Heralding
     -
        paths:
        - /data/heralding/log/auth.csv"
        document_type: Heralding

        fields:
        fields_under_root: true
        json.keys_under_root: false
        json.add_error_key: true
</code>```

Logstash conf

```<code># Heralding
  if [type] == "Heralding" {
    csv {
      columns => ["timestamp","auth_id","session_id","src_ip","src_port","dest_ip","dest_port","proto","username","password"] separator => ","
    }
    date {
      match => [ "timestamp", "yyyy-MM-dd HH:mm:ss.SSSSSS" ]
      remove_field => ["timestamp"]
    }
  }

# Conpot
  if [type] == "Conpot" {
    date {
      match => [ "timestamp", "ISO8601" ]
    }
    mutate {
      rename => {
        "dst_port" => "dest_port"
        "dst_ip" => "dest_ip"
      }
    }
  }

# Mailoney
  if [type] == "Mailoney" {
    grok {
      match => [ "message", "\A%{NAGIOSTIME}\[%{IPV4:src_ip}:%{INT:src_port:integer}] %{GREEDYDATA:smtp_input}" ]
    }
    mutate {
      add_field => {
        "dest_port" => "25"
      }
    }
    date {
      match => [ "nagios_epoch", "UNIX" ]
      remove_field => ["nagios_epoch"]
    }
  }
</code>```

答: I don't know if this is a typo because of copy-paste, but you have for #Conpot and #Heralding in filebeat.yml file only end quotation marks.

Title: issue sending logs with FileBeat

Body:
I am able to get some of my logs sent from FileBeat to Logstash, but I seem to be having an issue with a 2 of them.

Do you guys have any words of wisdom?

I see logs in the folders that FileBeat is suppose to read from, but I am getting no dice on getting them to be sent back.

Part of the Filebeat Yml

# Mailoney
     -
        paths:
        - /data/mailoney/log/commands.log
        input_type: log
        document_type: Mailoney

        fields:
        fields_under_root: true
        json.keys_under_root: false
        json.add_error_key: true

# Conpot
     -
        paths:
        - /data/conpot/log/*.json"
        input_type: log
        document_type: Conpot

        fields:
        fields_under_root: true
        json.keys_under_root: false
        json.add_error_key: true

# Heralding
     -
        paths:
        - /data/heralding/log/auth.csv"
        document_type: Heralding

        fields:
        fields_under_root: true
        json.keys_under_root: false
        json.add_error_key: true

Logstash conf

# Heralding
  if [type] == "Heralding" {
    csv {
      columns => ["timestamp","auth_id","session_id","src_ip","src_port","dest_ip","dest_port","proto","username","password"] separator => ","
    }
    date {
      match => [ "timestamp", "yyyy-MM-dd HH:mm:ss.SSSSSS" ]
      remove_field => ["timestamp"]
    }
  }

# Conpot
  if [type] == "Conpot" {
    date {
      match => [ "timestamp", "ISO8601" ]
    }
    mutate {
      rename => {
        "dst_port" => "dest_port"
        "dst_ip" => "dest_ip"
      }
    }
  }

# Mailoney
  if [type] == "Mailoney" {
    grok {
      match => [ "message", "\A%{NAGIOSTIME}\[%{IPV4:src_ip}:%{INT:src_port:integer}] %{GREEDYDATA:smtp_input}" ]
    }
    mutate {
      add_field => {
        "dest_port" => "25"
      }
    }
    date {
      match => [ "nagios_epoch", "UNIX" ]
      remove_field => ["nagios_epoch"]
    }
  }


问:
getmeasuredheight() and getmeasuredwidth() returns 0 after View.measure()
After measuring a View with a constant dimensions with view.measure(), the getMeasuredHeight() and getMeasureWidth() is returning 0.

layout_view.xml, layout which is inflated to create the view

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp">
</FrameLayout>
</code>```

function which measures the dimensions

```<code>public void measureView(Context context){
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.layout_view,null,false);

    view.measure( View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

    Log.d(TAG,"Error width : " + view.getMeasuredWidth());
    Log.d(TAG,"Error height : " + view.getMeasuredHeight());

}
</code>```

答:
You can use getViewTreeObserver in onCreate/onCreateView and other events.

```<code>fun setGlobalLayoutListener(view: View, method: () -> Unit) {
    val vto1 = view.viewTreeObserver
    if (vto1.isAlive) {
        vto1.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val vto2 = view.viewTreeObserver
                if (vto2.isAlive) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        vto2.removeOnGlobalLayoutListener(this)
                    } else {
                        @Suppress("DEPRECATION")
                        vto2.removeGlobalOnLayoutListener(this)
                    }
                    // Your actions are here:
                    method()
                }
            }
        })
    }
}
</code>```

And call it: setGlobalLayoutListener(view) {updateUI(view)}.

I also tried

```<code>view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
</code>```

and then called view.control.measuredWidth in onCreateView()/onViewCreated(). But in some emulators (API 19) it returned wrong results.

Body:
After measuring a View with a constant dimensions with view.measure(), the getMeasuredHeight() and getMeasureWidth() is returning 0.

layout_view.xml, layout which is inflated to create the view

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="100dp">
</FrameLayout>

function which measures the dimensions

public void measureView(Context context){
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.layout_view,null,false);

    view.measure( View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

    Log.d(TAG,"Error width : " + view.getMeasuredWidth());
    Log.d(TAG,"Error height : " + view.getMeasuredHeight());

}

Body:
You can use getViewTreeObserver in onCreate/onCreateView and other events.

fun setGlobalLayoutListener(view: View, method: () -> Unit) {
    val vto1 = view.viewTreeObserver
    if (vto1.isAlive) {
        vto1.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val vto2 = view.viewTreeObserver
                if (vto2.isAlive) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        vto2.removeOnGlobalLayoutListener(this)
                    } else {
                        @Suppress("DEPRECATION")
                        vto2.removeGlobalOnLayoutListener(this)
                    }
                    // Your actions are here:
                    method()
                }
            }
        })
    }
}

And call it: setGlobalLayoutListener(view) {updateUI(view)}.

I also tried

view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)

and then called view.control.measuredWidth in onCreateView()/onViewCreated(). But in some emulators (API 19) it returned wrong results.


答:
Another idea, similar's to @jezrael's but work with seconds for higher precision:

```<code>def get_series(a):
    s, e, h = a
    idx = pd.date_range(s,e, freq='6s')
    return pd.Series(h/len(idx), index=idx)

(pd.concat(map(get_series, zip(df.Pay_Time_Start,
                          df.Pay_Time_End,
                          df.Hours)))
   .resample('H').sum()
)
</code>```

Output:

```<code>2019-05-24 11:00:00    0.998668
2019-05-24 12:00:00    0.750500
2019-05-24 13:00:00    0.500832
Freq: H, dtype: float64
</code>```

Title: unstacking shift data (start and end time) into hourly data

Body:
Another idea, similar's to @jezrael's but work with seconds for higher precision:

def get_series(a):
    s, e, h = a
    idx = pd.date_range(s,e, freq='6s')
    return pd.Series(h/len(idx), index=idx)

(pd.concat(map(get_series, zip(df.Pay_Time_Start,
                          df.Pay_Time_End,
                          df.Hours)))
   .resample('H').sum()
)

Output:

2019-05-24 11:00:00    0.998668
2019-05-24 12:00:00    0.750500
2019-05-24 13:00:00    0.500832
Freq: H, dtype: float64


问:
JQuery active class a tag don't execute
I am trying to create a navbar with a dynamic active menu using jquery.
I have already the code and it is working except on 1 things

```<code>$(document).ready(function(){
          $('ul li a').click(function(){
            $('li a').removeClass("active");
            $(this).addClass("active");
            return false;
          });
});

 <li class="nav-item">
     <a class="nav-link" href="index.php?page=logout">Logout</a>
 </li>
</code>```

The above code work and I get a active menu when I click on a  tag.
Only the  tag won't work. And when I commend out the return false the  tag is working but I don't get a active class.
I also tried e.preventDefault() but then I prevent my a tag to execute. I know that return false in preventDefault() the function has to stop executing on my a tag. But how can I work around that ?

I hope that I get my active class dynamic and my a tag is still executing.

答:
You are going to a new page so the state is lost after the page is loaded, you need send the state to the new page, you can use for that localStorage</p>

```<code>$(document).ready(function(){
          var state = localStorage.getItem('activeLink');//get the state from localstorage
          if(state !== null && state.length) {
           $('.nav-link[href="'+state+'"]').addClass('active');//set the active class

          }
          $('ul li a').click(function(){
            $('li a').removeClass("active");
            $(this).addClass("active");
            localStorage.setItem('activeLink',$(this).attr('href'));//save the clicked link in localstorage
          });
});

 <li class="nav-item">
     <a class="nav-link" href="index.php?page=logout">Logout</a>
 </li>
</code>```

Title: JQuery active class a tag don't execute

Body:
I am trying to create a navbar with a dynamic active menu using jquery.
I have already the code and it is working except on 1 things

$(document).ready(function(){
          $('ul li a').click(function(){
            $('li a').removeClass("active");
            $(this).addClass("active");
            return false;
          });
});

     Logout

The above code work and I get a active menu when I click on a  tag.
Only the  tag won't work. And when I commend out the return false the  tag is working but I don't get a active class.
I also tried e.preventDefault() but then I prevent my a tag to execute. I know that return false in preventDefault() the function has to stop executing on my a tag. But how can I work around that ?

I hope that I get my active class dynamic and my a tag is still executing.

Body:
You are going to a new page so the state is lost after the page is loaded, you need send the state to the new page, you can use for that localStorage

$(document).ready(function(){
          var state = localStorage.getItem('activeLink');//get the state from localstorage
          if(state !== null && state.length) {
           $('.nav-link[href="'+state+'"]').addClass('active');//set the active class

          }
          $('ul li a').click(function(){
            $('li a').removeClass("active");
            $(this).addClass("active");
            localStorage.setItem('activeLink',$(this).attr('href'));//save the clicked link in localstorage
          });
});

 <li class="nav-item">
     <a class="nav-link" href="index.php?page=logout">Logout</a>
 </li>


问:
Not getting value from scope, getting error : Cannot set property 'value' of undefined
```<code>var app = angular.module("Main", []);

app.controller("MainCtrl", [ function ($scope) {
    $scope.value = 545
}]);`
var app = angular.module("Main", []);

app.controller("MainCtrl", [ function ($scope) {
    $scope.value = 545
}]);
</code>```

答:
Dependency Injection is not correct. Try this.    </p>

```<code> var app = angular.module("Main", []);

    app.controller("MainCtrl", [ "$scope", function ($scope) {
      $scope.value = 545
    }]);
</code>```

Body:
Dependency Injection is not correct. Try this.

 var app = angular.module("Main", []);

    app.controller("MainCtrl", [ "$scope", function ($scope) {
      $scope.value = 545
    }]);


问:
Using DTOs properly in a Restful web service
I am developing a restful web service using spring framework. I have a few questions on how to use DTOs properly in my project.

First of all, I saw a lot of code examples on using DTOs and there is always a one to one mapping with entities. For User entity we have UserDto, For Country, we have CountryDto and etc. I think this is not flexible at all. For every service, I need two DTOs for input and output. is that ok?

If I define two DTOs for each service, Can I name them with request and response suffixes? For example for createUser service, I have two DTO objects called CreateUserRequest and CreateUserResponse.

Some services have no outputs(Just a status code) or inputs(Just an Id in URL). Should I Define an empty DTO for them or not? If I don't define a DTO in these scenarios, it is a bit confusing because sometimes you define two DTOs for service and sometimes just one.

Should I map path variables like /users/{id} to DTO objects too? for example instead of:

```<code>@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") Long id)
</code>```

do something like:

```<code>@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") GetUserRequest request)
</code>```

答:
In the ideal restful web service you manipulate resources with properties, not request-response structures. So, if you create User, it's ok to accept and return the same DTO and the method looks like this:

```<code>@PostMapping("/")
public ResponseEntity<User> addUser(@RequestBody User user)
</code>```

Using request body for GET is technically possible, but de-facto is deprecated, use path variables and request params.

Some services have no outputs(Just a status code) or inputs(Just an Id in URL). Should I Define an empty DTO for them or not?

No, you should not define DTO for objects that you do not have.

And the last detail: if you have multiple methods manipulating same resource (e.g. User), do not make multiple User DTOs for get, post, etc.

Body:
I am developing a restful web service using spring framework. I have a few questions on how to use DTOs properly in my project.

First of all, I saw a lot of code examples on using DTOs and there is always a one to one mapping with entities. For User entity we have UserDto, For Country, we have CountryDto and etc. I think this is not flexible at all. For every service, I need two DTOs for input and output. is that ok?

If I define two DTOs for each service, Can I name them with request and response suffixes? For example for createUser service, I have two DTO objects called CreateUserRequest and CreateUserResponse.

Some services have no outputs(Just a status code) or inputs(Just an Id in URL). Should I Define an empty DTO for them or not? If I don't define a DTO in these scenarios, it is a bit confusing because sometimes you define two DTOs for service and sometimes just one.

Should I map path variables like /users/{id} to DTO objects too? for example instead of:

@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") Long id)

do something like:

@GetMapping("/users/{id}")
public ResponseEntity getUser(@PathVariable(value = "id") GetUserRequest request)

Body:
In the ideal restful web service you manipulate resources with properties, not request-response structures. So, if you create User, it's ok to accept and return the same DTO and the method looks like this:

@PostMapping("/")
public ResponseEntity<User> addUser(@RequestBody User user)

Using request body for GET is technically possible, but de-facto is deprecated, use path variables and request params.

Some services have no outputs(Just a status code) or inputs(Just an Id in URL). Should I Define an empty DTO for them or not?

No, you should not define DTO for objects that you do not have.

And the last detail: if you have multiple methods manipulating same resource (e.g. User), do not make multiple User DTOs for get, post, etc.


问:
Check if user is offline
I have an online game. I wish to show how many user are online. The problem is to know when a user is offline.
Is there a way to perform a check on sessions cookie to acknowledge whether the session with the broswer was closed?
I was thinking about simply set a timeout on the server which launch a script that count how many session cookie are present, but how do I check if the session cookie is about somebody who's logged and not just a visitor?

How did you handle this?

1) I don't want to rely on a script fired with the logout button, since nobody ever logout... people simply close the browser.

2) About timestamps and registering activity? Since in my game users interact with an svg (not moving through pages), they generate a huge amount of clicks. Making a query for each click for each of them refreshing a record would be very expensive.

答:
Since your code gets executed when the page is loaded you cannot make a check if the user closed his browser or not.

So the common approach would be to use timestamps and update this stamp if the user does something on your site and if the timestamp is older than say 5 minutes you just assume he is offline

Title: Check if user is offline


问:
How to make a horizontal StackView to have the first element's width and fill the rest of it
I'm new with swift and trying to create an input field at the moment. My problem is, that I would like to have a Label as shown in the picture:

So far, I'm working with StackViews: One vertical one for the input fields, and three horizontal ones to have the Title and the user input. My code so far is as follows:

```<code>// Initialize outter stackview
    let feedbackOutterSV = UIStackView()
    view.addSubview(feedbackOutterSV)
    feedbackOutterSV.translatesAutoresizingMaskIntoConstraints = false
    feedbackOutterSV.axis = NSLayoutConstraint.Axis.vertical
    NSLayoutConstraint.activate([
        feedbackOutterSV.topAnchor.constraint(equalTo: tutorialText.bottomAnchor, constant: 10),
        feedbackOutterSV.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        feedbackOutterSV.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        feedbackOutterSV.heightAnchor.constraint(equalToConstant: 300)
    ])

    // Initalize inner stackview for title
    let feedbackInnerSVTitle = UIStackView()
    feedbackOutterSV.addArrangedSubview(feedbackInnerSVTitle)
    feedbackInnerSVTitle.translatesAutoresizingMaskIntoConstraints = false
    feedbackInnerSVTitle.axis = .horizontal
    feedbackInnerSVTitle.alignment = .fill
    feedbackInnerSVTitle.distribution = .fillProportionally

    let titleLabel = UILabel()
    feedbackInnerSVTitle.addArrangedSubview(titleLabel)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = "feedback.input.title".localize()
    titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
    titleLabel.textColor = .gray

    let titleTextView = UITextView()
    feedbackInnerSVTitle.addArrangedSubview(titleTextView)
    titleTextView.translatesAutoresizingMaskIntoConstraints = false
    titleTextView.font = UIFont.preferredFont(forTextStyle: .body)
    titleTextView.isScrollEnabled = false

    NSLayoutConstraint.activate([
        titleLabel.widthAnchor.constraint(equalToConstant: 39)
    ])
</code>```

This code gives the expected output for English, however I have to implement it in different languages, so I can't use a constant width.

Can anyone tell me how to change my code, so I don't need the constant constraint but the width of the Label is adjusted to the length of the word?

Thanks in advance

答:
Couple things...

I assume you want the "title label" to be top-aligned with your textView, so change .fill to .top:

```<code>    feedbackInnerSVTitle.alignment = .top // .fill
</code>```

and, don't use .fillProportionally

```<code>    feedbackInnerSVTitle.distribution = .fill // .fillProportionally
</code>```

Now, you'll likely see each element taking 50% of the width, so change the content hugging priority for your title label:

```<code>    titleLabel.setContentHuggingPriority(.required, for: .horizontal)
</code>```

and, finally, don't set a width constraint on your title label:

```<code>//      NSLayoutConstraint.activate([
//          titleLabel.widthAnchor.constraint(equalToConstant: 39)
//          ])
</code>```

Result:

Body:
I'm new with swift and trying to create an input field at the moment. My problem is, that I would like to have a Label as shown in the picture:

So far, I'm working with StackViews: One vertical one for the input fields, and three horizontal ones to have the Title and the user input. My code so far is as follows:

// Initialize outter stackview
    let feedbackOutterSV = UIStackView()
    view.addSubview(feedbackOutterSV)
    feedbackOutterSV.translatesAutoresizingMaskIntoConstraints = false
    feedbackOutterSV.axis = NSLayoutConstraint.Axis.vertical
    NSLayoutConstraint.activate([
        feedbackOutterSV.topAnchor.constraint(equalTo: tutorialText.bottomAnchor, constant: 10),
        feedbackOutterSV.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        feedbackOutterSV.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        feedbackOutterSV.heightAnchor.constraint(equalToConstant: 300)
    ])

    // Initalize inner stackview for title
    let feedbackInnerSVTitle = UIStackView()
    feedbackOutterSV.addArrangedSubview(feedbackInnerSVTitle)
    feedbackInnerSVTitle.translatesAutoresizingMaskIntoConstraints = false
    feedbackInnerSVTitle.axis = .horizontal
    feedbackInnerSVTitle.alignment = .fill
    feedbackInnerSVTitle.distribution = .fillProportionally

    let titleLabel = UILabel()
    feedbackInnerSVTitle.addArrangedSubview(titleLabel)
    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = "feedback.input.title".localize()
    titleLabel.font = UIFont.preferredFont(forTextStyle: .body)
    titleLabel.textColor = .gray

    let titleTextView = UITextView()
    feedbackInnerSVTitle.addArrangedSubview(titleTextView)
    titleTextView.translatesAutoresizingMaskIntoConstraints = false
    titleTextView.font = UIFont.preferredFont(forTextStyle: .body)
    titleTextView.isScrollEnabled = false

    NSLayoutConstraint.activate([
        titleLabel.widthAnchor.constraint(equalToConstant: 39)
    ])

This code gives the expected output for English, however I have to implement it in different languages, so I can't use a constant width.

Can anyone tell me how to change my code, so I don't need the constant constraint but the width of the Label is adjusted to the length of the word?

Thanks in advance

Body:
Couple things...

I assume you want the "title label" to be top-aligned with your textView, so change .fill to .top:

    feedbackInnerSVTitle.alignment = .top // .fill

and, don't use .fillProportionally

    feedbackInnerSVTitle.distribution = .fill // .fillProportionally

Now, you'll likely see each element taking 50% of the width, so change the content hugging priority for your title label:

    titleLabel.setContentHuggingPriority(.required, for: .horizontal)

and, finally, don't set a width constraint on your title label:

//      NSLayoutConstraint.activate([
//          titleLabel.widthAnchor.constraint(equalToConstant: 39)
//          ])

Result: